react-native-theme-transition 1.0.4 → 1.0.6

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.
@@ -9,33 +9,37 @@
9
9
  * @module
10
10
  */
11
11
 
12
- import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react';
13
- import { Appearance, AppState, Image, View } from 'react-native';
14
- import Animated, {
15
- useAnimatedProps,
16
- useSharedValue,
17
- withTiming,
18
- } from 'react-native-reanimated';
19
- import { captureRef } from 'react-native-view-shot';
20
- import { scheduleOnRN } from 'react-native-worklets';
12
+ import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react'
13
+ import { Appearance, AppState, Image, View } from 'react-native'
14
+ import Animated, { useAnimatedProps, useSharedValue, withTiming } from 'react-native-reanimated'
15
+ import { captureRef } from 'react-native-view-shot'
16
+ import { scheduleOnRN } from 'react-native-worklets'
17
+ import { TAG } from './constants'
21
18
  import type {
22
- ThemeTransitionConfig,
23
- UseThemeResult,
24
19
  SetThemeOptions,
25
20
  SystemThemeMap,
26
21
  ThemeDefinition,
27
22
  ThemeNames,
23
+ ThemeTransitionConfig,
28
24
  TokenNames,
29
- } from './types';
30
- import { TAG } from './constants';
25
+ UseThemeResult,
26
+ } from './types'
31
27
 
32
- const ABSOLUTE_FILL = { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 } as const;
28
+ const ABSOLUTE_FILL = { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 } as const
33
29
  // Avoids layout clipping on certain Android API levels.
34
- const ROOT_STYLE = { flex: 1 } as const;
30
+ const ROOT_STYLE = { flex: 1 } as const
35
31
 
36
32
  /** Calls `fn` and swallows errors with a console.warn tagged by `label`. */
37
- function safeCall<A extends unknown[]>(label: string, fn: ((...args: A) => void) | undefined, ...args: A): void {
38
- try { fn?.(...args); } catch (e) { console.warn(`${TAG} ${label} threw:`, e); }
33
+ function safeCall<A extends unknown[]>(
34
+ label: string,
35
+ fn: ((...args: A) => void) | undefined,
36
+ ...args: A
37
+ ): void {
38
+ try {
39
+ fn?.(...args)
40
+ } catch (e) {
41
+ console.warn(`${TAG} ${label} threw:`, e)
42
+ }
39
43
  }
40
44
 
41
45
  /**
@@ -55,13 +59,13 @@ function safeCall<A extends unknown[]>(label: string, fn: ((...args: A) => void)
55
59
  */
56
60
  function waitFrames(n: number): Promise<void> {
57
61
  return new Promise((resolve) => {
58
- let remaining = n;
62
+ let remaining = n
59
63
  const tick = () => {
60
- if (--remaining <= 0) resolve();
61
- else requestAnimationFrame(tick);
62
- };
63
- requestAnimationFrame(tick);
64
- });
64
+ if (--remaining <= 0) resolve()
65
+ else requestAnimationFrame(tick)
66
+ }
67
+ requestAnimationFrame(tick)
68
+ })
65
69
  }
66
70
 
67
71
  /**
@@ -74,10 +78,13 @@ function waitFrames(n: number): Promise<void> {
74
78
  *
75
79
  * @internal
76
80
  */
