diff --git a/packages/react-devtools-shared/src/devtools/views/hooks.js b/packages/react-devtools-shared/src/devtools/views/hooks.js index 3af0ceaeb29ad..54b1d7d20ce8b 100644 --- a/packages/react-devtools-shared/src/devtools/views/hooks.js +++ b/packages/react-devtools-shared/src/devtools/views/hooks.js @@ -207,14 +207,13 @@ export function useModalDismissSignal( return () => {}; } - const handleDocumentKeyDown = ({key}: any) => { - if (key === 'Escape') { + const handleDocumentKeyDown = (event: any) => { + if (event.key === 'Escape') { dismissCallback(); } }; const handleDocumentClick = (event: any) => { - // $FlowFixMe if ( modalRef.current !== null && !modalRef.current.contains(event.target) @@ -226,18 +225,33 @@ export function useModalDismissSignal( } }; - // It's important to listen to the ownerDocument to support the browser extension. - // Here we use portals to render individual tabs (e.g. Profiler), - // and the root document might belong to a different window. - const ownerDocument = modalRef.current.ownerDocument; - ownerDocument.addEventListener('keydown', handleDocumentKeyDown); - if (dismissOnClickOutside) { - ownerDocument.addEventListener('click', handleDocumentClick); - } + let ownerDocument = null; + + // Delay until after the current call stack is empty, + // in case this effect is being run while an event is currently bubbling. + // In that case, we don't want to listen to the pre-existing event. + let timeoutID = setTimeout(() => { + timeoutID = null; + + // It's important to listen to the ownerDocument to support the browser extension. + // Here we use portals to render individual tabs (e.g. Profiler), + // and the root document might belong to a different window. + ownerDocument = ((modalRef.current: any): HTMLDivElement).ownerDocument; + ownerDocument.addEventListener('keydown', handleDocumentKeyDown); + if (dismissOnClickOutside) { + ownerDocument.addEventListener('click', handleDocumentClick); + } + }, 0); return () => { - ownerDocument.removeEventListener('keydown', handleDocumentKeyDown); - ownerDocument.removeEventListener('click', handleDocumentClick); + if (timeoutID !== null) { + clearTimeout(timeoutID); + } + + if (ownerDocument !== null) { + ownerDocument.removeEventListener('keydown', handleDocumentKeyDown); + ownerDocument.removeEventListener('click', handleDocumentClick); + } }; }, [modalRef, dismissCallback, dismissOnClickOutside]); }