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.

Add useDialogDismiss hook

+39 -2
+1
src/index.ts
··· 1 1 export * from './useModalFocus'; 2 2 export * from './useDialogFocus'; 3 3 export * from './useMenuFocus'; 4 + export * from './useDialogDismiss';
+36
src/useDialogDismiss.ts
··· 1 + import { useLayoutEffect } from './utils/react'; 2 + import { contains } from './utils/element'; 3 + import { makePriorityHook } from './usePriority'; 4 + import { Ref } from './types'; 5 + 6 + const usePriority = makePriorityHook(); 7 + 8 + export function useDialogDismiss<T extends HTMLElement>(ref: Ref<T>, onDismiss: () => void) { 9 + const hasPriority = usePriority(ref); 10 + 11 + useLayoutEffect(() => { 12 + if (!hasPriority) return; 13 + 14 + function onKey(event: KeyboardEvent) { 15 + if (event.isComposing || event.defaultPrevented || event.code !== 'Escape') return; 16 + event.preventDefault(); 17 + onDismiss(); 18 + }; 19 + 20 + function onClick(event: MouseEvent | TouchEvent) { 21 + if (!ref.current || contains(ref.current, event.target) || event.defaultPrevented) return; 22 + event.preventDefault(); 23 + onDismiss(); 24 + } 25 + 26 + document.addEventListener('mousedown', onClick); 27 + document.addEventListener('touchstart', onClick); 28 + document.addEventListener('keydown', onKey); 29 + 30 + return () => { 31 + document.removeEventListener('mousedown', onClick); 32 + document.removeEventListener('touchstart', onClick); 33 + document.removeEventListener('keydown', onKey); 34 + }; 35 + }, [ref, hasPriority, onDismiss]); 36 + }
+1 -1
src/useDialogFocus.ts
··· 63 63 } 64 64 65 65 function onKey(event: KeyboardEvent) { 66 - if (!ref.current || event.defaultPrevented) return; 66 + if (!ref.current || event.defaultPrevented || event.isComposing) return; 67 67 68 68 // Mark whether focus is moving forward for the `onFocus` handler 69 69 if (event.code === 'Tab') {
+1 -1
src/useMenuFocus.ts
··· 36 36 } 37 37 38 38 function onKey(event: KeyboardEvent) { 39 - if (!ref.current || event.defaultPrevented) return; 39 + if (!ref.current || event.defaultPrevented || event.isComposing) return; 40 40 41 41 const owner = (ownerRef && ownerRef.current) || selection && selection.element; 42 42 const active = document.activeElement as HTMLElement;