77
- function normalizeScheme(colorScheme?: string | null, fallback: 'light' | 'dark' = 'light'): 'light' | 'dark' {
78
- if (colorScheme === 'dark') return 'dark';
79
- if (colorScheme === 'light') return 'light';
80
- return fallback;
81
+ function normalizeScheme(
82
+ colorScheme?: string | null,
83
+ fallback: 'light' | 'dark' = 'light',
84
+ ): 'light' | 'dark' {
85
+ if (colorScheme === 'dark') return 'dark'
86
+ if (colorScheme === 'light') return 'light'
87
+ return fallback
81
88
  }
82
89
 
83
90
  /**
@@ -96,7 +103,7 @@ function mapSchemeToTheme<Names extends string>(
96
103
  scheme: 'light' | 'dark',
97
104
  mapping?: SystemThemeMap<Names>,
98
105
  ): Names {
99
- return mapping?.[scheme] ?? (scheme as Names);
106
+ return mapping?.[scheme] ?? (scheme as Names)
100
107
  }
101
108
 
102
109
  /**
@@ -108,7 +115,10 @@ function resolveSystemTheme<Names extends string>(
108
115
  mapping?: SystemThemeMap<Names>,
109
116
  fallbackScheme?: 'light' | 'dark',
110
117
  ): Names {
111
- return mapSchemeToTheme<Names>(normalizeScheme(Appearance.getColorScheme(), fallbackScheme), mapping);
118
+ return mapSchemeToTheme<Names>(
119
+ normalizeScheme(Appearance.getColorScheme(), fallbackScheme),
120
+ mapping,
121
+ )
112
122
  }
113
123
 
114
124
  /**
@@ -116,334 +126,363 @@ function resolveSystemTheme<Names extends string>(
116
126
  *
117
127
  * @internal Used by {@link createThemeTransition}; not part of the public API.
118
128
  */
119
- export function createProviderAndContext<
120
- T extends Record<string, ThemeDefinition>,
121
- >(config: ThemeTransitionConfig<T>) {
129
+ export function createProviderAndContext<T extends Record<string, ThemeDefinition>>(
130
+ config: ThemeTransitionConfig<T>,
131
+ ) {
122
132
  const {
123
- themes, duration = 350, systemThemeMap, darkThemes: darkThemesConfig,
133
+ themes,
134
+ duration = 350,
135
+ systemThemeMap,
136
+ darkThemes: darkThemesConfig,
124
137
  onTransitionStart: configOnTransitionStart,
125
138
  onTransitionEnd: configOnTransitionEnd,
126
139
  onThemeChange,
127
- } = config;
140
+ } = config
128
141
 
129
142
  const darkThemeSet = new Set<string>(
130
143
  darkThemesConfig ?? (systemThemeMap ? [systemThemeMap.dark] : ['dark']),
131
- );
144
+ )
132
145
 
133
- const schemeOf = (name: string): 'light' | 'dark' => darkThemeSet.has(name) ? 'dark' : 'light';
146
+ const schemeOf = (name: string): 'light' | 'dark' => (darkThemeSet.has(name) ? 'dark' : 'light')
134
147
 
135
- type Names = ThemeNames<T>;
136
- type Tokens = TokenNames<T>;
148
+ type Names = ThemeNames<T>
149
+ type Tokens = TokenNames<T>
137
150
 
138
- const Context = createContext<UseThemeResult<Tokens, Names> | null>(null);
151
+ const Context = createContext<UseThemeResult<Tokens, Names> | null>(null)
139
152
 
140
153
  function getColors(name: Names): Record<Tokens, string> {
141
- return { ...themes[name] } as Record<Tokens, string>;
154
+ return { ...themes[name] } as Record<Tokens, string>
142
155
  }
143
156
 
144
157
  function ThemeTransitionProvider({
145
158
  children,
146
159
  initialTheme,
147
160
  }: {
148
- children: React.ReactNode;
149
- initialTheme: Names | 'system';
161
+ children: React.ReactNode
162
+ initialTheme: Names | 'system'
150
163
  }) {
151
- const [activeTheme, setActiveTheme] = useState<{ colors: Record<Tokens, string>; name: Names }>(() => {
152
- const isInitialSystem = initialTheme === 'system';
153
- const startTheme = isInitialSystem
154
- ? resolveSystemTheme<Names>(systemThemeMap)
155
- : initialTheme;
156
-
157
- if (!(startTheme in themes)) {
158
- throw new Error(
159
- `${TAG} initialTheme resolved to "${startTheme}" which does not exist in themes.${
160
- isInitialSystem ? ' Provide `systemThemeMap` in the config to map OS appearance to your theme names.' : ''
161
- }`,
162
- );
163
- }
164
+ const [activeTheme, setActiveTheme] = useState<{ colors: Record<Tokens, string>; name: Names }>(
165
+ () => {
166
+ const isInitialSystem = initialTheme === 'system'
167
+ const startTheme = isInitialSystem
168
+ ? resolveSystemTheme<Names>(systemThemeMap)
169
+ : initialTheme
170
+
171
+ if (!(startTheme in themes)) {
172
+ throw new Error(
173
+ `${TAG} initialTheme resolved to "${startTheme}" which does not exist in themes.${
174
+ isInitialSystem
175
+ ? ' Provide `systemThemeMap` in the config to map OS appearance to your theme names.'
176
+ : ''
177
+ }`,
178
+ )
179
+ }
164
180
 
165
- return { colors: getColors(startTheme), name: startTheme };
166
- });
181
+ return { colors: getColors(startTheme), name: startTheme }
182
+ },
183
+ )
167
184
 
168
- const targetThemeRef = useRef(activeTheme.name);
169
- const rootRef = useRef<View>(null);
170
- const transitioningRef = useRef(false);
185
+ const targetThemeRef = useRef(activeTheme.name)
186
+ const rootRef = useRef<View>(null)
187
+ const transitioningRef = useRef(false)
171
188
  // Guards async callbacks against running after unmount.
172
- const mountedRef = useRef(true);
173
- const [isTransitioning, setIsTransitioning] = useState(false);
189
+ const mountedRef = useRef(true)
190
+ const [isTransitioning, setIsTransitioning] = useState(false)
174
191
 
175
- const systemModeRef = useRef(initialTheme === 'system');
192
+ const systemModeRef = useRef(initialTheme === 'system')
176
193
  // State mirror of systemModeRef — drives the Appearance.setColorScheme effect.
177
- const [isSystemMode, setIsSystemMode] = useState(initialTheme === 'system');
178
- const appStateRef = useRef(AppState.currentState);
194
+ const [isSystemMode, setIsSystemMode] = useState(initialTheme === 'system')
195
+ const appStateRef = useRef(AppState.currentState)
179
196
  // Pending OS scheme change that arrived mid-transition. Applied by finishTransition.
180
- const pendingSchemeRef = useRef<'light' | 'dark' | null>(null);
197
+ const pendingSchemeRef = useRef<'light' | 'dark' | null>(null)
181
198
  // Last observed OS scheme — lets manual→system resolve without calling
182
199
  // setColorScheme('unspecified') (which flashes the Android status bar).
183
200
  const lastKnownOsSchemeRef = useRef<'light' | 'dark'>(
184
201
  normalizeScheme(Appearance.getColorScheme()),
185
- );
202
+ )
186
203
  // Manual override scheme while a deferred setColorScheme('unspecified') is pending.
187
204
  // finishTransition uses this to correct the theme if the OS scheme diverged.
188
- const deferredSystemRestoreRef = useRef<'light' | 'dark' | null>(null);
205
+ const deferredSystemRestoreRef = useRef<'light' | 'dark' | null>(null)
189
206
 
190
207
  // SharedValue (not state) so touch blocking takes effect on the native thread
191
208
  // within one frame, without waiting for a React re-render cycle.
192
- const isBlocking = useSharedValue(false);
209
+ const isBlocking = useSharedValue(false)
193
210
  const blockerProps = useAnimatedProps(() => ({
194
- pointerEvents: isBlocking.value ? 'auto' as const : 'none' as const,
195
- }));
211
+ pointerEvents: isBlocking.value ? ('auto' as const) : ('none' as const),
212
+ }))
196
213
 
