@remit/ui 0.0.181 → 0.0.183

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
+ }
@@ -17,6 +17,8 @@ let container: HTMLElement;
17
17
  let root: Root;
18
18
 
19
19
  const accepted: string[] = [];
20
+ const comboboxPropsRenders: unknown[] = [];
21
+ const handleKeyDownRenders: unknown[] = [];
20
22
 
21
23
  function Field(props: { options: string[] }) {
22
24
  const [value, setValue] = useState("typed");
@@ -24,6 +26,8 @@ function Field(props: { options: string[] }) {
24
26
  count: props.options.length,
25
27
  onAccept: (index) => accepted.push(props.options[index]),
26
28
  });
29
+ comboboxPropsRenders.push(suggest.comboboxProps);
30
+ handleKeyDownRenders.push(suggest.handleKeyDown);
27
31
  return createElement("input", {
28
32
  id: "field",
29
33
  value,
@@ -38,6 +42,17 @@ function Field(props: { options: string[] }) {
38
42
  });
39
43
  }
40
44
 
45
+ const typeInto = (field: Element, value: string) => {
46
+ const setter = Object.getOwnPropertyDescriptor(
47
+ HTMLInputElement.prototype,
48
+ "value",
49
+ )?.set;
50
+ act(() => {
51
+ setter?.call(field, value);
52
+ field.dispatchEvent(new Event("input", { bubbles: true }));
53
+ });
54
+ };
55
+
41
56
  function mount(options: string[]) {
42
57
  act(() => {
43
58
  root.render(createElement(Field, { options }));
@@ -66,6 +81,8 @@ function press(field: Element, key: string) {
66
81
 
67
82
  beforeEach(() => {
68
83
  accepted.length = 0;
84
+ comboboxPropsRenders.length = 0;
85
+ handleKeyDownRenders.length = 0;
69
86
  container = document.getElementById("root") as unknown as HTMLElement;
70
87
  container.innerHTML = "";
71
88
  root = createRoot(container);
@@ -142,4 +159,56 @@ describe("useSuggestList", () => {
142
159
  assert.equal(field.getAttribute("data-open"), "true");
143
160
  assert.equal(field.getAttribute("data-active"), "-1");
144
161
  });
162
+
163
+ it("keeps the same comboboxProps object across a keystroke that changes nothing about the list", () => {
164
+ const field = mount(OPTIONS);
165
+ const rendersBefore = comboboxPropsRenders.length;
166
+ const before = comboboxPropsRenders.at(-1);
167
+ typeInto(field, "typed!");
168
+ assert.equal(
169
+ (field as HTMLInputElement).value,
170
+ "typed!",
171
+ "the keystroke landed",
172
+ );
173
+ assert.ok(
174
+ comboboxPropsRenders.length > rendersBefore,
175
+ "the keystroke did not re-render, so stability was never put to the test",
176
+ );
177
+ assert.equal(
178
+ comboboxPropsRenders.at(-1),
179
+ before,
180
+ "comboboxProps should be referentially stable across an idle re-render",
181
+ );
182
+ });
183
+
184
+ it("keeps the same handleKeyDown across a changed onAccept and a changed list", () => {
185
+ const field = mount(OPTIONS);
186
+ const first = handleKeyDownRenders.at(-1);
187
+ typeInto(field, "typed!");
188
+ press(field, "ArrowDown");
189
+ act(() => {
190
+ root.render(createElement(Field, { options: ["only"] }));
191
+ });
192
+ assert.ok(
193
+ handleKeyDownRenders.length > 1,
194
+ "nothing re-rendered, so stability was never put to the test",
195
+ );
196
+ assert.ok(
197
+ handleKeyDownRenders.every((handler) => handler === first),
198
+ "handleKeyDown should be referentially stable, so an inline onAccept at the call site cannot defeat a memo downstream",
199
+ );
200
+ });
201
+
202
+ // The handler is stable, so it must read the state a key arrives at rather
203
+ // than the state it was bound in.
204
+ it("still accepts from the list it is looking at, not the one it was bound to", () => {
205
+ const field = mount(OPTIONS);
206
+ act(() => {
207
+ root.render(createElement(Field, { options: ["alpha", "beta"] }));
208
+ });
209
+ press(field, "ArrowDown");
210
+ press(field, "ArrowDown");
211
+ press(field, "Enter");
212
+ assert.deepEqual(accepted, ["beta"]);
213
+ });
145
214
  });
@@ -3,6 +3,8 @@ import {
3
3
  useCallback,
4
4
  useEffect,
5
5
  useId,
6
+ useMemo,
7
+ useRef,
6
8
  useState,
7
9
  } from "react";
8
10
  import { suggestKeyAction } from "./suggest-keys.js";
@@ -40,7 +42,10 @@ export interface SuggestListState {
40
42
  dismiss: () => void;
41
43
  /** Offer the list again — what a fresh keystroke does after a dismissal. */
42
44
  reopen: () => void;
43
- /** Returns true when the list consumed the key and the caller should stop. */
45
+ /**
46
+ * Returns true when the list consumed the key and the caller should stop.
47
+ * The same function for the life of the field, whatever the list is showing.
48
+ */
44
49
  handleKeyDown: (event: KeyboardEvent) => boolean;
45
50
  listId: string;
46
51
  optionId: (index: number) => string;
@@ -82,23 +87,45 @@ export function useSuggestList({
82
87
 
83
88
  const open = count > 0 && !dismissed;
84
89
 
85
- const handleKeyDown = useCallback(
86
- (event: KeyboardEvent): boolean => {
87
- const action = suggestKeyAction({
88
- key: event.key,
89
- open,
90
- count,
91
- activeIndex,
92
- acceptKeys,
93
- });
94
- if (action.type === "none") return false;
95
- event.preventDefault();
96
- if (action.type === "move") setActiveIndex(action.index);
97
- if (action.type === "dismiss") setDismissed(true);
98
- if (action.type === "accept") onAccept(action.index);
99
- return true;
100
- },
101
- [open, count, activeIndex, acceptKeys, onAccept],
90
+ // What the handler reads when a key arrives, rather than what it closed over
91
+ // when it was bound. Every call site passes an inline `onAccept`, so a handler
92
+ // listing it as a dependency is a new function on every render, and that
93
+ // defeats every memo the props it sits in belong to (#506).
94
+ const latest = useRef({ open, count, activeIndex, acceptKeys, onAccept });
95
+ latest.current = { open, count, activeIndex, acceptKeys, onAccept };
96
+
97
+ const handleKeyDown = useCallback((event: KeyboardEvent): boolean => {
98
+ const current = latest.current;
99
+ const action = suggestKeyAction({
100
+ key: event.key,
101
+ open: current.open,
102
+ count: current.count,
103
+ activeIndex: current.activeIndex,
104
+ acceptKeys: current.acceptKeys,
105
+ });
106
+ if (action.type === "none") return false;
107
+ event.preventDefault();
108
+ if (action.type === "move") setActiveIndex(action.index);
109
+ if (action.type === "dismiss") setDismissed(true);
110
+ if (action.type === "accept") current.onAccept(action.index);
111
+ return true;
112
+ }, []);
113
+
114
+ // Stable while open, listId and activeIndex don't change: this is spread onto
115
+ // the field on every render, and a fresh object here would defeat every memo
116
+ // downstream that takes it as a dependency (#506).
117
+ const comboboxProps = useMemo<ComboboxProps>(
118
+ () => ({
119
+ role: "combobox",
120
+ "aria-expanded": open,
121
+ "aria-controls": listId,
122
+ "aria-autocomplete": "list",
123
+ ...(activeIndex >= 0
124
+ ? { "aria-activedescendant": optionId(activeIndex) }
125
+ : {}),
126
+ ...(open ? { "data-escape-owner": "" as const } : {}),
127
+ }),
128
+ [open, listId, activeIndex, optionId],
102
129
  );
103
130
 
104
131
  return {
@@ -110,15 +137,6 @@ export function useSuggestList({
110
137
  handleKeyDown,
111
138
  listId,
112
139
  optionId,
113
- comboboxProps: {
114
- role: "combobox",
115
- "aria-expanded": open,
116
- "aria-controls": listId,
117
- "aria-autocomplete": "list",
118
- ...(activeIndex >= 0
119
- ? { "aria-activedescendant": optionId(activeIndex) }
120
- : {}),
121
- ...(open ? { "data-escape-owner": "" as const } : {}),
122
- },
140
+ comboboxProps,
123
141
  };
124
142
  }
@@ -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
- }