react-native-theme-transition 1.0.7 → 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 +273 -210
  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 +383 -249
  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,55 +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
- // OS scheme change that arrived while the overlay was animating.
197
- const pendingSchemeRef = useRef<'light' | 'dark' | null>(null)
198
- // Avoids calling setColorScheme('unspecified') pre-overlay (Android status bar flash).
199
- const lastKnownOsSchemeRef = useRef<'light' | 'dark'>(
200
- 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),
201
265
  )
202
- // Non-null while setColorScheme('unspecified') is deferred behind the overlay.
203
- const deferredSystemRestoreRef = useRef<'light' | 'dark' | null>(null)
204
-
205
- // SharedValue (not state) so touch blocking takes effect on the native thread
206
- // 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.
207
275
  const isBlocking = useSharedValue(false)
208
- const blockerProps = useAnimatedProps(() => ({
209
- pointerEvents: isBlocking.value ? ('auto' as const) : ('none' as const),
276
+ const blockerStyle = useAnimatedStyle(() => ({
277
+ pointerEvents: isBlocking.value ? 'auto' : 'none',
210
278
  }))
211
279
 
212
- // State (not ref) so unsetting it unmounts the Image, freeing the captured bitmap.
213
- const [overlayUri, setOverlayUri] = useState<string | null>(null)
214
- const overlayOpacity = useSharedValue(0)
215
- // Stable ref so Reanimated doesn't re-process the style on every render.
216
- const overlayStyle = useMemo(() => ({ opacity: overlayOpacity }), [overlayOpacity])
217
- const overlayDecodeRef = useRef<{ resolve: () => void; reject: () => void } | null>(null)
218
- const overlaySource = useMemo(
219
- () => (overlayUri ? { uri: overlayUri } : undefined),
220
- [overlayUri],
221
- )
222
- const onOverlayLoad = useCallback(() => {
223
- overlayDecodeRef.current?.resolve()
224
- }, [])
225
- const onOverlayError = useCallback(() => {
226
- 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
+ }
227
299
  }, [])
228
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.
229
307
  useEffect(() => {
230
308
  mountedRef.current = true
231
309
  return () => {
@@ -233,10 +311,12 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
233
311
  }
234
312
  }, [])
235
313
 
236
- // Keeps native Appearance (alerts, keyboards, status bar) in sync with mode.
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.
237
318
  useEffect(() => {
238
319
  if (isSystemMode) {
239
- // Explicit mode masks the real OS scheme from the Appearance listener.
240
320
  if (!transitioningRef.current) {
241
321
  deferredSystemRestoreRef.current = null
242
322
  Appearance.setColorScheme('unspecified')
@@ -249,137 +329,179 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
249
329
 
250
330
  const resetTransition = useCallback(() => {
251
331
  transitioningRef.current = false
252
- isBlocking.value = false
332
+ isBlocking.set(false)
253
333
  setIsTransitioning(false)
254
- 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)
255
341
  }, [isBlocking])
256
342
 
257
343
  const runTransition = useCallback(
258
- async (initialName: Names, options?: SetThemeOptions<Names>) => {
344
+ async (
345
+ initialName: Names,
346
+ options: ResolvedOptions<Names>,
347
+ transitionType: TransitionType,
348
+ ) => {
259
349
  let name: Names = initialName
260
- try {
261
- // 2 frames for JS → Shadow Tree → Native UI to paint before capture.
262
- // useTheme's requestAnimationFrame adds a 3rd — enough for 120Hz.
263
- 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
+ })
264
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
+ }
265
388
 
266
- // jpg 0.8: ~30% smaller than png, no visible degradation during a cross-fade.
267
- 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)
268
395
  if (!mountedRef.current) return
269
396
 
270
- overlayOpacity.set(1)
397
+ const capturedOld = await captureView(innerRef)
398
+ if (!mountedRef.current) return
271
399
 
272
- await new Promise<void>((resolve, reject) => {
273
- overlayDecodeRef.current = { resolve, reject }
274
- 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,
275
428
  })
276
- if (!mountedRef.current) return
429
+ setSkImage(capturedOld)
430
+ pending.pop() // ownership transferred to state
277
431
 
278
- await waitFrames(1)
432
+ await waitFrames(SETTLE.skiaPaint)
279
433
  if (!mountedRef.current) return
280
434
 
281
- // Deferred: setting this earlier would re-render under the overlay,
282
- // flashing state-dependent visuals before the screenshot hides them.
435
+ // Commit 2 - overlay covers the screen, safe to swap colors.
283
436
  setIsTransitioning(true)
284
-
285
437
  setActiveTheme({ colors: getColors(name), name })
438
+ await deferredRestore()
286
439
 
287
- // Deferred setColorScheme('unspecified') — done now while the overlay is
288
- // opaque so any theme correction (OS scheme diverged) is invisible to the user.
289
- if (deferredSystemRestoreRef.current !== null) {
290
- const manualScheme = deferredSystemRestoreRef.current
291
-
292
- let resolved = false
293
- const realScheme = await new Promise<'light' | 'dark'>((resolve) => {
294
- const sub = Appearance.addChangeListener(({ colorScheme }) => {
295
- if (resolved) return
296
- resolved = true
297
- sub.remove()
298
- resolve(normalizeScheme(colorScheme))
299
- })
300
- Appearance.setColorScheme('unspecified')
301
- // No event → OS scheme already matches the manual override.
302
- requestAnimationFrame(() => {
303
- if (resolved) return
304
- resolved = true
305
- sub.remove()
306
- resolve(manualScheme)
307
- })
308
- })
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)
309
445
  if (!mountedRef.current) return
446
+ }
310
447
 
311
- deferredSystemRestoreRef.current = null
312
- lastKnownOsSchemeRef.current = realScheme
313
-
314
- const corrected = mapSchemeToTheme<Names>(realScheme, systemThemeMap)
315
- if (corrected in themes && corrected !== name) {
316
- name = corrected as Names
317
- targetThemeRef.current = corrected
318
- 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
319
457
  }
320
458
  }
321
459
 
322
- await waitFrames(1)
323
- if (!mountedRef.current) return
324
-
325
- const finishTransition = () => {
460
+ progress.set(withTiming(1, { duration: effectiveDuration, easing: effectiveEasing }))
461
+ finishTimerRef.current = setTimeout(() => {
462
+ finishTimerRef.current = null
326
463
  if (!mountedRef.current) return
327
464
  resetTransition()
328
465
  safeCall('config onTransitionEnd', configOnTransitionEnd, name)
329
- safeCall('per-call onTransitionEnd', options?.onTransitionEnd, name)
466
+ safeCall('per-call onTransitionEnd', options.onTransitionEnd, name)
330
467
  safeCall('config onThemeChange', onThemeChange, name)
331
-
332
- // OS may have changed while the overlay was up.
333
468
  if (systemModeRef.current && pendingSchemeRef.current !== null) {
334
469
  const resolved = mapSchemeToTheme<Names>(pendingSchemeRef.current, systemThemeMap)
335
470
  pendingSchemeRef.current = null
336
471
  if (resolved in themes && resolved !== name) {
337
- targetThemeRef.current = resolved
472
+ intendedThemeRef.current = resolved
338
473
  setActiveTheme({ colors: getColors(resolved), name: resolved })
339
474
  safeCall('config onThemeChange', onThemeChange, resolved)
340
475
  }
341
476
  }
342
- }
343
-
344
- overlayOpacity.set(
345
- withTiming(0, { duration }, (finished) => {
346
- 'worklet'
347
- if (finished) scheduleOnRN(finishTransition)
348
- }),
349
- )
477
+ }, effectiveDuration)
350
478
  } catch (error) {
351
- // If capture fails, apply theme instantly — no animation beats a stuck overlay.
352
479
  console.warn(
353
- `${TAG} Failed to capture screenshot. Falling back to instant theme switch.`,
480
+ `${TAG} Failed to capture snapshot. Falling back to instant theme switch.`,
354
481
  error,
355
482
  )
356
483
  if (!mountedRef.current) return
357
- setActiveTheme({ colors: getColors(name), name })
358
- overlayOpacity.set(0)
359
- resetTransition()
360
- safeCall('config onThemeChange', onThemeChange, name)
484
+ instantFallback()
485
+ } finally {
486
+ for (const img of pending) img.dispose()
361
487
  }
362
488
  },
363
- [overlayOpacity, resetTransition],
489
+ [progress, resetTransition],
364
490
  )
