@baukit/a11y-core 0.7.2 → 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.
@@ -0,0 +1,171 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import {
5
+ createRouteFocusController,
6
+ type RouteFocusController,
7
+ type RouteFocusRuntime,
8
+ type RouteFocusTarget,
9
+ } from './route-focus.js';
10
+
11
+ const FRAME_MS = 16;
12
+ const RETRY_TIMEOUT_MS = 100;
13
+ const controllers: RouteFocusController[] = [];
14
+
15
+ function runtime(): RouteFocusRuntime {
16
+ return {
17
+ document,
18
+ requestAnimationFrame: (callback) =>
19
+ window.setTimeout(() => {
20
+ callback(performance.now());
21
+ }, FRAME_MS),
22
+ cancelAnimationFrame: (handle) => {
23
+ window.clearTimeout(handle);
24
+ },
25
+ setTimeout: (callback, delayMs) => window.setTimeout(callback, delayMs),
26
+ clearTimeout: (handle) => {
27
+ window.clearTimeout(handle);
28
+ },
29
+ now: () => Date.now(),
30
+ };
31
+ }
32
+
33
+ function controller(): RouteFocusController {
34
+ const instance = createRouteFocusController(runtime(), {
35
+ focusRetryTimeoutMs: RETRY_TIMEOUT_MS,
36
+ });
37
+ controllers.push(instance);
38
+ return instance;
39
+ }
40
+
41
+ function focusable<K extends keyof HTMLElementTagNameMap>(tag: K): HTMLElementTagNameMap[K] {
42
+ const element = document.createElement(tag);
43
+ element.tabIndex = -1;
44
+ document.body.append(element);
45
+ return element;
46
+ }
47
+
48
+ beforeEach(() => {
49
+ vi.useFakeTimers();
50
+ vi.setSystemTime(0);
51
+ });
52
+
53
+ afterEach(() => {
54
+ for (const instance of controllers.splice(0)) instance.dispose();
55
+ document.body.innerHTML = '';
56
+ vi.useRealTimers();
57
+ });
58
+
59
+ describe('createRouteFocusController', () => {
60
+ it('waits for the entry target to mount and restores the initiating control', () => {
61
+ const instance = controller();
62
+ const trigger = focusable('button');
63
+ trigger.focus();
64
+ let heading: HTMLHeadingElement | null = null;
65
+
66
+ const leaveRoute = instance.enterRoute(() => heading);
67
+ vi.advanceTimersByTime(FRAME_MS);
68
+
69
+ expect(document.activeElement).toBe(trigger);
70
+
71
+ heading = focusable('h1');
72
+ vi.advanceTimersByTime(FRAME_MS);
73
+
74
+ expect(document.activeElement).toBe(heading);
75
+
76
+ leaveRoute();
77
+ vi.advanceTimersByTime(FRAME_MS);
78
+
79
+ expect(document.activeElement).toBe(trigger);
80
+ });
81
+
82
+ it('keeps the real return target after an inert transition blurs focus to body', () => {
83
+ const instance = controller();
84
+ const scene = document.createElement('section');
85
+ const trigger = document.createElement('button');
86
+ scene.append(trigger);
87
+ document.body.append(scene);
88
+ trigger.focus();
89
+ const focusTrigger = vi.spyOn(trigger, 'focus');
90
+
91
+ scene.setAttribute('inert', '');
92
+ trigger.blur();
93
+ expect(document.activeElement).toBe(document.body);
94
+
95
+ const heading = focusable('h1');
96
+ const leaveRoute = instance.enterRoute(() => heading);
97
+ vi.advanceTimersByTime(FRAME_MS);
98
+ leaveRoute();
99
+ vi.advanceTimersByTime(FRAME_MS);
100
+
101
+ expect(focusTrigger).not.toHaveBeenCalled();
102
+
103
+ scene.removeAttribute('inert');
104
+ vi.advanceTimersByTime(FRAME_MS);
105
+
106
+ expect(focusTrigger).toHaveBeenCalledWith({ preventScroll: true });
107
+ expect(document.activeElement).toBe(trigger);
108
+ });
109
+
110
+ it('stops retrying after the configured timeout', () => {
111
+ const instance = controller();
112
+ const getTarget = vi.fn<() => RouteFocusTarget | null>(() => null);
113
+
114
+ instance.enterRoute(getTarget);
115
+ vi.advanceTimersByTime(RETRY_TIMEOUT_MS + FRAME_MS);
116
+ const callsAtTimeout = getTarget.mock.calls.length;
117
+ vi.advanceTimersByTime(RETRY_TIMEOUT_MS * 2);
118
+
119
+ expect(callsAtTimeout).toBeGreaterThan(0);
120
+ expect(getTarget).toHaveBeenCalledTimes(callsAtTimeout);
121
+ expect(vi.getTimerCount()).toBe(0);
122
+ });
123
+
124
+ it('does not steal focus when the user moves to another reachable control', () => {
125
+ const instance = controller();
126
+ const trigger = focusable('button');
127
+ trigger.focus();
128
+ let heading: HTMLHeadingElement | null = null;
129
+ instance.enterRoute(() => heading);
130
+ vi.advanceTimersByTime(FRAME_MS);
131
+
132
+ const input = focusable('input');
133
+ input.focus();
134
+ heading = focusable('h1');
135
+ const focusHeading = vi.spyOn(heading, 'focus');
136
+ vi.advanceTimersByTime(FRAME_MS);
137
+
138
+ expect(focusHeading).not.toHaveBeenCalled();
139
+ expect(document.activeElement).toBe(input);
140
+ });
141
+
142
+ it('never focuses targets under inert or aria-hidden ancestors', () => {
143
+ const instance = controller();
144
+ const trigger = focusable('button');
145
+ trigger.focus();
146
+ const inertScene = document.createElement('section');
147
+ inertScene.setAttribute('inert', '');
148
+ const inertTarget = document.createElement('h1');
149
+ inertTarget.tabIndex = -1;
150
+ inertScene.append(inertTarget);
151
+ document.body.append(inertScene);
152
+ const hiddenScene = document.createElement('section');
153
+ hiddenScene.setAttribute('aria-hidden', 'true');
154
+ const hiddenTarget = document.createElement('h1');
155
+ hiddenTarget.tabIndex = -1;
156
+ hiddenScene.append(hiddenTarget);
157
+ document.body.append(hiddenScene);
158
+ let target: RouteFocusTarget = inertTarget;
159
+ const focusInert = vi.spyOn(inertTarget, 'focus');
160
+ const focusHidden = vi.spyOn(hiddenTarget, 'focus');
161
+
162
+ instance.enterRoute(() => target);
163
+ vi.advanceTimersByTime(FRAME_MS);
164
+ target = hiddenTarget;
165
+ vi.advanceTimersByTime(FRAME_MS);
166
+
167
+ expect(focusInert).not.toHaveBeenCalled();
168
+ expect(focusHidden).not.toHaveBeenCalled();
169
+ expect(document.activeElement).toBe(trigger);
170
+ });
171
+ });
@@ -0,0 +1,177 @@
1
+ const DEFAULT_FOCUS_RETRY_TIMEOUT_MS = 1500;
2
+ const UNREACHABLE_ANCESTOR = '[inert], [aria-hidden="true"], [hidden]';
3
+
4
+ export type RouteFocusTarget = Element & {
5
+ focus(options?: FocusOptions): void;
6
+ };
7
+
8
+ export interface RouteFocusRuntime {
9
+ document: Document;
10
+ requestAnimationFrame(callback: FrameRequestCallback): number;
11
+ cancelAnimationFrame(handle: number): void;
12
+ setTimeout(callback: () => void, delayMs: number): number;
13
+ clearTimeout(handle: number): void;
14
+ now(): number;
15
+ }
16
+
17
+ export interface RouteFocusControllerOptions {
18
+ focusRetryTimeoutMs?: number;
19
+ }
20
+
21
+ export interface RouteFocusController {
22
+ enterRoute(target: () => RouteFocusTarget | null): () => void;
23
+ dispose(): void;
24
+ }
25
+
26
+ function browserRuntime(): RouteFocusRuntime {
27
+ return {
28
+ document: globalThis.document,
29
+ requestAnimationFrame: (callback) => globalThis.requestAnimationFrame(callback),
30
+ cancelAnimationFrame: (handle) => {
31
+ globalThis.cancelAnimationFrame(handle);
32
+ },
33
+ setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
34
+ clearTimeout: (handle) => {
35
+ globalThis.clearTimeout(handle);
36
+ },
37
+ now: () => Date.now(),
38
+ };
39
+ }
40
+
41
+ function asRouteFocusTarget(value: unknown): RouteFocusTarget | null {
42
+ if (typeof value !== 'object' || value === null) return null;
43
+ const candidate = value as Partial<RouteFocusTarget>;
44
+ return typeof candidate.focus === 'function' && typeof candidate.closest === 'function'
45
+ ? (candidate as RouteFocusTarget)
46
+ : null;
47
+ }
48
+
49
+ /** Tracks route entry and restores focus when the returned cleanup runs. */
50
+ export function createRouteFocusController(
51
+ runtime: RouteFocusRuntime = browserRuntime(),
52
+ options: RouteFocusControllerOptions = {},
53
+ ): RouteFocusController {
54
+ const { document } = runtime;
55
+ const focusRetryTimeoutMs = Math.max(
56
+ 0,
57
+ options.focusRetryTimeoutMs ?? DEFAULT_FOCUS_RETRY_TIMEOUT_MS,
58
+ );
59
+ let lastFocusedTarget: RouteFocusTarget | null = null;
60
+ let cancelRetry: () => void = () => undefined;
61
+ let disposed = false;
62
+ let session = 0;
63
+
64
+ const reachable = (target: RouteFocusTarget): boolean => {
65
+ if (target.ownerDocument !== document || !target.isConnected) return false;
66
+ if (target.closest(UNREACHABLE_ANCESTOR) !== null) return false;
67
+ return !('disabled' in target && target.disabled === true);
68
+ };
69
+
70
+ const activeTarget = (): RouteFocusTarget | null => asRouteFocusTarget(document.activeElement);
71
+
72
+ const onFocusIn = (event: FocusEvent) => {
73
+ const target = asRouteFocusTarget(event.target);
74
+ if (target !== null && target !== document.body && reachable(target)) {
75
+ lastFocusedTarget = target;
76
+ }
77
+ };
78
+ document.addEventListener('focusin', onFocusIn, true);
79
+
80
+ const retryFocus = (
81
+ getTarget: () => RouteFocusTarget | null,
82
+ allowedActiveTargets: ReadonlySet<RouteFocusTarget>,
83
+ observedTargets?: Set<RouteFocusTarget>,
84
+ ): (() => void) => {
85
+ const startedAt = runtime.now();
86
+ let frame: number | null = null;
87
+ let timer: number | null = null;
88
+ let stopped = false;
89
+
90
+ const stop = () => {
91
+ if (stopped) return;
92
+ stopped = true;
93
+ if (frame !== null) runtime.cancelAnimationFrame(frame);
94
+ if (timer !== null) runtime.clearTimeout(timer);
95
+ frame = null;
96
+ timer = null;
97
+ };
98
+
99
+ const attempt = () => {
100
+ frame = null;
101
+ if (stopped) return;
102
+ if (runtime.now() - startedAt >= focusRetryTimeoutMs) {
103
+ stop();
104
+ return;
105
+ }
106
+
107
+ const target = getTarget();
108
+ if (target !== null) observedTargets?.add(target);
109
+ const active = activeTarget();
110
+ if (active === target && target !== null && reachable(target)) {
111
+ stop();
112
+ return;
113
+ }
114
+ if (
115
+ active !== null &&
116
+ active !== document.body &&
117
+ reachable(active) &&
118
+ !allowedActiveTargets.has(active)
119
+ ) {
120
+ stop();
121
+ return;
122
+ }
123
+
124
+ if (target !== null && reachable(target)) {
125
+ target.focus({ preventScroll: true });
126
+ const focused = activeTarget();
127
+ if (
128
+ focused === target ||
129
+ (focused !== null &&
130
+ focused !== document.body &&
131
+ reachable(focused) &&
132
+ !allowedActiveTargets.has(focused))
133
+ ) {
134
+ stop();
135
+ return;
136
+ }
137
+ }
138
+
139
+ frame = runtime.requestAnimationFrame(attempt);
140
+ };
141
+
142
+ timer = runtime.setTimeout(stop, focusRetryTimeoutMs);
143
+ frame = runtime.requestAnimationFrame(attempt);
144
+ return stop;
145
+ };
146
+
147
+ const enterRoute = (getTarget: () => RouteFocusTarget | null): (() => void) => {
148
+ cancelRetry();
149
+ const id = ++session;
150
+ const active = activeTarget();
151
+ const returnTarget =
152
+ active !== null && active !== document.body && reachable(active) ? active : lastFocusedTarget;
153
+ const allowedOnEntry = new Set<RouteFocusTarget>();
154
+ if (returnTarget !== null) allowedOnEntry.add(returnTarget);
155
+ const entryTargets = new Set<RouteFocusTarget>();
156
+ cancelRetry = retryFocus(getTarget, allowedOnEntry, entryTargets);
157
+
158
+ return () => {
159
+ if (disposed || id !== session) return;
160
+ session += 1;
161
+ cancelRetry();
162
+ if (returnTarget === null) return;
163
+ cancelRetry = retryFocus(() => returnTarget, entryTargets);
164
+ };
165
+ };
166
+
167
+ return {
168
+ enterRoute,
169
+ dispose() {
170
+ if (disposed) return;
171
+ disposed = true;
172
+ session += 1;
173
+ cancelRetry();
174
+ document.removeEventListener('focusin', onFocusIn, true);
175
+ },
176
+ };
177
+ }
@@ -0,0 +1,122 @@
1
+ // @vitest-environment jsdom
2
+ import { act, cleanup, renderHook } from '@testing-library/react';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ const platform = { OS: 'web' as string };
6
+
7
+ vi.mock('react-native', () => ({
8
+ get Platform() {
9
+ return platform;
10
+ },
11
+ }));
12
+
13
+ import { useEnterToNext } from './use-enter-to-next.js';
14
+
15
+ /** A real input stands in for the TextInput that React Native Web renders. */
16
+ function input(id: string): HTMLInputElement {
17
+ const node = document.createElement('input');
18
+ node.id = id;
19
+ document.body.appendChild(node);
20
+ return node;
21
+ }
22
+
23
+ afterEach(() => {
24
+ cleanup();
25
+ document.body.innerHTML = '';
26
+ platform.OS = 'web';
27
+ });
28
+
29
+ describe('useEnterToNext on web', () => {
30
+ it('moves focus to the next field and submits from the last one', () => {
31
+ const onSubmit = vi.fn();
32
+ const view = renderHook(() => useEnterToNext(2, onSubmit));
33
+ const first = view.result.current.registerField(0);
34
+ const second = view.result.current.registerField(1);
35
+ first.ref(input('first') as never);
36
+ second.ref(input('second') as never);
37
+
38
+ expect(first.returnKeyType).toBe('next');
39
+ expect(second.returnKeyType).toBe('done');
40
+
41
+ act(() => {
42
+ first.onSubmitEditing?.({} as never);
43
+ });
44
+ expect(document.activeElement?.id).toBe('second');
45
+ expect(onSubmit).not.toHaveBeenCalled();
46
+
47
+ act(() => {
48
+ second.onSubmitEditing?.({} as never);
49
+ });
50
+ expect(onSubmit).toHaveBeenCalledTimes(1);
51
+ });
52
+
53
+ it('skips a multiline field and leaves its Enter key alone', () => {
54
+ const onSubmit = vi.fn();
55
+ const view = renderHook(() => useEnterToNext(3, onSubmit));
56
+ const first = view.result.current.registerField(0);
57
+ const multiline = view.result.current.registerField(1, { multiline: true });
58
+ const third = view.result.current.registerField(2);
59
+ first.ref(input('first') as never);
60
+ multiline.ref(input('multiline') as never);
61
+ third.ref(input('third') as never);
62
+
63
+ expect(multiline.returnKeyType).toBeUndefined();
64
+ expect(multiline.onSubmitEditing).toBeUndefined();
65
+ expect(third.returnKeyType).toBe('done');
66
+
67
+ act(() => {
68
+ first.onSubmitEditing?.({} as never);
69
+ });
70
+ expect(document.activeElement?.id).toBe('third');
71
+ });
72
+
73
+ it('submits when no later field has mounted yet', () => {
74
+ const onSubmit = vi.fn();
75
+ const view = renderHook(() => useEnterToNext(2, onSubmit));
76
+ view.result.current.registerField(1);
77
+
78
+ act(() => {
79
+ view.result.current.registerField(0).onSubmitEditing?.({} as never);
80
+ });
81
+
82
+ expect(onSubmit).toHaveBeenCalledTimes(1);
83
+ });
84
+
85
+ it('marks the last single-line field done when the form ends with a multiline field', () => {
86
+ const view = renderHook(() => useEnterToNext(2, vi.fn()));
87
+ view.result.current.registerField(1, { multiline: true });
88
+
89
+ expect(view.result.current.registerField(0).returnKeyType).toBe('done');
90
+ });
91
+
92
+ it('re-registering a field as single-line puts it back in the chain', () => {
93
+ const view = renderHook(() => useEnterToNext(2, vi.fn()));
94
+ view.result.current.registerField(1, { multiline: true });
95
+ view.result.current.registerField(1);
96
+
97
+ expect(view.result.current.registerField(0).returnKeyType).toBe('next');
98
+ });
99
+
100
+ it('exposes submit directly', () => {
101
+ const onSubmit = vi.fn();
102
+ const view = renderHook(() => useEnterToNext(1, onSubmit));
103
+
104
+ act(() => {
105
+ view.result.current.submit();
106
+ });
107
+
108
+ expect(onSubmit).toHaveBeenCalledTimes(1);
109
+ });
110
+ });
111
+
112
+ describe('useEnterToNext on native', () => {
113
+ it.each(['ios', 'android'])('leaves the platform keyboard behavior alone on %s', (os) => {
114
+ platform.OS = os;
115
+ const view = renderHook(() => useEnterToNext(2, vi.fn()));
116
+
117
+ const props = view.result.current.registerField(0);
118
+
119
+ expect(props.returnKeyType).toBeUndefined();
120
+ expect(props.onSubmitEditing).toBeUndefined();
121
+ });
122
+ });
@@ -0,0 +1,63 @@
1
+ import { useCallback, useRef } from 'react';
2
+ import { Platform, type TextInput, type TextInputProps } from 'react-native';
3
+
4
+ export interface RegisterFieldOptions {
5
+ multiline?: boolean;
6
+ }
7
+
8
+ export type RegisteredFieldProps = Pick<TextInputProps, 'onSubmitEditing' | 'returnKeyType'> & {
9
+ ref: (node: TextInput | null) => void;
10
+ };
11
+
12
+ export interface EnterToNextResult {
13
+ registerField: (index: number, options?: RegisterFieldOptions) => RegisteredFieldProps;
14
+ submit: () => void;
15
+ }
16
+
17
+ /**
18
+ * Makes Enter walk a web form field by field and submit from the last one.
19
+ * Multiline fields keep their newline behavior and are skipped on the way.
20
+ */
21
+ export function useEnterToNext(fieldCount: number, onSubmit: () => void): EnterToNextResult {
22
+ const fieldRefs = useRef<(TextInput | null)[]>([]);
23
+ const multilineFields = useRef(new Set<number>());
24
+
25
+ const submit = useCallback(() => {
26
+ onSubmit();
27
+ }, [onSubmit]);
28
+
29
+ const registerField = useCallback(
30
+ (index: number, options: RegisterFieldOptions = {}): RegisteredFieldProps => {
31
+ if (options.multiline === true) multilineFields.current.add(index);
32
+ else multilineFields.current.delete(index);
33
+
34
+ const ref = (node: TextInput | null) => {
35
+ fieldRefs.current[index] = node;
36
+ };
37
+ if (Platform.OS !== 'web' || options.multiline === true) return { ref };
38
+
39
+ const lastSingleLineField = Array.from({ length: fieldCount }, (_, candidate) => candidate)
40
+ .reverse()
41
+ .find((candidate) => !multilineFields.current.has(candidate));
42
+
43
+ return {
44
+ ref,
45
+ returnKeyType: index === lastSingleLineField ? 'done' : 'next',
46
+ onSubmitEditing: () => {
47
+ for (let nextIndex = index + 1; nextIndex < fieldCount; nextIndex += 1) {
48
+ if (multilineFields.current.has(nextIndex)) continue;
49
+ const nextField = fieldRefs.current[nextIndex];
50
+ if (nextField) {
51
+ nextField.focus();
52
+ return;
53
+ }
54
+ }
55
+ submit();
56
+ },
57
+ };
58
+ },
59
+ [fieldCount, submit],
60
+ );
61
+
62
+ return { registerField, submit };
63
+ }