197
214
  // State (not ref) so unsetting it unmounts the Image, freeing the captured bitmap.
198
- const [overlayUri, setOverlayUri] = useState<string | null>(null);
199
- const overlayOpacity = useSharedValue(0);
215
+ const [overlayUri, setOverlayUri] = useState<string | null>(null)
216
+ const overlayOpacity = useSharedValue(0)
200
217
  // Stable ref so Reanimated doesn't re-process the style on every render.
201
- const overlayStyle = useMemo(() => ({ opacity: overlayOpacity }), [overlayOpacity]);
202
- const overlayDecodeRef = useRef<{ resolve: () => void; reject: () => void } | null>(null);
203
- const overlaySource = useMemo(() => overlayUri ? { uri: overlayUri } : undefined, [overlayUri]);
218
+ const overlayStyle = useMemo(() => ({ opacity: overlayOpacity }), [overlayOpacity])
219
+ const overlayDecodeRef = useRef<{ resolve: () => void; reject: () => void } | null>(null)
220
+ const overlaySource = useMemo(
221
+ () => (overlayUri ? { uri: overlayUri } : undefined),
222
+ [overlayUri],
223
+ )
204
224
  const onOverlayLoad = useCallback(() => {
205
- overlayDecodeRef.current?.resolve();
206
- }, []);
225
+ overlayDecodeRef.current?.resolve()
226
+ }, [])
207
227
  const onOverlayError = useCallback(() => {
208
- overlayDecodeRef.current?.reject();
209
- }, []);
228
+ overlayDecodeRef.current?.reject()
229
+ }, [])
210
230
 
