import { FocusEvent , KeyboardEvent , RefObject , SyntheticEvent } from "react" ; import { FocusScope , Keys , isNil , mergeProps , useEventCallback , useRefState } from "../../shared" ; import { UseOverlayLightDismissOptions , useOverlayLightDismiss } from "./useOverlayLightDismiss" ; import { isDevToolsBlurEvent } from "./isDevtoolsBlurEvent" ; import { isTargetParent } from "./isTargetParent" ; export function usePopupLightDismiss ( triggerRef , focusScope , { hideOnEscape , hideOnLeave , hideOnOutsideClick , isDisabled , onHide , trigger } = { } ) { const [ isHandled , setIsHandled ] = useRefState ( false ) ; const hide = ( event ) => { if ( ! isNil ( onHide ) ) { onHide ( event ) ; } } ; const handleKeyDown = useEventCallback ( ( event ) => { if ( event . key === Keys . tab ) { setIsHandled ( true ) ; if ( hideOnLeave ) { hide ( event ) ; } } } ) ; const props = useOverlayLightDismiss ( focusScope , { hideOnEscape , hideOnLeave , hideOnOutsideClick , isDisabled , onHide : useEventCallback ( ( event ) => { switch ( event . type ) { case "mouseup" : case "click" : { if ( ! isTargetParent ( event . target , triggerRef ) ) { hide ( event ) ; } break ; } case "blur" : { setTimeout ( ( ) => { if ( ! isHandled . current ) { if ( ! isDevToolsBlurEvent ( focusScope ) ) { if ( ( event as FocusEvent ) . relatedTarget !== triggerRef . current ) { hide ( event ) ; } } } setIsHandled ( false ) ; } , 0 ) ; break ; } default : { hide ( event ) ; } } } ) , trigger } ) ; return mergeProps ( props , { onKeyDown : handleKeyDown } ) ; }