UNPKG

@visa/nova-react

Version:

Visa Product Design System Nova React library

18 lines (17 loc) 2.15 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. * **/ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");const t={autoSelect:!1,defaultSelected:-1},r=r=>{const{defaultSelected:l,...u}={...t,...r},a=e.useRef([]),s=e.useRef(null),[o,n]=e.useState(Array.isArray(l)?l.length?l[0]:-1:l),[c,i]=e.useState([]),[d,f]=e.useState(l),S=Array.isArray(d),b=-1===o?0:c.indexOf(o),x=c.length,y=x-1,p=u?.ref||a,m=e.useCallback((e=>S?d.includes(e):d===e),[S,d]),g=e.useCallback((e=>{f(S?t=>m(e)?t.filter((t=>t!==e)):[...t,e]:m(e)?-1:e),n(e)}),[m,S]);return e.useEffect((()=>{if(S&&u.autoSelect)throw new Error("ERROR useListbox: autoSelect is not compatible with multi select listbox, try removing {autoSelect: true} or set autoSelect to false, or make only one element in the listbox selected by default")}),[u,S]),e.useEffect((()=>{i(p.current?.map(((e,t)=>(!e?.ariaDisabled||"false"===e?.ariaDisabled)&&t)).filter((e=>!1!==e)))}),[p]),{isIndexSelected:m,getTabIndex:(e,t=!1)=>(t||null!==s.current||(s.current=e),S?o===e||-1===o&&s.current===e?0:-1:d===e||-1===d&&s.current===e?0:-1),onKeyNavigation:e=>{const t=e.key;let r=null;if("ArrowDown"===t?r=(b+1)%x:"ArrowUp"===t?r=b-1<0?y:b-1:"End"===t?r=y:"Home"===t&&(r=0),"Enter"!==t&&" "!==t||g(c[b]),"Tab"===t&&n(S?c[b]:d),p.current&&null!==r&&x){e.preventDefault();const t=c[r];u.autoSelect&&f(t),n(t),p.current[t]?.focus()}},ref:p,selectedIndex:d,selectedIndices:d,toggleIndexSelected:g}};r.displayName="useListbox",r.defaultProps={autoSelect:!1,defaultSelected:-1},exports.default=r,exports.useListbox=r;