@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baukit/a11y-core",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "description": "Accessibility behavior shared by web and React Native products: overlay focus, inert background content, announcements, reduced motion, and keyboard movement.",
5
5
  "license": "MIT",
6
6
  "author": "Patrick Koss",
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "files": [
37
37
  "dist",
38
+ "src",
38
39
  "README.md",
39
40
  "LICENSE"
40
41
  ],
@@ -0,0 +1,110 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ vi.mock('react-native', () => {
5
+ throw new Error('the web announcer must not import react-native');
6
+ });
7
+
8
+ import { announce, DEFAULT_LIVE_REGION_ID } from './announce-web.js';
9
+
10
+ function region(id: string = DEFAULT_LIVE_REGION_ID): HTMLElement | null {
11
+ return document.getElementById(id);
12
+ }
13
+
14
+ function liveRegion(id: string = DEFAULT_LIVE_REGION_ID): HTMLElement {
15
+ const element = region(id);
16
+ if (element === null) throw new Error(`no live region ${id}`);
17
+ return element;
18
+ }
19
+
20
+ afterEach(() => {
21
+ document.body.innerHTML = '';
22
+ });
23
+
24
+ describe('announce on web', () => {
25
+ it('creates one polite live region under the default id', () => {
26
+ announce('Import complete');
27
+
28
+ const live = region();
29
+ expect(live).not.toBeNull();
30
+ expect(live?.getAttribute('aria-live')).toBe('polite');
31
+ expect(live?.getAttribute('role')).toBe('status');
32
+ expect(live?.getAttribute('aria-atomic')).toBe('true');
33
+ expect(live?.textContent).toBe('Import complete');
34
+ });
35
+
36
+ it('keeps the region out of sight', () => {
37
+ announce('Saved');
38
+
39
+ const style = region()?.style;
40
+ expect(style?.position).toBe('absolute');
41
+ expect(style?.width).toBe('1px');
42
+ expect(style?.overflow).toBe('hidden');
43
+ });
44
+
45
+ it('raises urgency when assertive is requested', () => {
46
+ announce('Sync failed', { assertive: true });
47
+
48
+ expect(region()?.getAttribute('aria-live')).toBe('assertive');
49
+ expect(region()?.getAttribute('role')).toBe('alert');
50
+ });
51
+
52
+ it('reuses the same region instead of stacking one per call', () => {
53
+ announce('First');
54
+ announce('Second');
55
+
56
+ expect(document.querySelectorAll(`#${DEFAULT_LIVE_REGION_ID}`)).toHaveLength(1);
57
+ expect(region()?.textContent).toBe('Second');
58
+ });
59
+
60
+ it('changes urgency on the region it already created', () => {
61
+ announce('Saved');
62
+ announce('Sync failed', { assertive: true });
63
+
64
+ expect(document.querySelectorAll(`#${DEFAULT_LIVE_REGION_ID}`)).toHaveLength(1);
65
+ expect(region()?.getAttribute('aria-live')).toBe('assertive');
66
+ });
67
+
68
+ it('places the region under a product-owned id', () => {
69
+ announce('Saved', { liveRegionId: 'product-announcer' });
70
+
71
+ expect(region('product-announcer')?.textContent).toBe('Saved');
72
+ expect(region()).toBeNull();
73
+ });
74
+
75
+ it('adopts a region the product rendered itself', () => {
76
+ const own = document.createElement('div');
77
+ own.id = 'product-announcer';
78
+ document.body.appendChild(own);
79
+
80
+ announce('Saved', { liveRegionId: 'product-announcer' });
81
+
82
+ expect(document.querySelectorAll('#product-announcer')).toHaveLength(1);
83
+ expect(own.textContent).toBe('Saved');
84
+ });
85
+
86
+ it('clears the region so the same message twice is announced twice', () => {
87
+ announce('Set saved');
88
+ const live = liveRegion();
89
+
90
+ const observer = new MutationObserver(() => undefined);
91
+ observer.observe(live, { characterData: true, childList: true, subtree: true });
92
+
93
+ announce('Set saved');
94
+ const records = observer.takeRecords();
95
+ observer.disconnect();
96
+
97
+ // A screen reader re-reads the region only when its content actually
98
+ // changes, so repeating a message has to clear it first.
99
+ expect(records.length).toBeGreaterThan(1);
100
+ expect(live.textContent).toBe('Set saved');
101
+ });
102
+
103
+ it('drops a blank message without disturbing the region', () => {
104
+ announce('Set saved');
105
+
106
+ announce(' ');
107
+
108
+ expect(region()?.textContent).toBe('Set saved');
109
+ });
110
+ });
@@ -0,0 +1,42 @@
1
+ /** Default DOM id of the shared web live region. Override it per product. */
2
+ export const DEFAULT_LIVE_REGION_ID = 'baukit-announcer';
3
+
4
+ const VISUALLY_HIDDEN =
5
+ 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;';
6
+
7
+ export interface AnnounceOptions {
8
+ /** Interrupts the screen reader instead of waiting for a pause. */
9
+ assertive?: boolean;
10
+ /** DOM id of the web live region. Defaults to `DEFAULT_LIVE_REGION_ID`. */
11
+ liveRegionId?: string;
12
+ }
13
+
14
+ function liveRegion(assertive: boolean, liveRegionId: string): HTMLElement | null {
15
+ if (typeof document === 'undefined') return null;
16
+ let region = document.getElementById(liveRegionId);
17
+ if (!region) {
18
+ region = document.createElement('div');
19
+ region.id = liveRegionId;
20
+ region.style.cssText = VISUALLY_HIDDEN;
21
+ document.body.appendChild(region);
22
+ }
23
+ region.setAttribute('aria-atomic', 'true');
24
+ region.setAttribute('aria-live', assertive ? 'assertive' : 'polite');
25
+ region.setAttribute('role', assertive ? 'alert' : 'status');
26
+ return region;
27
+ }
28
+
29
+ /** Announces an outcome through a visually hidden ARIA live region. */
30
+ export function announce(
31
+ message: string,
32
+ { assertive = false, liveRegionId = DEFAULT_LIVE_REGION_ID }: AnnounceOptions = {},
33
+ ): void {
34
+ const trimmed = message.trim();
35
+ if (!trimmed) return;
36
+ const region = liveRegion(assertive, liveRegionId);
37
+ if (!region) return;
38
+ region.textContent = '';
39
+ // Force a distinct mutation so the same message twice is spoken twice.
40
+ region.getBoundingClientRect();
41
+ region.textContent = trimmed;
42
+ }
@@ -0,0 +1,57 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ const platform = { OS: 'web' as string };
5
+ const announceForAccessibility = vi.fn<(message: string) => void>();
6
+
7
+ vi.mock('react-native', () => ({
8
+ get Platform() {
9
+ return platform;
10
+ },
11
+ AccessibilityInfo: {
12
+ announceForAccessibility: (message: string) => {
13
+ announceForAccessibility(message);
14
+ },
15
+ },
16
+ }));
17
+
18
+ import { announce, DEFAULT_LIVE_REGION_ID } from './announce.js';
19
+
20
+ function region(id: string = DEFAULT_LIVE_REGION_ID): HTMLElement | null {
21
+ return document.getElementById(id);
22
+ }
23
+
24
+ afterEach(() => {
25
+ announceForAccessibility.mockReset();
26
+ platform.OS = 'web';
27
+ document.body.innerHTML = '';
28
+ });
29
+
30
+ describe('announce on native', () => {
31
+ it.each(['ios', 'android'])('uses the platform accessibility API on %s', (os) => {
32
+ platform.OS = os;
33
+
34
+ announce(' Set saved ', { assertive: true });
35
+
36
+ expect(announceForAccessibility).toHaveBeenCalledWith('Set saved');
37
+ expect(region()).toBeNull();
38
+ });
39
+
40
+ it('drops a blank message', () => {
41
+ platform.OS = 'ios';
42
+
43
+ announce(' ');
44
+
45
+ expect(announceForAccessibility).not.toHaveBeenCalled();
46
+ });
47
+ });
48
+
49
+ describe('announce on React Native Web', () => {
50
+ it('writes into the live region instead of the native API', () => {
51
+ announce(' Import complete ', { assertive: true, liveRegionId: 'product-announcer' });
52
+
53
+ expect(announceForAccessibility).not.toHaveBeenCalled();
54
+ expect(region('product-announcer')?.textContent).toBe('Import complete');
55
+ expect(region('product-announcer')?.getAttribute('aria-live')).toBe('assertive');
56
+ });
57
+ });
@@ -0,0 +1,16 @@
1
+ import { AccessibilityInfo, Platform } from 'react-native';
2
+
3
+ import { announce as announceOnWeb, type AnnounceOptions } from './announce-web.js';
4
+
5
+ export { DEFAULT_LIVE_REGION_ID, type AnnounceOptions } from './announce-web.js';
6
+
7
+ /** Announces an outcome without requiring a visible live-region component. */
8
+ export function announce(message: string, options: AnnounceOptions = {}): void {
9
+ if (Platform.OS === 'web') {
10
+ announceOnWeb(message, options);
11
+ return;
12
+ }
13
+ const trimmed = message.trim();
14
+ if (!trimmed) return;
15
+ AccessibilityInfo.announceForAccessibility(trimmed);
16
+ }
@@ -0,0 +1,80 @@
1
+ // @vitest-environment jsdom
2
+ import type { RefObject } from 'react';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ import {
6
+ activeFocusTarget,
7
+ asFocusContainer,
8
+ asFocusTarget,
9
+ asTreeElement,
10
+ hostElement,
11
+ } from './dom-boundary.js';
12
+
13
+ function ref(current: unknown): RefObject<never> {
14
+ return { current } as unknown as RefObject<never>;
15
+ }
16
+
17
+ afterEach(() => {
18
+ vi.unstubAllGlobals();
19
+ document.body.innerHTML = '';
20
+ });
21
+
22
+ describe('hostElement', () => {
23
+ it('returns null for an undefined ref, an empty ref, and a non-object host', () => {
24
+ expect(hostElement(undefined)).toBeNull();
25
+ expect(hostElement(ref(null))).toBeNull();
26
+ expect(hostElement(ref(42))).toBeNull();
27
+ });
28
+
29
+ it('returns the host element when one is attached', () => {
30
+ const host = document.createElement('div');
31
+ expect(hostElement(ref(host))).toBe(host);
32
+ });
33
+ });
34
+
35
+ describe('capability narrowing', () => {
36
+ it('accepts a real DOM element for every capability', () => {
37
+ const element = document.createElement('button');
38
+ document.body.appendChild(element);
39
+
40
+ expect(asFocusTarget(ref(element))).toBe(element);
41
+ expect(asFocusContainer(ref(element))).toBe(element);
42
+ expect(asTreeElement(ref(element))).toBe(element);
43
+ });
44
+
45
+ it('rejects a native host that has no DOM capabilities', () => {
46
+ const nativeView = { measure: () => undefined };
47
+
48
+ expect(asFocusTarget(ref(nativeView))).toBeNull();
49
+ expect(asFocusContainer(ref(nativeView))).toBeNull();
50
+ expect(asTreeElement(ref(nativeView))).toBeNull();
51
+ });
52
+
53
+ it('rejects a container that can query but cannot receive focus', () => {
54
+ expect(asFocusContainer(ref({ querySelectorAll: () => [] }))).toBeNull();
55
+ });
56
+
57
+ it('narrows a text node to nothing, since it has no element methods', () => {
58
+ expect(asFocusTarget(ref(document.createTextNode('text')))).toBeNull();
59
+ expect(asTreeElement(ref(document.createTextNode('text')))).toBeNull();
60
+ });
61
+ });
62
+
63
+ describe('activeFocusTarget', () => {
64
+ it('returns null without a document', () => {
65
+ vi.stubGlobal('document', undefined);
66
+ expect(activeFocusTarget()).toBeNull();
67
+ });
68
+
69
+ it('returns the body when nothing has been focused', () => {
70
+ expect(activeFocusTarget()).toBe(document.body);
71
+ });
72
+
73
+ it('returns the focused element', () => {
74
+ const button = document.createElement('button');
75
+ document.body.appendChild(button);
76
+ button.focus();
77
+
78
+ expect(activeFocusTarget()).toBe(button);
79
+ });
80
+ });
@@ -0,0 +1,84 @@
1
+ import type { RefObject } from 'react';
2
+
3
+ /**
4
+ * React Native Web renders a `View` as a DOM element, but the `View` type never
5
+ * says so. Every crossing from a ref to a DOM capability goes through this
6
+ * module so the unchecked cast exists once instead of at each call site.
7
+ */
8
+
9
+ /**
10
+ * A ref to whatever the host rendered: a `View` instance under React Native, an
11
+ * element under React DOM. Naming neither type keeps this module importable
12
+ * from a product that has no React Native types installed.
13
+ */
14
+ export type HostRef = RefObject<object | null>;
15
+
16
+ export interface FocusTarget {
17
+ focus(options?: { preventScroll?: boolean }): void;
18
+ }
19
+
20
+ export interface AttributeHost {
21
+ getAttribute(name: string): string | null;
22
+ hasAttribute(name: string): boolean;
23
+ removeAttribute(name: string): void;
24
+ setAttribute(name: string, value: string): void;
25
+ }
26
+
27
+ export interface FocusableElement extends FocusTarget {
28
+ disabled?: boolean;
29
+ getAttribute(name: string): string | null;
30
+ hasAttribute(name: string): boolean;
31
+ }
32
+
33
+ export interface QueryRoot {
34
+ querySelectorAll(selector: string): Iterable<AttributeHost>;
35
+ }
36
+
37
+ export interface FocusContainer extends FocusableElement {
38
+ querySelectorAll(selector: string): Iterable<FocusableElement>;
39
+ }
40
+
41
+ export interface TreeElement extends AttributeHost {
42
+ children: ArrayLike<TreeElement>;
43
+ parentElement: TreeElement | null;
44
+ }
45
+
46
+ function hasMethod<K extends string>(
47
+ value: object,
48
+ name: K,
49
+ ): value is Record<K, (...args: never[]) => unknown> {
50
+ return typeof (value as Record<string, unknown>)[name] === 'function';
51
+ }
52
+
53
+ /** Reads the host object behind a ref, or null when the ref is empty. */
54
+ export function hostElement(ref: HostRef | undefined): object | null {
55
+ const current = ref?.current;
56
+ return typeof current === 'object' && current !== null ? current : null;
57
+ }
58
+
59
+ export function asFocusTarget(ref: HostRef | undefined): FocusTarget | null {
60
+ const host = hostElement(ref);
61
+ return host !== null && hasMethod(host, 'focus') ? host : null;
62
+ }
63
+
64
+ export function asFocusContainer(ref: HostRef | undefined): FocusContainer | null {
65
+ const host = hostElement(ref);
66
+ if (host === null || !hasMethod(host, 'querySelectorAll') || !hasMethod(host, 'focus')) {
67
+ return null;
68
+ }
69
+ return host as FocusContainer;
70
+ }
71
+
72
+ export function asTreeElement(ref: HostRef | undefined): TreeElement | null {
73
+ const host = hostElement(ref);
74
+ return host !== null && hasMethod(host, 'setAttribute') ? (host as TreeElement) : null;
75
+ }
76
+
77
+ /** The element that currently holds DOM focus, or null outside a browser document. */
78
+ export function activeFocusTarget(): FocusTarget | null {
79
+ if (typeof document === 'undefined') return null;
80
+ const active: unknown = document.activeElement;
81
+ return typeof active === 'object' && active !== null && hasMethod(active, 'focus')
82
+ ? active
83
+ : null;
84
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ export * from './announce.js';
2
+ export * from './dom-boundary.js';
3
+ export { focusAccessibilityElement } from './native-focus.js';
4
+ export * from './route-focus.js';
5
+ export * from './use-enter-to-next.js';
6
+ export * from './use-focus-trap.js';
7
+ export * from './use-inert.js';
8
+ export * from './use-overlay-a11y.js';
9
+ export * from './use-reduced-motion.js';
10
+ export * from './use-roving-menu.js';
11
+ export * from './use-roving-radio-group.js';
12
+ export * from './use-single-flight.js';
@@ -0,0 +1,73 @@
1
+ import type { RefObject } from 'react';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ const platform = { OS: 'ios' as string };
5
+ const setAccessibilityFocus = vi.fn<(tag: number) => void>();
6
+ const findNodeHandle = vi.fn<(target: object) => number | null>();
7
+
8
+ vi.mock('react-native', () => ({
9
+ get Platform() {
10
+ return platform;
11
+ },
12
+ AccessibilityInfo: {
13
+ setAccessibilityFocus: (tag: number) => {
14
+ setAccessibilityFocus(tag);
15
+ },
16
+ },
17
+ findNodeHandle: (target: object) => findNodeHandle(target),
18
+ }));
19
+
20
+ import { focusAccessibilityElement } from './native-focus.js';
21
+
22
+ const HEADING_TAG = 42;
23
+
24
+ function ref(current: object | null): RefObject<object | null> {
25
+ return { current };
26
+ }
27
+
28
+ afterEach(() => {
29
+ setAccessibilityFocus.mockReset();
30
+ findNodeHandle.mockReset();
31
+ platform.OS = 'ios';
32
+ });
33
+
34
+ describe('focusAccessibilityElement', () => {
35
+ it('moves native screen-reader focus to the view tag', () => {
36
+ const heading = { id: 'heading' };
37
+ findNodeHandle.mockReturnValue(HEADING_TAG);
38
+
39
+ expect(focusAccessibilityElement(ref(heading))).toBe(true);
40
+ expect(findNodeHandle).toHaveBeenCalledWith(heading);
41
+ expect(setAccessibilityFocus).toHaveBeenCalledWith(HEADING_TAG);
42
+ });
43
+
44
+ it('reports false when the native view is missing or unmounted', () => {
45
+ expect(focusAccessibilityElement(ref(null))).toBe(false);
46
+ expect(focusAccessibilityElement(undefined)).toBe(false);
47
+
48
+ findNodeHandle.mockReturnValue(null);
49
+ expect(focusAccessibilityElement(ref({}))).toBe(false);
50
+
51
+ findNodeHandle.mockImplementation(() => {
52
+ throw new Error('unmounted');
53
+ });
54
+ expect(focusAccessibilityElement(ref({}))).toBe(false);
55
+ expect(setAccessibilityFocus).not.toHaveBeenCalled();
56
+ });
57
+
58
+ it('focuses the DOM element without scrolling on web', () => {
59
+ platform.OS = 'web';
60
+ const focus = vi.fn();
61
+
62
+ expect(focusAccessibilityElement(ref({ focus }))).toBe(true);
63
+ expect(focus).toHaveBeenCalledWith({ preventScroll: true });
64
+ expect(findNodeHandle).not.toHaveBeenCalled();
65
+ });
66
+
67
+ it('reports false on web when the element cannot take focus', () => {
68
+ platform.OS = 'web';
69
+
70
+ expect(focusAccessibilityElement(ref({}))).toBe(false);
71
+ expect(focusAccessibilityElement(ref(null))).toBe(false);
72
+ });
73
+ });
@@ -0,0 +1,31 @@
1
+ import { AccessibilityInfo, findNodeHandle, Platform } from 'react-native';
2
+
3
+ import { asFocusTarget, hostElement, type HostRef } from './dom-boundary.js';
4
+
5
+ /** Native view tag behind a ref, or null when the ref is empty or unmounted. */
6
+ export function nativeNodeHandle(ref: HostRef | undefined): number | null {
7
+ const host = hostElement(ref);
8
+ if (host === null) return null;
9
+ try {
10
+ return findNodeHandle(host as Parameters<typeof findNodeHandle>[0]);
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Moves screen-reader focus to the element behind `ref`. Web focuses the DOM
18
+ * element without scrolling; native asks VoiceOver or TalkBack to focus the
19
+ * view. Returns false when there was nothing to focus.
20
+ */
21
+ export function focusAccessibilityElement(ref: HostRef | undefined): boolean {
22
+ if (Platform.OS === 'web') {
23
+ const target = asFocusTarget(ref);
24
+ target?.focus({ preventScroll: true });
25
+ return target !== null;
26
+ }
27
+ const handle = nativeNodeHandle(ref);
28
+ if (handle === null) return false;
29
+ AccessibilityInfo.setAccessibilityFocus(handle);
30
+ return true;
31
+ }
@@ -0,0 +1,19 @@
1
+ // @vitest-environment jsdom
2
+ import { describe, expect, it, vi } from 'vitest';
3
+
4
+ import { hasDocument } from './platform.js';
5
+
6
+ describe('hasDocument', () => {
7
+ it('is true in a document environment', () => {
8
+ expect(hasDocument()).toBe(true);
9
+ });
10
+
11
+ it('is false where React Native runs, which has no document', () => {
12
+ vi.stubGlobal('document', undefined);
13
+ try {
14
+ expect(hasDocument()).toBe(false);
15
+ } finally {
16
+ vi.unstubAllGlobals();
17
+ }
18
+ });
19
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The DOM-only hooks must be importable from a plain React web app that has no
3
+ * React Native in its dependency tree. A static `react-native` import would put
4
+ * React Native's Flow source in that app's bundler, so those hooks ask for a
5
+ * document instead of asking `Platform` which OS this is.
6
+ *
7
+ * The two questions have the same answer for this package. Every branch guarded
8
+ * by `Platform.OS === 'web'` in `use-focus-trap` and `use-inert` reads or writes
9
+ * the DOM, React Native Web runs them against a real document, and React Native
10
+ * has no document at all. Hooks that need a genuine platform split, such as
11
+ * `announce` and `useOverlayA11y`, keep importing `Platform` directly.
12
+ */
13
+
14
+ /** True when a DOM document is available to read and mutate. */
15
+ export function hasDocument(): boolean {
16
+ return typeof document !== 'undefined';
17
+ }