UNPKG

@visa/nova-react

Version:

Visa Product Design System Nova React library

18 lines (17 loc) 1.56 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{useRef as e,useState as r,useCallback as a,useEffect as n}from"react";const t={defaultExpanded:""},d=d=>{const{defaultExpanded:l,...o}={...t,...d},i=e([]),[f,s]=r(l),[u,c]=r(-1),[p,x]=r([]),y=-1===u?0:p.indexOf(u),E=p.length,m=E-1,A=Array.isArray(f),b=o?.ref||i,g=a((e=>A?f.includes(e):f===e),[f,A]),h=a((e=>{s(A?r=>g(e)?r.filter((r=>r!==e)):[...r,e]:g(e)?"":e),c(e)}),[g,A]);return n((()=>{x(b.current?.map(((e,r)=>e&&!(e.disabled||e.ariaDisabled)&&r)).filter((e=>!1!==e)))}),[b]),{isIndexExpanded:g,onKeyNavigation:e=>{const r=e.key;let a=null;if("Tab"===r&&e.shiftKey&&y-1>=0?a=y-1:"Tab"===r&&!e.shiftKey&&y+1<=m?a=y+1:"ArrowUp"===r?a=y-1<0?m:y-1:"ArrowDown"===r?a=(y+1)%E:"End"===r?a=m:"Home"===r&&(a=0),b.current&&null!==a&&E){u!==a&&e.preventDefault();const r=p[a];c(r),b.current[r]?.focus()}},ref:b,toggleIndexExpanded:h}};d.displayName="useAccordion",d.defaultProps={defaultExpanded:""};export{d as default,d as useAccordion};