211
231
  useEffect(() => {
212
- mountedRef.current = true;
232
+ mountedRef.current = true
213
233
  return () => {
214
- mountedRef.current = false;
215
- };
216
- }, []);
234
+ mountedRef.current = false
235
+ }
236
+ }, [])
217
237
 
218
238
  // Sync native UI (alerts, keyboards) with theme. Skipped in system mode
219
239
  // where the OS drives appearance via 'unspecified'.
220
240
  useEffect(() => {
221
- if (isSystemMode) return;
222
- if (isTransitioning) return;
223
- Appearance.setColorScheme(schemeOf(activeTheme.name));
224
- }, [isSystemMode, activeTheme.name, isTransitioning]);
241
+ if (isSystemMode) return
242
+ if (isTransitioning) return
243
+ Appearance.setColorScheme(schemeOf(activeTheme.name))
244
+ }, [isSystemMode, activeTheme.name, isTransitioning])
225
245
 
226
246
  const resetTransition = useCallback(() => {
227
- transitioningRef.current = false;
228
- isBlocking.value = false;
229
- setIsTransitioning(false);
230
- setOverlayUri(null);
231
- }, [isBlocking]);
232
-
233
- const runTransition = useCallback(async (initialName: Names, options?: SetThemeOptions<Names>) => {
234
- let name: Names = initialName;
235
- try {
236
- // 2 frames for JS → Shadow Tree → Native UI to paint before capture.
237
- // useTheme's requestAnimationFrame adds a 3rd — enough for 120Hz.
238
- await waitFrames(2);
239
- if (!mountedRef.current) return;
240
-
241
- // jpg 0.8: ~30% smaller than png, no visible degradation during a cross-fade.
242
- const uri = await captureRef(rootRef, { format: 'jpg', quality: 0.8 });
243
- if (!mountedRef.current) return;
244
-
245
- overlayOpacity.set(1);
246
-
247
- await new Promise<void>((resolve, reject) => {
248
- overlayDecodeRef.current = { resolve, reject };
249
- setOverlayUri(uri);
250
- });
251
- if (!mountedRef.current) return;
252
-
253
- await waitFrames(1);
254
- if (!mountedRef.current) return;
255
-
256
- // Deferred: setting this earlier would re-render under the overlay,
257
- // flashing state-dependent visuals before the screenshot hides them.
258
- setIsTransitioning(true);
259
-
260
- setActiveTheme({ colors: getColors(name), name });
261
-
262
- // Deferred setColorScheme('unspecified') — done now while the overlay is
263
- // opaque so any theme correction (OS scheme diverged) is invisible to the user.
264
- if (deferredSystemRestoreRef.current !== null) {
265
- const manualScheme = deferredSystemRestoreRef.current;
266
-
267
- let resolved = false;
268
- const realScheme = await new Promise<'light' | 'dark'>((resolve) => {
269
- const sub = Appearance.addChangeListener(({ colorScheme }) => {
270
- if (resolved) return;
271
- resolved = true;
272
- sub.remove();
273
- resolve(normalizeScheme(colorScheme));
274
- });
275
- Appearance.setColorScheme('unspecified');
276
- // No event → OS scheme already matches the manual override.
277
- requestAnimationFrame(() => {
278
- if (resolved) return;
279
- resolved = true;
280
- sub.remove();
281
- resolve(manualScheme);
282
- });
283
- });
284
- if (!mountedRef.current) return;
285
-
286
- deferredSystemRestoreRef.current = null;
287
- lastKnownOsSchemeRef.current = realScheme;
288
-
289
- const corrected = mapSchemeToTheme<Names>(realScheme, systemThemeMap);
290
- if (corrected in themes && corrected !== name) {
291
- name = corrected as Names;
292
- targetThemeRef.current = corrected;
293
- setActiveTheme({ colors: getColors(corrected), name: corrected });
247
+ transitioningRef.current = false
248
+ isBlocking.value = false
249
+ setIsTransitioning(false)
250
+ setOverlayUri(null)
251
+ }, [isBlocking])
252
+
253
+ const runTransition = useCallback(
254
+ async (initialName: Names, options?: SetThemeOptions<Names>) => {
255
+ let name: Names = initialName
256
+ try {
257
+ // 2 frames for JS → Shadow Tree → Native UI to paint before capture.
258
+ // useTheme's requestAnimationFrame adds a 3rd — enough for 120Hz.
259
+ await waitFrames(2)
260
+ if (!mountedRef.current) return
261
+
262
+ // jpg 0.8: ~30% smaller than png, no visible degradation during a cross-fade.
263
+ const uri = await captureRef(rootRef, { format: 'jpg', quality: 0.8 })
264
+ if (!mountedRef.current) return
265
+
266
+ overlayOpacity.set(1)
267
+
268
+ await new Promise<void>((resolve, reject) => {
269
+ overlayDecodeRef.current = { resolve, reject }
270
+ setOverlayUri(uri)
271
+ })
272
+ if (!mountedRef.current) return
273
+
274
+ await waitFrames(1)
275
+ if (!mountedRef.current) return
276
+
277
+ // Deferred: setting this earlier would re-render under the overlay,
278
+ // flashing state-dependent visuals before the screenshot hides them.
279
+ setIsTransitioning(true)
280
+
281
+ setActiveTheme({ colors: getColors(name), name })
282
+
283
+ // Deferred setColorScheme('unspecified') — done now while the overlay is
284
+ // opaque so any theme correction (OS scheme diverged) is invisible to the user.
285
+ if (deferredSystemRestoreRef.current !== null) {
286
+ const manualScheme = deferredSystemRestoreRef.current
287
+
288
+ let resolved = false
289
+ const realScheme = await new Promise<'light' | 'dark'>((resolve) => {
290
+ const sub = Appearance.addChangeListener(({ colorScheme }) => {
291
+ if (resolved) return
292
+ resolved = true
293
+ sub.remove()
294
+ resolve(normalizeScheme(colorScheme))
295
+ })
296
+ Appearance.setColorScheme('unspecified')
297
+ // No event → OS scheme already matches the manual override.
298
+ requestAnimationFrame(() => {
299
+ if (resolved) return
300
+ resolved = true
301
+ sub.remove()
302
+ resolve(manualScheme)
303
+ })
304
+ })
305
+ if (!mountedRef.current) return
306
+
307
+ deferredSystemRestoreRef.current = null
308
+ lastKnownOsSchemeRef.current = realScheme
309
+
310
+ const corrected = mapSchemeToTheme<Names>(realScheme, systemThemeMap)
311
+ if (corrected in themes && corrected !== name) {
312
+ name = corrected as Names
313
+ targetThemeRef.current = corrected
314
+ setActiveTheme({ colors: getColors(corrected), name: corrected })
315
+ }
294
316
  }
295
- }
296
317
 
297
- await waitFrames(1);
298
- if (!mountedRef.current) return;
299
-
300
- const finishTransition = () => {
301
- if (!mountedRef.current) return;
302
- resetTransition();
303
- safeCall('config onTransitionEnd', configOnTransitionEnd, name);
304
- safeCall('per-call onTransitionEnd', options?.onTransitionEnd, name);
305
- safeCall('config onThemeChange', onThemeChange, name);
306
-
307
- // Apply any OS scheme change that arrived mid-transition.
308
- if (systemModeRef.current && pendingSchemeRef.current !== null) {
309
- const resolved = mapSchemeToTheme<Names>(pendingSchemeRef.current, systemThemeMap);
310
- pendingSchemeRef.current = null;
311
- if (resolved in themes && resolved !== name) {
312
- targetThemeRef.current = resolved;
313
- setActiveTheme({ colors: getColors(resolved), name: resolved });
314
- safeCall('config onThemeChange', onThemeChange, resolved);
318
+ await waitFrames(1)
319
+ if (!mountedRef.current) return
320
+
321
+ const finishTransition = () => {
322
+ if (!mountedRef.current) return
323
+ resetTransition()
324
+ safeCall('config onTransitionEnd', configOnTransitionEnd, name)
325
+ safeCall('per-call onTransitionEnd', options?.onTransitionEnd, name)
326
+ safeCall('config onThemeChange', onThemeChange, name)
327
+
328
+ // Apply any OS scheme change that arrived mid-transition.
329
+ if (systemModeRef.current && pendingSchemeRef.current !== null) {
330
+ const resolved = mapSchemeToTheme<Names>(pendingSchemeRef.current, systemThemeMap)
331
+ pendingSchemeRef.current = null
332
+ if (resolved in themes && resolved !== name) {
333
+ targetThemeRef.current = resolved
334
+ setActiveTheme({ colors: getColors(resolved), name: resolved })
335
+ safeCall('config onThemeChange', onThemeChange, resolved)
336
+ }
315
337
  }
316
338
  }
317
- };
318
-
319
- overlayOpacity.set(withTiming(0, { duration }, (finished) => {
320
- 'worklet';
321
- if (finished) scheduleOnRN(finishTransition);
322
- }));
323
- } catch (error) {
324
- // If capture fails, apply theme instantly — no animation beats a stuck overlay.
325
- console.warn(
326
- `${TAG} Failed to capture screenshot. Falling back to instant theme switch.`,
327
- error,
328
- );
329
- if (!mountedRef.current) return;
330
- setActiveTheme({ colors: getColors(name), name });
331
- overlayOpacity.set(0);
332
- resetTransition();
333
- safeCall('config onThemeChange', onThemeChange, name);
334
- }
335
- }, [overlayOpacity, resetTransition]);
336
-
337
- const setTheme = useCallback((name: Names | 'system', options?: SetThemeOptions<Names>): boolean => {
338
- // Manual→system: resolve from cached OS scheme to avoid the Android
339
- // status bar flash that setColorScheme('unspecified') causes pre-overlay.
340
- if (name === 'system' && !systemModeRef.current) {
341
- if (transitioningRef.current) return false;
342
-
343
- setIsSystemMode(true);
344
- systemModeRef.current = true;
345
- deferredSystemRestoreRef.current = schemeOf(targetThemeRef.current);
346
- return setTheme('system', options);
347
- }
348
339
 
349
- const resolvedTheme = name === 'system'
350
- ? mapSchemeToTheme<Names>(lastKnownOsSchemeRef.current, systemThemeMap)
351
- : name;
352
- if (!(resolvedTheme in themes)) {
353
- const resolutionHint = name === 'system'
354
- ? ' Provide `systemThemeMap` in the config to map OS appearance to your theme names.'
355
- : '';
356
- throw new Error(
357
- `${TAG} setTheme("${name}") resolved to "${resolvedTheme}" which does not exist in themes.${resolutionHint}`,
358
- );
359
- }
340
+ overlayOpacity.set(
341
+ withTiming(0, { duration }, (finished) => {
342
+ 'worklet'
343
+ if (finished) scheduleOnRN(finishTransition)
344
+ }),
345
+ )
346
+ } catch (error) {
347
+ // If capture fails, apply theme instantly — no animation beats a stuck overlay.
348
+ console.warn(
349
+ `${TAG} Failed to capture screenshot. Falling back to instant theme switch.`,
350
+ error,
351
+ )
352
+ if (!mountedRef.current) return
353
+ setActiveTheme({ colors: getColors(name), name })
354
+ overlayOpacity.set(0)
355
+ resetTransition()
356
+ safeCall('config onThemeChange', onThemeChange, name)
357
+ }
358
+ },
359
+ [overlayOpacity, resetTransition],
360
+ )
361
+
362
+ const setTheme = useCallback(
363
+ (name: Names | 'system', options?: SetThemeOptions<Names>): boolean => {
364
+ // Manual→system: resolve from cached OS scheme to avoid the Android
365
+ // status bar flash that setColorScheme('unspecified') causes pre-overlay.
366
+ if (name === 'system' && !systemModeRef.current) {
367
+ if (transitioningRef.current) return false
368
+
369
+ setIsSystemMode(true)
370
+ systemModeRef.current = true
371
+ deferredSystemRestoreRef.current = schemeOf(targetThemeRef.current)
372
+ return setTheme('system', options)
373
+ }
360
374
 
361
- if (transitioningRef.current) return false;
375
+ const resolvedTheme =
376
+ name === 'system'
377
+ ? mapSchemeToTheme<Names>(lastKnownOsSchemeRef.current, systemThemeMap)
378
+ : name
379
+ if (!(resolvedTheme in themes)) {
380
+ const resolutionHint =
381
+ name === 'system'
382
+ ? ' Provide `systemThemeMap` in the config to map OS appearance to your theme names.'
383
+ : ''
384
+ throw new Error(
385
+ `${TAG} setTheme("${name}") resolved to "${resolvedTheme}" which does not exist in themes.${resolutionHint}`,
386
+ )
387
+ }
362
388
 
363
- // After transition guard — a rejected call must not activate system mode.
364
- const wasSystemMode = systemModeRef.current;
365
- systemModeRef.current = name === 'system';
389
+ if (transitioningRef.current) return false
366
390
 
367
- if (systemModeRef.current !== wasSystemMode) {
368
- setIsSystemMode(systemModeRef.current);
369
- }
391
+ // After transition guard — a rejected call must not activate system mode.
392
+ const wasSystemMode = systemModeRef.current
393
+ systemModeRef.current = name === 'system'
370
394
 
371
- if (resolvedTheme === targetThemeRef.current) {
372
- // Manual↔system mode switch is valid even when the resolved theme matches —
373
- // returning true prevents select() from reverting the user's selection.
374
- return wasSystemMode !== systemModeRef.current;
375
- }
395
+ if (systemModeRef.current !== wasSystemMode) {
396
+ setIsSystemMode(systemModeRef.current)
397
+ }
376
398
 
377
- targetThemeRef.current = resolvedTheme;
399
+ if (resolvedTheme === targetThemeRef.current) {
400
+ // Manual↔system mode switch is valid even when the resolved theme matches —
401
+ // returning true prevents select() from reverting the user's selection.
402
+ return wasSystemMode !== systemModeRef.current
403
+ }
378
404
 
379
- if (options?.animated === false) {
380
- setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme });
381
- safeCall('config onThemeChange', onThemeChange, resolvedTheme);
382
- return true;
383
- }
405
+ targetThemeRef.current = resolvedTheme
384
406
 
385
- // Block before user callbacks to prevent re-entrant setTheme.
386
- transitioningRef.current = true;
387
- isBlocking.value = true;
388
-
389
- try {
390
- configOnTransitionStart?.(resolvedTheme);
391
- options?.onTransitionStart?.(resolvedTheme);
392
- } catch (e) {
393
- // Reset guards so a callback error doesn't permanently block transitions.
394
- resetTransition();
395
- throw e;
396
- }
397
- runTransition(resolvedTheme, options).catch(() => {});
398
- return true;
399
- }, [isBlocking, resetTransition, runTransition]);
407
+ if (options?.animated === false) {
408
+ setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme })
409
+ safeCall('config onThemeChange', onThemeChange, resolvedTheme)
410
+ return true
411
+ }
412
+
413
+ // Block before user callbacks to prevent re-entrant setTheme.
414
+ transitioningRef.current = true
415
+ isBlocking.value = true
416
+
417
+ try {
418
+ configOnTransitionStart?.(resolvedTheme)
419
+ options?.onTransitionStart?.(resolvedTheme)
420
+ } catch (e) {
421
+ // Reset guards so a callback error doesn't permanently block transitions.
422
+ resetTransition()
423
+ throw e
424
+ }
425
+ runTransition(resolvedTheme, options).catch(() => {})
426
+ return true
427
+ },
428
+ [isBlocking, resetTransition, runTransition],
429
+ )
400
430
 
