From 13a7b78172d2443c867ae7d83e133c8ba5f7c439 Mon Sep 17 00:00:00 2001 From: EdJoPaTo Date: Tue, 6 Feb 2024 22:06:00 +0100 Subject: [PATCH] feat(pagination): currentPage can be Infinity it will be clamped to [1..totalPages] --- source/buttons/pagination.test.ts | 6 ++++++ source/buttons/pagination.ts | 22 +++++++++------------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/source/buttons/pagination.test.ts b/source/buttons/pagination.test.ts index fcb9f0b..6c9cfbe 100644 --- a/source/buttons/pagination.test.ts +++ b/source/buttons/pagination.test.ts @@ -31,6 +31,12 @@ await test('pagination', async t => { 9, 10, ]); + await macro( + 'currentPage Infinity is max page', + 10, + Number.POSITIVE_INFINITY, + [1, 9, 10], + ); // When there are 19 items / 2 per page there are... 9.5 pages -> 10 await macro('when totalPages is float use ceil', 9.5, 10, [1, 9, 10]); diff --git a/source/buttons/pagination.ts b/source/buttons/pagination.ts index 65630b3..a68e37a 100644 --- a/source/buttons/pagination.ts +++ b/source/buttons/pagination.ts @@ -54,24 +54,19 @@ export function createPaginationChoices( totalPages: number, currentPage: number | undefined, ): Record { - // Numbers have to be within - // currentPage in [1..totalPages] - const totalPagesFixed = Math.ceil(totalPages); - const currentPageFinite = (typeof currentPage === 'number' && Number.isFinite(currentPage)) ? currentPage : 1; - const currentPageFixed = clamp(currentPageFinite, 1, totalPagesFixed); - const buttons: Record = {}; - if ( - !Number.isFinite(totalPagesFixed) - || !Number.isFinite(currentPageFixed) - || totalPagesFixed < 2 - ) { + + const totalPagesFixed = Math.ceil(totalPages); + if (!Number.isFinite(totalPagesFixed) || totalPagesFixed < 2) { return buttons; } - const before = currentPageFixed - 1; - const after = currentPageFixed + 1; + const currentPageFixed + = (typeof currentPage === 'number' && !Number.isNaN(currentPage)) + ? clamp(currentPage, 1, totalPagesFixed) + : 1; + const before = currentPageFixed - 1; if (currentPageFixed > 1) { if (before > 1) { buttons[1] = '1 ⏪'; @@ -82,6 +77,7 @@ export function createPaginationChoices( buttons[currentPageFixed] = String(currentPageFixed); + const after = currentPageFixed + 1; if (currentPageFixed < totalPagesFixed) { buttons[after] = `▶️ ${after}`;