react-native-theme-transition 2.0.0 → 2.0.2

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.
@@ -4,37 +4,40 @@
4
4
  * @remarks
5
5
  * Capture and overlay both use `@shopify/react-native-skia`; a single
6
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.
7
+ * library has no explicit Reduce Motion check; `withTiming` inherits
8
+ * Reanimated's system setting. `animated: false` also skips capture.
9
9
  *
10
10
  * **State machine.** Each animated transition runs the following steps
11
11
  * in order:
12
12
  *
13
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
14
+ * `intendedThemeRef`). The config and per-call `onTransitionStart`
15
+ * callbacks run before capture. The user's pick is stashed in a ref
16
+ * until commit 2, avoiding an early context update for manual swaps.
17
+ * System-mode changes can still enqueue React state, and consumer
18
+ * callbacks may enqueue their own updates.
19
+ * 2. **Capture old**: `captureView` grabs a CPU-backed `SkImage` of the
21
20
  * inner tree. If capture fails, the engine falls back to an instant
22
21
  * swap (no overlay, only `onThemeChange` fires).
23
- * 4. **Commit 1**: `setOverlayParams` + `setSkImage` mount the snapshot
22
+ * 3. **Commit 1**: `setOverlayParams` + `setSkImage` mount the snapshot
24
23
  * 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
24
+ * 4. **`SETTLE.overlayCommit` + `SETTLE.skiaPaintSynced`**: one frame
25
+ * lets the mounted snapshot reach the native Canvas,
26
+ * `syncOverlayPaint` then spends a Skia paint round trip on it, and
27
+ * one more frame allows compositing before swapping the inner tree.
28
+ * This is an empirical guard, not a display-presentation callback.
29
+ * Falls back to `SETTLE.skiaPaint` when the probe is unavailable.
30
+ * 5. **Commit 2**: `setIsTransitioning(true)` + `setActiveTheme(new)`
31
+ * swap the inner tree underneath the now-covering overlay, and the
32
+ * stashed pick lands in `preference` in the same commit.
33
+ * 6. **`SETTLE.treeRepaint` (conditional)**: for reveal, shape, and
31
34
  * dual-image transitions, wait an extra frame so the inner tree
32
35
  * has repainted in the new theme before the second capture.
33
- * 8. **Capture new (conditional)**: for `slide` and `pixelize`
36
+ * 7. **Capture new (conditional)**: for `slide` and `pixelize`
34
37
  * (`TRANSITION_META[kind].capturesNew === true`), capture a second
35
38
  * snapshot of the inner tree in the new theme and mount it as
36
39
  * `imageNew` on the overlay.
37
- * 9. **Animate**: Reanimated animates `progress` 0 → 1 and a
40
+ * 8. **Animate**: Reanimated animates `progress` 0 → 1 and a
38
41
  * `setTimeout(duration)` fires the `finish` cleanup, which resets
39
42
  * the overlay and fires `onTransitionEnd` (config and per-call) and
40
43
  * `onThemeChange`. If the OS appearance changed while in `'system'`
@@ -52,9 +55,16 @@
52
55
  * @internal
53
56
  */
54
57
 
55
- import type { SkImage } from '@shopify/react-native-skia'
58
+ import type { CanvasRef, SkImage } from '@shopify/react-native-skia'
56
59
  import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react'
