import { KeyboardEvent , useCallback } from 'react' ; import { ValueType , UseSelectProps } from '../../../types' ; import { normalizeArrowKey , focusRef } from '../../../utils' ; import useArrowsKeyDownHandler from '../use-arrows-keydown-handler' ; import useEnterOrSpaceKeyDownHandler from '../use-enter-or-space-keydown-handler' ; import useEscapeKeyDownHandler from '../use-escape-keydown-handler' ; const useSelectKeyDownHandler = < T extends ValueType , M extends boolean = false > ( { selectProps : { onKeyDown , native } , searchInputRef , selectState : { isOpen , showSearch } , handleArrowsKeyDown , handleEnterOrSpaceKeyDown , handleEscapeKeyDown } ) => useCallback ( ( event ) => { if ( native ) { onKeyDown ?. ( event ) ; return ; } const key = normalizeArrowKey ( event ) ; const isCharacterKey = key . length === 1 ; if ( key === 'ArrowUp' || key === 'ArrowDown' ) { handleArrowsKeyDown ( key , event ) ; } else if ( key === 'Enter' || key === ' ' ) { handleEnterOrSpaceKeyDown ( event ) ; } else if ( key === 'Escape' ) { handleEscapeKeyDown ( event ) ; } else if ( key === 'Tab' && isOpen && showSearch ) { event . preventDefault ( ) ; focusRef ( searchInputRef ) ; } else if ( isCharacterKey || key === 'Backspace' ) { focusRef ( searchInputRef ) ; } onKeyDown ?. ( event ) ; } , [ native , onKeyDown , searchInputRef , isOpen , showSearch , handleArrowsKeyDown , handleEnterOrSpaceKeyDown , handleEscapeKeyDown ] ) ; export default useSelectKeyDownHandler ;