@baukit/a11y-core 0.7.1 → 0.7.3
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.
- package/package.json +2 -1
- package/src/announce-web.test.ts +110 -0
- package/src/announce-web.ts +42 -0
- package/src/announce.test.ts +57 -0
- package/src/announce.ts +16 -0
- package/src/dom-boundary.test.ts +80 -0
- package/src/dom-boundary.ts +84 -0
- package/src/index.ts +12 -0
- package/src/native-focus.test.ts +73 -0
- package/src/native-focus.ts +31 -0
- package/src/platform.test.ts +19 -0
- package/src/platform.ts +17 -0
- package/src/route-focus.test.ts +171 -0
- package/src/route-focus.ts +177 -0
- package/src/use-enter-to-next.test.ts +122 -0
- package/src/use-enter-to-next.ts +63 -0
- package/src/use-focus-trap.test.ts +349 -0
- package/src/use-focus-trap.ts +159 -0
- package/src/use-inert.test.ts +262 -0
- package/src/use-inert.ts +126 -0
- package/src/use-overlay-a11y.test.ts +207 -0
- package/src/use-overlay-a11y.ts +95 -0
- package/src/use-reduced-motion-web.test.ts +103 -0
- package/src/use-reduced-motion-web.ts +49 -0
- package/src/use-reduced-motion.test.ts +179 -0
- package/src/use-reduced-motion.ts +61 -0
- package/src/use-roving-menu.test.ts +635 -0
- package/src/use-roving-menu.ts +173 -0
- package/src/use-roving-radio-group.test.ts +223 -0
- package/src/use-roving-radio-group.ts +79 -0
- package/src/use-single-flight.test.ts +74 -0
- package/src/use-single-flight.ts +22 -0
- package/src/web.test.ts +40 -0
- package/src/web.ts +19 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act, cleanup, render, renderHook } from '@testing-library/react';
|
|
3
|
+
import { createElement, useRef } from 'react';
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import type { FocusContainer, FocusTarget, HostRef } from './dom-boundary.js';
|
|
7
|
+
import {
|
|
8
|
+
applyFocusTrapKey,
|
|
9
|
+
focusableElements,
|
|
10
|
+
focusOverlayEntry,
|
|
11
|
+
useFocusTrap,
|
|
12
|
+
wrapFocusAtBoundary,
|
|
13
|
+
type FocusTrapKeyEvent,
|
|
14
|
+
} from './use-focus-trap.js';
|
|
15
|
+
|
|
16
|
+
function mount(html: string): HTMLElement {
|
|
17
|
+
const host = document.createElement('div');
|
|
18
|
+
host.innerHTML = html;
|
|
19
|
+
document.body.appendChild(host);
|
|
20
|
+
return host;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** React Native Web renders a View as this element; the tests supply it directly. */
|
|
24
|
+
function asContainer(element: HTMLElement): FocusContainer {
|
|
25
|
+
return element;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function containerRef(element: HTMLElement | null): HostRef {
|
|
29
|
+
return { current: element };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ids(elements: readonly FocusTarget[]): string[] {
|
|
33
|
+
return (elements as unknown as HTMLElement[]).map((element) => element.id);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function keyEvent(key: string, extras: { shiftKey?: boolean; target?: unknown } = {}) {
|
|
37
|
+
const calls = { preventDefault: 0, stopPropagation: 0 };
|
|
38
|
+
const event: FocusTrapKeyEvent & { calls: typeof calls } = {
|
|
39
|
+
calls,
|
|
40
|
+
nativeEvent: { key, ...extras },
|
|
41
|
+
preventDefault: () => {
|
|
42
|
+
calls.preventDefault += 1;
|
|
43
|
+
},
|
|
44
|
+
stopPropagation: () => {
|
|
45
|
+
calls.stopPropagation += 1;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
return event;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
afterEach(() => {
|
|
52
|
+
cleanup();
|
|
53
|
+
document.body.innerHTML = '';
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('focusableElements', () => {
|
|
57
|
+
it('drops elements the browser would skip', () => {
|
|
58
|
+
const host = mount(`
|
|
59
|
+
<button id="keep">keep</button>
|
|
60
|
+
<button disabled>disabled</button>
|
|
61
|
+
<button tabindex="-1">skipped</button>
|
|
62
|
+
<button aria-disabled="true">aria-disabled</button>
|
|
63
|
+
<button aria-hidden="true">aria-hidden</button>
|
|
64
|
+
<button inert>inert</button>
|
|
65
|
+
`);
|
|
66
|
+
|
|
67
|
+
expect(ids(focusableElements(asContainer(host)))).toEqual(['keep']);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('finds links, inputs, textareas, selects, and widget roles', () => {
|
|
71
|
+
const host = mount(`
|
|
72
|
+
<a href="#one" id="link">link</a>
|
|
73
|
+
<input id="input" />
|
|
74
|
+
<textarea id="textarea"></textarea>
|
|
75
|
+
<select id="select"></select>
|
|
76
|
+
<div role="button" tabindex="0" id="rolebutton"></div>
|
|
77
|
+
<div role="menuitem" tabindex="0" id="menuitem"></div>
|
|
78
|
+
<div role="radio" tabindex="0" id="radio"></div>
|
|
79
|
+
`);
|
|
80
|
+
|
|
81
|
+
expect(ids(focusableElements(asContainer(host)))).toEqual([
|
|
82
|
+
'link',
|
|
83
|
+
'input',
|
|
84
|
+
'textarea',
|
|
85
|
+
'select',
|
|
86
|
+
'rolebutton',
|
|
87
|
+
'menuitem',
|
|
88
|
+
'radio',
|
|
89
|
+
]);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('wrapFocusAtBoundary', () => {
|
|
94
|
+
it('does nothing for an empty container', () => {
|
|
95
|
+
expect(wrapFocusAtBoundary([], null, false)).toBe(false);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('wraps forward from the last element to the first', () => {
|
|
99
|
+
const host = mount('<button id="a">a</button><button id="b">b</button>');
|
|
100
|
+
host.querySelector<HTMLElement>('#b')?.focus();
|
|
101
|
+
|
|
102
|
+
expect(
|
|
103
|
+
wrapFocusAtBoundary(focusableElements(asContainer(host)), document.activeElement, false),
|
|
104
|
+
).toBe(true);
|
|
105
|
+
expect(document.activeElement?.id).toBe('a');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('wraps backward from the first element to the last', () => {
|
|
109
|
+
const host = mount('<button id="a">a</button><button id="b">b</button>');
|
|
110
|
+
host.querySelector<HTMLElement>('#a')?.focus();
|
|
111
|
+
|
|
112
|
+
expect(
|
|
113
|
+
wrapFocusAtBoundary(focusableElements(asContainer(host)), document.activeElement, true),
|
|
114
|
+
).toBe(true);
|
|
115
|
+
expect(document.activeElement?.id).toBe('b');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('pulls an active element from outside the trap back in', () => {
|
|
119
|
+
const host = mount('<button id="a">a</button><button id="b">b</button>');
|
|
120
|
+
const outside = mount('<button id="outside">outside</button>');
|
|
121
|
+
(outside.firstElementChild as HTMLElement).focus();
|
|
122
|
+
|
|
123
|
+
expect(
|
|
124
|
+
wrapFocusAtBoundary(focusableElements(asContainer(host)), document.activeElement, false),
|
|
125
|
+
).toBe(true);
|
|
126
|
+
expect(document.activeElement?.id).toBe('a');
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('leaves interior movement to the browser', () => {
|
|
130
|
+
const host = mount(
|
|
131
|
+
'<button id="a">a</button><button id="b">b</button><button id="c">c</button>',
|
|
132
|
+
);
|
|
133
|
+
host.querySelector<HTMLElement>('#b')?.focus();
|
|
134
|
+
const ring = focusableElements(asContainer(host));
|
|
135
|
+
|
|
136
|
+
expect(wrapFocusAtBoundary(ring, document.activeElement, false)).toBe(false);
|
|
137
|
+
expect(wrapFocusAtBoundary(ring, document.activeElement, true)).toBe(false);
|
|
138
|
+
expect(document.activeElement?.id).toBe('b');
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
describe('focusOverlayEntry', () => {
|
|
143
|
+
it('prefers the requested initial target', () => {
|
|
144
|
+
const host = mount(
|
|
145
|
+
'<button id="child">child</button><button id="requested">requested</button>',
|
|
146
|
+
);
|
|
147
|
+
const requested = host.querySelector('#requested') as unknown as FocusTarget;
|
|
148
|
+
|
|
149
|
+
focusOverlayEntry(asContainer(host), requested);
|
|
150
|
+
|
|
151
|
+
expect(document.activeElement?.id).toBe('requested');
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('falls back to the first focusable child', () => {
|
|
155
|
+
const host = mount('<button id="first">first</button><button id="second">second</button>');
|
|
156
|
+
|
|
157
|
+
focusOverlayEntry(asContainer(host), null);
|
|
158
|
+
|
|
159
|
+
expect(document.activeElement?.id).toBe('first');
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('falls back to the container when it holds nothing focusable', () => {
|
|
163
|
+
const host = mount('<p>no controls here</p>');
|
|
164
|
+
host.id = 'shell';
|
|
165
|
+
host.tabIndex = -1;
|
|
166
|
+
|
|
167
|
+
focusOverlayEntry(asContainer(host), null);
|
|
168
|
+
|
|
169
|
+
expect(document.activeElement?.id).toBe('shell');
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('tolerates a container that has not mounted', () => {
|
|
173
|
+
expect(() => {
|
|
174
|
+
focusOverlayEntry(null, null);
|
|
175
|
+
}).not.toThrow();
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe('applyFocusTrapKey', () => {
|
|
180
|
+
it('reports Escape and stops the event from travelling further', () => {
|
|
181
|
+
const host = mount('<button>only</button>');
|
|
182
|
+
const event = keyEvent('Escape');
|
|
183
|
+
|
|
184
|
+
expect(applyFocusTrapKey(asContainer(host), event)).toBe('escape');
|
|
185
|
+
expect(event.calls.preventDefault).toBe(1);
|
|
186
|
+
expect(event.calls.stopPropagation).toBe(1);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('ignores keys other than Tab and Escape', () => {
|
|
190
|
+
const host = mount('<button>only</button>');
|
|
191
|
+
const event = keyEvent('ArrowDown');
|
|
192
|
+
|
|
193
|
+
expect(applyFocusTrapKey(asContainer(host), event)).toBe('ignored');
|
|
194
|
+
expect(event.calls.preventDefault).toBe(0);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it('ignores Tab before the container mounts', () => {
|
|
198
|
+
expect(applyFocusTrapKey(null, keyEvent('Tab'))).toBe('ignored');
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('holds focus on an empty container instead of letting Tab escape', () => {
|
|
202
|
+
const host = mount('<p>nothing focusable</p>');
|
|
203
|
+
host.id = 'shell';
|
|
204
|
+
host.tabIndex = -1;
|
|
205
|
+
const event = keyEvent('Tab');
|
|
206
|
+
|
|
207
|
+
expect(applyFocusTrapKey(asContainer(host), event)).toBe('wrapped');
|
|
208
|
+
expect(event.calls.preventDefault).toBe(1);
|
|
209
|
+
expect(document.activeElement?.id).toBe('shell');
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it('wraps at the end of the ring using the real active element', () => {
|
|
213
|
+
const host = mount('<button id="a">a</button><button id="b">b</button>');
|
|
214
|
+
host.querySelector<HTMLElement>('#b')?.focus();
|
|
215
|
+
const event = keyEvent('Tab');
|
|
216
|
+
|
|
217
|
+
expect(applyFocusTrapKey(asContainer(host), event)).toBe('wrapped');
|
|
218
|
+
expect(event.calls.preventDefault).toBe(1);
|
|
219
|
+
expect(document.activeElement?.id).toBe('a');
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('wraps backward past the first element', () => {
|
|
223
|
+
const host = mount('<button id="a">a</button><button id="b">b</button>');
|
|
224
|
+
host.querySelector<HTMLElement>('#a')?.focus();
|
|
225
|
+
const event = keyEvent('Tab', { shiftKey: true });
|
|
226
|
+
|
|
227
|
+
expect(applyFocusTrapKey(asContainer(host), event)).toBe('wrapped');
|
|
228
|
+
expect(document.activeElement?.id).toBe('b');
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('leaves interior Tab movement alone', () => {
|
|
232
|
+
const host = mount(
|
|
233
|
+
'<button id="a">a</button><button id="b">b</button><button id="c">c</button>',
|
|
234
|
+
);
|
|
235
|
+
host.querySelector<HTMLElement>('#b')?.focus();
|
|
236
|
+
const event = keyEvent('Tab');
|
|
237
|
+
|
|
238
|
+
expect(applyFocusTrapKey(asContainer(host), event)).toBe('ignored');
|
|
239
|
+
expect(event.calls.preventDefault).toBe(0);
|
|
240
|
+
expect(document.activeElement?.id).toBe('b');
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe('useFocusTrap', () => {
|
|
245
|
+
it('moves focus to the first control when the overlay opens', () => {
|
|
246
|
+
const host = mount('<button id="first">first</button><button id="second">second</button>');
|
|
247
|
+
|
|
248
|
+
renderHook(() => useFocusTrap({ active: true, containerRef: containerRef(host) }));
|
|
249
|
+
|
|
250
|
+
expect(document.activeElement?.id).toBe('first');
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it('restores focus to the opener on the next task', async () => {
|
|
254
|
+
const opener = mount('<button id="opener">open</button>')
|
|
255
|
+
.firstElementChild as HTMLButtonElement;
|
|
256
|
+
opener.focus();
|
|
257
|
+
const host = mount('<button id="inside">inside</button>');
|
|
258
|
+
|
|
259
|
+
const view = renderHook(() => useFocusTrap({ active: true, containerRef: containerRef(host) }));
|
|
260
|
+
expect(document.activeElement?.id).toBe('inside');
|
|
261
|
+
|
|
262
|
+
view.unmount();
|
|
263
|
+
// The restore is deliberately deferred so useInert can release the trigger.
|
|
264
|
+
expect(document.activeElement?.id).toBe('inside');
|
|
265
|
+
|
|
266
|
+
await act(async () => {
|
|
267
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
268
|
+
});
|
|
269
|
+
expect(document.activeElement?.id).toBe('opener');
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it('prefers the requested initial focus target', () => {
|
|
273
|
+
const host = mount('<button id="first">first</button><button id="wanted">wanted</button>');
|
|
274
|
+
|
|
275
|
+
renderHook(() =>
|
|
276
|
+
useFocusTrap({
|
|
277
|
+
active: true,
|
|
278
|
+
containerRef: containerRef(host),
|
|
279
|
+
initialFocusRef: containerRef(host.querySelector('#wanted')),
|
|
280
|
+
}),
|
|
281
|
+
);
|
|
282
|
+
|
|
283
|
+
expect(document.activeElement?.id).toBe('wanted');
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it('does nothing while inactive', () => {
|
|
287
|
+
const host = mount('<button id="first">first</button>');
|
|
288
|
+
const onEscape = vi.fn();
|
|
289
|
+
|
|
290
|
+
const view = renderHook(() =>
|
|
291
|
+
useFocusTrap({ active: false, containerRef: containerRef(host), onEscape }),
|
|
292
|
+
);
|
|
293
|
+
act(() => {
|
|
294
|
+
view.result.current.onKeyDown(keyEvent('Escape'));
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
expect(document.activeElement).toBe(document.body);
|
|
298
|
+
expect(onEscape).not.toHaveBeenCalled();
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it('traps a real Tab press at the end of the ring', () => {
|
|
302
|
+
const host = mount('<button id="a">a</button><button id="b">b</button>');
|
|
303
|
+
|
|
304
|
+
const view = renderHook(() => useFocusTrap({ active: true, containerRef: containerRef(host) }));
|
|
305
|
+
host.querySelector<HTMLElement>('#b')?.focus();
|
|
306
|
+
const event = keyEvent('Tab');
|
|
307
|
+
act(() => {
|
|
308
|
+
view.result.current.onKeyDown(event);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
expect(event.calls.preventDefault).toBe(1);
|
|
312
|
+
expect(document.activeElement?.id).toBe('a');
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
it('reports Escape through the latest callback', () => {
|
|
316
|
+
const host = mount('<button id="a">a</button>');
|
|
317
|
+
const first = vi.fn();
|
|
318
|
+
const second = vi.fn();
|
|
319
|
+
|
|
320
|
+
const view = renderHook(
|
|
321
|
+
({ onEscape }: { onEscape: () => void }) =>
|
|
322
|
+
useFocusTrap({ active: true, containerRef: containerRef(host), onEscape }),
|
|
323
|
+
{ initialProps: { onEscape: first } },
|
|
324
|
+
);
|
|
325
|
+
view.rerender({ onEscape: second });
|
|
326
|
+
act(() => {
|
|
327
|
+
view.result.current.onKeyDown(keyEvent('Escape'));
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
expect(first).not.toHaveBeenCalled();
|
|
331
|
+
expect(second).toHaveBeenCalledTimes(1);
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
it('focuses the rendered dialog when React owns the ref', () => {
|
|
335
|
+
function Dialog() {
|
|
336
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
337
|
+
const props = useFocusTrap({ active: true, containerRef: ref });
|
|
338
|
+
return createElement(
|
|
339
|
+
'div',
|
|
340
|
+
{ ref, onKeyDown: props.onKeyDown },
|
|
341
|
+
createElement('button', { id: 'confirm' }, 'confirm'),
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
render(createElement(Dialog));
|
|
346
|
+
|
|
347
|
+
expect(document.activeElement?.id).toBe('confirm');
|
|
348
|
+
});
|
|
349
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef } from 'react';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
activeFocusTarget,
|
|
5
|
+
asFocusContainer,
|
|
6
|
+
asFocusTarget,
|
|
7
|
+
type FocusContainer,
|
|
8
|
+
type FocusableElement,
|
|
9
|
+
type FocusTarget,
|
|
10
|
+
type HostRef,
|
|
11
|
+
} from './dom-boundary.js';
|
|
12
|
+
import { hasDocument } from './platform.js';
|
|
13
|
+
|
|
14
|
+
const FOCUSABLE_SELECTOR = [
|
|
15
|
+
'a[href]',
|
|
16
|
+
'button:not([disabled])',
|
|
17
|
+
'input:not([disabled])',
|
|
18
|
+
'select:not([disabled])',
|
|
19
|
+
'textarea:not([disabled])',
|
|
20
|
+
'[role="button"]:not([aria-disabled="true"])',
|
|
21
|
+
'[role="link"]',
|
|
22
|
+
'[role="menuitem"]:not([aria-disabled="true"])',
|
|
23
|
+
'[role="radio"]:not([aria-disabled="true"])',
|
|
24
|
+
'[tabindex]:not([tabindex="-1"])',
|
|
25
|
+
].join(',');
|
|
26
|
+
|
|
27
|
+
export interface FocusTrapKeyEvent {
|
|
28
|
+
nativeEvent: { key: string; shiftKey?: boolean; target?: unknown };
|
|
29
|
+
preventDefault(): void;
|
|
30
|
+
stopPropagation?(): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface FocusTrapOptions {
|
|
34
|
+
active: boolean;
|
|
35
|
+
containerRef: HostRef;
|
|
36
|
+
initialFocusRef?: HostRef | undefined;
|
|
37
|
+
onEscape?: (() => void) | undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface FocusTrapProps {
|
|
41
|
+
onKeyDown: (event: FocusTrapKeyEvent) => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isAvailable(element: FocusableElement): boolean {
|
|
45
|
+
return (
|
|
46
|
+
element.disabled !== true &&
|
|
47
|
+
element.getAttribute('tabindex') !== '-1' &&
|
|
48
|
+
element.getAttribute('aria-disabled') !== 'true' &&
|
|
49
|
+
element.getAttribute('aria-hidden') !== 'true' &&
|
|
50
|
+
!element.hasAttribute('inert')
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function focusableElements(container: FocusContainer): FocusableElement[] {
|
|
55
|
+
return Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR)).filter(isAvailable);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Moves focus to the far end when Tab leaves the trap, reporting whether it wrapped. */
|
|
59
|
+
export function wrapFocusAtBoundary(
|
|
60
|
+
focusable: readonly FocusTarget[],
|
|
61
|
+
activeElement: unknown,
|
|
62
|
+
movingBackward: boolean,
|
|
63
|
+
): boolean {
|
|
64
|
+
if (focusable.length === 0) return false;
|
|
65
|
+
const currentIndex = focusable.findIndex((element) => element === activeElement);
|
|
66
|
+
const shouldWrap = movingBackward
|
|
67
|
+
? currentIndex <= 0
|
|
68
|
+
: currentIndex === -1 || currentIndex === focusable.length - 1;
|
|
69
|
+
if (!shouldWrap) return false;
|
|
70
|
+
focusable[movingBackward ? focusable.length - 1 : 0]?.focus({ preventScroll: true });
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Contains web Tab order inside an overlay and restores focus to its opener. */
|
|
75
|
+
/** Focuses the requested target, else the first focusable child, else the container. */
|
|
76
|
+
export function focusOverlayEntry(
|
|
77
|
+
container: FocusContainer | null,
|
|
78
|
+
requestedInitial: FocusTarget | null,
|
|
79
|
+
): void {
|
|
80
|
+
const firstFocusable = container ? focusableElements(container)[0] : undefined;
|
|
81
|
+
(requestedInitial ?? firstFocusable ?? container)?.focus({ preventScroll: true });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Applies one key press to a trapped container. Returns `escape` when the caller
|
|
86
|
+
* should close, `wrapped` when focus moved, and `ignored` otherwise.
|
|
87
|
+
*/
|
|
88
|
+
export function applyFocusTrapKey(
|
|
89
|
+
container: FocusContainer | null,
|
|
90
|
+
event: FocusTrapKeyEvent,
|
|
91
|
+
): 'escape' | 'wrapped' | 'ignored' {
|
|
92
|
+
const key = event.nativeEvent.key;
|
|
93
|
+
if (key === 'Escape') {
|
|
94
|
+
event.preventDefault();
|
|
95
|
+
event.stopPropagation?.();
|
|
96
|
+
return 'escape';
|
|
97
|
+
}
|
|
98
|
+
if (key !== 'Tab' || !container) return 'ignored';
|
|
99
|
+
|
|
100
|
+
const focusable = focusableElements(container);
|
|
101
|
+
if (focusable.length === 0) {
|
|
102
|
+
event.preventDefault();
|
|
103
|
+
container.focus({ preventScroll: true });
|
|
104
|
+
return 'wrapped';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const activeElement = activeFocusTarget() ?? event.nativeEvent.target;
|
|
108
|
+
if (!wrapFocusAtBoundary(focusable, activeElement, event.nativeEvent.shiftKey === true)) {
|
|
109
|
+
return 'ignored';
|
|
110
|
+
}
|
|
111
|
+
event.preventDefault();
|
|
112
|
+
return 'wrapped';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function useFocusTrap({
|
|
116
|
+
active,
|
|
117
|
+
containerRef,
|
|
118
|
+
initialFocusRef,
|
|
119
|
+
onEscape,
|
|
120
|
+
}: FocusTrapOptions): FocusTrapProps {
|
|
121
|
+
const onEscapeRef = useRef(onEscape);
|
|
122
|
+
const restoreTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
|
123
|
+
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
onEscapeRef.current = onEscape;
|
|
126
|
+
}, [onEscape]);
|
|
127
|
+
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
if (!hasDocument() || !active) return;
|
|
130
|
+
if (restoreTimerRef.current !== undefined) {
|
|
131
|
+
clearTimeout(restoreTimerRef.current);
|
|
132
|
+
restoreTimerRef.current = undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const previouslyFocused = activeFocusTarget();
|
|
136
|
+
focusOverlayEntry(asFocusContainer(containerRef), asFocusTarget(initialFocusRef));
|
|
137
|
+
|
|
138
|
+
return () => {
|
|
139
|
+
// useInert releases outside siblings in a sibling effect cleanup. Restore on
|
|
140
|
+
// the next task so the browser does not reject focus on a still-inert trigger.
|
|
141
|
+
restoreTimerRef.current = setTimeout(() => {
|
|
142
|
+
restoreTimerRef.current = undefined;
|
|
143
|
+
previouslyFocused?.focus({ preventScroll: true });
|
|
144
|
+
}, 0);
|
|
145
|
+
};
|
|
146
|
+
}, [active, containerRef, initialFocusRef]);
|
|
147
|
+
|
|
148
|
+
const onKeyDown = useCallback(
|
|
149
|
+
(event: FocusTrapKeyEvent) => {
|
|
150
|
+
if (!hasDocument() || !active) return;
|
|
151
|
+
if (applyFocusTrapKey(asFocusContainer(containerRef), event) === 'escape') {
|
|
152
|
+
onEscapeRef.current?.();
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
[active, containerRef],
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
return { onKeyDown };
|
|
159
|
+
}
|