UNPKG

@workday/canvas-kit-react

Version:

The parent module that contains all Workday Canvas Kit React components

66 lines (65 loc) 2.05 kB
import * as React from 'react'; import { buildPageRange } from './buildPageRange'; import { getRangeMax, getRangeMin } from './common/utils/helpers'; export const PaginationContext = React.createContext({}); export const usePaginationModel = (config) => { const { firstPage = 1, initialCurrentPage = 1, lastPage, rangeSize = 5, onPageChange } = config; const [currentPage, setCurrentPage] = React.useState(initialCurrentPage); const changePage = (page) => { // Don't fire an `onPageChange` event if the page number is the same as the current page. // `setCurrentPage` doesn't need this check, because React won't update the state if the values are the same. if (currentPage !== page) { onPageChange === null || onPageChange === void 0 ? void 0 : onPageChange(page); } setCurrentPage(page); }; const first = () => { changePage(firstPage); }; const last = () => { changePage(lastPage); }; const next = () => { changePage(currentPage + 1); }; const previous = () => { changePage(currentPage - 1); }; const goTo = (pageNumber) => { if (pageNumber < firstPage) { // a safeguard to prevent for going to a page below the range changePage(firstPage); } else if (pageNumber > lastPage) { // a safeguard to prevent going to a page above the range changePage(lastPage); } else { changePage(pageNumber); } }; const range = buildPageRange({ currentPage, lastPage, rangeSize }); const rangeMin = getRangeMin(range); const rangeMax = getRangeMax(range); const state = { firstPage, currentPage, lastPage, range, rangeSize, rangeMin, rangeMax, }; const events = { setCurrentPage: changePage, first, last, next, previous, goTo, }; return { state, events, }; };