@@ -207,26 +207,13 @@ export function useModalDismissSignal(
207207 return ( ) => { } ;
208208 }
209209
210- const timeOfEffect = performance . now ( ) ;
211-
212210 const handleDocumentKeyDown = ( event : any ) => {
213- if ( timeOfEffect > event . timeStamp ) {
214- // Don't let the same event that showed the dialog also hide it.
215- return ;
216- }
217-
218211 if ( event . key === 'Escape' ) {
219212 dismissCallback ( ) ;
220213 }
221214 } ;
222215
223216 const handleDocumentClick = ( event : any ) => {
224- if ( timeOfEffect > event . timeStamp ) {
225- // Don't let the same event that showed the dialog also hide it.
226- return ;
227- }
228-
229- // $FlowFixMe
230217 if (
231218 modalRef . current !== null &&
232219 ! modalRef . current . contains ( event . target )
@@ -238,19 +225,33 @@ export function useModalDismissSignal(
238225 }
239226 } ;
240227
241- // It's important to listen to the ownerDocument to support the browser extension.
242- // Here we use portals to render individual tabs (e.g. Profiler),
243- // and the root document might belong to a different window.
244- const ownerDocument = ( ( modalRef . current : any ) : HTMLDivElement )
245- . ownerDocument ;
246- ownerDocument . addEventListener ( 'keydown' , handleDocumentKeyDown ) ;
247- if ( dismissOnClickOutside ) {
248- ownerDocument . addEventListener ( 'click' , handleDocumentClick ) ;
249- }
228+ let ownerDocument = null ;
229+
230+ // Delay until after the current call stack is empty,
231+ // in case this effect is being run while an event is currently bubbling.
232+ // In that case, we don't want to listen to the pre-existing event.
233+ let timeoutID = setTimeout ( ( ) => {
234+ timeoutID = null ;
235+
236+ // It's important to listen to the ownerDocument to support the browser extension.
237+ // Here we use portals to render individual tabs (e.g. Profiler),
238+ // and the root document might belong to a different window.
239+ ownerDocument = ( ( modalRef . current : any ) : HTMLDivElement ) . ownerDocument ;
240+ ownerDocument . addEventListener ( 'keydown' , handleDocumentKeyDown ) ;
241+ if ( dismissOnClickOutside ) {
242+ ownerDocument . addEventListener ( 'click' , handleDocumentClick ) ;
243+ }
244+ } , 0 ) ;
250245
251246 return ( ) => {
252- ownerDocument . removeEventListener ( 'keydown' , handleDocumentKeyDown ) ;
253- ownerDocument . removeEventListener ( 'click' , handleDocumentClick ) ;
247+ if ( timeoutID !== null ) {
248+ clearTimeout ( timeoutID ) ;
249+ }
250+
251+ if ( ownerDocument !== null ) {
252+ ownerDocument . removeEventListener ( 'keydown' , handleDocumentKeyDown ) ;
253+ ownerDocument . removeEventListener ( 'click' , handleDocumentClick ) ;
254+ }
254255 } ;
255256 } , [ modalRef , dismissCallback , dismissOnClickOutside ] ) ;
256257}
0 commit comments