365
491
 
366
492
  const setTheme = useCallback(
367
- (name: Names | 'system', options?: SetThemeOptions<Names>): boolean => {
368
- // Calling setColorScheme('unspecified') pre-overlay flashes the Android status bar.
369
- if (name === 'system' && !systemModeRef.current) {
370
- if (transitioningRef.current) return false
371
-
372
- setIsSystemMode(true)
373
- systemModeRef.current = true
374
- deferredSystemRestoreRef.current = schemeOf(targetThemeRef.current)
375
- // Entering system mode is always a valid change for select().
376
- setTheme('system', options)
377
- return true
378
- }
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'
379
501
 
380
502
  const resolvedTheme =
381
503
  name === 'system'
382
- ? mapSchemeToTheme<Names>(lastKnownOsSchemeRef.current, systemThemeMap)
504
+ ? mapSchemeToTheme<Names>(normalizeScheme(Appearance.getColorScheme()), systemThemeMap)
383
505
  : name
384
506
  if (!(resolvedTheme in themes)) {
385
507
  const resolutionHint =
@@ -391,85 +513,92 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
391
513
  )
392
514
  }
393
515
 
394
- if (transitioningRef.current) return false
395
-
396
- // After transition guard — a rejected call must not activate system mode.
397
516
  const wasSystemMode = systemModeRef.current
398
- systemModeRef.current = name === 'system'
399
-
400
- if (systemModeRef.current !== wasSystemMode) {
401
- setIsSystemMode(systemModeRef.current)
402
- // Stale deferred ref would override the user's explicit choice.
403
- if (!systemModeRef.current) {
404
- deferredSystemRestoreRef.current = null
405
- }
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
406
528
  }
407
529
 
408
- if (resolvedTheme === targetThemeRef.current) {
409
- // Manual↔system mode switch is valid even when the resolved theme matches —
410
- // returning true prevents select() from reverting the user's selection.
411
- return wasSystemMode !== systemModeRef.current
412
- }
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'
413
543
 
414
- targetThemeRef.current = resolvedTheme
544
+ intendedThemeRef.current = resolvedTheme
415
545
 
416
- if (options?.animated === false) {
546
+ const animatedOpt = options?.animated ?? configAnimated
547
+ if (animatedOpt === false) {
417
548
  setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme })
418
549
  safeCall('config onThemeChange', onThemeChange, resolvedTheme)
419
- return true
550
+ return 'accepted'
420
551
  }
