@visa/nova-react
Version:
Visa Product Design System Nova React library
18 lines (17 loc) • 1.95 kB
JavaScript
/**
* 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 t,useEffect as n}from"react";const r={autoSelect:!1,defaultSelected:-1,arrowKeyNavigation:null},a=a=>{const{defaultSelected:l,...o}={...r,...a},c=e([]),[i,u]=t(l),[s,d]=t(l),[f,v]=t([]),[g,p]=t("horizontal"),w=-1===s?0:f.indexOf(s),m=e(null),y=f.length,h=y-1,N=o?.ref||c;return n((()=>{v(N.current?.map(((e,t)=>!e?.disabled&&t)).filter((e=>!1!==e)))}),[N]),n((()=>{(()=>{if(null===o.arrowKeyNavigation){if(N.current&&N.current[0]instanceof HTMLElement){const e=N.current[0].parentElement?.parentElement;e&&e.classList.contains("v-tabs-vertical")&&p("vertical")}}else p(o.arrowKeyNavigation)})()}),[]),{getTabIndex:(e,t=!1)=>(t||null!==m.current||(m.current=e),i===e||-1===i&&m.current===e?0:-1),onIndexChange:(e,t=!1)=>{t||(u(e),d(e))},onKeyNavigation:e=>{const t=e.key;let n=null;if("ArrowRight"===t&&"vertical"!==g&&"none"!==g||"ArrowDown"===t&&"horizontal"!==g&&"none"!==g?n=(w+1)%y:"ArrowLeft"===t&&"vertical"!==g&&"none"!==g||"ArrowUp"===t&&"horizontal"!==g&&"none"!==g?n=w-1<0?h:w-1:"End"===t?n=h:"Home"===t&&(n=0),"Tab"===t&&d(i),N.current&&null!==n&&y){e.preventDefault();const t=f[n];o.autoSelect&&u(t),d(t),N.current[t]?.focus()}},ref:N,selectedIndex:i}};a.displayName="useTabs",a.defaultProps={autoSelect:!1,defaultSelected:-1,arrowKeyNavigation:null};export{a as default,a as useTabs};