401
431
  useEffect(() => {
402
432
  const appearanceSub = Appearance.addChangeListener(({ colorScheme }) => {
403
- if (!systemModeRef.current) return;
404
- lastKnownOsSchemeRef.current = normalizeScheme(colorScheme);
433
+ if (!systemModeRef.current) return
434
+ lastKnownOsSchemeRef.current = normalizeScheme(colorScheme)
405
435
  // Deferred restore listener in runTransition handles these.
406
- if (deferredSystemRestoreRef.current !== null) return;
436
+ if (deferredSystemRestoreRef.current !== null) return
407
437
  if (transitioningRef.current) {
408
- pendingSchemeRef.current = normalizeScheme(colorScheme);
409
- return;
438
+ pendingSchemeRef.current = normalizeScheme(colorScheme)
439
+ return
410
440
  }
411
441
  if (appStateRef.current === 'active') {
412
- setTheme('system');
442
+ setTheme('system')
413
443
  } else {
414
444
  // Background: apply directly. iOS may defer — AppState handler re-applies on foreground.
415
- const resolved = mapSchemeToTheme<Names>(normalizeScheme(colorScheme), systemThemeMap);
416
- if (!(resolved in themes) || resolved === targetThemeRef.current) return;
417
- targetThemeRef.current = resolved;
418
- setActiveTheme({ colors: getColors(resolved), name: resolved });
419
- safeCall('config onThemeChange', onThemeChange, resolved);
445
+ const resolved = mapSchemeToTheme<Names>(normalizeScheme(colorScheme), systemThemeMap)
446
+ if (!(resolved in themes) || resolved === targetThemeRef.current) return
447
+ targetThemeRef.current = resolved
448
+ setActiveTheme({ colors: getColors(resolved), name: resolved })
449
+ safeCall('config onThemeChange', onThemeChange, resolved)
420
450
  }
421
- });
451
+ })
422
452
 