421
552
 
422
- // Block before user callbacks to prevent re-entrant setTheme.
423
553
  transitioningRef.current = true
424
- isBlocking.value = true
554
+ isBlocking.set(true)
425
555
 
426
556
  try {
427
557
  configOnTransitionStart?.(resolvedTheme)
428
558
  options?.onTransitionStart?.(resolvedTheme)
429
559
  } catch (e) {
430
- // Reset guards so a callback error doesn't permanently block transitions.
431
560
  resetTransition()
432
561
  throw e
433
562
  }
434
- runTransition(resolvedTheme, options).catch(() => {})
435
- return true
563
+
564
+ const effectiveTransition = options?.transition ?? configTransition
565
+ runTransition(resolvedTheme, options ?? {}, effectiveTransition).catch(() => {})
566
+ return 'accepted'
436
567
  },
437
568
  [isBlocking, resetTransition, runTransition],
438
569
  )
439
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
+
440
576
  useEffect(() => {
441
577
  const appearanceSub = Appearance.addChangeListener(({ colorScheme }) => {
442
578
  if (!systemModeRef.current) return
443
- lastKnownOsSchemeRef.current = normalizeScheme(colorScheme)
444
- // Deferred restore listener in runTransition handles these.
445
579
  if (deferredSystemRestoreRef.current !== null) return
446
580
  if (transitioningRef.current) {
447
581
  pendingSchemeRef.current = normalizeScheme(colorScheme)
448
582
  return
449
583
  }
450
584
  if (appStateRef.current === 'active') {
451
- setTheme('system')
585
+ setThemeRef.current('system')
452
586
  } else {
453
- // Background: apply directly. iOS may defer — AppState handler re-applies on foreground.
454
587
  const resolved = mapSchemeToTheme<Names>(normalizeScheme(colorScheme), systemThemeMap)
455
- if (!(resolved in themes) || resolved === targetThemeRef.current) return
456
- targetThemeRef.current = resolved
588
+ if (!(resolved in themes) || resolved === intendedThemeRef.current) return
589
+ intendedThemeRef.current = resolved
457
590
  setActiveTheme({ colors: getColors(resolved), name: resolved })
458
591
  safeCall('config onThemeChange', onThemeChange, resolved)
459
592
  }
460
593
  })
461
594
 
462
- // Re-read OS scheme on foreground return — iOS may not deliver
463
- // Appearance events while suspended, or may defer the React commit.
464
595
  const appSub = AppState.addEventListener('change', (next) => {
465
596
  if (appStateRef.current !== 'active' && next === 'active' && systemModeRef.current) {
466
- const resolved = resolveSystemTheme<Names>(
467
- systemThemeMap,
468
- schemeOf(targetThemeRef.current),
469
- )
597
+ const osScheme = normalizeScheme(Appearance.getColorScheme())
598
+ const resolved = resolveSystemTheme<Names>(systemThemeMap, osScheme)
470
599
  if (resolved in themes) {
471
- const changed = resolved !== targetThemeRef.current
472
- targetThemeRef.current = resolved
600
+ const changed = resolved !== intendedThemeRef.current
601
+ intendedThemeRef.current = resolved
473
602
  setActiveTheme({ colors: getColors(resolved), name: resolved })
474
603
  if (changed) safeCall('config onThemeChange', onThemeChange, resolved)
475
604
  }
@@ -481,39 +610,44 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
481
610
  appearanceSub.remove()
482
611
  appSub.remove()
483
612
  }
484
- }, [setTheme])
613
+ }, [])
485
614
 
