UNPKG

@workday/canvas-kit-react

Version:

The parent module that contains all Workday Canvas Kit React components

93 lines (92 loc) 3.31 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.usePaginationModel = exports.PaginationContext = void 0; const React = __importStar(require("react")); const buildPageRange_1 = require("./buildPageRange"); const helpers_1 = require("./common/utils/helpers"); exports.PaginationContext = React.createContext({}); 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 = (0, buildPageRange_1.buildPageRange)({ currentPage, lastPage, rangeSize }); const rangeMin = (0, helpers_1.getRangeMin)(range); const rangeMax = (0, helpers_1.getRangeMax)(range); const state = { firstPage, currentPage, lastPage, range, rangeSize, rangeMin, rangeMax, }; const events = { setCurrentPage: changePage, first, last, next, previous, goTo, }; return { state, events, }; }; exports.usePaginationModel = usePaginationModel;