react-native-theme-transition 1.0.6 → 2.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.
Files changed (66) hide show
  1. package/README.md +55 -43
  2. package/README.npm.md +55 -43
  3. package/dist/constants.d.ts +1 -2
  4. package/dist/constants.d.ts.map +1 -1
  5. package/dist/constants.js +4 -0
  6. package/dist/constants.js.map +1 -1
  7. package/dist/createThemeTransition.d.ts +6 -18
  8. package/dist/createThemeTransition.d.ts.map +1 -1
  9. package/dist/createThemeTransition.js +37 -35
  10. package/dist/createThemeTransition.js.map +1 -1
  11. package/dist/index.d.ts +9 -9
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +8 -8
  14. package/dist/index.js.map +1 -1
  15. package/dist/overlay/SkiaOverlay.d.ts +17 -0
  16. package/dist/overlay/SkiaOverlay.d.ts.map +1 -0
  17. package/dist/overlay/SkiaOverlay.js +297 -0
  18. package/dist/overlay/SkiaOverlay.js.map +1 -0
  19. package/dist/overlay/captureView.d.ts +7 -0
  20. package/dist/overlay/captureView.d.ts.map +1 -0
  21. package/dist/overlay/captureView.js +31 -0
  22. package/dist/overlay/captureView.js.map +1 -0
  23. package/dist/overlay/resolveOrigin.d.ts +8 -0
  24. package/dist/overlay/resolveOrigin.d.ts.map +1 -0
  25. package/dist/overlay/resolveOrigin.js +68 -0
  26. package/dist/overlay/resolveOrigin.js.map +1 -0
  27. package/dist/overlay/types.d.ts +15 -0
  28. package/dist/overlay/types.d.ts.map +1 -0
  29. package/dist/overlay/types.js +61 -0
  30. package/dist/overlay/types.js.map +1 -0
  31. package/dist/setThemeDecision.d.ts +14 -0
  32. package/dist/setThemeDecision.d.ts.map +1 -0
  33. package/dist/setThemeDecision.js +27 -0
  34. package/dist/setThemeDecision.js.map +1 -0
  35. package/dist/transitionEngine.d.ts +48 -17
  36. package/dist/transitionEngine.d.ts.map +1 -1
  37. package/dist/transitionEngine.js +279 -208
  38. package/dist/transitionEngine.js.map +1 -1
  39. package/dist/transitionMeta.d.ts +136 -0
  40. package/dist/transitionMeta.d.ts.map +1 -0
  41. package/dist/transitionMeta.js +131 -0
  42. package/dist/transitionMeta.js.map +1 -0
  43. package/dist/types.d.ts +254 -193
  44. package/dist/types.d.ts.map +1 -1
  45. package/dist/validateSetThemeOptions.d.ts +15 -0
  46. package/dist/validateSetThemeOptions.d.ts.map +1 -0
  47. package/dist/validateSetThemeOptions.js +54 -0
  48. package/dist/validateSetThemeOptions.js.map +1 -0
  49. package/package.json +14 -6
  50. package/src/constants.ts +6 -0
  51. package/src/createThemeTransition.ts +57 -39
  52. package/src/index.ts +12 -9
  53. package/src/overlay/SkiaOverlay.tsx +629 -0
  54. package/src/overlay/captureView.ts +32 -0
  55. package/src/overlay/resolveOrigin.ts +81 -0
  56. package/src/overlay/types.ts +83 -0
  57. package/src/setThemeDecision.ts +48 -0
  58. package/src/transitionEngine.tsx +390 -247
  59. package/src/transitionMeta.ts +176 -0
  60. package/src/types.ts +272 -193
  61. package/src/validateSetThemeOptions.ts +76 -0
  62. package/dist/hooks/useTheme.d.ts +0 -14
  63. package/dist/hooks/useTheme.d.ts.map +0 -1
  64. package/dist/hooks/useTheme.js +0 -46
  65. package/dist/hooks/useTheme.js.map +0 -1
  66. package/src/hooks/useTheme.ts +0 -72
