MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useOverlay

Function useOverlay

packages/react-aria/src/overlays/useOverlay.ts:67–175  ·  view source on GitHub ↗
(props: AriaOverlayProps, ref: RefObject<Element | null>)

Source from the content-addressed store, hash-verified

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

Callers 6

ExampleFunction · 0.90
usePopoverFunction · 0.90
useModalOverlayFunction · 0.90
PopoverFunction · 0.90
MenuPopupFunction · 0.90
PopoverFunction · 0.90

Calls 5

useInteractOutsideFunction · 0.90
useFocusWithinFunction · 0.90
pushMethod · 0.80

Tested by 1

ExampleFunction · 0.72