@baukit/a11y-core 0.7.2 → 0.7.4

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,262 @@
1
+ // @vitest-environment jsdom
2
+ import { cleanup, renderHook } from '@testing-library/react';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ import type { HostRef, QueryRoot, TreeElement } from './dom-boundary.js';
6
+ import {
7
+ ARIA_HIDDEN_INERT_OPT_OUT,
8
+ makeOutsideSiblingsInert,
9
+ syncAriaHiddenInert,
10
+ useAriaHiddenInert,
11
+ useInert,
12
+ } from './use-inert.js';
13
+
14
+ const MANAGED = 'data-baukit-aria-hidden-inert';
15
+
16
+ function element(tag = 'div', id?: string): HTMLElement {
17
+ const node = document.createElement(tag);
18
+ if (id !== undefined) node.id = id;
19
+ return node;
20
+ }
21
+
22
+ function asTree(node: HTMLElement): TreeElement {
23
+ return node;
24
+ }
25
+
26
+ function treeById(id: string): TreeElement {
27
+ const element = document.querySelector<HTMLElement>(`#${id}`);
28
+ if (element === null) throw new Error(`no element with id ${id}`);
29
+ return asTree(element);
30
+ }
31
+
32
+ function ref(node: HTMLElement | null): HostRef {
33
+ return { current: node };
34
+ }
35
+
36
+ function bodyRoot(): QueryRoot {
37
+ return document.body;
38
+ }
39
+
40
+ afterEach(() => {
41
+ cleanup();
42
+ document.body.innerHTML = '';
43
+ });
44
+
45
+ describe('syncAriaHiddenInert', () => {
46
+ it('adds inert to an aria-hidden element and marks it as managed', () => {
47
+ const hidden = element('div', 'scene');
48
+ hidden.setAttribute('aria-hidden', 'true');
49
+ document.body.appendChild(hidden);
50
+
51
+ syncAriaHiddenInert(bodyRoot());
52
+
53
+ expect(hidden.hasAttribute('inert')).toBe(true);
54
+ expect(hidden.hasAttribute(MANAGED)).toBe(true);
55
+ });
56
+
57
+ it('marks the whole aria-hidden scene, not just its controls', () => {
58
+ document.body.innerHTML = `
59
+ <div id="scene" aria-hidden="true"><button id="behind">behind</button></div>
60
+ <button id="front">front</button>
61
+ `;
62
+
63
+ syncAriaHiddenInert(bodyRoot());
64
+
65
+ // jsdom 30 does not implement inert, so this asserts the attribute the
66
+ // browser acts on. The real focus-blocking is a browser-level check.
67
+ expect(document.querySelector('#scene')?.hasAttribute('inert')).toBe(true);
68
+ expect(document.querySelector('#front')?.hasAttribute('inert')).toBe(false);
69
+ });
70
+
71
+ it('leaves an opted-out element focusable', () => {
72
+ const hidden = element();
73
+ hidden.setAttribute('aria-hidden', 'true');
74
+ hidden.setAttribute(ARIA_HIDDEN_INERT_OPT_OUT, '');
75
+ document.body.appendChild(hidden);
76
+
77
+ syncAriaHiddenInert(bodyRoot());
78
+
79
+ expect(hidden.hasAttribute('inert')).toBe(false);
80
+ });
81
+
82
+ it('releases inert once aria-hidden is gone', () => {
83
+ const scene = element();
84
+ scene.setAttribute('aria-hidden', 'true');
85
+ document.body.appendChild(scene);
86
+ syncAriaHiddenInert(bodyRoot());
87
+
88
+ scene.removeAttribute('aria-hidden');
89
+ syncAriaHiddenInert(bodyRoot());
90
+
91
+ expect(scene.hasAttribute('inert')).toBe(false);
92
+ expect(scene.hasAttribute(MANAGED)).toBe(false);
93
+ });
94
+
95
+ it('never removes inert that the product set itself', () => {
96
+ const own = element();
97
+ own.setAttribute('inert', '');
98
+ document.body.appendChild(own);
99
+
100
+ syncAriaHiddenInert(bodyRoot());
101
+
102
+ expect(own.hasAttribute('inert')).toBe(true);
103
+ expect(own.hasAttribute(MANAGED)).toBe(false);
104
+ });
105
+ });
106
+
107
+ describe('makeOutsideSiblingsInert', () => {
108
+ it('marks every ancestor sibling inert and restores them on release', () => {
109
+ document.body.innerHTML = `
110
+ <div id="middle"><div id="overlay"></div><div id="sibling"></div></div>
111
+ <div id="uncle"></div>
112
+ `;
113
+ const overlay = document.querySelector<HTMLElement>('#overlay');
114
+ const sibling = document.querySelector<HTMLElement>('#sibling');
115
+ const uncle = document.querySelector<HTMLElement>('#uncle');
116
+ const middle = document.querySelector<HTMLElement>('#middle');
117
+
118
+ const release = makeOutsideSiblingsInert(treeById('overlay'));
119
+
120
+ expect(sibling?.hasAttribute('inert')).toBe(true);
121
+ expect(uncle?.hasAttribute('inert')).toBe(true);
122
+ expect(overlay?.hasAttribute('inert')).toBe(false);
123
+ expect(middle?.hasAttribute('inert')).toBe(false);
124
+
125
+ release();
126
+
127
+ expect(sibling?.hasAttribute('inert')).toBe(false);
128
+ expect(uncle?.hasAttribute('inert')).toBe(false);
129
+ });
130
+
131
+ it('marks the background but never the overlay it protects', () => {
132
+ document.body.innerHTML = `
133
+ <div id="overlay"><button id="confirm">confirm</button></div>
134
+ <button id="background">background</button>
135
+ `;
136
+ const overlay = document.querySelector<HTMLElement>('#overlay');
137
+
138
+ makeOutsideSiblingsInert(treeById('overlay'));
139
+
140
+ expect(document.querySelector('#background')?.hasAttribute('inert')).toBe(true);
141
+ expect(overlay?.hasAttribute('inert')).toBe(false);
142
+ expect(document.querySelector('#confirm')?.hasAttribute('inert')).toBe(false);
143
+
144
+ // The overlay's own controls stay reachable.
145
+ document.querySelector<HTMLElement>('#confirm')?.focus();
146
+ expect(document.activeElement?.id).toBe('confirm');
147
+ });
148
+
149
+ it('keeps a sibling inert until the last overlay releases it', () => {
150
+ document.body.innerHTML = `
151
+ <div id="first"></div><div id="second"></div><div id="sibling"></div>
152
+ `;
153
+ const sibling = document.querySelector<HTMLElement>('#sibling');
154
+
155
+ const releaseFirst = makeOutsideSiblingsInert(treeById('first'));
156
+ const releaseSecond = makeOutsideSiblingsInert(treeById('second'));
157
+
158
+ expect(sibling?.hasAttribute('inert')).toBe(true);
159
+ releaseFirst();
160
+ expect(sibling?.hasAttribute('inert')).toBe(true);
161
+ releaseSecond();
162
+ expect(sibling?.hasAttribute('inert')).toBe(false);
163
+ });
164
+
165
+ it('leaves a sibling that was already inert before the overlay opened', () => {
166
+ document.body.innerHTML = '<div id="overlay"></div><div id="frozen" inert></div>';
167
+ const frozen = document.querySelector<HTMLElement>('#frozen');
168
+
169
+ makeOutsideSiblingsInert(treeById('overlay'))();
170
+
171
+ expect(frozen?.hasAttribute('inert')).toBe(true);
172
+ });
173
+
174
+ it('stops climbing at the document body', () => {
175
+ document.body.innerHTML = '<div id="overlay"></div>';
176
+ const head = document.head;
177
+
178
+ makeOutsideSiblingsInert(treeById('overlay'));
179
+
180
+ expect(head.hasAttribute('inert')).toBe(false);
181
+ expect(document.body.hasAttribute('inert')).toBe(false);
182
+ });
183
+ });
184
+
185
+ describe('useInert', () => {
186
+ it('makes the outside inert while active and releases it on unmount', () => {
187
+ document.body.innerHTML = '<div id="overlay"></div><div id="sibling"></div>';
188
+ const overlay = document.querySelector<HTMLElement>('#overlay');
189
+ const sibling = document.querySelector<HTMLElement>('#sibling');
190
+
191
+ const view = renderHook(() => {
192
+ useInert(ref(overlay), true);
193
+ });
194
+ expect(sibling?.hasAttribute('inert')).toBe(true);
195
+
196
+ view.unmount();
197
+ expect(sibling?.hasAttribute('inert')).toBe(false);
198
+ });
199
+
200
+ it('does nothing while inactive', () => {
201
+ document.body.innerHTML = '<div id="overlay"></div><div id="sibling"></div>';
202
+
203
+ renderHook(() => {
204
+ useInert(ref(document.querySelector('#overlay')), false);
205
+ });
206
+
207
+ expect(document.querySelector('#sibling')?.hasAttribute('inert')).toBe(false);
208
+ });
209
+
210
+ it('does nothing before the container mounts or when it has no parent', () => {
211
+ expect(() => {
212
+ renderHook(() => {
213
+ useInert(ref(null), true);
214
+ });
215
+ renderHook(() => {
216
+ useInert(ref(element()), true);
217
+ });
218
+ }).not.toThrow();
219
+ });
220
+ });
221
+
222
+ describe('useAriaHiddenInert', () => {
223
+ it('syncs on mount, follows mutations, and cleans up on unmount', async () => {
224
+ const scene = element('div', 'scene');
225
+ scene.setAttribute('aria-hidden', 'true');
226
+ document.body.appendChild(scene);
227
+
228
+ const view = renderHook(() => {
229
+ useAriaHiddenInert();
230
+ });
231
+ expect(scene.hasAttribute('inert')).toBe(true);
232
+
233
+ scene.removeAttribute('aria-hidden');
234
+ await vi.waitFor(() => {
235
+ expect(scene.hasAttribute('inert')).toBe(false);
236
+ });
237
+
238
+ scene.setAttribute('aria-hidden', 'true');
239
+ await vi.waitFor(() => {
240
+ expect(scene.hasAttribute('inert')).toBe(true);
241
+ });
242
+
243
+ view.unmount();
244
+ expect(scene.hasAttribute('inert')).toBe(false);
245
+ expect(scene.hasAttribute(MANAGED)).toBe(false);
246
+ });
247
+
248
+ it('picks up a scene added after mount', async () => {
249
+ const view = renderHook(() => {
250
+ useAriaHiddenInert();
251
+ });
252
+
253
+ const late = element('div', 'late');
254
+ late.setAttribute('aria-hidden', 'true');
255
+ document.body.appendChild(late);
256
+
257
+ await vi.waitFor(() => {
258
+ expect(late.hasAttribute('inert')).toBe(true);
259
+ });
260
+ view.unmount();
261
+ });
262
+ });
@@ -0,0 +1,126 @@
1
+ import { useEffect } from 'react';
2
+
3
+ import {
4
+ asTreeElement,
5
+ type AttributeHost,
6
+ type HostRef,
7
+ type QueryRoot,
8
+ type TreeElement,
9
+ } from './dom-boundary.js';
10
+ import { hasDocument } from './platform.js';
11
+
12
+ const MANAGED_ARIA_HIDDEN_INERT = 'data-baukit-aria-hidden-inert';
13
+
14
+ /** Put this attribute on an element that must stay focusable while aria-hidden. */
15
+ export const ARIA_HIDDEN_INERT_OPT_OUT = 'data-baukit-inert-opt-out';
16
+
17
+ /**
18
+ * Routers mark inactive web scenes aria-hidden, but aria-hidden alone leaves
19
+ * their descendants in the keyboard focus order. This keeps inert in lockstep
20
+ * without relying on React Native Web to forward an unknown DOM prop.
21
+ */
22
+ export function syncAriaHiddenInert(root: QueryRoot): void {
23
+ for (const element of root.querySelectorAll(
24
+ `[aria-hidden="true"], [${MANAGED_ARIA_HIDDEN_INERT}]`,
25
+ )) {
26
+ const shouldBeInert =
27
+ element.getAttribute('aria-hidden') === 'true' &&
28
+ !element.hasAttribute(ARIA_HIDDEN_INERT_OPT_OUT);
29
+
30
+ if (shouldBeInert) {
31
+ if (!element.hasAttribute('inert')) {
32
+ element.setAttribute('inert', '');
33
+ element.setAttribute(MANAGED_ARIA_HIDDEN_INERT, '');
34
+ }
35
+ } else if (element.hasAttribute(MANAGED_ARIA_HIDDEN_INERT)) {
36
+ element.removeAttribute(MANAGED_ARIA_HIDDEN_INERT);
37
+ element.removeAttribute('inert');
38
+ }
39
+ }
40
+ }
41
+
42
+ /** Mirrors aria-hidden onto inert for the whole document while mounted. */
43
+ export function useAriaHiddenInert(): void {
44
+ useEffect(() => {
45
+ if (!hasDocument()) return;
46
+
47
+ const root = document.body as unknown as QueryRoot;
48
+ syncAriaHiddenInert(root);
49
+ const observer = new MutationObserver(() => {
50
+ syncAriaHiddenInert(root);
51
+ });
52
+ observer.observe(document.body, {
53
+ attributeFilter: ['aria-hidden'],
54
+ attributes: true,
55
+ childList: true,
56
+ subtree: true,
57
+ });
58
+
59
+ return () => {
60
+ observer.disconnect();
61
+ const managed: Iterable<AttributeHost> = root.querySelectorAll(
62
+ `[${MANAGED_ARIA_HIDDEN_INERT}]`,
63
+ );
64
+ for (const element of managed) {
65
+ element.removeAttribute(MANAGED_ARIA_HIDDEN_INERT);
66
+ element.removeAttribute('inert');
67
+ }
68
+ };
69
+ }, []);
70
+ }
71
+
72
+ interface InertState {
73
+ count: number;
74
+ wasInert: boolean;
75
+ }
76
+
77
+ const overlayInertStates = new WeakMap<object, InertState>();
78
+
79
+ function acquireInert(element: TreeElement): () => void {
80
+ const current = overlayInertStates.get(element);
81
+ if (current) {
82
+ current.count += 1;
83
+ } else {
84
+ overlayInertStates.set(element, { count: 1, wasInert: element.hasAttribute('inert') });
85
+ element.setAttribute('inert', '');
86
+ }
87
+
88
+ return () => {
89
+ const state = overlayInertStates.get(element);
90
+ if (!state) return;
91
+ state.count -= 1;
92
+ if (state.count > 0) return;
93
+ overlayInertStates.delete(element);
94
+ if (!state.wasInert) element.removeAttribute('inert');
95
+ };
96
+ }
97
+
98
+ /** Marks every ancestor sibling of the container inert, preserving its own subtree. */
99
+ export function makeOutsideSiblingsInert(container: TreeElement): () => void {
100
+ const releases: (() => void)[] = [];
101
+ const body: unknown = typeof document === 'undefined' ? undefined : document.body;
102
+ let branch: TreeElement = container;
103
+
104
+ while (branch.parentElement !== null) {
105
+ const parent: TreeElement = branch.parentElement;
106
+ for (const sibling of Array.from(parent.children)) {
107
+ if (sibling !== branch) releases.push(acquireInert(sibling));
108
+ }
109
+ branch = parent;
110
+ if (body !== undefined && (parent as unknown) === body) break;
111
+ }
112
+
113
+ return () => {
114
+ for (const release of releases.reverse()) release();
115
+ };
116
+ }
117
+
118
+ /** Makes content outside a web overlay unavailable while the overlay is active. */
119
+ export function useInert(containerRef: HostRef, active: boolean): void {
120
+ useEffect(() => {
121
+ if (!hasDocument() || !active) return;
122
+ const container = asTreeElement(containerRef);
123
+ if (!container?.parentElement) return;
124
+ return makeOutsideSiblingsInert(container);
125
+ }, [active, containerRef]);
126
+ }
@@ -0,0 +1,207 @@
1
+ // @vitest-environment jsdom
2
+ import { act, cleanup, renderHook } from '@testing-library/react';
3
+ import type { RefObject } from 'react';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ const platform = { OS: 'ios' as string };
7
+ const setAccessibilityFocus = vi.fn<(tag: number) => void>();
8
+ const findNodeHandle = vi.fn<(target: object) => number | null>();
9
+ const pendingInteractions: (() => void)[] = [];
10
+ const cancel = vi.fn();
11
+
12
+ vi.mock('react-native', () => ({
13
+ get Platform() {
14
+ return platform;
15
+ },
16
+ AccessibilityInfo: {
17
+ setAccessibilityFocus: (tag: number) => {
18
+ setAccessibilityFocus(tag);
19
+ },
20
+ },
21
+ findNodeHandle: (target: object) => findNodeHandle(target),
22
+ InteractionManager: {
23
+ runAfterInteractions: (task: () => void) => {
24
+ pendingInteractions.push(task);
25
+ return { cancel };
26
+ },
27
+ },
28
+ }));
29
+
30
+ import { useOverlayA11y } from './use-overlay-a11y.js';
31
+
32
+ const CONTAINER = { id: 'container' };
33
+ const TRIGGER = { id: 'trigger' };
34
+
35
+ function ref(current: unknown): RefObject<never> {
36
+ return { current } as unknown as RefObject<never>;
37
+ }
38
+
39
+ function flushInteractions(): void {
40
+ const tasks = pendingInteractions.splice(0, pendingInteractions.length);
41
+ for (const task of tasks) task();
42
+ }
43
+
44
+ afterEach(() => {
45
+ cleanup();
46
+ setAccessibilityFocus.mockReset();
47
+ findNodeHandle.mockReset();
48
+ cancel.mockReset();
49
+ pendingInteractions.length = 0;
50
+ platform.OS = 'ios';
51
+ document.body.innerHTML = '';
52
+ });
53
+
54
+ describe('useOverlayA11y on native', () => {
55
+ it('waits for layout before moving accessibility focus into the overlay', () => {
56
+ findNodeHandle.mockImplementation((target) => (target === CONTAINER ? 7 : null));
57
+
58
+ renderHook(() =>
59
+ useOverlayA11y({ active: true, containerRef: ref(CONTAINER), triggerRef: ref(null) }),
60
+ );
61
+
62
+ expect(setAccessibilityFocus).not.toHaveBeenCalled();
63
+
64
+ act(() => {
65
+ flushInteractions();
66
+ });
67
+
68
+ expect(setAccessibilityFocus).toHaveBeenCalledWith(7);
69
+ });
70
+
71
+ it('returns focus to the trigger when the overlay closes', () => {
72
+ findNodeHandle.mockImplementation((target) =>
73
+ target === CONTAINER ? 7 : target === TRIGGER ? 3 : null,
74
+ );
75
+
76
+ const view = renderHook(() =>
77
+ useOverlayA11y({ active: true, containerRef: ref(CONTAINER), triggerRef: ref(TRIGGER) }),
78
+ );
79
+ act(() => {
80
+ flushInteractions();
81
+ });
82
+ setAccessibilityFocus.mockReset();
83
+
84
+ view.unmount();
85
+
86
+ expect(cancel).toHaveBeenCalled();
87
+ expect(setAccessibilityFocus).toHaveBeenCalledWith(3);
88
+ });
89
+
90
+ it('prefers a trigger handle the caller already resolved', () => {
91
+ findNodeHandle.mockReturnValue(null);
92
+
93
+ const view = renderHook(() =>
94
+ useOverlayA11y({ active: true, containerRef: ref(CONTAINER), triggerHandle: 42 }),
95
+ );
96
+ view.unmount();
97
+
98
+ expect(setAccessibilityFocus).toHaveBeenCalledWith(42);
99
+ });
100
+
101
+ it('restores nothing when the trigger no longer exists', () => {
102
+ findNodeHandle.mockReturnValue(null);
103
+
104
+ const view = renderHook(() =>
105
+ useOverlayA11y({ active: true, containerRef: ref(CONTAINER), triggerRef: ref(null) }),
106
+ );
107
+ act(() => {
108
+ flushInteractions();
109
+ });
110
+ view.unmount();
111
+
112
+ expect(setAccessibilityFocus).not.toHaveBeenCalled();
113
+ });
114
+
115
+ it('survives a host node that disappears between layout and focus', () => {
116
+ findNodeHandle.mockImplementation(() => {
117
+ throw new Error('view unmounted');
118
+ });
119
+
120
+ expect(() => {
121
+ renderHook(() =>
122
+ useOverlayA11y({ active: true, containerRef: ref(CONTAINER), triggerRef: ref(TRIGGER) }),
123
+ );
124
+ act(() => {
125
+ flushInteractions();
126
+ });
127
+ }).not.toThrow();
128
+ expect(setAccessibilityFocus).not.toHaveBeenCalled();
129
+ });
130
+
131
+ it('hides the background from the accessibility tree only while active', () => {
132
+ const open = renderHook(() => useOverlayA11y({ active: true, containerRef: ref(CONTAINER) }));
133
+ const closed = renderHook(() =>
134
+ useOverlayA11y({ active: false, containerRef: ref(CONTAINER) }),
135
+ );
136
+
137
+ expect(open.result.current.backgroundProps).toEqual({
138
+ accessibilityElementsHidden: true,
139
+ importantForAccessibility: 'no-hide-descendants',
140
+ });
141
+ expect(closed.result.current.backgroundProps).toEqual({});
142
+ });
143
+
144
+ it('schedules nothing while the overlay is closed', () => {
145
+ renderHook(() => useOverlayA11y({ active: false, containerRef: ref(CONTAINER) }));
146
+
147
+ expect(pendingInteractions).toHaveLength(0);
148
+ });
149
+
150
+ it('lets the caller drive focus from its own layout event', () => {
151
+ findNodeHandle.mockReturnValue(9);
152
+ let layout: (() => void) | undefined;
153
+ const cancelLayout = vi.fn();
154
+ const deferFocus = (task: () => void) => {
155
+ layout = task;
156
+ return { cancel: cancelLayout };
157
+ };
158
+
159
+ const view = renderHook(() =>
160
+ useOverlayA11y({ active: true, containerRef: ref(CONTAINER), deferFocus }),
161
+ );
162
+
163
+ expect(pendingInteractions).toHaveLength(0);
164
+ expect(setAccessibilityFocus).not.toHaveBeenCalled();
165
+
166
+ act(() => {
167
+ layout?.();
168
+ });
169
+ expect(setAccessibilityFocus).toHaveBeenCalledWith(9);
170
+
171
+ view.unmount();
172
+ expect(cancelLayout).toHaveBeenCalled();
173
+ });
174
+ });
175
+
176
+ describe('useOverlayA11y on web', () => {
177
+ it('traps focus in the real overlay and leaves the background props empty', () => {
178
+ platform.OS = 'web';
179
+ document.body.innerHTML = `
180
+ <div id="overlay"><button id="confirm">confirm</button></div>
181
+ <button id="background">background</button>
182
+ `;
183
+ const overlay = document.querySelector<HTMLElement>('#overlay');
184
+ const onEscape = vi.fn();
185
+
186
+ const view = renderHook(() =>
187
+ useOverlayA11y({ active: true, containerRef: ref(overlay), onEscape }),
188
+ );
189
+
190
+ expect(view.result.current.backgroundProps).toEqual({});
191
+ expect(pendingInteractions).toHaveLength(0);
192
+ expect(document.activeElement?.id).toBe('confirm');
193
+ expect(document.querySelector('#background')?.hasAttribute('inert')).toBe(true);
194
+
195
+ act(() => {
196
+ view.result.current.containerProps.onKeyDown({
197
+ nativeEvent: { key: 'Escape' },
198
+ preventDefault: vi.fn(),
199
+ });
200
+ });
201
+
202
+ expect(onEscape).toHaveBeenCalledTimes(1);
203
+
204
+ view.unmount();
205
+ expect(document.querySelector('#background')?.hasAttribute('inert')).toBe(false);
206
+ });
207
+ });
@@ -0,0 +1,95 @@
1
+ import { useEffect, useRef, type RefObject } from 'react';
2
+ import {
3
+ AccessibilityInfo,
4
+ InteractionManager,
5
+ Platform,
6
+ type View,
7
+ type ViewProps,
8
+ } from 'react-native';
9
+
10
+ import type { HostRef } from './dom-boundary.js';
11
+ import { nativeNodeHandle } from './native-focus.js';
12
+ import { useFocusTrap, type FocusTrapProps } from './use-focus-trap.js';
13
+ import { useInert } from './use-inert.js';
14
+
15
+ /**
16
+ * Runs `task` once the overlay has laid out and returns a canceller. Products
17
+ * that already have a presentation event should pass their own.
18
+ */
19
+ export type DeferFocus = (task: () => void) => { cancel: () => void };
20
+
21
+ export interface OverlayA11yOptions {
22
+ active: boolean;
23
+ containerRef: RefObject<View | null>;
24
+ /** Overrides how the native focus request waits for layout. */
25
+ deferFocus?: DeferFocus | undefined;
26
+ /** Container whose outside siblings go inert. Defaults to `containerRef`. */
27
+ inertContainerRef?: RefObject<View | null> | undefined;
28
+ initialFocusRef?: HostRef | undefined;
29
+ onEscape?: (() => void) | undefined;
30
+ /** Native tag of the opener, when the caller already resolved it. */
31
+ triggerHandle?: number | null | undefined;
32
+ triggerRef?: RefObject<View | null> | undefined;
33
+ }
34
+
35
+ export type OverlayBackgroundProps = Pick<
36
+ ViewProps,
37
+ 'accessibilityElementsHidden' | 'importantForAccessibility'
38
+ >;
39
+
40
+ export interface OverlayA11yResult {
41
+ backgroundProps: OverlayBackgroundProps;
42
+ containerProps: FocusTrapProps;
43
+ }
44
+
45
+ // InteractionManager is deprecated in React Native 0.86 with no replacement for
46
+ // "after the overlay presented". It stays the default so existing callers keep
47
+ // working; pass `deferFocus` to drive focus from a real layout event instead.
48
+ const deferUntilInteractionsDone: DeferFocus = (task) =>
49
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
50
+ InteractionManager.runAfterInteractions(task);
51
+
52
+ /**
53
+ * One contract for overlay focus on both platforms. Web traps Tab, closes on
54
+ * Escape, and makes the background inert. Native moves accessibility focus into
55
+ * the overlay after layout and returns it to the trigger on close.
56
+ */
57
+ export function useOverlayA11y({
58
+ active,
59
+ containerRef,
60
+ deferFocus = deferUntilInteractionsDone,
61
+ inertContainerRef,
62
+ initialFocusRef,
63
+ onEscape,
64
+ triggerHandle,
65
+ triggerRef,
66
+ }: OverlayA11yOptions): OverlayA11yResult {
67
+ const triggerHandleRef = useRef<number | null>(null);
68
+ const containerProps = useFocusTrap({ active, containerRef, initialFocusRef, onEscape });
69
+ useInert(inertContainerRef ?? containerRef, active);
70
+
71
+ useEffect(() => {
72
+ if (Platform.OS === 'web' || !active) return;
73
+
74
+ triggerHandleRef.current = triggerHandle ?? nativeNodeHandle(triggerRef);
75
+ const task = deferFocus(() => {
76
+ const containerHandle = nativeNodeHandle(containerRef);
77
+ if (containerHandle !== null) AccessibilityInfo.setAccessibilityFocus(containerHandle);
78
+ });
79
+
80
+ return () => {
81
+ task.cancel();
82
+ const openerHandle = triggerHandleRef.current;
83
+ triggerHandleRef.current = null;
84
+ if (openerHandle !== null) AccessibilityInfo.setAccessibilityFocus(openerHandle);
85
+ };
86
+ }, [active, containerRef, deferFocus, triggerHandle, triggerRef]);
87
+
88
+ return {
89
+ backgroundProps:
90
+ Platform.OS !== 'web' && active
91
+ ? { accessibilityElementsHidden: true, importantForAccessibility: 'no-hide-descendants' }
92
+ : {},
93
+ containerProps,
94
+ };
95
+ }