Skip to content

Commit

Permalink
feat(pagination): currentPage can be Infinity
Browse files Browse the repository at this point in the history
it will be clamped to [1..totalPages]
  • Loading branch information
EdJoPaTo committed Feb 6, 2024
1 parent 80bfb44 commit 13a7b78
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
6 changes: 6 additions & 0 deletions source/buttons/pagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
22 changes: 9 additions & 13 deletions source/buttons/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,19 @@ export function createPaginationChoices(
totalPages: number,
currentPage: number | undefined,
): Record<number, string> {
// 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<number, string> = {};
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 ⏪';
Expand All @@ -82,6 +77,7 @@ export function createPaginationChoices(

buttons[currentPageFixed] = String(currentPageFixed);

const after = currentPageFixed + 1;
if (currentPageFixed < totalPagesFixed) {
buttons[after] = `▶️ ${after}`;

Expand Down

0 comments on commit 13a7b78

Please sign in to comment.