import { FocusManager , Keys , isNil , useDocumentListener , useEventCallback , useRefState } from "../../shared" ; export interface UseTrapFocusOptions { isDisabled ? : boolean ; } export function useTrapFocus ( focusManager , { isDisabled } = { } ) { const [ focusedElementRef , setFocusedElement ] = useRefState < HTMLElement > ( ) ; const handleKeyDown = useEventCallback ( ( event ) => { if ( event . key === Keys . tab ) { const currentActiveElement = event . target ; if ( focusManager . isInScope ( currentActiveElement as HTMLElement ) ) { event . preventDefault ( ) ; event . stopPropagation ( ) ; if ( event . shiftKey ) { const element = focusManager . focusPrevious ( { tabbableOnly : true } ) ; setFocusedElement ( element ) ; } else { const element = focusManager . focusNext ( { tabbableOnly : true } ) ; setFocusedElement ( element ) ; } } } } ) ; const handleFocus = useEventCallback ( ( event ) => { const target = event . target as HTMLElement ; if ( ! focusManager . isInScope ( target , { includeChildScopes : true } ) ) { if ( ! isNil ( focusedElementRef . current ) ) { focusedElementRef . current . focus ( ) ; } else { const element = focusManager . focusFirst ( { tabbableOnly : true } ) ; setFocusedElement ( element ) ; } } else { setFocusedElement ( target ) ; } } ) ; useDocumentListener ( "keydown" , handleKeyDown , ! isDisabled , { capture : true } ) ; useDocumentListener ( "focusin" , handleFocus , ! isDisabled ) ; }