1import { useEffect, useRef, type RefObject } from "react";2 3const FOCUSABLE_SELECTOR = [4 "a[href]",5 "area[href]",6 "button:not([disabled])",7 "input:not([disabled])",
8 "select:not([disabled])",
9 "textarea:not([disabled])",
10 "[contenteditable='true']",
11 "[tabindex]:not([tabindex='-1'])",
12].join(",");
13
14let nextDialogId = 0;
15const activeDialogIds: number[] = [];
16
17interface UseModalDialogOptions {
18 dialogRef: RefObject<HTMLElement | null>;
19 initialFocusRef?: RefObject<HTMLElement | null>;
20 onDismiss: () => void;
21 canDismiss?: boolean;
22 enabled?: boolean;
23 selectInitialText?: boolean;
24}
25
26function focusableElements(container: HTMLElement): HTMLElement[] {
27 return Array.from(
28 container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
29 ).filter(
30 (element) =>
31 !element.hasAttribute("hidden") &&
32 element.getAttribute("aria-hidden") !== "true",
33 );
34}
35
36export function useModalDialog({
37 dialogRef,
38 initialFocusRef,
39 onDismiss,
40 canDismiss = true,
41 enabled = true,
42 selectInitialText = false,
43}: UseModalDialogOptions): void {
44 const dismissRef = useRef(onDismiss);
45 const canDismissRef = useRef(canDismiss);
46
47 dismissRef.current = onDismiss;
48 canDismissRef.current = canDismiss;
49
50 useEffect(() => {
51 if (!enabled || typeof document === "undefined") {
52 return;
53 }
54
55 const dialogId = ++nextDialogId;
56 activeDialogIds.push(dialogId);
57 const previousFocus =
58 document.activeElement instanceof HTMLElement
59 ? document.activeElement
60 : null;
61
62 const focusInitialElement = () => {
63 const dialog = dialogRef.current;
64 if (!dialog) return;
65
66 const initial = initialFocusRef?.current ?? focusableElements(dialog)[0];
67 if (initial) {
68 initial.focus({ preventScroll: true });
69 if (selectInitialText && initial instanceof HTMLInputElement) {
70 initial.select();
71 }
72 return;
73 }
74
75 dialog.focus({ preventScroll: true });
76 };
77
78 const animationFrame = window.requestAnimationFrame(focusInitialElement);
79 const handleKeyDown = (event: KeyboardEvent) => {
80 if (activeDialogIds[activeDialogIds.length - 1] !== dialogId) return;
81
82 if (event.key === "Escape" && canDismissRef.current) {
83 event.preventDefault();
84 event.stopPropagation();
85 dismissRef.current();
86 return;
87 }
88
89 if (event.key !== "Tab") return;
90
91 const dialog = dialogRef.current;
92 if (!dialog) return;
93
94 const focusable = focusableElements(dialog);
95 if (focusable.length === 0) {
96 event.preventDefault();
97 dialog.focus({ preventScroll: true });
98 return;
99 }
100
101 const activeElement = document.activeElement as HTMLElement | null;
102 const currentIndex = activeElement
103 ? focusable.indexOf(activeElement)
104 : -1;
105 const first = focusable[0];
106 const last = focusable[focusable.length - 1];
107
108 if (event.shiftKey) {
109 if (currentIndex <= 0) {
110 event.preventDefault();
111 last.focus({ preventScroll: true });
112 }
113 } else if (currentIndex === -1 || currentIndex === focusable.length - 1) {
114 event.preventDefault();
115 first.focus({ preventScroll: true });
116 }
117 };
118
119 document.addEventListener("keydown", handleKeyDown);
120 return () => {
121 window.cancelAnimationFrame(animationFrame);
122 document.removeEventListener("keydown", handleKeyDown);
123 const index = activeDialogIds.lastIndexOf(dialogId);
124 if (index >= 0) activeDialogIds.splice(index, 1);
125
126 window.requestAnimationFrame(() => {
127 if (previousFocus?.isConnected) {
128 previousFocus.focus({ preventScroll: true });
129 }
130 });
131 };
132 }, [dialogRef, enabled, initialFocusRef, selectInitialText]);
133}
134