486
615
  const contextValue = useMemo(
487
616
  () => ({
488
- colors: activeTheme.colors,
489
- name: activeTheme.name,
617
+ theme: {
618
+ name: activeTheme.name,
619
+ colors: activeTheme.colors,
620
+ scheme: schemeOf(activeTheme.name),
621
+ },
622
+ preference,
490
623
  setTheme,
491
624
  isTransitioning,
492
625
  }),
493
- [activeTheme, setTheme, isTransitioning],
626
+ [activeTheme, preference, setTheme, isTransitioning],
494
627
  )
495
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
+
496
636
  return (
497
- <Context.Provider value={contextValue}>
498
- {/* collapsable={false}: Android flattens views by default, breaking captureRef. */}
499
- <View ref={rootRef} style={ROOT_STYLE} collapsable={false}>
500
- {children}
501
- <Animated.View style={ABSOLUTE_FILL} animatedProps={blockerProps} />
502
- {/* Always mounted — avoids shared-value race on conditional mount. */}
503
- <Animated.View style={[ABSOLUTE_FILL, overlayStyle]} pointerEvents="none">
504
- {overlayUri != null ? (
505
- <Image
506
- source={overlaySource}
507
- style={ABSOLUTE_FILL}
508
- resizeMode="cover"
509
- fadeDuration={0}
510
- onLoad={onOverlayLoad}
511
- onError={onOverlayError}
512
- />
513
- ) : null}
514
- </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
+ />
515
649
  </View>
516
- </Context.Provider>
650
+ </Context>
517
651
  )
518
652
  }
519
653