import { useEffect , useRef , useState } from 'react' ; import { Tab } from './index.d' ; import useRightToLeft from '../../containers/rightToLeft/useRightToLeft' ; const getWidth = ( el ) => { return el . getClientRects ( ) ?. [ 0 ] ?. width ?? 0 ; } ; const getComputedMargin = ( el ) => { const value = window . getComputedStyle ( el ) ?. marginRight ; if ( value . includes ( 'px' ) ) { return Number ( value . slice ( 0 , - 2 ) ) ; } return 0 ; } ; const INITIAL_STATE = { scale : 0 , translate : '0px' , } ; export const useIndicator = ( tabs , currentTabIndex ) => { const tabsRef = useRef < HTMLUListElement > ( null ) ; const [ isRTL ] = useRightToLeft ( ) ; const [ { scale , translate } , setIndicatorParams ] = useState ( INITIAL_STATE ) ; useEffect ( ( ) => { const tabsEl = tabsRef . current ; if ( ! tabsEl ) { setIndicatorParams ( INITIAL_STATE ) ; return ; } const tabsListItems = tabsEl . querySelectorAll < HTMLLIElement > ( '.tabs-list-item' ) ; const tabProperties = [ ... tabsListItems ] . map ( ( el ) => ( { width : getWidth ( el ) , margin : getComputedMargin ( el ) , } ) ) ; const totalTabWidth = tabProperties . reduce ( ( acc , { width , margin } ) => acc + width + margin , 0 ) ; if ( totalTabWidth > getWidth ( tabsEl ) ) { setIndicatorParams ( INITIAL_STATE ) ; return ; } const { offset , width } = tabProperties . reduce ( ( acc , { width , margin } , index ) => { if ( index < currentTabIndex ) { acc . offset += width + margin ; } if ( index === currentTabIndex ) { acc . width = width ; } return acc ; } , { offset : 0 , width : 0 } ) ; setIndicatorParams ( { scale : width / getWidth ( tabsEl ) , translate : isRTL ? `-${ offset }px` : `${ offset }px` , } ) ; } , [ tabs , currentTabIndex ] ) ; return { scale , translate , ref : tabsRef , } ; } ;