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

use-focus-trap.ts

93 lines3.5 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/** Elements Tab can reach inside `container`, in DOM order (inert and hidden ones skipped). */
14function tabbables(container: HTMLElement): HTMLElement[] {
15 return Array.from(container.querySelectorAll<HTMLElement>(TABBABLE)).filter(
16 (element) =>
17 !element.closest("[inert]") &&
18 element.getClientRects().length > 0 &&
19 getComputedStyle(element).visibility !== "hidden",
20 );
22​
23/**
24 * Keeps keyboard focus inside `containerRef` while `active`, for modal
25 * surfaces whose content must stay mounted (so no unmount-based focus scope):
26 *
27 * - focuses the container when activated, and gives focus back to whatever
28 * had it when deactivated,
29 * - wraps Tab / Shift+Tab at both ends, and pulls focus back in if it got out,
30 * - recovers focus when the focused element disappears (e.g. the app inside
31 * changes screens), instead of letting it fall to <body>.
32 *
33 * Listens on the document rather than the container, because content can be
34 * portalled in from elsewhere in the React tree (React key events wouldn't
35 * bubble through the container's handlers).
36 */
37export function useFocusTrap(containerRef: RefObject<HTMLElement | null>, active: boolean) {
38 useEffect(() => {
39 const container = containerRef.current;
40 if (!active || !container) return;
41​
42 const returnFocusTo = document.activeElement;
43 container.focus({ preventScroll: true });
44​
45 const onKeyDown = (event: KeyboardEvent) => {
46 if (event.key !== "Tab" || event.defaultPrevented) return;
47 const items = tabbables(container);
48 const first = items[0];
49 const last = items.at(-1);
50 const focused = document.activeElement;
51 if (!first || !last) {
52 event.preventDefault();
53 container.focus({ preventScroll: true });
54 } else if (!(focused instanceof Node) || !container.contains(focused)) {
55 event.preventDefault();
56 (event.shiftKey ? last : first).focus();
57 } else if (event.shiftKey && (focused === first || focused === container)) {
58 event.preventDefault();
59 last.focus();
60 } else if (!event.shiftKey && focused === last) {
61 event.preventDefault();
62 first.focus();
63 }
64 };
65​
66 // Something outside got focus (a click on a devtools overlay, a script): take it back.
67 const onFocusIn = (event: FocusEvent) => {
68 if (event.target instanceof Node && !container.contains(event.target)) {
69 container.focus({ preventScroll: true });
70 }
71 };
72​
73 // Removing the focused element moves focus to <body> without any event.
74 const observer = new MutationObserver(() => {
75 if (document.activeElement === document.body || document.activeElement === null) {
76 container.focus({ preventScroll: true });
77 }
78 });
79​
80 document.addEventListener("keydown", onKeyDown);
81 document.addEventListener("focusin", onFocusIn);
82 observer.observe(container, { childList: true, subtree: true });
83​
84 return () => {
85 document.removeEventListener("keydown", onKeyDown);
86 document.removeEventListener("focusin", onFocusIn);
87 observer.disconnect();
88 if (returnFocusTo instanceof HTMLElement && returnFocusTo.isConnected) {
89 returnFocusTo.focus({ preventScroll: true });
90 }
91 };
92 }, [containerRef, active]);