From 5b7ccf0b671e2999b62befc729a3e517a0433728 Mon Sep 17 00:00:00 2001 From: Bertrand Yuan Date: Mon, 15 Dec 2025 23:48:10 +0800 Subject: initial commit -- the front-end prototype The initial code is base on Anirudh's work. More to see at: https://github.com/techwithanirudh/shadcn-blog Therefore, the code in this commit is under MIT license. --- src/hooks/use-pagination.tsx | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/hooks/use-pagination.tsx (limited to 'src/hooks') diff --git a/src/hooks/use-pagination.tsx b/src/hooks/use-pagination.tsx new file mode 100644 index 0000000..d009cd4 --- /dev/null +++ b/src/hooks/use-pagination.tsx @@ -0,0 +1,61 @@ +type UsePaginationProps = { + currentPage: number; + totalPages: number; + paginationItemsToDisplay: number; +}; + +type UsePaginationReturn = { + pages: number[]; + showLeftEllipsis: boolean; + showRightEllipsis: boolean; +}; + +export function usePagination({ + currentPage, + totalPages, + paginationItemsToDisplay, +}: UsePaginationProps): UsePaginationReturn { + const showLeftEllipsis = currentPage - 1 > paginationItemsToDisplay / 2; + const showRightEllipsis = + totalPages - currentPage + 1 > paginationItemsToDisplay / 2; + + function calculatePaginationRange(): number[] { + if (totalPages <= paginationItemsToDisplay) { + return Array.from({ length: totalPages }, (_, i) => i + 1); + } + + const halfDisplay = Math.floor(paginationItemsToDisplay / 2); + const initialRange = { + start: currentPage - halfDisplay, + end: currentPage + halfDisplay, + }; + + const adjustedRange = { + start: Math.max(1, initialRange.start), + end: Math.min(totalPages, initialRange.end), + }; + + if (adjustedRange.start === 1) { + adjustedRange.end = paginationItemsToDisplay; + } + if (adjustedRange.end === totalPages) { + adjustedRange.start = totalPages - paginationItemsToDisplay + 1; + } + + if (showLeftEllipsis) adjustedRange.start++; + if (showRightEllipsis) adjustedRange.end--; + + return Array.from( + { length: adjustedRange.end - adjustedRange.start + 1 }, + (_, i) => adjustedRange.start + i, + ); + } + + const pages = calculatePaginationRange(); + + return { + pages, + showLeftEllipsis, + showRightEllipsis, + }; +} -- cgit v1.2.3