@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,103 @@
1
+ // @vitest-environment jsdom
2
+ import { act, cleanup, renderHook } from '@testing-library/react';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ vi.mock('react-native', () => {
6
+ throw new Error('the web reduced-motion hooks must not import react-native');
7
+ });
8
+
9
+ import { useReducedMotion, useReducedMotionPreference } from './use-reduced-motion-web.js';
10
+
11
+ type MediaListener = () => void;
12
+
13
+ /** jsdom has no matchMedia. Each call returns a fresh list that reads the current setting. */
14
+ function stubMatchMedia(initial: boolean) {
15
+ let matches = initial;
16
+ const listeners = new Set<MediaListener>();
17
+ const matchMedia = vi.fn((query: string) => ({
18
+ get matches() {
19
+ return matches;
20
+ },
21
+ media: query,
22
+ addEventListener: (_event: string, listener: MediaListener) => {
23
+ listeners.add(listener);
24
+ },
25
+ removeEventListener: (_event: string, listener: MediaListener) => {
26
+ listeners.delete(listener);
27
+ },
28
+ }));
29
+ vi.stubGlobal('matchMedia', matchMedia);
30
+ return {
31
+ matchMedia,
32
+ listenerCount: () => listeners.size,
33
+ change(next: boolean) {
34
+ matches = next;
35
+ for (const listener of listeners) listener();
36
+ },
37
+ };
38
+ }
39
+
40
+ afterEach(() => {
41
+ cleanup();
42
+ vi.unstubAllGlobals();
43
+ });
44
+
45
+ describe('useReducedMotion on the web entry', () => {
46
+ it('reads the media query on the first render', () => {
47
+ const media = stubMatchMedia(true);
48
+
49
+ const { result } = renderHook(() => useReducedMotion());
50
+
51
+ expect(result.current).toBe(true);
52
+ expect(media.matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
53
+ });
54
+
55
+ it('follows changes and unsubscribes on unmount', () => {
56
+ const media = stubMatchMedia(false);
57
+ const { result, unmount } = renderHook(() => useReducedMotion());
58
+
59
+ act(() => {
60
+ media.change(true);
61
+ });
62
+ expect(result.current).toBe(true);
63
+
64
+ unmount();
65
+ expect(media.listenerCount()).toBe(0);
66
+ });
67
+
68
+ it('reports no preference when matchMedia is missing', () => {
69
+ const { result } = renderHook(() => useReducedMotionPreference());
70
+
71
+ expect(result.current).toEqual({ reducedMotion: false, resolved: true });
72
+ });
73
+ });
74
+
75
+ describe('useReducedMotionPreference on the web entry', () => {
76
+ it('resolves on the first client render and keeps a stable object', () => {
77
+ stubMatchMedia(true);
78
+ const { result, rerender } = renderHook(() => useReducedMotionPreference());
79
+ const first = result.current;
80
+
81
+ rerender();
82
+
83
+ expect(first).toEqual({ reducedMotion: true, resolved: true });
84
+ expect(result.current).toBe(first);
85
+ });
86
+
87
+ it('hydrates from the server value, then resolves', () => {
88
+ stubMatchMedia(true);
89
+ const seen: unknown[] = [];
90
+
91
+ renderHook(
92
+ () => {
93
+ const preference = useReducedMotionPreference();
94
+ seen.push(preference);
95
+ return preference;
96
+ },
97
+ { hydrate: true },
98
+ );
99
+
100
+ expect(seen[0]).toEqual({ reducedMotion: false, resolved: false });
101
+ expect(seen.at(-1)).toEqual({ reducedMotion: true, resolved: true });
102
+ });
103
+ });
@@ -0,0 +1,49 @@
1
+ import { useMemo, useSyncExternalStore } from 'react';
2
+
3
+ const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
4
+
5
+ export interface ReducedMotionPreference {
6
+ reducedMotion: boolean;
7
+ resolved: boolean;
8
+ }
9
+
10
+ /** The `prefers-reduced-motion` media query, or `null` where the host has no `matchMedia`. */
11
+ export function reducedMotionQuery(): MediaQueryList | null {
12
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
13
+ ? window.matchMedia(REDUCED_MOTION_QUERY)
14
+ : null;
15
+ }
16
+
17
+ function subscribeToQuery(onChange: () => void): () => void {
18
+ const query = reducedMotionQuery();
19
+ if (query === null) {
20
+ return () => undefined;
21
+ }
22
+ query.addEventListener('change', onChange);
23
+ return () => {
24
+ query.removeEventListener('change', onChange);
25
+ };
26
+ }
27
+
28
+ function subscribeToNothing(): () => void {
29
+ return () => undefined;
30
+ }
31
+
32
+ const readQuery = () => reducedMotionQuery()?.matches ?? false;
33
+ const onClient = () => true;
34
+ const onServer = () => false;
35
+
36
+ /**
37
+ * Follows `prefers-reduced-motion` through `matchMedia`. `resolved` is `false` only while
38
+ * rendering on a server, which cannot see the user's setting.
39
+ */
40
+ export function useReducedMotionPreference(): ReducedMotionPreference {
41
+ const reducedMotion = useSyncExternalStore(subscribeToQuery, readQuery, onServer);
42
+ const resolved = useSyncExternalStore(subscribeToNothing, onClient, onServer);
43
+ return useMemo(() => ({ reducedMotion, resolved }), [reducedMotion, resolved]);
44
+ }
45
+
46
+ /** Follows `prefers-reduced-motion` and its changes during the session. */
47
+ export function useReducedMotion(): boolean {
48
+ return useSyncExternalStore(subscribeToQuery, readQuery, onServer);
49
+ }
@@ -0,0 +1,179 @@
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
+ const isReduceMotionEnabled = vi.fn<() => Promise<boolean>>();
7
+ const addEventListener =
8
+ vi.fn<(event: string, listener: (enabled: boolean) => void) => { remove: () => void }>();
9
+
10
+ vi.mock('react-native', () => ({
11
+ get Platform() {
12
+ return platform;
13
+ },
14
+ AccessibilityInfo: {
15
+ isReduceMotionEnabled: () => isReduceMotionEnabled(),
16
+ addEventListener: (event: string, listener: (enabled: boolean) => void) =>
17
+ addEventListener(event, listener),
18
+ },
19
+ }));
20
+
21
+ import { useReducedMotion, useReducedMotionPreference } from './use-reduced-motion.js';
22
+
23
+ /** jsdom has no matchMedia, so the query it would return is supplied here. */
24
+ type MediaListener = (event: MediaQueryListEvent) => void;
25
+
26
+ function stubMatchMedia(matches: boolean) {
27
+ const listeners = new Set<MediaListener>();
28
+ const removeEventListener = vi.fn((_event: string, listener: MediaListener) => {
29
+ listeners.delete(listener);
30
+ });
31
+ const matchMedia = vi.fn((query: string) => ({
32
+ matches,
33
+ media: query,
34
+ addEventListener: (_event: string, listener: MediaListener) => {
35
+ listeners.add(listener);
36
+ },
37
+ removeEventListener,
38
+ }));
39
+ vi.stubGlobal('matchMedia', matchMedia);
40
+ return {
41
+ matchMedia,
42
+ removeEventListener,
43
+ change(next: boolean) {
44
+ for (const listener of listeners) listener({ matches: next } as MediaQueryListEvent);
45
+ },
46
+ };
47
+ }
48
+
49
+ afterEach(() => {
50
+ cleanup();
51
+ vi.unstubAllGlobals();
52
+ isReduceMotionEnabled.mockReset();
53
+ addEventListener.mockReset();
54
+ platform.OS = 'web';
55
+ });
56
+
57
+ describe('useReducedMotion on web', () => {
58
+ it('reads the media query and resolves on the first render', () => {
59
+ stubMatchMedia(true);
60
+
61
+ expect(renderHook(() => useReducedMotion()).result.current).toBe(true);
62
+ expect(renderHook(() => useReducedMotionPreference()).result.current).toEqual({
63
+ reducedMotion: true,
64
+ resolved: true,
65
+ });
66
+ });
67
+
68
+ it('asks for the reduced-motion query specifically', () => {
69
+ const media = stubMatchMedia(false);
70
+
71
+ renderHook(() => useReducedMotion());
72
+
73
+ expect(media.matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
74
+ });
75
+
76
+ it('follows a preference change during the session', () => {
77
+ const media = stubMatchMedia(false);
78
+ const view = renderHook(() => useReducedMotion());
79
+ expect(view.result.current).toBe(false);
80
+
81
+ act(() => {
82
+ media.change(true);
83
+ });
84
+
85
+ expect(view.result.current).toBe(true);
86
+ });
87
+
88
+ it('unsubscribes on unmount', () => {
89
+ const media = stubMatchMedia(false);
90
+ const view = renderHook(() => useReducedMotion());
91
+
92
+ view.unmount();
93
+
94
+ expect(media.removeEventListener).toHaveBeenCalled();
95
+ });
96
+
97
+ it('reports no preference when matchMedia is unavailable', () => {
98
+ vi.stubGlobal('matchMedia', undefined);
99
+
100
+ expect(renderHook(() => useReducedMotion()).result.current).toBe(false);
101
+ });
102
+ });
103
+
104
+ describe('useReducedMotion on native', () => {
105
+ it('starts unresolved while the platform query is pending', () => {
106
+ platform.OS = 'ios';
107
+ isReduceMotionEnabled.mockReturnValue(new Promise(() => undefined));
108
+ addEventListener.mockReturnValue({ remove: vi.fn() });
109
+
110
+ expect(renderHook(() => useReducedMotionPreference()).result.current).toEqual({
111
+ reducedMotion: false,
112
+ resolved: false,
113
+ });
114
+ });
115
+
116
+ it.each(['ios', 'android'])('resolves and observes the platform setting on %s', async (os) => {
117
+ platform.OS = os;
118
+ isReduceMotionEnabled.mockResolvedValue(true);
119
+ let listener: ((enabled: boolean) => void) | undefined;
120
+ const remove = vi.fn();
121
+ addEventListener.mockImplementation((_event, next) => {
122
+ listener = next;
123
+ return { remove };
124
+ });
125
+
126
+ const view = renderHook(() => useReducedMotionPreference());
127
+
128
+ await vi.waitFor(() => {
129
+ expect(view.result.current).toEqual({ reducedMotion: true, resolved: true });
130
+ });
131
+ expect(addEventListener).toHaveBeenCalledWith('reduceMotionChanged', expect.any(Function));
132
+
133
+ act(() => {
134
+ listener?.(false);
135
+ });
136
+ expect(view.result.current).toEqual({ reducedMotion: false, resolved: true });
137
+
138
+ view.unmount();
139
+ expect(remove).toHaveBeenCalled();
140
+ });
141
+
142
+ it('resolves after a rejected platform query', async () => {
143
+ platform.OS = 'ios';
144
+ isReduceMotionEnabled.mockRejectedValue(new Error('query unavailable'));
145
+ addEventListener.mockReturnValue({ remove: vi.fn() });
146
+
147
+ const view = renderHook(() => useReducedMotionPreference());
148
+
149
+ await vi.waitFor(() => {
150
+ expect(view.result.current).toEqual({ reducedMotion: false, resolved: true });
151
+ });
152
+ });
153
+
154
+ it('does not update after unmount when a slow read resolves', async () => {
155
+ platform.OS = 'ios';
156
+ let resolveQuery: ((enabled: boolean) => void) | undefined;
157
+ isReduceMotionEnabled.mockReturnValue(
158
+ new Promise((resolve) => {
159
+ resolveQuery = resolve;
160
+ }),
161
+ );
162
+ const remove = vi.fn();
163
+ addEventListener.mockReturnValue({ remove });
164
+ let renders = 0;
165
+
166
+ const view = renderHook(() => {
167
+ renders += 1;
168
+ return useReducedMotionPreference();
169
+ });
170
+ view.unmount();
171
+ await act(async () => {
172
+ resolveQuery?.(true);
173
+ await Promise.resolve();
174
+ });
175
+
176
+ expect(renders).toBe(1);
177
+ expect(remove).toHaveBeenCalledOnce();
178
+ });
179
+ });
@@ -0,0 +1,61 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { AccessibilityInfo, Platform } from 'react-native';
3
+
4
+ import { reducedMotionQuery, type ReducedMotionPreference } from './use-reduced-motion-web.js';
5
+
6
+ export type { ReducedMotionPreference };
7
+
8
+ /** Tracks when the reduced-motion preference is ready and follows later changes. */
9
+ export function useReducedMotionPreference(): ReducedMotionPreference {
10
+ const [preference, setPreference] = useState<ReducedMotionPreference>(() => {
11
+ const web = Platform.OS === 'web';
12
+ return {
13
+ reducedMotion: web && (reducedMotionQuery()?.matches ?? false),
14
+ resolved: web,
15
+ };
16
+ });
17
+
18
+ useEffect(() => {
19
+ if (Platform.OS === 'web') {
20
+ const query = reducedMotionQuery();
21
+ if (!query) return;
22
+ const onChange = (event: MediaQueryListEvent) => {
23
+ setPreference({ reducedMotion: event.matches, resolved: true });
24
+ };
25
+ query.addEventListener('change', onChange);
26
+ return () => {
27
+ query.removeEventListener('change', onChange);
28
+ };
29
+ }
30
+
31
+ let mounted = true;
32
+ let preferenceChanged = false;
33
+ const settle = (reducedMotion?: boolean) => {
34
+ if (!mounted) return;
35
+ setPreference((current) => ({
36
+ reducedMotion:
37
+ reducedMotion === undefined || preferenceChanged ? current.reducedMotion : reducedMotion,
38
+ resolved: true,
39
+ }));
40
+ };
41
+ void AccessibilityInfo.isReduceMotionEnabled().then(settle, () => {
42
+ settle();
43
+ });
44
+ const subscription = AccessibilityInfo.addEventListener('reduceMotionChanged', (enabled) => {
45
+ if (!mounted) return;
46
+ preferenceChanged = true;
47
+ setPreference({ reducedMotion: enabled, resolved: true });
48
+ });
49
+ return () => {
50
+ mounted = false;
51
+ subscription.remove();
52
+ };
53
+ }, []);
54
+
55
+ return preference;
56
+ }
57
+
58
+ /** Tracks the reduced-motion preference and follows changes during the session. */
59
+ export function useReducedMotion(): boolean {
60
+ return useReducedMotionPreference().reducedMotion;
61
+ }