Mirror: React hooks for accessible, common web interactions. UI super powers without the UI.
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Let useDialogDismiss override priority when target has focus

+26 -18
+26 -18
src/useDialogDismiss.ts
··· 12 12 const hasPriority = usePriority(ref); 13 13 14 14 useLayoutEffect(() => { 15 - if (!hasPriority) return; 15 + if (!ref.current || !hasPriority) return; 16 16 17 17 function onKey(event: KeyboardEvent) { 18 - if ( 19 - event.isComposing || 20 - event.defaultPrevented || 21 - event.code !== 'Escape' 22 - ) 23 - return; 24 - event.preventDefault(); 25 - onDismiss(); 18 + if (event.defaultPrevented || event.isComposing) return; 19 + 20 + if (event.code === 'Escape') { 21 + // The current dialog can be dismissed by pressing escape if it either has focus 22 + // or it has priority 23 + const active = document.activeElement; 24 + if (hasPriority || (active && contains(ref.current, active))) { 25 + event.preventDefault(); 26 + onDismiss(); 27 + } 28 + } 26 29 } 27 30 28 31 function onClick(event: MouseEvent | TouchEvent) { 29 - if ( 30 - !ref.current || 31 - contains(ref.current, event.target) || 32 - event.defaultPrevented 33 - ) 32 + const { target } = event; 33 + if (contains(ref.current, target) || event.defaultPrevented) { 34 34 return; 35 + } 36 + 35 37 event.preventDefault(); 36 38 onDismiss(); 37 39 } 38 40 39 - document.addEventListener('mousedown', onClick); 40 - document.addEventListener('touchstart', onClick); 41 + if (hasPriority) { 42 + document.addEventListener('mousedown', onClick); 43 + document.addEventListener('touchstart', onClick); 44 + } 45 + 41 46 document.addEventListener('keydown', onKey); 42 47 43 48 return () => { 44 - document.removeEventListener('mousedown', onClick); 45 - document.removeEventListener('touchstart', onClick); 49 + if (hasPriority) { 50 + document.removeEventListener('mousedown', onClick); 51 + document.removeEventListener('touchstart', onClick); 52 + } 53 + 46 54 document.removeEventListener('keydown', onKey); 47 55 }; 48 56 }, [ref, hasPriority, onDismiss]);