31 lines
1012 B
TypeScript
31 lines
1012 B
TypeScript
import { useMemo } from 'react'
|
|
|
|
interface UsePaginationProps {
|
|
currentPage: number
|
|
totalPages: number
|
|
paginationItemsToDisplay?: number
|
|
}
|
|
|
|
export function usePagination({ currentPage, totalPages, paginationItemsToDisplay = 5 }: UsePaginationProps) {
|
|
return useMemo(() => {
|
|
if (totalPages <= 0) {
|
|
return { pages: [] as number[], showLeftEllipsis: false, showRightEllipsis: false }
|
|
}
|
|
|
|
const visibleCount = Math.max(1, paginationItemsToDisplay)
|
|
const half = Math.floor(visibleCount / 2)
|
|
let startPage = Math.max(1, currentPage - half)
|
|
let endPage = Math.min(totalPages, startPage + visibleCount - 1)
|
|
|
|
if (endPage - startPage + 1 < visibleCount) {
|
|
startPage = Math.max(1, endPage - visibleCount + 1)
|
|
}
|
|
|
|
return {
|
|
pages: Array.from({ length: endPage - startPage + 1 }, (_, index) => startPage + index),
|
|
showLeftEllipsis: startPage > 1,
|
|
showRightEllipsis: endPage < totalPages,
|
|
}
|
|
}, [currentPage, paginationItemsToDisplay, totalPages])
|
|
}
|