@remit/ui 0.0.181 → 0.0.182

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,158 @@
1
+ import { type RefObject, useEffect } from "react";
2
+ import { useOverlayDepth } from "./overlay-scope.js";
3
+
4
+ const FOCUSABLE_SELECTOR =
5
+ 'a[href], button, input, select, textarea, iframe, [tabindex], [contenteditable]:not([contenteditable="false"])';
6
+
7
+ /**
8
+ * Everything the selector matches is in the tab order unless it takes itself
9
+ * out of it. A declared `tabindex` is the only reading of that which holds: a
10
+ * browser reports `tabIndex` -1 for an editing host and for an iframe, so
11
+ * trusting the property drops the rich-text body of a compose sheet from the
12
+ * ring and Tab walks past it.
13
+ */
14
+ function isTabbable(element: HTMLElement): boolean {
15
+ if (Number(element.getAttribute("tabindex") ?? 0) < 0) return false;
16
+ if (element.hasAttribute("disabled")) return false;
17
+ if (element.getAttribute("aria-disabled") === "true") return false;
18
+ if (element.closest("[inert], [hidden], [aria-hidden='true']")) return false;
19
+ const style = getComputedStyle(element);
20
+ return style.display !== "none" && style.visibility !== "hidden";
21
+ }
22
+
23
+ /**
24
+ * The controls Tab may reach inside this surface, in the order it reaches them.
25
+ *
26
+ * A modal opened from inside the surface takes the ring with it: the
27
+ * intelligence pane's reclassify dialog renders under the drawer's own panel,
28
+ * so a ring scoped to the panel puts its Cancel last and leaves every control
29
+ * behind that dialog's backdrop in the cycle — Tab walks onto buttons no
30
+ * pointer can reach, which is the bug the trap exists to prevent (#747).
31
+ */
32
+ function tabRing(container: HTMLElement): HTMLElement[] {
33
+ const nested = container.querySelectorAll<HTMLElement>(
34
+ '[role="dialog"][aria-modal="true"]',
35
+ );
36
+ const root = nested[nested.length - 1] ?? container;
37
+ return [...root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)].filter(
38
+ isTabbable,
39
+ );
40
+ }
41
+
42
+ /** Open traps, by their position in the React tree. See {@link isTopTrap}. */
43
+ const openTraps = new Set<number>();
44
+
45
+ /**
46
+ * Whether this surface is the innermost one trapping focus.
47
+ *
48
+ * Two surfaces can be up over overlapping DOM — the narrow-width nav drawer and
49
+ * a dialog raised over it, a confirmation opened from inside a drawer — and only
50
+ * the top one may answer Tab. Listener order cannot decide that: handlers run in
51
+ * the order their effects registered, so the surface that opened first takes the
52
+ * key and pulls focus out from under the one above it. Depth is the ordering
53
+ * that holds, and `overlay-scope` already hands it out.
54
+ */
55
+ function isTopTrap(depth: number): boolean {
56
+ for (const other of openTraps) {
57
+ if (other > depth) return false;
58
+ }
59
+ return true;
60
+ }
61
+
62
+ /**
63
+ * Focus another surface is holding, which this one leaves where it is: an error
64
+ * banner and the fatal-error overlay paint above every modal from outside its
65
+ * subtree, and a trap that reclaims every Tab strands them (#970).
66
+ *
67
+ * Focus resting nowhere is not that. Clicking the title of a dialog — a region
68
+ * no control owns — leaves it on the body, and a trap that reads that as
69
+ * somebody else's hands the next Tab to the surface behind the modal (#1204).
70
+ */
71
+ function heldElsewhere(
72
+ container: HTMLElement,
73
+ active: Element | null,
74
+ ): boolean {
75
+ if (!(active instanceof HTMLElement)) return false;
76
+ if (active === document.body || active === document.documentElement) {
77
+ return false;
78
+ }
79
+ return !container.contains(active);
80
+ }
81
+
82
+ /**
83
+ * The keyboard contract of an `aria-modal` surface, in one hook: focus moves
84
+ * into `ref` when `open` turns true, Tab stays inside it while it is up, and
85
+ * focus goes back to whatever held it once the surface closes or leaves — the
86
+ * trigger can have gone with it, so the restore is guarded.
87
+ *
88
+ * The trap is a Tab handler rather than `inert` on the background: these
89
+ * surfaces do not portal to the body, so there is no stable set of background
90
+ * nodes to mark. It wraps at the ring's ends and pulls in focus that sits inside
91
+ * the surface but outside the ring, under a nested dialog's backdrop (#973), or
92
+ * on nothing at all. Focus another surface holds is the one exemption, and it is
93
+ * narrow — see {@link heldElsewhere}.
94
+ */
95
+ export function useModalFocus(
96
+ ref: RefObject<HTMLElement | null>,
97
+ open: boolean,
98
+ ): void {
99
+ const depth = useOverlayDepth();
100
+
101
+ useEffect(() => {
102
+ if (!open) return;
103
+ openTraps.add(depth);
104
+ return () => {
105
+ openTraps.delete(depth);
106
+ };
107
+ }, [open, depth]);
108
+
109
+ useEffect(() => {
110
+ if (!open) return;
111
+ const restoreTo =
112
+ document.activeElement instanceof HTMLElement
113
+ ? document.activeElement
114
+ : null;
115
+ const container = ref.current;
116
+ if (container) (tabRing(container)[0] ?? container).focus();
117
+ return () => {
118
+ if (restoreTo?.isConnected) restoreTo.focus();
119
+ };
120
+ }, [open, ref]);
121
+
122
+ useEffect(() => {
123
+ if (!open) return;
124
+
125
+ const onKeyDown = (event: KeyboardEvent) => {
126
+ if (event.key !== "Tab" || event.defaultPrevented) return;
127
+ if (!isTopTrap(depth)) return;
128
+ const container = ref.current;
129
+ if (!container) return;
130
+ const active = document.activeElement;
131
+ if (heldElsewhere(container, active)) return;
132
+
133
+ const ring = tabRing(container);
134
+ const first = ring[0];
135
+ const last = ring.at(-1);
136
+ if (!first || !last) {
137
+ event.preventDefault();
138
+ container.focus();
139
+ return;
140
+ }
141
+ const inside = active instanceof HTMLElement && ring.includes(active);
142
+ if (event.shiftKey) {
143
+ if (!inside || active === first) {
144
+ event.preventDefault();
145
+ last.focus();
146
+ }
147
+ return;
148
+ }
149
+ if (!inside || active === last) {
150
+ event.preventDefault();
151
+ first.focus();
152
+ }
153
+ };
154
+
155
+ document.addEventListener("keydown", onKeyDown);
156
+ return () => document.removeEventListener("keydown", onKeyDown);
157
+ }, [open, ref, depth]);
158
+ }
@@ -1,78 +0,0 @@
1
- import "@remit/test-dom";
2
- import assert from "node:assert/strict";
3
- import { afterEach, beforeEach, describe, it } from "node:test";
4
- import { act, createElement, useRef } from "react";
5
- import { createRoot, type Root } from "react-dom/client";
6
- import { useInitialFocus } from "./use-initial-focus.js";
7
-
8
- let root: Root;
9
-
10
- beforeEach(() => {
11
- const container = document.getElementById("root") as unknown as HTMLElement;
12
- container.innerHTML = "";
13
- root = createRoot(container);
14
- });
15
-
16
- afterEach(() => {
17
- act(() => root.unmount());
18
- });
19
-
20
- function Panel({ open }: { open: boolean }) {
21
- const ref = useRef<HTMLDivElement>(null);
22
- useInitialFocus(ref, open);
23
- return createElement(
24
- "div",
25
- { ref },
26
- createElement("span", null, "not focusable"),
27
- createElement("button", { type: "button" }, "First action"),
28
- createElement("button", { type: "button" }, "Second action"),
29
- );
30
- }
31
-
32
- describe("useInitialFocus", () => {
33
- it("focuses the first focusable descendant once open", () => {
34
- act(() => root.render(createElement(Panel, { open: true })));
35
- assert.equal(document.activeElement?.textContent, "First action");
36
- });
37
-
38
- it("leaves focus on the body while closed", () => {
39
- act(() => root.render(createElement(Panel, { open: false })));
40
- assert.equal(document.activeElement, document.body);
41
- });
42
-
43
- it("moves focus in when an already-mounted panel opens", () => {
44
- act(() => root.render(createElement(Panel, { open: false })));
45
- assert.equal(document.activeElement, document.body);
46
-
47
- act(() => root.render(createElement(Panel, { open: true })));
48
- assert.equal(document.activeElement?.textContent, "First action");
49
- });
50
-
51
- it("returns focus to the trigger once the panel closes", () => {
52
- const trigger = document.createElement("button");
53
- trigger.textContent = "Open panel";
54
- document.body.appendChild(trigger);
55
- trigger.focus();
56
- assert.equal(document.activeElement, trigger);
57
-
58
- act(() => root.render(createElement(Panel, { open: true })));
59
- assert.equal(document.activeElement?.textContent, "First action");
60
-
61
- act(() => root.render(createElement(Panel, { open: false })));
62
- assert.equal(document.activeElement, trigger);
63
-
64
- trigger.remove();
65
- });
66
-
67
- it("does not throw restoring focus to a trigger that left the DOM", () => {
68
- const trigger = document.createElement("button");
69
- document.body.appendChild(trigger);
70
- trigger.focus();
71
-
72
- act(() => root.render(createElement(Panel, { open: true })));
73
- trigger.remove();
74
-
75
- act(() => root.render(createElement(Panel, { open: false })));
76
- assert.notEqual(document.activeElement, trigger);
77
- });
78
- });
@@ -1,36 +0,0 @@
1
- import { type RefObject, useEffect, useRef } from "react";
2
-
3
- const FOCUSABLE_SELECTOR =
4
- 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
5
-
6
- /**
7
- * Moves focus to the first focusable descendant of `ref` when `open` turns
8
- * true, so a dialog or sheet never leaves a keyboard user parked on whatever
9
- * was focused behind it, and gives it back to whatever held it before once
10
- * `open` turns false again — guarded, since the trigger can have left the DOM
11
- * while the dialog was up.
12
- */
13
- export function useInitialFocus(
14
- ref: RefObject<HTMLElement | null>,
15
- open: boolean,
16
- ): void {
17
- const restoreTo = useRef<HTMLElement | null>(null);
18
-
19
- useEffect(() => {
20
- if (!open) {
21
- const previous = restoreTo.current;
22
- restoreTo.current = null;
23
- if (previous && document.contains(previous)) previous.focus();
24
- return;
25
- }
26
- restoreTo.current =
27
- document.activeElement instanceof HTMLElement
28
- ? document.activeElement
29
- : null;
30
- const container = ref.current;
31
- if (!container) return;
32
- const focusable =
33
- container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
34
- focusable[0]?.focus();
35
- }, [open, ref]);
36
- }