import { FocusEvent , KeyboardEvent , MouseEvent , SyntheticEvent } from "react" ; import { FocusScope , Keys , isNil , useEventCallback , useFocusWithin } from "../../shared" ; import { OverlayTrigger } from "./useOverlayTrigger" ; import { isDevToolsBlurEvent } from "./isDevtoolsBlurEvent" ; import { useInteractOutside } from "./useInteractOutside" ; export interface UseOverlayLightDismissOptions { hideOnEscape ? : boolean ; hideOnLeave ? : boolean ; hideOnOutsideClick ? : boolean | ( ( event : MouseEvent ) => void ) ; isDisabled ? : boolean ; onHide ? : ( event : SyntheticEvent ) => void ; trigger ? : OverlayTrigger ; } export function useOverlayLightDismiss ( focusScope , { hideOnEscape , hideOnLeave , hideOnOutsideClick , isDisabled , onHide , trigger = "click" } = { } ) { const hide = ( event ) => { if ( ! isNil ( onHide ) ) { onHide ( event ) ; } } ; const handleKeyDown = useEventCallback ( ( event ) => { if ( event . key === Keys . esc ) { if ( hideOnEscape ) { const currentActiveElement = event . target ; if ( focusScope . isInScope ( currentActiveElement as HTMLElement ) ) { event . preventDefault ( ) ; hide ( event ) ; } } } } ) ; const handleBlur = useEventCallback ( ( event ) => { if ( ! isDevToolsBlurEvent ( focusScope ) ) { hide ( event ) ; } } ) ; const handleMouseLeave = useEventCallback ( ( event ) => { hide ( event ) ; } ) ; const handleInteractOutside = useEventCallback ( ( event ) => { hide ( event ) ; } ) ; useInteractOutside ( focusScope , { isDisabled : isDisabled || ! hideOnOutsideClick , onInteractOutside : handleInteractOutside } ) ; const focusWithinProps = useFocusWithin ( { isDisabled : isDisabled || ! hideOnLeave , onBlur : handleBlur } ) ; if ( isDisabled ) { return { } ; } switch ( trigger ) { case "click" : return { ... focusWithinProps , onKeyDown : handleKeyDown } ; case "hover" : return { ... focusWithinProps , onKeyDown : handleKeyDown , onMouseLeave : hideOnLeave ? handleMouseLeave : undefined } ; default : return { } ; } }