57
- import { Appearance, AppState, Dimensions, type LayoutChangeEvent, View } from 'react-native'
60
+ import {
61
+ Appearance,
62
+ AppState,
63
+ Dimensions,
64
+ type LayoutChangeEvent,
65
+ Platform,
66
+ View,
67
+ } from 'react-native'
58
68
  import Animated, {
59
69
  Easing,
60
70
  useAnimatedStyle,
@@ -73,7 +83,7 @@ import {
73
83
  DEFAULT_SPLIT_MODE,
74
84
  type OverlayParams,
75
85
  } from './overlay/types'
76
- import { decideSetTheme } from './setThemeDecision'
86
+ import { decideSetTheme, preferenceWriteTiming } from './setThemeDecision'
77
87
  import type { SplitMode, WipeDirection } from './transitionMeta'
78
88
  import { TRANSITION_META } from './transitionMeta'
79
89
  import type {
@@ -87,6 +97,7 @@ import type {
87
97
  TokenNames,
88
98
  TransitionType,
89
99
  UseThemeResult,
100
+ ViewRef,
90
101
  } from './types'
91
102
  import { validateSetThemeOptions } from './validateSetThemeOptions'
92
103
 
@@ -137,16 +148,48 @@ function waitFrames(n: number): Promise<void> {
137
148
  /**
138
149
  * @internal Frame budgets for the engine's settle points. Tuned empirically.
139
150
  *
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.
151
+ * - `overlayCommit` (1): lets the mounted snapshot reach the native
152
+ * Canvas before {@link syncOverlayPaint} probes its paint.
153
+ * - `skiaPaintSynced` (1): after the offscreen probe completes,
154
+ * allow a frame for compositing; presentation is not acknowledged.
155
+ * - `skiaPaint` (2/3): fallback when that probe is unavailable. Without
156
+ * it Android occasionally loses the race between the color swap and the
157
+ * Canvas's first paint and flashes the new theme through for a frame.
145
158
  * - `treeRepaint` (1): gives Android a frame to repaint deep
146
159
  * ScrollView children before a reveal/shape animation exposes them
147
160
  * through a growing hole.
148
161
  */
149
- const SETTLE = { beforeCapture: 1, skiaPaint: 2, treeRepaint: 1 } as const
162
+ const SETTLE = {
163
+ overlayCommit: 1,
164
+ skiaPaintSynced: 1,
165
+ skiaPaint: Platform.select({ android: 3, default: 2 }) ?? 2,
166
+ treeRepaint: 1,
167
+ } as const
168
+
169
+ /**
170
+ * @internal Spends a Skia paint round trip on the mounted snapshot.
171
+ *
172
+ * RN Skia 2.x exposes no paint callback, so the colour swap used to be gated
173
+ * only by a frame budget; when the render thread was still uploading the
174
+ * snapshot, the swap could show the new theme for a frame. After an
175
+ * overlay-commit frame, `makeImageSnapshotAsync` re-renders the Canvas's
176
+ * current picture offscreen on the main thread and reads it back. This
177
+ * adds a measured rendering round trip while the swap stays blocked,
178
+ * but does not acknowledge a particular React commit or on-screen paint.
179
+ * Returns `false` when the handle or call is unavailable; callers then
180
+ * fall back to the frame budget.
181
+ */
182
+ async function syncOverlayPaint(ref: { current: CanvasRef | null }): Promise<boolean> {
183
+ try {
184
+ const canvas = ref.current
185
+ if (!canvas) return false
186
+ const probe = await canvas.makeImageSnapshotAsync()
187
+ probe.dispose()
188
+ return true
189
+ } catch {
190
+ return false
191
+ }
192
+ }
150
193
 
151
194
  /** @internal Coerces an `Appearance.getColorScheme()` return value to a {@link ColorScheme}. */
152
195
  function normalizeScheme(
@@ -241,13 +284,14 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
241
284
  // descendants - capturing `innerRef` yields the app tree without
242
285
  // them, so the second-snapshot capture (slide/pixelize) doesn't
243
286
  // re-photograph the in-flight overlay.
244
- const innerRef = useRef<View>(null)
287
+ const innerRef = useRef<ViewRef>(null)
288
+ const overlayCanvasRef = useRef<CanvasRef | null>(null)
245
289
  // Measured layout, not `Dimensions.get('window')`: on Android
246
290
  // edge-to-edge the window dims don't match the painted area and
247
291
  // the overlay snapshot would render at the wrong height.
248
292
  const innerSizeRef = useRef({ width: 0, height: 0 })
249
293
  // Sync guard for concurrent `setTheme` calls. Mirrors the React
250
- // `isTransitioning` state but flips one frame earlier.
294
+ // `isTransitioning` state but flips before capture and paint waits.
251
295
  const transitioningRef = useRef(false)
252
296
  const mountedRef = useRef(true)
253
297
  const [isTransitioning, setIsTransitioning] = useState(false)
@@ -257,15 +301,26 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
257
301
  // below so `setColorScheme('unspecified')` lands AFTER the overlay
258
302
  // is covering the screen (otherwise it flashes Android's status bar).
259
303
  const [isSystemMode, setIsSystemMode] = useState(initialTheme === 'system')
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).
304
+ // The user's explicit pick. Animated transitions stash it in
305
+ // `deferredPreferenceRef` and the commit that swaps the colour tokens
306
+ // flushes it here, so pickers that highlight against it move with the
307
+ // theme without an early preference-driven context update.
263
308
  const [preference, setPreference] = useState<Names | 'system'>(() =>
264
309
  initialTheme === 'system' ? 'system' : (initialTheme as Names),
265
310
  )
266
311
  const appStateRef = useRef(AppState.currentState)
267
312
  const pendingSchemeRef = useRef<ColorScheme | null>(null)
268
313
  const deferredSystemRestoreRef = useRef<ColorScheme | null>(null)
314
+ // The pick an animated transition stashes instead of writing it up front,
315
+ // applied by the commit that swaps the colour tokens (or by the fallback
316
+ // paths when the transition never reaches that commit).
317
+ const deferredPreferenceRef = useRef<Names | 'system' | null>(null)
318
+
319
+ const flushDeferredPreference = useCallback(() => {
320
+ if (deferredPreferenceRef.current === null) return
321
+ setPreference(deferredPreferenceRef.current)
322
+ deferredPreferenceRef.current = null
323
+ }, [])
269
324
 
270
325
  // Touch blocker. The Canvas has `pointerEvents="none"` so taps
271
326
  // pass through it; this sibling view catches them while the
@@ -283,10 +338,9 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
283
338
  const [skImageNew, setSkImageNew] = useState<SkImage | null>(null)
284
339
  const [overlayParams, setOverlayParams] = useState<OverlayParams | null>(null)
285
340
  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.
341
+ // Cleanup currently uses a JS timer instead of worklet completion.
342
+ // It shares the configured duration, but its scheduling is independent
343
+ // of UI animation frames and can be delayed when JS is busy.
290
344
  // The handle lives in a ref so unmount can cancel an in-flight timer.
291
345
  const finishTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
292
346
  useEffect(() => {
@@ -381,17 +435,17 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
381
435
  }
382
436
 
383
437
  const instantFallback = () => {
438
+ flushDeferredPreference()
384
439
  setActiveTheme({ colors: getColors(name), name })
385
440
  resetTransition()
386
441
  safeCall('config onThemeChange', onThemeChange, name)
387
442
  }
388
443
 
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.
444
+ // Images registered here are disposed in `finally` until ownership
445
+ // transfers to state. State-owned images and captures that resolve
446
+ // after unmount are outside this list's cleanup coverage.
392
447
  const pending: SkImage[] = []
393
448
  try {
394
- await waitFrames(SETTLE.beforeCapture)
395
449
  if (!mountedRef.current) return
396
450
 
397
451
  const capturedOld = await captureView(innerRef)
@@ -429,12 +483,17 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
429
483
  setSkImage(capturedOld)
430
484
  pending.pop() // ownership transferred to state
431
485
 
432
- await waitFrames(SETTLE.skiaPaint)
486
+ await waitFrames(SETTLE.overlayCommit)
487
+ if (!mountedRef.current) return
488
+
489
+ const paintSynced = await syncOverlayPaint(overlayCanvasRef)
490
+ await waitFrames(paintSynced ? SETTLE.skiaPaintSynced : SETTLE.skiaPaint)
433
491
  if (!mountedRef.current) return
434
492
 
435
- // Commit 2 - overlay covers the screen, safe to swap colors.
493
+ // Commit 2 - swap after the offscreen probe and composite margin.
436
494
  setIsTransitioning(true)
437
495
  setActiveTheme({ colors: getColors(name), name })
496
+ flushDeferredPreference()
438
497
  await deferredRestore()
439
498
 
440
499
  // Reveal/shape transitions and any transition that captures
@@ -452,7 +511,10 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
452
511
  pending.push(capturedNew)
453
512
  setSkImageNew(capturedNew)
454
513
  pending.pop()
455
- await waitFrames(SETTLE.skiaPaint)
514
+ await waitFrames(SETTLE.overlayCommit)
515
+ if (!mountedRef.current) return
516
+ const newPaintSynced = await syncOverlayPaint(overlayCanvasRef)
517
+ await waitFrames(newPaintSynced ? SETTLE.skiaPaintSynced : SETTLE.skiaPaint)
456
518
  if (!mountedRef.current) return
457
519
  }
458
520
  }
@@ -486,7 +548,7 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
486
548
  for (const img of pending) img.dispose()
487
549
  }
488
550
  },
489
- [progress, resetTransition],
551
+ [progress, resetTransition, flushDeferredPreference],
490
552
  )
