Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

use-focus-trap.ts

112 lines4.1 KB

1import { useEffect } from "react";
2import type { RefObject } from "react";
3​
4const TABBABLE = [
5 "a[href]",
6 "button:not([disabled])",
7 "input:not([disabled]):not([type=hidden])",
8 "select:not([disabled])",
9 "textarea:not([disabled])",
10 "[tabindex]:not([tabindex='-1'])",
11].join(",");
12​
13/**
14 * Menus, dialogs and toasts are portalled to <body>, outside the trap. They
15 * manage their own focus, so the trap leaves them alone.
16 */
17const LAYER =
18 "[data-radix-popper-content-wrapper], [role=dialog], [role=alertdialog], [data-sonner-toaster]";
19​
20function isInLayer(node: Node): boolean {
21 const element = node instanceof Element ? node : node.parentElement;
22 return element?.closest(LAYER) != null;
24​
25/** Elements Tab can reach inside `container`, in DOM order (inert and hidden ones skipped). */
26function tabbables(container: HTMLElement): HTMLElement[] {
27 return Array.from(container.querySelectorAll<HTMLElement>(TABBABLE)).filter(
28 (element) =>
29 !element.closest("[inert]") &&
30 element.getClientRects().length > 0 &&
31 getComputedStyle(element).visibility !== "hidden",
32 );
34​
35/**
36 * Keeps keyboard focus inside `containerRef` while `active`, for modal
37 * surfaces whose content must stay mounted (so no unmount-based focus scope):
38 *
39 * - focuses the container when activated, and gives focus back to whatever
40 * had it when deactivated,
41 * - wraps Tab / Shift+Tab at both ends, and pulls focus back in if it got out,
42 * - recovers focus when the focused element disappears (e.g. the app inside
43 * changes screens), instead of letting it fall to <body>.
44 *
45 * Menus and dialogs opened from inside get to keep focus while they're open.
46 *
47 * Listens on the document rather than the container, because content can be
48 * portalled in from elsewhere in the React tree (React key events wouldn't
49 * bubble through the container's handlers).
50 */
51export function useFocusTrap(containerRef: RefObject<HTMLElement | null>, active: boolean) {
52 useEffect(() => {
53 const container = containerRef.current;
54 if (!active || !container) return;
55​
56 const returnFocusTo = document.activeElement;
57 container.focus({ preventScroll: true });
58​
59 const onKeyDown = (event: KeyboardEvent) => {
60 if (event.key !== "Tab" || event.defaultPrevented) return;
61 const items = tabbables(container);
62 const first = items[0];
63 const last = items.at(-1);
64 const focused = document.activeElement;
65 if (focused && !container.contains(focused) && isInLayer(focused)) return;
66 if (!first || !last) {
67 event.preventDefault();
68 container.focus({ preventScroll: true });
69 } else if (!(focused instanceof Node) || !container.contains(focused)) {
70 event.preventDefault();
71 (event.shiftKey ? last : first).focus();
72 } else if (event.shiftKey && (focused === first || focused === container)) {
73 event.preventDefault();
74 last.focus();
75 } else if (!event.shiftKey && focused === last) {
76 event.preventDefault();
77 first.focus();
78 }
79 };
80​
81 // Something outside got focus (a click on a devtools overlay, a script): take it back.
82 const onFocusIn = (event: FocusEvent) => {
83 if (
84 event.target instanceof Node &&
85 !container.contains(event.target) &&
86 !isInLayer(event.target)
87 ) {
88 container.focus({ preventScroll: true });
89 }
90 };
91​
92 // Removing the focused element moves focus to <body> without any event.
93 const observer = new MutationObserver(() => {
94 if (document.activeElement === document.body || document.activeElement === null) {
95 container.focus({ preventScroll: true });
96 }
97 });
98​
99 document.addEventListener("keydown", onKeyDown);
100 document.addEventListener("focusin", onFocusIn);
101 observer.observe(container, { childList: true, subtree: true });
102​
103 return () => {
104 document.removeEventListener("keydown", onKeyDown);
105 document.removeEventListener("focusin", onFocusIn);
106 observer.disconnect();
107 if (returnFocusTo instanceof HTMLElement && returnFocusTo.isConnected) {
108 returnFocusTo.focus({ preventScroll: true });
109 }
110 };
111 }, [containerRef, active]);