@@ -1,35 +1,115 @@
1
1
  /**
2
- * Screenshot-overlay transition engine and provider.
2
+ * Provider and context for the theme transition engine.
3
3
  *
4
4
  * @remarks
5
- * View hierarchy: content root → shared-value touch blocker → animated overlay
6
- * with decoded screenshot `Image`. The overlay is always mounted (no mount-time
7
- * race with the shared opacity value); only the `Image` inside is conditional.
5
+ * Capture and overlay both use `@shopify/react-native-skia`; a single
6
+ * 0 → 1 `progress` shared value drives every transition kind. The
7
+ * library is policy-free about OS Reduce Motion. Consumers who want
8
+ * to honor it pass `animated: false` per call.
9
+ *
10
+ * **State machine.** Each animated transition runs the following steps
11
+ * in order:
12
+ *
13
+ * 1. `setTheme`: sync writes (`transitioningRef`, `isBlocking`,
14
+ * `intendedThemeRef`, `preference`) so picker UIs repaint before
15
+ * capture. `runTransition` is kicked off async and the config and
16
+ * per-call `onTransitionStart` callbacks fire.
17
+ * 2. **`SETTLE.beforeCapture`**: wait one frame so React has flushed
18
+ * the sync writes and any pressed-state repaints made it to screen
19
+ * before the snapshot is taken.
20
+ * 3. **Capture old**: `captureView` grabs a CPU-backed `SkImage` of the
21
+ * inner tree. If capture fails, the engine falls back to an instant
22
+ * swap (no overlay, only `onThemeChange` fires).
23
+ * 4. **Commit 1**: `setOverlayParams` + `setSkImage` mount the snapshot
24
+ * on the pre-mounted Canvas.
25
+ * 5. **`SETTLE.skiaPaint`**: wait so Skia paints the snapshot before
26
+ * the inner tree swaps its colors. Otherwise the new theme flashes
27
+ * through on Android.
28
+ * 6. **Commit 2**: `setIsTransitioning(true)` + `setActiveTheme(new)`
29
+ * swap the inner tree underneath the now-covering overlay.
30
+ * 7. **`SETTLE.treeRepaint` (conditional)**: for reveal, shape, and
31
+ * dual-image transitions, wait an extra frame so the inner tree
32
+ * has repainted in the new theme before the second capture.
33
+ * 8. **Capture new (conditional)**: for `slide` and `pixelize`
34
+ * (`TRANSITION_META[kind].capturesNew === true`), capture a second
35
+ * snapshot of the inner tree in the new theme and mount it as
36
+ * `imageNew` on the overlay.
37
+ * 9. **Animate**: Reanimated animates `progress` 0 → 1 and a
38
+ * `setTimeout(duration)` fires the `finish` cleanup, which resets
39
+ * the overlay and fires `onTransitionEnd` (config and per-call) and
40
+ * `onThemeChange`. If the OS appearance changed while in `'system'`
41
+ * mode during the transition, the pending correction fires a
42
+ * second `onThemeChange`.
43
+ *
44
+ * **Why the SkiaOverlay stays permanently mounted:** Android paints a
45
+ * fresh native view at the same commit it gains content; if the Canvas
46
+ * mounted at commit 1, its first paint would be empty and the
47
+ * already-swapped inner tree would flash the new theme through for one
48
+ * frame. Keeping the Canvas mounted with `image={null}` between
49
+ * transitions avoids the layout pass entirely.
8
50
  *
9
51
  * @module
52
+ * @internal
10
53
  */
11
54
 
55
+ import type { SkImage } from '@shopify/react-native-skia'
12
56
  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'
57
+ import { Appearance, AppState, Dimensions, type LayoutChangeEvent, View } from 'react-native'
58
+ import Animated, {
59
+ Easing,
60
+ useAnimatedStyle,
61
+ useSharedValue,
62
+ withTiming,
63
+ } from 'react-native-reanimated'
64
+ import { ABSOLUTE_FILL, FLEX_FILL, TAG } from './constants'
65
+ import { captureView } from './overlay/captureView'
66
+ import { calculateMaxRadius, resolveOrigin } from './overlay/resolveOrigin'
67
+ import { SkiaOverlay } from './overlay/SkiaOverlay'
68
+ import {
69
+ DEFAULT_DIRECTION,
70
+ DEFAULT_DISSOLVE_NOISE_SIZE,
71
+ DEFAULT_OVERLAY_PARAMS,
72
+ DEFAULT_PIXELIZE_BLOCK_SIZE,
73
+ DEFAULT_SPLIT_MODE,
74
+ type OverlayParams,
75
+ } from './overlay/types'
76
+ import { decideSetTheme } from './setThemeDecision'
77
+ import type { SplitMode, WipeDirection } from './transitionMeta'
78
+ import { TRANSITION_META } from './transitionMeta'
18
79
  import type {
80
+ ColorScheme,
81
+ OriginSpec,
19
82
  SetThemeOptions,
20
83
  SystemThemeMap,
21
84
  ThemeDefinition,
22
85
  ThemeNames,
23
86
  ThemeTransitionConfig,
24
87
  TokenNames,
88
+ TransitionType,
25
89
  UseThemeResult,
26
90
  } from './types'
91
+ import { validateSetThemeOptions } from './validateSetThemeOptions'
27
92
 
28
- const ABSOLUTE_FILL = { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 } as const
29
- // Avoids layout clipping on certain Android API levels.
30
- const ROOT_STYLE = { flex: 1 } as const
93
+ /**
94
+ * @internal Flat view of the public {@link SetThemeOptions} union. The
95
+ * engine dispatches on `transition` first and reads the rest generically.
96
+ */
97
+ interface ResolvedOptions<Names extends string> {
98
+ animated?: boolean
99
+ duration?: number
100
+ easing?: (t: number) => number
101
+ transition?: TransitionType
102
+ origin?: OriginSpec
103
+ inverted?: boolean
104
+ direction?: WipeDirection
105
+ mode?: SplitMode
106
+ blockSize?: number
107
+ noiseSize?: number
108
+ onTransitionStart?: (themeName: Names) => void
109
+ onTransitionEnd?: (themeName: Names) => void
110
+ }
31
111
 
32
- /** Calls `fn` and swallows errors with a console.warn tagged by `label`. */
112
+ /** @internal Invokes a user callback; swallows + logs throws so they can't break the pipeline. */
33
113
  function safeCall<A extends unknown[]>(
34
114
  label: string,
35
115
  fn: ((...args: A) => void) | undefined,
@@ -42,21 +122,7 @@ function safeCall<A extends unknown[]>(
42
122
  }
43
123
  }
44
124
 