491
553
 
492
554
  const setTheme = useCallback(
@@ -535,7 +597,9 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
535
597
  })
536
598
  if (decision.status === 'ignored') return 'ignored'
537
599
 
538
- setPreference(name)
600
+ const animatedOpt = options?.animated ?? configAnimated
601
+ if (preferenceWriteTiming(decision.path, animatedOpt) === 'eager') setPreference(name)
602
+ else deferredPreferenceRef.current = name
539
603
  // `mode-flip-noop`: same painted theme but the user's system
540
604
  // pick changed. `preference` is already synced above; nothing
541
605
  // left to animate.
@@ -543,7 +607,6 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
543
607
 
544
608
  intendedThemeRef.current = resolvedTheme
545
609
 
546
- const animatedOpt = options?.animated ?? configAnimated
547
610
  if (animatedOpt === false) {
548
611
  setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme })
549
612
  safeCall('config onThemeChange', onThemeChange, resolvedTheme)
@@ -557,6 +620,7 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
557
620
  configOnTransitionStart?.(resolvedTheme)
558
621
  options?.onTransitionStart?.(resolvedTheme)
559
622
  } catch (e) {
623
+ flushDeferredPreference()
560
624
  resetTransition()
561
625
  throw e
562
626
  }
@@ -565,7 +629,7 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
565
629
  runTransition(resolvedTheme, options ?? {}, effectiveTransition).catch(() => {})
