import { KeyboardEvent , useCallback } from 'react' ; import { flattenOptions , getNextWrappingIndex } from '../../../utils' ; import { ValueType , UseSelectProps } from '../../../types' ; const useArrowsKeyDownHandler = < T extends ValueType , M extends boolean = false > ( { selectState : { isOpen , highlightedIndex , filteredOptions , setHighlightedIndex , open } } ) => useCallback ( ( key , event ) => { event . preventDefault ( ) ; if ( isOpen ) { const nonDisabledOptions = flattenOptions ( filteredOptions ) . map ( ( option , actualIndex ) => ( { ... option , actualIndex } ) ) . filter ( option => ! option . disabled ) ; const initialIndex = nonDisabledOptions . findIndex ( option => option . actualIndex === highlightedIndex ) ; const moveAmount = key === 'ArrowDown' ? 1 : - 1 ; const nextNonDisabledIndex = getNextWrappingIndex ( moveAmount , initialIndex , nonDisabledOptions . length ) ; const actualIndex = nonDisabledOptions [ nextNonDisabledIndex ] . actualIndex ; setHighlightedIndex ( actualIndex ) ; } else { open ( ) ; } } , [ isOpen , highlightedIndex , filteredOptions , setHighlightedIndex , open ] ) ; export default useArrowsKeyDownHandler ;