45
- /**
46
- * Waits for `n` native animation frames to complete.
47
- *
48
- * @remarks
49
- * React Native's rendering pipeline spans three phases:
50
- * 1. **JS thread** — React reconciliation produces a virtual tree.
51
- * 2. **Shadow Tree** — Yoga calculates layout from the virtual tree.
52
- * 3. **Native UI thread** — platform views are painted on screen.
53
- *
54
- * Each phase runs on its own frame cadence (~16.67 ms at 60 fps).
55
- * Waiting 1 frame lets React flush pending state or the compositor
56
- * paint a decoded image.
57
- *
58
- * @param n - Number of animation frames to wait.
59
- */
125
+ /** @internal Awaits `n` rAF ticks. The engine's settle primitive between React commits and native paint. */
60
126
  function waitFrames(n: number): Promise<void> {
61
127
  return new Promise((resolve) => {
62
128
  let remaining = n
@@ -69,51 +135,41 @@ function waitFrames(n: number): Promise<void> {
69
135
  }
70
136
 
71
137
  /**
72
- * Normalizes an OS color scheme string to `'light'` or `'dark'`.
73
- *
74
- * @remarks
75
- * Only accepts the two known values. Any other input — including `null`,
76
- * `undefined`, and `'unspecified'` (returned by RN after
77
- * `Appearance.setColorScheme('unspecified')`) — defaults to `'light'`.
138
+ * @internal Frame budgets for the engine's settle points. Tuned empirically.
78
139
  *
79
- * @internal
140
+ * - `beforeCapture` (1): lets React batching paint a picker's
141
+ * optimistic highlight before the snapshot.
142
+ * - `skiaPaint` (2): Android occasionally loses the race between the
143
+ * color swap and the Canvas's first paint and flashes the new theme
144
+ * through for a frame; one frame is enough on iOS.
145
+ * - `treeRepaint` (1): gives Android a frame to repaint deep
146
+ * ScrollView children before a reveal/shape animation exposes them
147
+ * through a growing hole.
80
148
  */
149
+ const SETTLE = { beforeCapture: 1, skiaPaint: 2, treeRepaint: 1 } as const
150
+
151
+ /** @internal Coerces an `Appearance.getColorScheme()` return value to a {@link ColorScheme}. */
81
152
  function normalizeScheme(
82
153
  colorScheme?: string | null,
83
- fallback: 'light' | 'dark' = 'light',
84
- ): 'light' | 'dark' {
154
+ fallback: ColorScheme = 'light',
155
+ ): ColorScheme {
85
156
  if (colorScheme === 'dark') return 'dark'
86
157
  if (colorScheme === 'light') return 'light'
87
158
  return fallback
88
159
  }
89
160
 
90
- /**
91
- * Maps an OS color scheme to a theme name via `systemThemeMap`.
92
- *
93
- * @remarks
94
- * The fallback `scheme as Names` is only safe when the themes are named `'light'` and
95
- * `'dark'`. Callers that use custom theme names must validate the result against `themes` —
96
- * both `ThemeTransitionProvider` (for `initialTheme="system"`) and `setTheme`
97
- * (for `setTheme('system')`) perform this validation and throw a clear error if the
98
- * resolved name is not a registered theme.
99
- *
100
- * @internal
101
- */
161
+ /** @internal Maps an OS scheme to a theme name via `systemThemeMap`. */
102
162
  function mapSchemeToTheme<Names extends string>(
103
- scheme: 'light' | 'dark',
163
+ scheme: ColorScheme,
104
164
  mapping?: SystemThemeMap<Names>,
105
165
  ): Names {
106
166
  return mapping?.[scheme] ?? (scheme as Names)
107
167
  }
108
168
 
109
- /**
110
- * Reads the current OS appearance and maps it to a theme name.
111
- *
112
- * @internal Convenience wrapper combining {@link normalizeScheme} and {@link mapSchemeToTheme}.
113
- */
169
+ /** @internal Reads the current OS appearance and maps it to a theme name. */
114
170
  function resolveSystemTheme<Names extends string>(
115
171
  mapping?: SystemThemeMap<Names>,
116
- fallbackScheme?: 'light' | 'dark',
172
+ fallbackScheme?: ColorScheme,
117
173
  ): Names {
118
174
  return mapSchemeToTheme<Names>(
119
175
  normalizeScheme(Appearance.getColorScheme(), fallbackScheme),
@@ -121,17 +177,14 @@ function resolveSystemTheme<Names extends string>(
121
177
  )
122
178
  }
123
179
 
124
- /**
125
- * Creates the React Context and provider component for a given theme configuration.
126
- *
127
- * @internal Used by {@link createThemeTransition}; not part of the public API.
128
- */
180
+ /** @internal Factory for a per-config Provider. Called by {@link createThemeTransition}. */
129
181
  export function createProviderAndContext<T extends Record<string, ThemeDefinition>>(
130
182
  config: ThemeTransitionConfig<T>,
131
183
  ) {
132
184
  const {
133
185
  themes,
134
- duration = 350,
186
+ animated: configAnimated = true,
187
+ transition: configTransition = 'fade',
135
188
  systemThemeMap,
136
189
  darkThemes: darkThemesConfig,
137
190
  onTransitionStart: configOnTransitionStart,
@@ -142,17 +195,16 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
142
195
  const darkThemeSet = new Set<string>(
143
196
  darkThemesConfig ?? (systemThemeMap ? [systemThemeMap.dark] : ['dark']),
144
197
  )
145
-
146
- const schemeOf = (name: string): 'light' | 'dark' => (darkThemeSet.has(name) ? 'dark' : 'light')
198
+ const schemeOf = (name: string): ColorScheme => (darkThemeSet.has(name) ? 'dark' : 'light')
147
199
 
148
200
  type Names = ThemeNames<T>
149
201
  type Tokens = TokenNames<T>
150
-
151
202
  const Context = createContext<UseThemeResult<Tokens, Names> | null>(null)
152
203
 
153
- function getColors(name: Names): Record<Tokens, string> {
154
- return { ...themes[name] } as Record<Tokens, string>
155
- }
204
+ // Themes are frozen by the consumer's config - hand back the same
205
+ // reference every time instead of cloning per transition.
206
+ const colorsByName = themes as Record<Names, Record<Tokens, string>>
207
+ const getColors = (name: Names): Record<Tokens, string> => colorsByName[name]
156
208
 
157
209
  function ThemeTransitionProvider({
158
210
  children,
@@ -167,7 +219,6 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
167
219
  const startTheme = isInitialSystem
168
220
  ? resolveSystemTheme<Names>(systemThemeMap)
169
221
  : initialTheme
170
-
171
222
  if (!(startTheme in themes)) {
172
223
  throw new Error(
173
224
  `${TAG} initialTheme resolved to "${startTheme}" which does not exist in themes.${
@@ -177,57 +228,82 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
177
228
  }`,
178
229
  )
179
230
  }
180
-
181
231
  return { colors: getColors(startTheme), name: startTheme }
182
232
  },
183
233
  )
184
234
 
185
- const targetThemeRef = useRef(activeTheme.name)
186
- const rootRef = useRef<View>(null)
235
+ // Sync source of truth for the in-flight theme. Written by
236
+ // `setTheme` before `runTransition` is awaited, so the same-theme
237
+ // guard sees the latest intent without waiting for React to commit
238
+ // `activeTheme` (which only lands at commit 2).
239
+ const intendedThemeRef = useRef(activeTheme.name)
240
+ // The blocker and SkiaOverlay are SIBLINGS of `innerRef`, not
241
+ // descendants - capturing `innerRef` yields the app tree without
242
+ // them, so the second-snapshot capture (slide/pixelize) doesn't
243
+ // re-photograph the in-flight overlay.
244
+ const innerRef = useRef<View>(null)
245
+ // Measured layout, not `Dimensions.get('window')`: on Android
246
+ // edge-to-edge the window dims don't match the painted area and
247
+ // the overlay snapshot would render at the wrong height.
248
+ const innerSizeRef = useRef({ width: 0, height: 0 })
249
+ // Sync guard for concurrent `setTheme` calls. Mirrors the React
250
+ // `isTransitioning` state but flips one frame earlier.
187
251
  const transitioningRef = useRef(false)
188
- // Guards async callbacks against running after unmount.
189
252
  const mountedRef = useRef(true)
190
253
  const [isTransitioning, setIsTransitioning] = useState(false)
191
254
 
192
255
  const systemModeRef = useRef(initialTheme === 'system')
193
- // State mirror of systemModeRef — drives the Appearance.setColorScheme effect.
256
+ // React mirror of `systemModeRef` - drives the Appearance effect
257
+ // below so `setColorScheme('unspecified')` lands AFTER the overlay
258
+ // is covering the screen (otherwise it flashes Android's status bar).
194
259
  const [isSystemMode, setIsSystemMode] = useState(initialTheme === 'system')
195
- const appStateRef = useRef(AppState.currentState)
196
- // Pending OS scheme change that arrived mid-transition. Applied by finishTransition.
197
- const pendingSchemeRef = useRef<'light' | 'dark' | null>(null)
198
- // Last observed OS scheme — lets manual→system resolve without calling
199
- // setColorScheme('unspecified') (which flashes the Android status bar).
200
- const lastKnownOsSchemeRef = useRef<'light' | 'dark'>(
201
- normalizeScheme(Appearance.getColorScheme()),
260
+ // The user's explicit pick. Written synchronously inside `setTheme`
261
+ // so pickers that highlight against it repaint BEFORE the snapshot
262
+ // - `activeTheme` is too late (commit 2).
263
+ const [preference, setPreference] = useState<Names | 'system'>(() =>
264
+ initialTheme === 'system' ? 'system' : (initialTheme as Names),
202
265
  )
203
- // Manual override scheme while a deferred setColorScheme('unspecified') is pending.
204
- // finishTransition uses this to correct the theme if the OS scheme diverged.
205
- const deferredSystemRestoreRef = useRef<'light' | 'dark' | null>(null)
206
-
207
- // SharedValue (not state) so touch blocking takes effect on the native thread
208
- // within one frame, without waiting for a React re-render cycle.
266
+ const appStateRef = useRef(AppState.currentState)
267
+ const pendingSchemeRef = useRef<ColorScheme | null>(null)
268
+ const deferredSystemRestoreRef = useRef<ColorScheme | null>(null)
269
+
270
+ // Touch blocker. The Canvas has `pointerEvents="none"` so taps
271
+ // pass through it; this sibling view catches them while the
272
+ // animation runs. On Fabric `pointerEvents` must live in `style`,
273
+ // so it's driven by `useAnimatedStyle` - JSI updates beat any
274
+ // React commit timing.
209
275
  const isBlocking = useSharedValue(false)
210
- const blockerProps = useAnimatedProps(() => ({
211
- pointerEvents: isBlocking.value ? ('auto' as const) : ('none' as const),
276
+ const blockerStyle = useAnimatedStyle(() => ({
277
+ pointerEvents: isBlocking.value ? 'auto' : 'none',
212
278
  }))
213
279
 
214
- // State (not ref) so unsetting it unmounts the Image, freeing the captured bitmap.
215
- const [overlayUri, setOverlayUri] = useState<string | null>(null)
216
- const overlayOpacity = useSharedValue(0)
217
- // Stable ref so Reanimated doesn't re-process the style on every render.
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
- )
224
- const onOverlayLoad = useCallback(() => {
225
- overlayDecodeRef.current?.resolve()
226
- }, [])
227
- const onOverlayError = useCallback(() => {
228
- overlayDecodeRef.current?.reject()
280
+ const [skImage, setSkImage] = useState<SkImage | null>(null)
281
+ // Second snapshot, captured AFTER the swap, for transitions that
282
+ // need both themes on screen at once (slide, pixelize).
283
+ const [skImageNew, setSkImageNew] = useState<SkImage | null>(null)
284
+ const [overlayParams, setOverlayParams] = useState<OverlayParams | null>(null)
285
+ const progress = useSharedValue(0)
286
+ // Reanimated 4's worklet completion callback doesn't reliably fire
287
+ // for dynamic closures created inside nested async functions, so
288
+ // we drive `finish` from a plain `setTimeout(duration)` instead -
289
+ // same clock as the UI-thread animation, no worklet serialization.
290
+ // The handle lives in a ref so unmount can cancel an in-flight timer.
291
+ const finishTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
292
+ useEffect(() => {
293
+ return () => {
294
+ if (finishTimerRef.current !== null) {
295
+ clearTimeout(finishTimerRef.current)
296
+ finishTimerRef.current = null
297
+ }
298
+ }
229
299
  }, [])
230
300
 
301
+ // Lifecycle flag for the async transition pipeline. Setup writes
302
+ // `true` explicitly (not just initial value) so `<StrictMode>`'s
303
+ // simulated unmount/remount cycle in development re-arms the
304
+ // ref - otherwise the cleanup pass leaves `current = false` and
305
+ // subsequent transitions bail at every `if (!mountedRef.current)`
306
+ // check.
231
307
  useEffect(() => {
232
308
  mountedRef.current = true
233
309
  return () => {
@@ -235,146 +311,197 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
235
311
  }
236
312
  }, [])
237
313
 
238
- // Sync native UI (alerts, keyboards) with theme. Skipped in system mode
239
- // where the OS drives appearance via 'unspecified'.
314
+ // Syncs native `Appearance` (alerts, keyboards, status bar) with
315
+ // the committed theme. Routed through React state so the call lands
316
+ // AFTER the overlay covers the screen - see comments at the
317
+ // `isSystemMode` declaration for the Android flash details.
240
318
  useEffect(() => {
241
- if (isSystemMode) return
319
+ if (isSystemMode) {
320
+ if (!transitioningRef.current) {
321
+ deferredSystemRestoreRef.current = null
322
+ Appearance.setColorScheme('unspecified')
323
+ }
324
+ return
325
+ }
242
326
  if (isTransitioning) return
243
327
  Appearance.setColorScheme(schemeOf(activeTheme.name))
244
328
  }, [isSystemMode, activeTheme.name, isTransitioning])
245
329
 
246
330
  const resetTransition = useCallback(() => {
247
331
  transitioningRef.current = false
248
- isBlocking.value = false
332
+ isBlocking.set(false)
249
333
  setIsTransitioning(false)
250
- setOverlayUri(null)
334
+ // Texture release is deferred one frame so it can't block cleanup.
335
+ const disposeAndClear = (prev: SkImage | null) => {
336
+ if (prev) requestAnimationFrame(() => prev.dispose())
337
+ return null
338
+ }
339
+ setSkImage(disposeAndClear)
340
+ setSkImageNew(disposeAndClear)
251
341
  }, [isBlocking])
252
342
 
253
343
  const runTransition = useCallback(
254
- async (initialName: Names, options?: SetThemeOptions<Names>) => {
344
+ async (
345
+ initialName: Names,
346
+ options: ResolvedOptions<Names>,
347
+ transitionType: TransitionType,
348
+ ) => {
255
349
  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)
350
+ const meta = TRANSITION_META[transitionType]
351
+ const effectiveDuration = options?.duration ?? meta.defaultDuration
352
+ const effectiveEasing = options?.easing ?? Easing.out(Easing.cubic)
353
+
354
+ const deferredRestore = async () => {
355
+ if (deferredSystemRestoreRef.current === null) return
356
+ const manualScheme = deferredSystemRestoreRef.current
357
+ let resolved = false
358
+ const realScheme = await new Promise<ColorScheme>((resolve) => {
359
+ const sub = Appearance.addChangeListener(({ colorScheme }) => {
360
+ if (resolved) return
361
+ resolved = true
362
+ sub.remove()
363
+ resolve(normalizeScheme(colorScheme))
364
+ })
365
+ Appearance.setColorScheme('unspecified')
366
+ requestAnimationFrame(() => {
367
+ if (resolved) return
368
+ resolved = true
369
+ sub.remove()
370
+ resolve(manualScheme)
371
+ })
372
+ })
260
373
  if (!mountedRef.current) return
374
+ deferredSystemRestoreRef.current = null
375
+ const corrected = mapSchemeToTheme<Names>(realScheme, systemThemeMap)
376
+ if (corrected in themes && corrected !== name) {
377
+ name = corrected as Names
378
+ intendedThemeRef.current = corrected
379
+ setActiveTheme({ colors: getColors(corrected), name: corrected })
380
+ }
381
+ }
382
+
383
+ const instantFallback = () => {
384
+ setActiveTheme({ colors: getColors(name), name })
385
+ resetTransition()
386
+ safeCall('config onThemeChange', onThemeChange, name)
387
+ }
261
388
 
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 })
389
+ // SkImages captured but not yet handed off to React state. The
390
+ // `finally` block disposes anything left here on error/unmount
391
+ // so a partially-completed transition can't leak GPU memory.
392
+ const pending: SkImage[] = []
393
+ try {
394
+ await waitFrames(SETTLE.beforeCapture)
264
395
  if (!mountedRef.current) return
265
396
 
266
- overlayOpacity.set(1)
397
+ const capturedOld = await captureView(innerRef)
398
+ if (!mountedRef.current) return
267
399
 
268
- await new Promise<void>((resolve, reject) => {
269
- overlayDecodeRef.current = { resolve, reject }
270
- setOverlayUri(uri)
400
+ if (!capturedOld) {
401
+ console.warn(`${TAG} Failed to capture snapshot. Falling back to instant theme switch.`)
402
+ instantFallback()
403
+ return
404
+ }
405
+ pending.push(capturedOld)
406
+
407
+ const measured = innerSizeRef.current
408
+ const fallback = Dimensions.get('window')
409
+ const screenW = measured.width > 0 ? measured.width : fallback.width
410
+ const screenH = measured.height > 0 ? measured.height : fallback.height
411
+ const origin = meta.needsOrigin
412
+ ? resolveOrigin(options.origin, screenW, screenH)
413
+ : { x: screenW / 2, y: screenH / 2 }
414
+
415
+ // Commit 1 - mount the snapshot on the overlay.
416
+ progress.set(0)
417
+ setOverlayParams({
418
+ mode: transitionType,
419
+ origin,
420
+ maxRadius: calculateMaxRadius(origin.x, origin.y, screenW, screenH),
421
+ screenWidth: screenW,
422
+ screenHeight: screenH,
423
+ inverted: options.inverted ?? false,
424
+ direction: options.direction ?? DEFAULT_DIRECTION,
425
+ splitMode: options.mode ?? DEFAULT_SPLIT_MODE,
426
+ blockSize: options.blockSize ?? DEFAULT_PIXELIZE_BLOCK_SIZE,
427
+ noiseSize: options.noiseSize ?? DEFAULT_DISSOLVE_NOISE_SIZE,
271
428
  })
272
- if (!mountedRef.current) return
429
+ setSkImage(capturedOld)
430
+ pending.pop() // ownership transferred to state
273
431
 
274
- await waitFrames(1)
432
+ await waitFrames(SETTLE.skiaPaint)
275
433
  if (!mountedRef.current) return
276
434
 
277
- // Deferred: setting this earlier would re-render under the overlay,
278
- // flashing state-dependent visuals before the screenshot hides them.
435
+ // Commit 2 - overlay covers the screen, safe to swap colors.
279
436
  setIsTransitioning(true)
280
-
281
437
  setActiveTheme({ colors: getColors(name), name })
438
+ await deferredRestore()
282
439
 
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
- })
440
+ // Reveal/shape transitions and any transition that captures
441
+ // the new tree need it fully repainted first - fade/wipe/
442
+ // split/dissolve hide the tree completely so they can skip.
443
+ if (meta.kind === 'reveal' || meta.kind === 'shape' || meta.capturesNew) {
444
+ await waitFrames(SETTLE.treeRepaint)
305
445
  if (!mountedRef.current) return
446
+ }
306
447
 
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 })
448
+ if (meta.capturesNew) {
449
+ const capturedNew = await captureView(innerRef)
450
+ if (!mountedRef.current) return
451
+ if (capturedNew) {
452
+ pending.push(capturedNew)
453
+ setSkImageNew(capturedNew)
454
+ pending.pop()
455
+ await waitFrames(SETTLE.skiaPaint)
456
+ if (!mountedRef.current) return
315
457
  }
316
458
  }
317
459
 
318
- await waitFrames(1)
319
- if (!mountedRef.current) return
320
-
321
- const finishTransition = () => {
460
+ progress.set(withTiming(1, { duration: effectiveDuration, easing: effectiveEasing }))
461
+ finishTimerRef.current = setTimeout(() => {
462
+ finishTimerRef.current = null
322
463
  if (!mountedRef.current) return
323
464
  resetTransition()
324
465
  safeCall('config onTransitionEnd', configOnTransitionEnd, name)
325
- safeCall('per-call onTransitionEnd', options?.onTransitionEnd, name)
466
+ safeCall('per-call onTransitionEnd', options.onTransitionEnd, name)
326
467
  safeCall('config onThemeChange', onThemeChange, name)
327
-
328
- // Apply any OS scheme change that arrived mid-transition.
329
468
  if (systemModeRef.current && pendingSchemeRef.current !== null) {
330
469
  const resolved = mapSchemeToTheme<Names>(pendingSchemeRef.current, systemThemeMap)
331
470
  pendingSchemeRef.current = null
332
471
  if (resolved in themes && resolved !== name) {
333
- targetThemeRef.current = resolved
472
+ intendedThemeRef.current = resolved
334
473
  setActiveTheme({ colors: getColors(resolved), name: resolved })
335
474
  safeCall('config onThemeChange', onThemeChange, resolved)
336
475
  }
337
476
  }
338
- }
339
-
340
- overlayOpacity.set(
341
- withTiming(0, { duration }, (finished) => {
342
- 'worklet'
343
- if (finished) scheduleOnRN(finishTransition)
344
- }),
345
- )
477
+ }, effectiveDuration)
346
478
  } catch (error) {
347
- // If capture fails, apply theme instantly — no animation beats a stuck overlay.
348
479
  console.warn(
349
- `${TAG} Failed to capture screenshot. Falling back to instant theme switch.`,
480
+ `${TAG} Failed to capture snapshot. Falling back to instant theme switch.`,
350
481
  error,
351
482
  )
352
483
  if (!mountedRef.current) return
353
- setActiveTheme({ colors: getColors(name), name })
354
- overlayOpacity.set(0)
355
- resetTransition()
356
- safeCall('config onThemeChange', onThemeChange, name)
484
+ instantFallback()
485
+ } finally {
486
+ for (const img of pending) img.dispose()
357
487
  }
358
488
  },
359
- [overlayOpacity, resetTransition],
489
+ [progress, resetTransition],
360
490
  )
361
491
 
362
492
  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
- }
493
+ (name: Names | 'system', publicOptions?: SetThemeOptions<Names>): 'accepted' | 'ignored' => {
494
+ const options = publicOptions as ResolvedOptions<Names> | undefined
495
+ // Validate numeric option bounds before anything else so misuse
496
+ // surfaces at the caller, not as broken animations downstream.
497
+ validateSetThemeOptions(options)
498
+ // Fast path for rapid taps: skip theme resolution and the native
499
+ // `Appearance.getColorScheme()` call while a transition is in flight.
500
+ if (transitioningRef.current) return 'ignored'
374
501
 
375
502
  const resolvedTheme =
376
503
  name === 'system'
377
- ? mapSchemeToTheme<Names>(lastKnownOsSchemeRef.current, systemThemeMap)
504
+ ? mapSchemeToTheme<Names>(normalizeScheme(Appearance.getColorScheme()), systemThemeMap)
378
505
  : name
379
506
  if (!(resolvedTheme in themes)) {
380
507
  const resolutionHint =
@@ -386,81 +513,92 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
386
513
  )
387
514
  }
388
515
 
389
- if (transitioningRef.current) return false
390
-
391
- // After transition guard — a rejected call must not activate system mode.
392
516
  const wasSystemMode = systemModeRef.current
393
- systemModeRef.current = name === 'system'
394
-
395
- if (systemModeRef.current !== wasSystemMode) {
396
- setIsSystemMode(systemModeRef.current)
517
+ const nowSystemMode = name === 'system'
518
+ const modeFlipped = nowSystemMode !== wasSystemMode
519
+ if (modeFlipped) {
520
+ systemModeRef.current = nowSystemMode
521
+ setIsSystemMode(nowSystemMode)
522
+ // Entering system mode: snapshot the current scheme so
523
+ // `deferredRestore` inside the overlay window can restore it
524
+ // without flashing Android's status bar.
525
+ deferredSystemRestoreRef.current = nowSystemMode
526
+ ? schemeOf(intendedThemeRef.current)
527
+ : null
397
528
  }
398
529
 
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
- }
530
+ const decision = decideSetTheme({
531
+ transitioning: false,
532
+ currentIntended: intendedThemeRef.current,
533
+ resolvedTarget: resolvedTheme,
534
+ modeFlipped,
535
+ })
536
+ if (decision.status === 'ignored') return 'ignored'
537
+
538
+ setPreference(name)
539
+ // `mode-flip-noop`: same painted theme but the user's system
540
+ // pick changed. `preference` is already synced above; nothing
541
+ // left to animate.
542
+ if (decision.path === 'mode-flip-noop') return 'accepted'
404
543
 
405
- targetThemeRef.current = resolvedTheme
544
+ intendedThemeRef.current = resolvedTheme
406
545
 
407
- if (options?.animated === false) {
546
+ const animatedOpt = options?.animated ?? configAnimated
547
+ if (animatedOpt === false) {
408
548
  setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme })
409
549
  safeCall('config onThemeChange', onThemeChange, resolvedTheme)
410
- return true
550
+ return 'accepted'
411
551
  }
412
552
 
413
- // Block before user callbacks to prevent re-entrant setTheme.
414
553
  transitioningRef.current = true
415
- isBlocking.value = true
554
+ isBlocking.set(true)
416
555
 
417
556
  try {
418
557
  configOnTransitionStart?.(resolvedTheme)
419
558
  options?.onTransitionStart?.(resolvedTheme)
420
559
  } catch (e) {
421
- // Reset guards so a callback error doesn't permanently block transitions.
422
560
  resetTransition()
423
561
  throw e
424
562
  }
425
- runTransition(resolvedTheme, options).catch(() => {})
426
- return true
563
+
564
+ const effectiveTransition = options?.transition ?? configTransition
565
+ runTransition(resolvedTheme, options ?? {}, effectiveTransition).catch(() => {})
566
+ return 'accepted'
427
567
  },
428
568
  [isBlocking, resetTransition, runTransition],
429
569
  )
430
570
 
571
+ // Mirror `setTheme` in a ref so the OS-listener effect runs with
572
+ // `[]` deps and never re-subscribes on render.
573
+ const setThemeRef = useRef(setTheme)
574
+ setThemeRef.current = setTheme
575
+
431
576
  useEffect(() => {
432
577
  const appearanceSub = Appearance.addChangeListener(({ colorScheme }) => {
433
578
  if (!systemModeRef.current) return
434
- lastKnownOsSchemeRef.current = normalizeScheme(colorScheme)
435
- // Deferred restore listener in runTransition handles these.
436
579
  if (deferredSystemRestoreRef.current !== null) return
437
580
  if (transitioningRef.current) {
438
581
  pendingSchemeRef.current = normalizeScheme(colorScheme)
439
582
  return
440
583
  }
441
584
  if (appStateRef.current === 'active') {
442
- setTheme('system')
585
+ setThemeRef.current('system')
443
586
  } else {
444
- // Background: apply directly. iOS may defer — AppState handler re-applies on foreground.
445
587
  const resolved = mapSchemeToTheme<Names>(normalizeScheme(colorScheme), systemThemeMap)
446
- if (!(resolved in themes) || resolved === targetThemeRef.current) return
447
- targetThemeRef.current = resolved
588
+ if (!(resolved in themes) || resolved === intendedThemeRef.current) return
589
+ intendedThemeRef.current = resolved
448
590
  setActiveTheme({ colors: getColors(resolved), name: resolved })
449
591
  safeCall('config onThemeChange', onThemeChange, resolved)
450
592
  }
451
593
  })
452
594
 
453
- // Re-read OS scheme on foreground return — iOS may not deliver
454
- // Appearance events while suspended, or may defer the React commit.
455
595
  const appSub = AppState.addEventListener('change', (next) => {
456
596
  if (appStateRef.current !== 'active' && next === 'active' && systemModeRef.current) {
457
- const resolved = resolveSystemTheme<Names>(
458
- systemThemeMap,
459
- schemeOf(targetThemeRef.current),
460
- )
597
+ const osScheme = normalizeScheme(Appearance.getColorScheme())
598
+ const resolved = resolveSystemTheme<Names>(systemThemeMap, osScheme)
461
599
  if (resolved in themes) {
462
- const changed = resolved !== targetThemeRef.current
463
- targetThemeRef.current = resolved
600
+ const changed = resolved !== intendedThemeRef.current
601
+ intendedThemeRef.current = resolved
464
602
  setActiveTheme({ colors: getColors(resolved), name: resolved })
465
603
  if (changed) safeCall('config onThemeChange', onThemeChange, resolved)
466
604
  }
@@ -472,39 +610,44 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
472
610
  appearanceSub.remove()
473
611
  appSub.remove()
474
612
  }
475
- }, [setTheme])
613
+ }, [])
476
614
 
477
615
  const contextValue = useMemo(
478
616
  () => ({
479
- colors: activeTheme.colors,
480
- name: activeTheme.name,
617
+ theme: {
618
+ name: activeTheme.name,
619
+ colors: activeTheme.colors,
620
+ scheme: schemeOf(activeTheme.name),
621
+ },
622
+ preference,
481
623
  setTheme,
482
624
  isTransitioning,
483
625
  }),
484
- [activeTheme, setTheme, isTransitioning],
626
+ [activeTheme, preference, setTheme, isTransitioning],
485
627
  )
486
628
 
629
+ const overlayParamsForRender = overlayParams ?? DEFAULT_OVERLAY_PARAMS
630
+
631
+ const handleInnerLayout = useCallback((e: LayoutChangeEvent) => {
632
+ const { width, height } = e.nativeEvent.layout
633
+ innerSizeRef.current = { width, height }
634
+ }, [])
635
+
487
636
  return (
488
- <Context.Provider value={contextValue}>
489
- {/* collapsable={false}: Android flattens views by default, breaking captureRef. */}
490
- <View ref={rootRef} style={ROOT_STYLE} collapsable={false}>
491
- {children}
492
- <Animated.View style={ABSOLUTE_FILL} animatedProps={blockerProps} />
493
- {/* Always mounted — avoids shared-value race on conditional mount. */}
494
- <Animated.View style={[ABSOLUTE_FILL, overlayStyle]} pointerEvents="none">
495
- {overlayUri != null ? (
496
- <Image
497
- source={overlaySource}
498
- style={ABSOLUTE_FILL}
499
- resizeMode="cover"
500
- fadeDuration={0}
501
- onLoad={onOverlayLoad}
502
- onError={onOverlayError}
503
- />
504
- ) : null}
505
- </Animated.View>
637
+ <Context value={contextValue}>
638
+ <View style={FLEX_FILL} collapsable={false}>
639
+ <View ref={innerRef} style={FLEX_FILL} collapsable={false} onLayout={handleInnerLayout}>
640
+ {children}
641
+ </View>
642
+ <Animated.View style={[ABSOLUTE_FILL, blockerStyle]} />
643
+ <SkiaOverlay
644
+ image={skImage}
645
+ imageNew={skImageNew}
646
+ progress={progress}
647
+ params={overlayParamsForRender}
648
+ />
506
649
  </View>
507
- </Context.Provider>
650
+ </Context>
508
651
  )
509
652
  }
510
653