566
630
  return 'accepted'
567
631
  },
568
- [isBlocking, resetTransition, runTransition],
632
+ [isBlocking, resetTransition, runTransition, flushDeferredPreference],
569
633
  )
570
634
 
571
635
  // Mirror `setTheme` in a ref so the OS-listener effect runs with
@@ -645,6 +709,7 @@ export function createProviderAndContext<T extends Record<string, ThemeDefinitio
645
709
  imageNew={skImageNew}
646
710
  progress={progress}
647
711
  params={overlayParamsForRender}
712
+ canvasRef={overlayCanvasRef}
648
713
  />
649
714
  </View>
650
715
  </Context>
@@ -51,8 +51,8 @@ interface TransitionMeta {
51
51
  * - `capturesNew`: whether the engine needs a second snapshot of the new
52
52
  * theme captured after the color swap, so the transition can render both
53
53
  * old and new simultaneously (`slide`, `pixelize`).
54
- * - `defaultDuration`: milliseconds used when no per-call or config-level
55
- * `duration` is set.
54
+ * - `defaultDuration`: milliseconds used when no per-call `duration` is set.
55
+ * The factory config has no duration field.
56
56
  *
57
57
  * Use this table to drive UIs that adapt to the selected transition, for
58
58
  * example showing an "Inverted" toggle only when `invertible` is `true`.
package/src/types.ts CHANGED
@@ -1,6 +1,18 @@
1
1
  import type { View } from 'react-native'
2
2
  import type { TransitionType } from './transitionMeta'
3
3
 
4
+ /**
5
+ * Host instance type of a `<View>` ref across every supported React
6
+ * Native version.
7
+ *
8
+ * `React.ComponentRef` resolves to the class instance on React Native
9
+ * 0.78–0.87 and to the host element type (`ViewInstance`) on 0.88+,
10
+ * where `View` itself is only a function component. Type your refs with
11
+ * this alias—`useRef<ViewRef>(null)`—so they satisfy both this
12
+ * library's `origin` prop and the `ref` prop of `<View>`.
13
+ */
14
+ export type ViewRef = React.ComponentRef<typeof View>
15
+
4
16
  /**
5
17
  * Supported transition names.
6
18
  *
@@ -41,7 +53,7 @@ export interface TransitionOrigin {
41
53
  *
42
54
  * @see https://react-native-theme-transition.vercel.app/docs/types#originspec
43
55
  */
44
- export type OriginSpec = TransitionOrigin | React.RefObject<View | null>
56
+ export type OriginSpec = TransitionOrigin | React.RefObject<ViewRef | null>
45
57
 
46
58
  /** Union of the theme names declared in `T`. */
47
59
  export type ThemeNames<T extends Record<string, ThemeDefinition>> = keyof T & string
@@ -131,8 +143,9 @@ export interface ThemeTransitionConfig<T extends Record<string, ThemeDefinition>
131
143
  onTransitionEnd?: (themeName: ThemeNames<T>) => void
132
144
 
133
145
  /**
134
- * Fires whenever the active theme changes, regardless of path. The
135
- * only callback guaranteed to fire on every code path. In `'system'`
146
+ * Notifies theme application after animated completion, instant switches,
147
+ * or capture-failure fallback. Ignored calls, mode-only no-ops, aborted
148
+ * start callbacks and unmounts do not notify. In `'system'`
136
149
  * mode it can fire twice for a single `setTheme` call if the OS
137
150
  * appearance changes while the transition is still in flight.
138
151
  *
@@ -328,11 +341,12 @@ export interface UseThemeResult<Tokens extends string, Names extends string> {
328
341
 
329
342
  /**
330
343
  * The theme the user explicitly picked. May be `'system'`. Mirrors
331
- * the last argument passed to {@link UseThemeResult.setTheme}.
344
+ * an accepted choice once it is applied. Animated transitions defer the
345
+ * preference update until the colour-swap commit.
332
346
  */
333
347
  preference: Names | 'system'
334
348
 
335
- /** `true` while a transition overlay is visible. */
349
+ /** `true` from the colour-swap commit until transition cleanup. */
336
350
  isTransitioning: boolean
337
351
 
338
352
  /**
@@ -340,7 +354,7 @@ export interface UseThemeResult<Tokens extends string, Names extends string> {
340
354
  *
341
355
  * @param name - Concrete theme name, or `'system'` to follow the OS.
342
356
  * @param options - Per-call transition configuration.
343
- * @returns `'accepted'` if the change will apply, `'ignored'` if rejected (same preference or transition in flight).
357
+ * @returns `'accepted'` if the change will apply, `'ignored'` for an unchanged resolved target and mode, or a transition in flight.
344
358
  * @see https://react-native-theme-transition.vercel.app/docs/api/use-theme#settheme
345
359
  */
346
360
  setTheme: (name: Names | 'system', options?: SetThemeOptions<Names>) => 'accepted' | 'ignored'