react-native-theme-transition 1.0.0

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,445 @@
1
+ /**
2
+ * Screenshot-overlay transition engine and provider.
3
+ *
4
+ * @module
5
+ */
6
+
7
+ import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
+ import { Appearance, AppState, Image, View } from 'react-native';
9
+ import Animated, {
10
+ useAnimatedProps,
11
+ useSharedValue,
12
+ withTiming,
13
+ } from 'react-native-reanimated';
14
+ import { captureRef } from 'react-native-view-shot';
15
+ import { scheduleOnRN } from 'react-native-worklets';
16
+ import type {
17
+ ThemeTransitionConfig,
18
+ UseThemeResult,
19
+ SetThemeOptions,
20
+ SystemThemeMap,
21
+ ThemeDefinition,
22
+ ThemeNames,
23
+ TokenNames,
24
+ } from './types';
25
+ import { TAG } from './constants';
26
+
27
+ const ABSOLUTE_FILL = { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 } as const;
28
+ // Avoids layout clipping on certain Android API levels.
29
+ const ROOT_STYLE = { flex: 1 } as const;
30
+
31
+ /** Calls `fn` and swallows errors with a console.warn tagged by `label`. */
32
+ function safeCall<A extends unknown[]>(label: string, fn: ((...args: A) => void) | undefined, ...args: A): void {
33
+ try { fn?.(...args); } catch (e) { console.warn(`${TAG} ${label} threw:`, e); }
34
+ }
35
+
36
+ /**
37
+ * Waits for `n` native animation frames to complete.
38
+ *
39
+ * @remarks
40
+ * React Native's rendering pipeline spans three phases:
41
+ * 1. **JS thread** — React reconciliation produces a virtual tree.
42
+ * 2. **Shadow Tree** — Yoga calculates layout from the virtual tree.
43
+ * 3. **Native UI thread** — platform views are painted on screen.
44
+ *
45
+ * Each phase runs on its own frame cadence (~16.67 ms at 60 fps).
46
+ * Waiting 1 frame lets React flush pending state or the compositor
47
+ * paint a decoded image.
48
+ *
49
+ * @param n - Number of animation frames to wait.
50
+ */
51
+ function waitFrames(n: number): Promise<void> {
52
+ return new Promise((resolve) => {
53
+ let remaining = n;
54
+ const tick = () => {
55
+ if (--remaining <= 0) resolve();
56
+ else requestAnimationFrame(tick);
57
+ };
58
+ requestAnimationFrame(tick);
59
+ });
60
+ }
61
+
62
+ /**
63
+ * Normalizes an OS color scheme string to `'light'` or `'dark'`.
64
+ *
65
+ * @remarks
66
+ * Only accepts the two known values. Any other input — including `null`,
67
+ * `undefined`, and `'unspecified'` (returned by RN after
68
+ * `Appearance.setColorScheme('unspecified')`) — defaults to `'light'`.
69
+ *
70
+ * @internal
71
+ */
72
+ function normalizeScheme(colorScheme?: string | null, fallback: 'light' | 'dark' = 'light'): 'light' | 'dark' {
73
+ if (colorScheme === 'dark') return 'dark';
74
+ if (colorScheme === 'light') return 'light';
75
+ return fallback;
76
+ }
77
+
78
+ /**
79
+ * Maps an OS color scheme to a theme name via `systemThemeMap`.
80
+ *
81
+ * @remarks
82
+ * The fallback `scheme as Names` is only safe when the themes are named `'light'` and
83
+ * `'dark'`. Callers that use custom theme names must validate the result against `themes` —
84
+ * both `ThemeTransitionProvider` (for `initialTheme="system"`) and `setTheme`
85
+ * (for `setTheme('system')`) perform this validation and throw a clear error if the
86
+ * resolved name is not a registered theme.
87
+ *
88
+ * @internal
89
+ */
90
+ function mapSchemeToTheme<Names extends string>(
91
+ scheme: 'light' | 'dark',
92
+ mapping?: SystemThemeMap<Names>,
93
+ ): Names {
94
+ return mapping?.[scheme] ?? (scheme as Names);
95
+ }
96
+
97
+ /**
98
+ * Reads the current OS appearance and maps it to a theme name.
99
+ *
100
+ * @internal Convenience wrapper combining {@link normalizeScheme} and {@link mapSchemeToTheme}.
101
+ */
102
+ function resolveSystemTheme<Names extends string>(
103
+ mapping?: SystemThemeMap<Names>,
104
+ fallbackScheme?: 'light' | 'dark',
105
+ ): Names {
106
+ return mapSchemeToTheme<Names>(normalizeScheme(Appearance.getColorScheme(), fallbackScheme), mapping);
107
+ }
108
+
109
+ /**
110
+ * Creates the React Context and provider component for a given theme configuration.
111
+ *
112
+ * @internal Used by {@link createThemeTransition}; not part of the public API.
113
+ */
114
+ export function createProviderAndContext<
115
+ T extends Record<string, ThemeDefinition>,
116
+ >(config: ThemeTransitionConfig<T>) {
117
+ const {
118
+ themes, duration = 350, systemThemeMap, darkThemes: darkThemesConfig,
119
+ onTransitionStart: configOnTransitionStart,
120
+ onTransitionEnd: configOnTransitionEnd,
121
+ onThemeChange,
122
+ } = config;
123
+
124
+ const darkThemeSet = new Set<string>(
125
+ darkThemesConfig ?? (systemThemeMap ? [systemThemeMap.dark] : ['dark']),
126
+ );
127
+
128
+ const schemeOf = (name: string): 'light' | 'dark' => darkThemeSet.has(name) ? 'dark' : 'light';
129
+
130
+ type Names = ThemeNames<T>;
131
+ type Tokens = TokenNames<T>;
132
+
133
+ const Context = createContext<UseThemeResult<Tokens, Names> | null>(null);
134
+
135
+ function getColors(name: Names): Record<Tokens, string> {
136
+ return { ...themes[name] } as Record<Tokens, string>;
137
+ }
138
+
139
+ function ThemeTransitionProvider({
140
+ children,
141
+ initialTheme,
142
+ }: {
143
+ children: React.ReactNode;
144
+ initialTheme: Names | 'system';
145
+ }) {
146
+ const [activeTheme, setActiveTheme] = useState<{ colors: Record<Tokens, string>; name: Names }>(() => {
147
+ const isInitialSystem = initialTheme === 'system';
148
+ const startTheme = isInitialSystem
149
+ ? resolveSystemTheme<Names>(systemThemeMap)
150
+ : initialTheme;
151
+
152
+ if (!(startTheme in themes)) {
153
+ throw new Error(
154
+ `${TAG} initialTheme resolved to "${startTheme}" which does not exist in themes.${
155
+ isInitialSystem ? ' Provide `systemThemeMap` in the config to map OS appearance to your theme names.' : ''
156
+ }`,
157
+ );
158
+ }
159
+
160
+ return { colors: getColors(startTheme), name: startTheme };
161
+ });
162
+
163
+ const targetThemeRef = useRef(activeTheme.name);
164
+ const rootRef = useRef<View>(null);
165
+ const transitioningRef = useRef(false);
166
+ // Guards async callbacks against running after unmount.
167
+ const mountedRef = useRef(true);
168
+ const [isTransitioning, setIsTransitioning] = useState(false);
169
+
170
+ const systemModeRef = useRef(initialTheme === 'system');
171
+ // State mirror of systemModeRef — triggers the Appearance.setColorScheme effect.
172
+ const [isSystemMode, setIsSystemMode] = useState(initialTheme === 'system');
173
+ const appStateRef = useRef(AppState.currentState);
174
+ // Stores a pending OS scheme change that arrived while a transition was
175
+ // running (and setTheme was rejected). Read by finishTransition.
176
+ const pendingSchemeRef = useRef<'light' | 'dark' | null>(null);
177
+
178
+ // Blocks touches within one native frame, without waiting for a React re-render.
179
+ const isBlocking = useSharedValue(false);
180
+ const blockerProps = useAnimatedProps(() => ({
181
+ pointerEvents: isBlocking.value ? 'auto' as const : 'none' as const,
182
+ }));
183
+
184
+ // State (not ref) so unsetting it unmounts the Image, freeing the captured bitmap.
185
+ const [overlayUri, setOverlayUri] = useState<string | null>(null);
186
+ const overlayOpacity = useSharedValue(0);
187
+ // Stable reference prevents Reanimated from re-processing the style on React re-renders.
188
+ const overlayStyle = useMemo(() => ({ opacity: overlayOpacity }), [overlayOpacity]);
189
+ // Settled when the overlay Image fires onLoad (resolve) or onError (reject).
190
+ const overlayDecodeRef = useRef<{ resolve: () => void; reject: () => void } | null>(null);
191
+ const overlaySource = useMemo(() => overlayUri ? { uri: overlayUri } : undefined, [overlayUri]);
192
+ const onOverlayLoad = useCallback(() => {
193
+ overlayDecodeRef.current?.resolve();
194
+ }, []);
195
+ const onOverlayError = useCallback(() => {
196
+ overlayDecodeRef.current?.reject();
197
+ }, []);
198
+
199
+ useEffect(() => {
200
+ mountedRef.current = true;
201
+ return () => {
202
+ mountedRef.current = false;
203
+ };
204
+ }, []);
205
+
206
+ // Keep native UI elements (alerts, date pickers, keyboards) in sync.
207
+ // Only applies in manual mode — in system mode the OS drives native UI
208
+ // via 'unspecified' (set once by setTheme when entering system mode).
209
+ useEffect(() => {
210
+ if (isSystemMode) return;
211
+ if (isTransitioning) return;
212
+ Appearance.setColorScheme(schemeOf(activeTheme.name));
213
+ }, [isSystemMode, activeTheme.name, isTransitioning]);
214
+
215
+ const resetTransition = useCallback(() => {
216
+ transitioningRef.current = false;
217
+ isBlocking.value = false;
218
+ setIsTransitioning(false);
219
+ setOverlayUri(null);
220
+ }, [isBlocking]);
221
+
222
+ const runTransition = useCallback(async (name: Names, options?: SetThemeOptions<Names>) => {
223
+ try {
224
+ // Two frames so the JS → Shadow Tree → Native UI pipeline fully paints
225
+ // any pending state changes before the screenshot. useTheme({ initialSelection })
226
+ // adds its own requestAnimationFrame before calling setTheme, giving 3
227
+ // total frames — enough for React commit + native paint on 120Hz displays.
228
+ await waitFrames(2);
229
+ if (!mountedRef.current) return;
230
+
231
+ const uri = await captureRef(rootRef, { format: 'jpg', quality: 0.8 });
232
+ if (!mountedRef.current) return;
233
+
234
+ overlayOpacity.set(1);
235
+
236
+ await new Promise<void>((resolve, reject) => {
237
+ overlayDecodeRef.current = { resolve, reject };
238
+ setOverlayUri(uri);
239
+ });
240
+ if (!mountedRef.current) return;
241
+
242
+ await waitFrames(1);
243
+ if (!mountedRef.current) return;
244
+
245
+ // Deferred until the overlay covers the screen so the re-render
246
+ // doesn't flash state-dependent visuals before the screenshot hides them.
247
+ setIsTransitioning(true);
248
+
249
+ setActiveTheme({ colors: getColors(name), name });
250
+
251
+ // Wait for React to commit the new theme under the still-opaque overlay.
252
+ await waitFrames(1);
253
+ if (!mountedRef.current) return;
254
+
255
+ const finishTransition = () => {
256
+ if (!mountedRef.current) return;
257
+ resetTransition();
258
+ safeCall('config onTransitionEnd', configOnTransitionEnd, name);
259
+ safeCall('per-call onTransitionEnd', options?.onTransitionEnd, name);
260
+ safeCall('config onThemeChange', onThemeChange, name);
261
+
262
+ // Reconcile: if the OS appearance changed while the transition was
263
+ // running (stored in pendingSchemeRef by the listener), apply it now.
264
+ if (systemModeRef.current && pendingSchemeRef.current !== null) {
265
+ const resolved = mapSchemeToTheme<Names>(pendingSchemeRef.current, systemThemeMap);
266
+ pendingSchemeRef.current = null;
267
+ if (resolved in themes && resolved !== name) {
268
+ targetThemeRef.current = resolved;
269
+ setActiveTheme({ colors: getColors(resolved), name: resolved });
270
+ safeCall('config onThemeChange', onThemeChange, resolved);
271
+ }
272
+ }
273
+ };
274
+
275
+ overlayOpacity.set(withTiming(0, { duration }, (finished) => {
276
+ 'worklet';
277
+ if (finished) scheduleOnRN(finishTransition);
278
+ }));
279
+ } catch (error) {
280
+ // If capture fails, apply theme instantly — no animation beats a stuck overlay.
281
+ console.warn(
282
+ `${TAG} Failed to capture screenshot. Falling back to instant theme switch.`,
283
+ error,
284
+ );
285
+ if (!mountedRef.current) return;
286
+ setActiveTheme({ colors: getColors(name), name });
287
+ overlayOpacity.set(0);
288
+ resetTransition();
289
+ safeCall('config onThemeChange', onThemeChange, name);
290
+ }
291
+ }, [overlayOpacity, resetTransition]);
292
+
293
+ const setTheme = useCallback((name: Names | 'system', options?: SetThemeOptions<Names>): boolean => {
294
+ // When transitioning from manual to system mode, Android's getColorScheme()
295
+ // returns stale values synchronously after setColorScheme('unspecified').
296
+ // Clear the override and defer resolution by one frame so native settles.
297
+ if (name === 'system' && !systemModeRef.current) {
298
+ if (transitioningRef.current) return false;
299
+
300
+ // Don't set systemModeRef yet — while it's false the Appearance
301
+ // listener guard (`!systemModeRef.current`) naturally ignores
302
+ // stale events Android fires after setColorScheme('unspecified').
303
+ setIsSystemMode(true);
304
+ Appearance.setColorScheme('unspecified');
305
+
306
+ requestAnimationFrame(() => {
307
+ if (!mountedRef.current) return;
308
+ systemModeRef.current = true;
309
+ setTheme('system', options);
310
+ });
311
+ return true;
312
+ }
313
+
314
+ const resolvedTheme = name === 'system'
315
+ // When Android returns 'unspecified' (override matched OS, no config change),
316
+ // infer the OS scheme from the current theme's darkness classification.
317
+ ? resolveSystemTheme<Names>(systemThemeMap, schemeOf(targetThemeRef.current))
318
+ : name;
319
+
320
+ if (!(resolvedTheme in themes)) {
321
+ const resolutionHint = name === 'system'
322
+ ? ' Provide `systemThemeMap` in the config to map OS appearance to your theme names.'
323
+ : '';
324
+ throw new Error(
325
+ `${TAG} setTheme("${name}") resolved to "${resolvedTheme}" which does not exist in themes.${resolutionHint}`,
326
+ );
327
+ }
328
+
329
+ if (transitioningRef.current) return false;
330
+
331
+ // Set system mode AFTER the transition guard so a rejected call during an ongoing
332
+ // transition doesn't silently activate system-following mode.
333
+ const wasSystemMode = systemModeRef.current;
334
+ systemModeRef.current = name === 'system';
335
+
336
+ // Sync state so the Appearance.setColorScheme effect re-runs.
337
+ if (systemModeRef.current !== wasSystemMode) {
338
+ setIsSystemMode(systemModeRef.current);
339
+ }
340
+
341
+ if (resolvedTheme === targetThemeRef.current) {
342
+ // Switching between manual and system mode is a valid change even when
343
+ // the resolved theme is the same — return true so select() keeps the
344
+ // new selection instead of reverting.
345
+ return wasSystemMode !== systemModeRef.current;
346
+ }
347
+
348
+ targetThemeRef.current = resolvedTheme;
349
+
350
+ if (options?.animated === false) {
351
+ setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme });
352
+ safeCall('config onThemeChange', onThemeChange, resolvedTheme);
353
+ return true;
354
+ }
355
+
356
+ // Block touches and mark as transitioning BEFORE firing user callbacks to prevent
357
+ // re-entrant setTheme calls from starting a concurrent transition.
358
+ transitioningRef.current = true;
359
+ isBlocking.value = true;
360
+
361
+ try {
362
+ configOnTransitionStart?.(resolvedTheme);
363
+ options?.onTransitionStart?.(resolvedTheme);
364
+ } catch (e) {
365
+ // Reset guards so a callback error doesn't permanently block transitions.
366
+ resetTransition();
367
+ throw e;
368
+ }
369
+ // isTransitioning is set inside runTransition(), AFTER captureRef, so no React
370
+ // re-render can alter the native view before the screenshot is taken.
371
+ runTransition(resolvedTheme, options).catch(() => {});
372
+ return true;
373
+ }, [isBlocking, resetTransition, runTransition]);
374
+
375
+ useEffect(() => {
376
+ const appearanceSub = Appearance.addChangeListener(({ colorScheme }) => {
377
+ if (!systemModeRef.current) return;
378
+ if (transitioningRef.current) {
379
+ // Can't start a new transition now; store for reconciliation.
380
+ pendingSchemeRef.current = normalizeScheme(colorScheme);
381
+ return;
382
+ }
383
+ if (appStateRef.current === 'active') {
384
+ setTheme('system');
385
+ } else {
386
+ // Background: apply directly (works on Android where JS keeps running).
387
+ // On iOS the JS thread is suspended so this commit may be deferred —
388
+ // the AppState handler below re-applies on foreground return as a safety net.
389
+ const resolved = mapSchemeToTheme<Names>(normalizeScheme(colorScheme), systemThemeMap);
390
+ if (!(resolved in themes) || resolved === targetThemeRef.current) return;
391
+ targetThemeRef.current = resolved;
392
+ setActiveTheme({ colors: getColors(resolved), name: resolved });
393
+ safeCall('config onThemeChange', onThemeChange, resolved);
394
+ }
395
+ });
396
+
397
+ // Re-read OS scheme on foreground return. Catches two cases:
398
+ // 1. iOS never delivered Appearance events while suspended.
399
+ // 2. The BG setActiveTheme commit was deferred by iOS suspension.
400
+ const appSub = AppState.addEventListener('change', (next) => {
401
+ if (appStateRef.current !== 'active' && next === 'active' && systemModeRef.current) {
402
+ // Re-read OS scheme and force setActiveTheme. Even if the BG path
403
+ // already set targetThemeRef, iOS may have deferred the React commit.
404
+ // Calling setActiveTheme again guarantees an immediate commit now
405
+ // that the app is active.
406
+ const resolved = resolveSystemTheme<Names>(systemThemeMap, schemeOf(targetThemeRef.current));
407
+ if (resolved in themes) {
408
+ const changed = resolved !== targetThemeRef.current;
409
+ targetThemeRef.current = resolved;
410
+ setActiveTheme({ colors: getColors(resolved), name: resolved });
411
+ if (changed) safeCall('config onThemeChange', onThemeChange, resolved);
412
+ }
413
+ }
414
+ appStateRef.current = next;
415
+ });
416
+
417
+ return () => {
418
+ appearanceSub.remove();
419
+ appSub.remove();
420
+ };
421
+ }, [setTheme]);
422
+
423
+ const contextValue = useMemo(() => ({
424
+ colors: activeTheme.colors, name: activeTheme.name, setTheme, isTransitioning,
425
+ }), [activeTheme, setTheme, isTransitioning]);
426
+
427
+ return (
428
+ <Context.Provider value={contextValue}>
429
+ {/* collapsable={false} prevents Android from flattening the view, which breaks captureRef. */}
430
+ <View ref={rootRef} style={ROOT_STYLE} collapsable={false}>
431
+ {children}
432
+ <Animated.View style={ABSOLUTE_FILL} animatedProps={blockerProps} />
433
+ {/* Always mounted so the shared value is permanently connected — no mount-time race. */}
434
+ <Animated.View style={[ABSOLUTE_FILL, overlayStyle]} pointerEvents="none">
435
+ {overlayUri != null ? (
436
+ <Image source={overlaySource} style={ABSOLUTE_FILL} resizeMode="cover" fadeDuration={0} onLoad={onOverlayLoad} onError={onOverlayError} />
437
+ ) : null}
438
+ </Animated.View>
439
+ </View>
440
+ </Context.Provider>
441
+ );
442
+ }
443
+
444
+ return { Context, ThemeTransitionProvider };
445
+ }