| 66 | * or optionally, on blur. Only the top-most overlay will close at once. |
| 67 | */ |
| 68 | export function useOverlay(props: AriaOverlayProps, ref: RefObject<Element | null>): OverlayAria { |
| 69 | let { |
| 70 | onClose, |
| 71 | shouldCloseOnBlur, |
| 72 | isOpen, |
| 73 | isDismissable = false, |
| 74 | isKeyboardDismissDisabled = false, |
| 75 | shouldCloseOnInteractOutside |
| 76 | } = props; |
| 77 | |
| 78 | let lastVisibleOverlay = useRef<RefObject<Element | null>>(undefined); |
| 79 | |
| 80 | // Add the overlay ref to the stack of visible overlays on mount, and remove on unmount. |
| 81 | useEffect(() => { |
| 82 | if (isOpen && !visibleOverlays.includes(ref)) { |
| 83 | visibleOverlays.push(ref); |
| 84 | return () => { |
| 85 | let index = visibleOverlays.indexOf(ref); |
| 86 | if (index >= 0) { |
| 87 | visibleOverlays.splice(index, 1); |
| 88 | } |
| 89 | }; |
| 90 | } |
| 91 | }, [isOpen, ref]); |
| 92 | |
| 93 | // Only hide the overlay when it is the topmost visible overlay in the stack |
| 94 | let onHide = () => { |
| 95 | if (visibleOverlays[visibleOverlays.length - 1] === ref && onClose) { |
| 96 | onClose(); |
| 97 | } |
| 98 | }; |
| 99 | |
| 100 | let onInteractOutsideStart = (e: PointerEvent) => { |
| 101 | const topMostOverlay = visibleOverlays[visibleOverlays.length - 1]; |
| 102 | lastVisibleOverlay.current = topMostOverlay; |
| 103 | if ( |
| 104 | !shouldCloseOnInteractOutside || |
| 105 | shouldCloseOnInteractOutside(getEventTarget(e) as Element) |
| 106 | ) { |
| 107 | if (topMostOverlay === ref) { |
| 108 | e.stopPropagation(); |
| 109 | } |
| 110 | } |
| 111 | }; |
| 112 | |
| 113 | let onInteractOutside = (e: PointerEvent) => { |
| 114 | if ( |
| 115 | !shouldCloseOnInteractOutside || |
| 116 | shouldCloseOnInteractOutside(getEventTarget(e) as Element) |
| 117 | ) { |
| 118 | if (visibleOverlays[visibleOverlays.length - 1] === ref) { |
| 119 | e.stopPropagation(); |
| 120 | } |
| 121 | if (lastVisibleOverlay.current === ref) { |
| 122 | onHide(); |
| 123 | } |
| 124 | } |
| 125 | lastVisibleOverlay.current = undefined; |