UNPKG

@visa/nova-react

Version:

Visa Product Design System Nova React library

18 lines (17 loc) 2.1 kB
/** * Copyright (c) 2025 Visa, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **/ import{useState as e,useEffect as a}from"react";import{generateArray as t}from"./utils.mjs";export{calculatePagesFromTo,calculateTotalPages}from"./utils.mjs";const r={defaultSelected:1,endBlockMaxLength:3,maxPageNumber:null,middleBlockMaxLength:3,separator:-1,startBlockMaxLength:3,startPage:1},l=l=>{const{defaultSelected:o,endBlockMaxLength:n,maxPageNumber:g,middleBlockMaxLength:s,separator:m,startBlockMaxLength:c,startPage:u,totalPages:d}={...r,...l},[h,i]=e(Math.min(Math.max(o,u),d)),P=u,x=d+u-1,M=null===g?x:Math.min(g,x),L=h===P,f=h===M,k=d>n+s+c,B=h<P+c,p=h>M-n,b=!B&&!p,N=B?t(P,c):[P],w=(()=>{if(!b)return[];const e=Math.floor(s/2);return t(h-e<=P?h-(h-P)+1:h+e>=M?h+(M-h)-s:h-e,s)})(),F=p?t(M-n+1,n):[M],S=k?[N,w,F].map((e=>e.length?[...e,m]:[])).flat().slice(0,-1):t(P,M-P+1);return a((()=>{if(n<1||s<1||c<1)throw new Error("endBlockMaxLength, middleBlockMaxLength, and startBlockMaxLength all must be greater than 0");if(u<0||null!==g&&g<1)throw new Error("startPage must be 0 or greater, and maxPageNumber must be 1 or greater")}),[n,g,s,c,u]),{isFirstPage:L,isLastPage:f,onFirstPage:()=>i(P),onLastPage:()=>i(M),onNextPage:()=>i(Math.min(M,h+1)),onPageChange:e=>{i(e>M?M:e<P?P:e)},onPreviousPage:()=>i(Math.max(P,h-1)),pages:S,selectedPage:h}};l.displayName="usePagination",l.defaultProps={defaultSelected:1,endBlockMaxLength:3,maxPageNumber:null,middleBlockMaxLength:3,separator:-1,startBlockMaxLength:3,startPage:1};export{l as default,l as usePagination};