423
453
  // Re-read OS scheme on foreground return — iOS may not deliver
424
454
  // Appearance events while suspended, or may defer the React commit.
425
455
  const appSub = AppState.addEventListener('change', (next) => {
426
456
  if (appStateRef.current !== 'active' && next === 'active' && systemModeRef.current) {
427
- const resolved = resolveSystemTheme<Names>(systemThemeMap, schemeOf(targetThemeRef.current));
457
+ const resolved = resolveSystemTheme<Names>(
458
+ systemThemeMap,
459
+ schemeOf(targetThemeRef.current),
460
+ )
428
461
  if (resolved in themes) {
429
- const changed = resolved !== targetThemeRef.current;
430
- targetThemeRef.current = resolved;
431
- setActiveTheme({ colors: getColors(resolved), name: resolved });
432
- if (changed) safeCall('config onThemeChange', onThemeChange, resolved);
462
+ const changed = resolved !== targetThemeRef.current
463
+ targetThemeRef.current = resolved
464
+ setActiveTheme({ colors: getColors(resolved), name: resolved })
465
+ if (changed) safeCall('config onThemeChange', onThemeChange, resolved)
433
466
  }
434
467
  }
435
- appStateRef.current = next;
436
- });
468
+ appStateRef.current = next
469
+ })
437
470
 
