UNPKG

@visa/nova-react

Version:

Visa Product Design System Nova React library. Compatible with React ^19.

2 lines (1 loc) 2.66 kB
import{useState as e,useEffect as a,useMemo as t}from"react";import{generateArray as n}from"./utils.mjs";export{calculatePagesFromTo,calculateTotalPages}from"./utils.mjs";const o={blockMaxLength:3,compact:!1,defaultSelected:1,maxPageNumber:null,separator:-1,startPage:1,totalPages:1},l=(l=o)=>{const s=l.blockMaxLength??o.blockMaxLength,{blockMaxLength:g,compact:c,defaultSelected:d,selectedPage:i,setSelectedPage:r,separator:u,totalPages:m}={...o,...l};let{endBlockMaxLength:P,maxPageNumber:x,middleBlockMaxLength:h,startBlockMaxLength:M,startPage:L}={...o,endBlockMaxLength:s,middleBlockMaxLength:s,startBlockMaxLength:s,...l};M<1&&(M=3),h<1&&(h=3),P<1&&(P=3),L<0&&(L=1),null!==x&&x<1&&(x=null);const[k,B]=e(Math.min(Math.max(d,L),m)),b=void 0!==i&&void 0!==r,f=b?i:k,v=b?r:B;a(()=>{const e={...o,...l};void 0!==e.startBlockMaxLength&&e.startBlockMaxLength<1&&console.warn(`⚠️ usePagination: startBlockMaxLength must be >= 1. Received: ${e.startBlockMaxLength}. Using default: 3`),void 0!==e.middleBlockMaxLength&&e.middleBlockMaxLength<1&&console.warn(`⚠️ usePagination: middleBlockMaxLength must be >= 1. Received: ${e.middleBlockMaxLength}. Using default: 3`),void 0!==e.endBlockMaxLength&&e.endBlockMaxLength<1&&console.warn(`⚠️ usePagination: endBlockMaxLength must be >= 1. Received: ${e.endBlockMaxLength}. Using default: 3`),void 0!==e.startPage&&e.startPage<0&&console.warn(`⚠️ usePagination: startPage must be >= 0. Received: ${e.startPage}. Using default: 1`),null!==e.maxPageNumber&&void 0!==e.maxPageNumber&&e.maxPageNumber<1&&console.warn(`⚠️ usePagination: maxPageNumber must be >= 1 or null. Received: ${e.maxPageNumber}. Using default: null`)},[l]),a(()=>{const e=void 0!==i,a=void 0!==r;e!==a&&console.warn(`⚠️ usePagination: Both selectedPage and setSelectedPage must be provided together.\nCurrently: selectedPage=${e?i:"undefined"}, setSelectedPage=${a?"provided":"undefined"}\nFalling back to uncontrolled mode.`)},[i,r]);const p=L,N=m+L-1,$=null===x?N:Math.min(x,N),w=f===p,R=f===$,S=m>P+h+M,U=f<p+M,F=f>$-P,j=!U&&!F,y=U?n(p,M):[p],C=(()=>{if(!j)return[];const e=Math.floor(h/2);return n(f-e<=p?f-(f-p)+1:f+e>=$?f+($-f)-h:f-e,h)})(),T=F?n($-P+1,P):[$],q=t(()=>{if(g>m)return n(L,$-L+1);const e=Math.floor(g/2);return n(f-e<=L?L:f+e>=$?$-g+1:f-e,g)},[g,$,f,L,m]);return{isFirstPage:w,isLastPage:R,onFirstPage:()=>v(p),onLastPage:()=>v($),onNextPage:()=>v(Math.min($,f+1)),onPageChange:e=>{v(e>$?$:e<p?p:e)},onPreviousPage:()=>v(Math.max(p,f-1)),pages:c?q:S?[y,C,T].map(e=>e.length?[...e,u]:[]).flat().slice(0,-1):n(p,$-p+1),selectedPage:f}};l.displayName="usePagination";export{l as default,l as usePagination};