diff options
| author | Bertrand Yuan <bert.yuan@outlook.com> | 2025-12-15 23:48:10 +0800 |
|---|---|---|
| committer | Bertrand Yuan <bert.yuan@outlook.com> | 2025-12-15 23:48:10 +0800 |
| commit | 5b7ccf0b671e2999b62befc729a3e517a0433728 (patch) | |
| tree | 8bf476dc7c75914c221042546840dc76267366df /src/hooks | |
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.
Diffstat (limited to 'src/hooks')
| -rw-r--r-- | src/hooks/use-pagination.tsx | 61 |
1 files changed, 61 insertions, 0 deletions
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, + }; +} |
