import { useState , useEffect , useCallback , useMemo } from 'react' ; import { Option , Selection } from '../../types' ; interface Props { flatOptions : Option [ ] ; selection : Selection ; isOpen : boolean ; } const useHighlightedIndex = ( { flatOptions , isOpen , selection } ) => { const [ highlightedIndex , setHighlightedIndex ] = useState ( 0 ) ; const selectedIndicies = useMemo ( ( ) => flatOptions . reduce ( ( acc , option , index ) => selection . isOptionSelected ( option ) ? [ ... acc , index ] : acc , [ ] as number [ ] ) , [ selection , flatOptions ] ) ; const nonDisabledIndicies = useMemo ( ( ) => flatOptions . reduce ( ( acc , option , index ) => ( ! option . disabled ? [ ... acc , index ] : acc ) , [ ] as number [ ] ) , [ flatOptions ] ) ; const handleChange = useCallback ( ( nextIndex ) => ! flatOptions [ nextIndex ] . disabled && setHighlightedIndex ( nextIndex ) , [ flatOptions ] ) ; useEffect ( ( ) => { const hasSelectedAndNonDisabledOption = selectedIndicies . length === 1 && ! flatOptions [ selectedIndicies [ 0 ] ] . disabled ; const nextHighlightedIndex = hasSelectedAndNonDisabledOption ? selectedIndicies [ 0 ] : nonDisabledIndicies [ 0 ] ; setHighlightedIndex ( nextHighlightedIndex ) ; } , [ isOpen , flatOptions ] ) ; return [ highlightedIndex , handleChange ] as const ; } ; export default useHighlightedIndex ;