UNPKG

@yamada-ui/pagination

Version:

Yamada UI pagination component

97 lines (95 loc) 2.94 kB
"use client" // src/use-pagination.ts import { useControllableState } from "@yamada-ui/use-controllable-state"; import { useValue } from "@yamada-ui/use-value"; import { createContext } from "@yamada-ui/utils"; import { useCallback, useMemo } from "react"; var [PaginationProvider, usePaginationContext] = createContext({ name: "PaginationContext", errorMessage: `usePaginationContext returned is 'undefined'. Seems you forgot to wrap the components in "<Pagination />"` }); var computedRange = (start, end) => Array.from({ length: end - start + 1 }, (_, index) => index + start); var usePagination = ({ boundaries: _boundaries = 1, defaultPage = 1, isDisabled = false, disabled = isDisabled, page, siblings: _siblings = 1, total, onChange: onChangeProp }) => { const siblings = useValue(_siblings); const boundaries = useValue(_boundaries); const [currentPage, setCurrentPage] = useControllableState({ defaultValue: defaultPage, value: page, onChange: onChangeProp }); const range = useMemo(() => { const minimumTotal = siblings * 2 + 3 + boundaries * 2; if (minimumTotal >= total) return computedRange(1, total); const prevSiblings = Math.max(currentPage - siblings, boundaries); const nextSiblings = Math.min(currentPage + siblings, total - boundaries); const prevDots = prevSiblings > boundaries + 2; const nextDots = nextSiblings < total - (boundaries + 1); if (!prevDots && nextDots) { const prevPages = siblings * 2 + boundaries + 2; return [ ...computedRange(1, prevPages), "ellipsis", ...computedRange(total - (boundaries - 1), total) ]; } if (prevDots && !nextDots) { const nextPages = boundaries + 1 + 2 * siblings; return [ ...computedRange(1, boundaries), "ellipsis", ...computedRange(total - nextPages, total) ]; } return [ ...computedRange(1, boundaries), "ellipsis", ...computedRange(prevSiblings, nextSiblings), "ellipsis", ...computedRange(total - boundaries + 1, total) ]; }, [boundaries, siblings, currentPage, total]); const onFirst = useCallback(() => setCurrentPage(1), [setCurrentPage]); const onLast = useCallback( () => setCurrentPage(total), [setCurrentPage, total] ); const onPrev = useCallback( () => setCurrentPage((prev) => prev === 1 ? prev : prev - 1), [setCurrentPage] ); const onNext = useCallback( () => setCurrentPage((prev) => prev === total ? prev : prev + 1), [setCurrentPage, total] ); const onChange = useCallback( (page2) => setCurrentPage(page2), [setCurrentPage] ); return { currentPage, disabled, range, total, onChange, onFirst, onLast, onNext, onPrev }; }; export { PaginationProvider, usePaginationContext, computedRange, usePagination }; //# sourceMappingURL=chunk-ZOXC7X6K.mjs.map