438
471
  return () => {
439
- appearanceSub.remove();
440
- appSub.remove();
441
- };
442
- }, [setTheme]);
443
-
444
- const contextValue = useMemo(() => ({
445
- colors: activeTheme.colors, name: activeTheme.name, setTheme, isTransitioning,
446
- }), [activeTheme, setTheme, isTransitioning]);
472
+ appearanceSub.remove()
473
+ appSub.remove()
474
+ }
475
+ }, [setTheme])
476
+
477
+ const contextValue = useMemo(
478
+ () => ({
479
+ colors: activeTheme.colors,
480
+ name: activeTheme.name,
481
+ setTheme,
482
+ isTransitioning,
483
+ }),
484
+ [activeTheme, setTheme, isTransitioning],
485
+ )
447
486
 
448
487
  return (
449
488
  <Context.Provider value={contextValue}>
@@ -454,13 +493,20 @@ export function createProviderAndContext<
454
493
  {/* Always mounted — avoids shared-value race on conditional mount. */}
455
494
  <Animated.View style={[ABSOLUTE_FILL, overlayStyle]} pointerEvents="none">
456
495
  {overlayUri != null ? (
457
- <Image source={overlaySource} style={ABSOLUTE_FILL} resizeMode="cover" fadeDuration={0} onLoad={onOverlayLoad} onError={onOverlayError} />
496
+ <Image
497
+ source={overlaySource}
498
+ style={ABSOLUTE_FILL}
499
+ resizeMode="cover"
500
+ fadeDuration={0}
501
+ onLoad={onOverlayLoad}
502
+ onError={onOverlayError}
503
+ />
458
504
  ) : null}
459
505
  </Animated.View>
460
506
  </View>
461
507
  </Context.Provider>
462
- );
508
+ )
463
509
  }
464
510
 
465
- return { Context, ThemeTransitionProvider };
511
+ return { Context, ThemeTransitionProvider }
466
512
  }