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,24 +1,16 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- /**
3
- * Screenshot-overlay transition engine and provider.
4
- *
5
- * @remarks
6
- * View hierarchy: content root → shared-value touch blocker → animated overlay
7
- * with decoded screenshot `Image`. The overlay is always mounted (no mount-time
8
- * race with the shared opacity value); only the `Image` inside is conditional.
9
- *
10
- * @module
11
- */
12
2
  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';
18
- const ABSOLUTE_FILL = { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 };
19
- // Avoids layout clipping on certain Android API levels.
20
- const ROOT_STYLE = { flex: 1 };
21
- /** Calls `fn` and swallows errors with a console.warn tagged by `label`. */
3
+ import { Appearance, AppState, Dimensions, View } from 'react-native';
4
+ import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming, } from 'react-native-reanimated';
5
+ import { ABSOLUTE_FILL, FLEX_FILL, TAG } from './constants';
6
+ import { captureView } from './overlay/captureView';
7
+ import { calculateMaxRadius, resolveOrigin } from './overlay/resolveOrigin';
8
+ import { SkiaOverlay } from './overlay/SkiaOverlay';
9
+ import { DEFAULT_DIRECTION, DEFAULT_DISSOLVE_NOISE_SIZE, DEFAULT_OVERLAY_PARAMS, DEFAULT_PIXELIZE_BLOCK_SIZE, DEFAULT_SPLIT_MODE, } from './overlay/types';
10
+ import { decideSetTheme } from './setThemeDecision';
11
+ import { TRANSITION_META } from './transitionMeta';
12
+ import { validateSetThemeOptions } from './validateSetThemeOptions';
13
+ /** @internal Invokes a user callback; swallows + logs throws so they can't break the pipeline. */
22
14
  function safeCall(label, fn, ...args) {
23
15
  try {
24
16
  fn?.(...args);
@@ -27,21 +19,7 @@ function safeCall(label, fn, ...args) {
27
19
  console.warn(`${TAG} ${label} threw:`, e);
28
20
  }
29
21
  }
30
- /**
31
- * Waits for `n` native animation frames to complete.
32
- *
33
- * @remarks
34
- * React Native's rendering pipeline spans three phases:
35
- * 1. **JS thread** — React reconciliation produces a virtual tree.
36
- * 2. **Shadow Tree** — Yoga calculates layout from the virtual tree.
37
- * 3. **Native UI thread** — platform views are painted on screen.
38
- *
39
- * Each phase runs on its own frame cadence (~16.67 ms at 60 fps).
40
- * Waiting 1 frame lets React flush pending state or the compositor
41
- * paint a decoded image.
42
- *
43
- * @param n - Number of animation frames to wait.
44
- */
22
+ /** @internal Awaits `n` rAF ticks. The engine's settle primitive between React commits and native paint. */
45
23
  function waitFrames(n) {
46
24
  return new Promise((resolve) => {
47
25
  let remaining = n;
@@ -55,15 +33,19 @@ function waitFrames(n) {
55
33
  });
56
34
  }
57
35
  /**
58
- * Normalizes an OS color scheme string to `'light'` or `'dark'`.
59
- *
60
- * @remarks
61
- * Only accepts the two known values. Any other input — including `null`,
62
- * `undefined`, and `'unspecified'` (returned by RN after
63
- * `Appearance.setColorScheme('unspecified')`) — defaults to `'light'`.
36
+ * @internal Frame budgets for the engine's settle points. Tuned empirically.
64
37
  *
65
- * @internal
38
+ * - `beforeCapture` (1): lets React batching paint a picker's
39
+ * optimistic highlight before the snapshot.
40
+ * - `skiaPaint` (2): Android occasionally loses the race between the
41
+ * color swap and the Canvas's first paint and flashes the new theme
42
+ * through for a frame; one frame is enough on iOS.
43
+ * - `treeRepaint` (1): gives Android a frame to repaint deep
44
+ * ScrollView children before a reveal/shape animation exposes them
45
+ * through a growing hole.
66
46
  */
47
+ const SETTLE = { beforeCapture: 1, skiaPaint: 2, treeRepaint: 1 };
48
+ /** @internal Coerces an `Appearance.getColorScheme()` return value to a {@link ColorScheme}. */
67
49
  function normalizeScheme(colorScheme, fallback = 'light') {
68
50
  if (colorScheme === 'dark')
69
51
  return 'dark';
@@ -71,42 +53,24 @@ function normalizeScheme(colorScheme, fallback = 'light') {
71
53
  return 'light';
72
54
  return fallback;
73
55
  }
74
- /**
75
- * Maps an OS color scheme to a theme name via `systemThemeMap`.
76
- *
77
- * @remarks
78
- * The fallback `scheme as Names` is only safe when the themes are named `'light'` and
79
- * `'dark'`. Callers that use custom theme names must validate the result against `themes` —
80
- * both `ThemeTransitionProvider` (for `initialTheme="system"`) and `setTheme`
81
- * (for `setTheme('system')`) perform this validation and throw a clear error if the
82
- * resolved name is not a registered theme.
83
- *
84
- * @internal
85
- */
56
+ /** @internal Maps an OS scheme to a theme name via `systemThemeMap`. */
86
57
  function mapSchemeToTheme(scheme, mapping) {
87
58
  return mapping?.[scheme] ?? scheme;
88
59
  }
89
- /**
90
- * Reads the current OS appearance and maps it to a theme name.
91
- *
92
- * @internal Convenience wrapper combining {@link normalizeScheme} and {@link mapSchemeToTheme}.
93
- */
60
+ /** @internal Reads the current OS appearance and maps it to a theme name. */
94
61
  function resolveSystemTheme(mapping, fallbackScheme) {
95
62
  return mapSchemeToTheme(normalizeScheme(Appearance.getColorScheme(), fallbackScheme), mapping);
96
63
  }
97
- /**
98
- * Creates the React Context and provider component for a given theme configuration.
99
- *
100
- * @internal Used by {@link createThemeTransition}; not part of the public API.
101
- */
64
+ /** @internal Factory for a per-config Provider. Called by {@link createThemeTransition}. */
102
65
  export function createProviderAndContext(config) {
103
- const { themes, duration = 350, systemThemeMap, darkThemes: darkThemesConfig, onTransitionStart: configOnTransitionStart, onTransitionEnd: configOnTransitionEnd, onThemeChange, } = config;
66
+ const { themes, animated: configAnimated = true, transition: configTransition = 'fade', systemThemeMap, darkThemes: darkThemesConfig, onTransitionStart: configOnTransitionStart, onTransitionEnd: configOnTransitionEnd, onThemeChange, } = config;
104
67
  const darkThemeSet = new Set(darkThemesConfig ?? (systemThemeMap ? [systemThemeMap.dark] : ['dark']));
105
68
  const schemeOf = (name) => (darkThemeSet.has(name) ? 'dark' : 'light');
106
69
  const Context = createContext(null);
107
- function getColors(name) {
108
- return { ...themes[name] };
109
- }
70
+ // Themes are frozen by the consumer's config - hand back the same
71
+ // reference every time instead of cloning per transition.
72
+ const colorsByName = themes;
73
+ const getColors = (name) => colorsByName[name];
110
74
  function ThemeTransitionProvider({ children, initialTheme, }) {
111
75
  const [activeTheme, setActiveTheme] = useState(() => {
112
76
  const isInitialSystem = initialTheme === 'system';
@@ -120,51 +84,84 @@ export function createProviderAndContext(config) {
120
84
  }
121
85
  return { colors: getColors(startTheme), name: startTheme };
122
86
  });
123
- const targetThemeRef = useRef(activeTheme.name);
124
- const rootRef = useRef(null);
87
+ // Sync source of truth for the in-flight theme. Written by
88
+ // `setTheme` before `runTransition` is awaited, so the same-theme
89
+ // guard sees the latest intent without waiting for React to commit
90
+ // `activeTheme` (which only lands at commit 2).
91
+ const intendedThemeRef = useRef(activeTheme.name);
92
+ // The blocker and SkiaOverlay are SIBLINGS of `innerRef`, not
93
+ // descendants - capturing `innerRef` yields the app tree without
94
+ // them, so the second-snapshot capture (slide/pixelize) doesn't
95
+ // re-photograph the in-flight overlay.
96
+ const innerRef = useRef(null);
97
+ // Measured layout, not `Dimensions.get('window')`: on Android
98
+ // edge-to-edge the window dims don't match the painted area and
99
+ // the overlay snapshot would render at the wrong height.
100
+ const innerSizeRef = useRef({ width: 0, height: 0 });
101
+ // Sync guard for concurrent `setTheme` calls. Mirrors the React
102
+ // `isTransitioning` state but flips one frame earlier.
125
103
  const transitioningRef = useRef(false);
126
- // Guards async callbacks against running after unmount.
127
104
  const mountedRef = useRef(true);
128
105
  const [isTransitioning, setIsTransitioning] = useState(false);
129
106
  const systemModeRef = useRef(initialTheme === 'system');
130
- // State mirror of systemModeRef — drives the Appearance.setColorScheme effect.
107
+ // React mirror of `systemModeRef` - drives the Appearance effect
108
+ // below so `setColorScheme('unspecified')` lands AFTER the overlay
109
+ // is covering the screen (otherwise it flashes Android's status bar).
131
110
  const [isSystemMode, setIsSystemMode] = useState(initialTheme === 'system');
111
+ // The user's explicit pick. Written synchronously inside `setTheme`
112
+ // so pickers that highlight against it repaint BEFORE the snapshot
113
+ // - `activeTheme` is too late (commit 2).
114
+ const [preference, setPreference] = useState(() => initialTheme === 'system' ? 'system' : initialTheme);
132
115
  const appStateRef = useRef(AppState.currentState);
133
- // OS scheme change that arrived while the overlay was animating.
134
116
  const pendingSchemeRef = useRef(null);
135
- // Avoids calling setColorScheme('unspecified') pre-overlay (Android status bar flash).
136
- const lastKnownOsSchemeRef = useRef(normalizeScheme(Appearance.getColorScheme()));
137
- // Non-null while setColorScheme('unspecified') is deferred behind the overlay.
138
117
  const deferredSystemRestoreRef = useRef(null);
139
- // SharedValue (not state) so touch blocking takes effect on the native thread
140
- // within one frame, without waiting for a React re-render cycle.
118
+ // Touch blocker. The Canvas has `pointerEvents="none"` so taps
119
+ // pass through it; this sibling view catches them while the
120
+ // animation runs. On Fabric `pointerEvents` must live in `style`,
121
+ // so it's driven by `useAnimatedStyle` - JSI updates beat any
122
+ // React commit timing.
141
123
  const isBlocking = useSharedValue(false);
142
- const blockerProps = useAnimatedProps(() => ({
124
+ const blockerStyle = useAnimatedStyle(() => ({
143
125
  pointerEvents: isBlocking.value ? 'auto' : 'none',
144
126
  }));
145
- // State (not ref) so unsetting it unmounts the Image, freeing the captured bitmap.
146
- const [overlayUri, setOverlayUri] = useState(null);
147
- const overlayOpacity = useSharedValue(0);
148
- // Stable ref so Reanimated doesn't re-process the style on every render.
149
- const overlayStyle = useMemo(() => ({ opacity: overlayOpacity }), [overlayOpacity]);
150
- const overlayDecodeRef = useRef(null);
151
- const overlaySource = useMemo(() => (overlayUri ? { uri: overlayUri } : undefined), [overlayUri]);
152
- const onOverlayLoad = useCallback(() => {
153
- overlayDecodeRef.current?.resolve();
154
- }, []);
155
- const onOverlayError = useCallback(() => {
156
- overlayDecodeRef.current?.reject();
127
+ const [skImage, setSkImage] = useState(null);
128
+ // Second snapshot, captured AFTER the swap, for transitions that
129
+ // need both themes on screen at once (slide, pixelize).
130
+ const [skImageNew, setSkImageNew] = useState(null);
131
+ const [overlayParams, setOverlayParams] = useState(null);
132
+ const progress = useSharedValue(0);
133
+ // Reanimated 4's worklet completion callback doesn't reliably fire
134
+ // for dynamic closures created inside nested async functions, so
135
+ // we drive `finish` from a plain `setTimeout(duration)` instead -
136
+ // same clock as the UI-thread animation, no worklet serialization.
137
+ // The handle lives in a ref so unmount can cancel an in-flight timer.
138
+ const finishTimerRef = useRef(null);
139
+ useEffect(() => {
140
+ return () => {
141
+ if (finishTimerRef.current !== null) {
142
+ clearTimeout(finishTimerRef.current);
143
+ finishTimerRef.current = null;
144
+ }
145
+ };
157
146
  }, []);
147
+ // Lifecycle flag for the async transition pipeline. Setup writes
148
+ // `true` explicitly (not just initial value) so `<StrictMode>`'s
149
+ // simulated unmount/remount cycle in development re-arms the
150
+ // ref - otherwise the cleanup pass leaves `current = false` and
151
+ // subsequent transitions bail at every `if (!mountedRef.current)`
152
+ // check.
158
153
  useEffect(() => {
159
154
  mountedRef.current = true;
160
155
  return () => {
161
156
  mountedRef.current = false;
162
157
  };
163
158
  }, []);
164
- // Keeps native Appearance (alerts, keyboards, status bar) in sync with mode.
159
+ // Syncs native `Appearance` (alerts, keyboards, status bar) with
160
+ // the committed theme. Routed through React state so the call lands
161
+ // AFTER the overlay covers the screen - see comments at the
162
+ // `isSystemMode` declaration for the Android flash details.
165
163
  useEffect(() => {
166
164
  if (isSystemMode) {
167
- // Explicit mode masks the real OS scheme from the Appearance listener.
168
165
  if (!transitioningRef.current) {
169
166
  deferredSystemRestoreRef.current = null;
170
167
  Appearance.setColorScheme('unspecified');
@@ -177,122 +174,169 @@ export function createProviderAndContext(config) {
177
174
  }, [isSystemMode, activeTheme.name, isTransitioning]);
178
175
  const resetTransition = useCallback(() => {
179
176
  transitioningRef.current = false;
180
- isBlocking.value = false;
177
+ isBlocking.set(false);
181
178
  setIsTransitioning(false);
182
- setOverlayUri(null);
179
+ // Texture release is deferred one frame so it can't block cleanup.
180
+ const disposeAndClear = (prev) => {
181
+ if (prev)
182
+ requestAnimationFrame(() => prev.dispose());
183
+ return null;
184
+ };
185
+ setSkImage(disposeAndClear);
186
+ setSkImageNew(disposeAndClear);
183
187
  }, [isBlocking]);
184
- const runTransition = useCallback(async (initialName, options) => {
188
+ const runTransition = useCallback(async (initialName, options, transitionType) => {
185
189
  let name = initialName;
186
- try {
187
- // 2 frames for JS → Shadow Tree → Native UI to paint before capture.
188
- // useTheme's requestAnimationFrame adds a 3rd — enough for 120Hz.
189
- await waitFrames(2);
190
+ const meta = TRANSITION_META[transitionType];
191
+ const effectiveDuration = options?.duration ?? meta.defaultDuration;
192
+ const effectiveEasing = options?.easing ?? Easing.out(Easing.cubic);
193
+ const deferredRestore = async () => {
194
+ if (deferredSystemRestoreRef.current === null)
195
+ return;
196
+ const manualScheme = deferredSystemRestoreRef.current;
197
+ let resolved = false;
198
+ const realScheme = await new Promise((resolve) => {
199
+ const sub = Appearance.addChangeListener(({ colorScheme }) => {
200
+ if (resolved)
201
+ return;
202
+ resolved = true;
203
+ sub.remove();
204
+ resolve(normalizeScheme(colorScheme));
205
+ });
206
+ Appearance.setColorScheme('unspecified');
207
+ requestAnimationFrame(() => {
208
+ if (resolved)
209
+ return;
210
+ resolved = true;
211
+ sub.remove();
212
+ resolve(manualScheme);
213
+ });
214
+ });
190
215
  if (!mountedRef.current)
191
216
  return;
192
- // jpg 0.8: ~30% smaller than png, no visible degradation during a cross-fade.
193
- const uri = await captureRef(rootRef, { format: 'jpg', quality: 0.8 });
217
+ deferredSystemRestoreRef.current = null;
218
+ const corrected = mapSchemeToTheme(realScheme, systemThemeMap);
219
+ if (corrected in themes && corrected !== name) {
220
+ name = corrected;
221
+ intendedThemeRef.current = corrected;
222
+ setActiveTheme({ colors: getColors(corrected), name: corrected });
223
+ }
224
+ };
225
+ const instantFallback = () => {
226
+ setActiveTheme({ colors: getColors(name), name });
227
+ resetTransition();
228
+ safeCall('config onThemeChange', onThemeChange, name);
229
+ };
230
+ // SkImages captured but not yet handed off to React state. The
231
+ // `finally` block disposes anything left here on error/unmount
232
+ // so a partially-completed transition can't leak GPU memory.
233
+ const pending = [];
234
+ try {
235
+ await waitFrames(SETTLE.beforeCapture);
194
236
  if (!mountedRef.current)
195
237
  return;
196
- overlayOpacity.set(1);
197
- await new Promise((resolve, reject) => {
198
- overlayDecodeRef.current = { resolve, reject };
199
- setOverlayUri(uri);
200
- });
238
+ const capturedOld = await captureView(innerRef);
201
239
  if (!mountedRef.current)
202
240
  return;
203
- await waitFrames(1);
241
+ if (!capturedOld) {
242
+ console.warn(`${TAG} Failed to capture snapshot. Falling back to instant theme switch.`);
243
+ instantFallback();
244
+ return;
245
+ }
246
+ pending.push(capturedOld);
247
+ const measured = innerSizeRef.current;
248
+ const fallback = Dimensions.get('window');
249
+ const screenW = measured.width > 0 ? measured.width : fallback.width;
250
+ const screenH = measured.height > 0 ? measured.height : fallback.height;
251
+ const origin = meta.needsOrigin
252
+ ? resolveOrigin(options.origin, screenW, screenH)
253
+ : { x: screenW / 2, y: screenH / 2 };
254
+ // Commit 1 - mount the snapshot on the overlay.
255
+ progress.set(0);
256
+ setOverlayParams({
257
+ mode: transitionType,
258
+ origin,
259
+ maxRadius: calculateMaxRadius(origin.x, origin.y, screenW, screenH),
260
+ screenWidth: screenW,
261
+ screenHeight: screenH,
262
+ inverted: options.inverted ?? false,
263
+ direction: options.direction ?? DEFAULT_DIRECTION,
264
+ splitMode: options.mode ?? DEFAULT_SPLIT_MODE,
265
+ blockSize: options.blockSize ?? DEFAULT_PIXELIZE_BLOCK_SIZE,
266
+ noiseSize: options.noiseSize ?? DEFAULT_DISSOLVE_NOISE_SIZE,
267
+ });
268
+ setSkImage(capturedOld);
269
+ pending.pop(); // ownership transferred to state
270
+ await waitFrames(SETTLE.skiaPaint);
204
271
  if (!mountedRef.current)
205
272
  return;
206
- // Deferred: setting this earlier would re-render under the overlay,
207
- // flashing state-dependent visuals before the screenshot hides them.
273
+ // Commit 2 - overlay covers the screen, safe to swap colors.
208
274
  setIsTransitioning(true);
209
275
  setActiveTheme({ colors: getColors(name), name });
210
- // Deferred setColorScheme('unspecified') — done now while the overlay is
211
- // opaque so any theme correction (OS scheme diverged) is invisible to the user.
212
- if (deferredSystemRestoreRef.current !== null) {
213
- const manualScheme = deferredSystemRestoreRef.current;
214
- let resolved = false;
215
- const realScheme = await new Promise((resolve) => {
216
- const sub = Appearance.addChangeListener(({ colorScheme }) => {
217
- if (resolved)
218
- return;
219
- resolved = true;
220
- sub.remove();
221
- resolve(normalizeScheme(colorScheme));
222
- });
223
- Appearance.setColorScheme('unspecified');
224
- // No event → OS scheme already matches the manual override.
225
- requestAnimationFrame(() => {
226
- if (resolved)
227
- return;
228
- resolved = true;
229
- sub.remove();
230
- resolve(manualScheme);
231
- });
232
- });
276
+ await deferredRestore();
277
+ // Reveal/shape transitions and any transition that captures
278
+ // the new tree need it fully repainted first - fade/wipe/
279
+ // split/dissolve hide the tree completely so they can skip.
280
+ if (meta.kind === 'reveal' || meta.kind === 'shape' || meta.capturesNew) {
281
+ await waitFrames(SETTLE.treeRepaint);
233
282
  if (!mountedRef.current)
234
283
  return;
235
- deferredSystemRestoreRef.current = null;
236
- lastKnownOsSchemeRef.current = realScheme;
237
- const corrected = mapSchemeToTheme(realScheme, systemThemeMap);
238
- if (corrected in themes && corrected !== name) {
239
- name = corrected;
240
- targetThemeRef.current = corrected;
241
- setActiveTheme({ colors: getColors(corrected), name: corrected });
284
+ }
285
+ if (meta.capturesNew) {
286
+ const capturedNew = await captureView(innerRef);
287
+ if (!mountedRef.current)
288
+ return;
289
+ if (capturedNew) {
290
+ pending.push(capturedNew);
291
+ setSkImageNew(capturedNew);
292
+ pending.pop();
293
+ await waitFrames(SETTLE.skiaPaint);
294
+ if (!mountedRef.current)
295
+ return;
242
296
  }
243
297
  }
244
- await waitFrames(1);
245
- if (!mountedRef.current)
246
- return;
247
- const finishTransition = () => {
298
+ progress.set(withTiming(1, { duration: effectiveDuration, easing: effectiveEasing }));
299
+ finishTimerRef.current = setTimeout(() => {
300
+ finishTimerRef.current = null;
248
301
  if (!mountedRef.current)
249
302
  return;
250
303
  resetTransition();
251
304
  safeCall('config onTransitionEnd', configOnTransitionEnd, name);
252
- safeCall('per-call onTransitionEnd', options?.onTransitionEnd, name);
305
+ safeCall('per-call onTransitionEnd', options.onTransitionEnd, name);
253
306
  safeCall('config onThemeChange', onThemeChange, name);
254
- // OS may have changed while the overlay was up.
255
307
  if (systemModeRef.current && pendingSchemeRef.current !== null) {
256
308
  const resolved = mapSchemeToTheme(pendingSchemeRef.current, systemThemeMap);
257
309
  pendingSchemeRef.current = null;
258
310
  if (resolved in themes && resolved !== name) {
259
- targetThemeRef.current = resolved;
311
+ intendedThemeRef.current = resolved;
260
312
  setActiveTheme({ colors: getColors(resolved), name: resolved });
261
313
  safeCall('config onThemeChange', onThemeChange, resolved);
262
314
  }
263
315
  }
264
- };
265
- overlayOpacity.set(withTiming(0, { duration }, (finished) => {
266
- 'worklet';
267
- if (finished)
268
- scheduleOnRN(finishTransition);
269
- }));
316
+ }, effectiveDuration);
270
317
  }
271
318
  catch (error) {
272
- // If capture fails, apply theme instantly — no animation beats a stuck overlay.
273
- console.warn(`${TAG} Failed to capture screenshot. Falling back to instant theme switch.`, error);
319
+ console.warn(`${TAG} Failed to capture snapshot. Falling back to instant theme switch.`, error);
274
320
  if (!mountedRef.current)
275
321
  return;
276
- setActiveTheme({ colors: getColors(name), name });
277
- overlayOpacity.set(0);
278
- resetTransition();
279
- safeCall('config onThemeChange', onThemeChange, name);
322
+ instantFallback();
280
323
  }
281
- }, [overlayOpacity, resetTransition]);
282
- const setTheme = useCallback((name, options) => {
283
- // Calling setColorScheme('unspecified') pre-overlay flashes the Android status bar.
284
- if (name === 'system' && !systemModeRef.current) {
285
- if (transitioningRef.current)
286
- return false;
287
- setIsSystemMode(true);
288
- systemModeRef.current = true;
289
- deferredSystemRestoreRef.current = schemeOf(targetThemeRef.current);
290
- // Entering system mode is always a valid change for select().
291
- setTheme('system', options);
292
- return true;
324
+ finally {
325
+ for (const img of pending)
326
+ img.dispose();
293
327
  }
328
+ }, [progress, resetTransition]);
329
+ const setTheme = useCallback((name, publicOptions) => {
330
+ const options = publicOptions;
331
+ // Validate numeric option bounds before anything else so misuse
332
+ // surfaces at the caller, not as broken animations downstream.
333
+ validateSetThemeOptions(options);
334
+ // Fast path for rapid taps: skip theme resolution and the native
335
+ // `Appearance.getColorScheme()` call while a transition is in flight.
336
+ if (transitioningRef.current)
337
+ return 'ignored';
294
338
  const resolvedTheme = name === 'system'
295
- ? mapSchemeToTheme(lastKnownOsSchemeRef.current, systemThemeMap)
339
+ ? mapSchemeToTheme(normalizeScheme(Appearance.getColorScheme()), systemThemeMap)
296
340
  : name;
297
341
  if (!(resolvedTheme in themes)) {
298
342
  const resolutionHint = name === 'system'
@@ -300,50 +344,62 @@ export function createProviderAndContext(config) {
300
344
  : '';
301
345
  throw new Error(`${TAG} setTheme("${name}") resolved to "${resolvedTheme}" which does not exist in themes.${resolutionHint}`);
302
346
  }
303
- if (transitioningRef.current)
304
- return false;
305
- // After transition guard — a rejected call must not activate system mode.
306
347
  const wasSystemMode = systemModeRef.current;
307
- systemModeRef.current = name === 'system';
308
- if (systemModeRef.current !== wasSystemMode) {
309
- setIsSystemMode(systemModeRef.current);
310
- // Stale deferred ref would override the user's explicit choice.
311
- if (!systemModeRef.current) {
312
- deferredSystemRestoreRef.current = null;
313
- }
314
- }
315
- if (resolvedTheme === targetThemeRef.current) {
316
- // Manual↔system mode switch is valid even when the resolved theme matches —
317
- // returning true prevents select() from reverting the user's selection.
318
- return wasSystemMode !== systemModeRef.current;
348
+ const nowSystemMode = name === 'system';
349
+ const modeFlipped = nowSystemMode !== wasSystemMode;
350
+ if (modeFlipped) {
351
+ systemModeRef.current = nowSystemMode;
352
+ setIsSystemMode(nowSystemMode);
353
+ // Entering system mode: snapshot the current scheme so
354
+ // `deferredRestore` inside the overlay window can restore it
355
+ // without flashing Android's status bar.
356
+ deferredSystemRestoreRef.current = nowSystemMode
357
+ ? schemeOf(intendedThemeRef.current)
358
+ : null;
319
359
  }
320
- targetThemeRef.current = resolvedTheme;
321
- if (options?.animated === false) {
360
+ const decision = decideSetTheme({
361
+ transitioning: false,
362
+ currentIntended: intendedThemeRef.current,
363
+ resolvedTarget: resolvedTheme,
364
+ modeFlipped,
365
+ });
366
+ if (decision.status === 'ignored')
367
+ return 'ignored';
368
+ setPreference(name);
369
+ // `mode-flip-noop`: same painted theme but the user's system
370
+ // pick changed. `preference` is already synced above; nothing
371
+ // left to animate.
372
+ if (decision.path === 'mode-flip-noop')
373
+ return 'accepted';
374
+ intendedThemeRef.current = resolvedTheme;
375
+ const animatedOpt = options?.animated ?? configAnimated;
376
+ if (animatedOpt === false) {
322
377
  setActiveTheme({ colors: getColors(resolvedTheme), name: resolvedTheme });
323
378
  safeCall('config onThemeChange', onThemeChange, resolvedTheme);
324
- return true;
379
+ return 'accepted';
325
380
  }
326
- // Block before user callbacks to prevent re-entrant setTheme.
327
381
  transitioningRef.current = true;
328
- isBlocking.value = true;
382
+ isBlocking.set(true);
329
383
  try {
330
384
  configOnTransitionStart?.(resolvedTheme);
331
385
  options?.onTransitionStart?.(resolvedTheme);
332
386
  }
333
387
  catch (e) {
334
- // Reset guards so a callback error doesn't permanently block transitions.
335
388
  resetTransition();
336
389
  throw e;
337
390
  }
338
- runTransition(resolvedTheme, options).catch(() => { });
339
- return true;
391
+ const effectiveTransition = options?.transition ?? configTransition;
392
+ runTransition(resolvedTheme, options ?? {}, effectiveTransition).catch(() => { });
393
+ return 'accepted';
340
394
  }, [isBlocking, resetTransition, runTransition]);
395
+ // Mirror `setTheme` in a ref so the OS-listener effect runs with
396
+ // `[]` deps and never re-subscribes on render.
397
+ const setThemeRef = useRef(setTheme);
398
+ setThemeRef.current = setTheme;
341
399
  useEffect(() => {
342
400
  const appearanceSub = Appearance.addChangeListener(({ colorScheme }) => {
343
401
  if (!systemModeRef.current)
344
402
  return;
345
- lastKnownOsSchemeRef.current = normalizeScheme(colorScheme);
346
- // Deferred restore listener in runTransition handles these.
347
403
  if (deferredSystemRestoreRef.current !== null)
348
404
  return;
349
405
  if (transitioningRef.current) {
@@ -351,26 +407,24 @@ export function createProviderAndContext(config) {
351
407
  return;
352
408
  }
353
409
  if (appStateRef.current === 'active') {
354
- setTheme('system');
410
+ setThemeRef.current('system');
355
411
  }
356
412
  else {
357
- // Background: apply directly. iOS may defer — AppState handler re-applies on foreground.
358
413
  const resolved = mapSchemeToTheme(normalizeScheme(colorScheme), systemThemeMap);
359
- if (!(resolved in themes) || resolved === targetThemeRef.current)
414
+ if (!(resolved in themes) || resolved === intendedThemeRef.current)
360
415
  return;
361
- targetThemeRef.current = resolved;
416
+ intendedThemeRef.current = resolved;
362
417
  setActiveTheme({ colors: getColors(resolved), name: resolved });
363
418
  safeCall('config onThemeChange', onThemeChange, resolved);
364
419
  }
365
420
  });
366
- // Re-read OS scheme on foreground return — iOS may not deliver
367
- // Appearance events while suspended, or may defer the React commit.
368
421
  const appSub = AppState.addEventListener('change', (next) => {
369
422
  if (appStateRef.current !== 'active' && next === 'active' && systemModeRef.current) {
370
- const resolved = resolveSystemTheme(systemThemeMap, schemeOf(targetThemeRef.current));
423
+ const osScheme = normalizeScheme(Appearance.getColorScheme());
424
+ const resolved = resolveSystemTheme(systemThemeMap, osScheme);
371
425
  if (resolved in themes) {
372
- const changed = resolved !== targetThemeRef.current;
373
- targetThemeRef.current = resolved;
426
+ const changed = resolved !== intendedThemeRef.current;
427
+ intendedThemeRef.current = resolved;
374
428
  setActiveTheme({ colors: getColors(resolved), name: resolved });
375
429
  if (changed)
376
430
  safeCall('config onThemeChange', onThemeChange, resolved);
@@ -382,14 +436,23 @@ export function createProviderAndContext(config) {
382
436
  appearanceSub.remove();
383
437
  appSub.remove();
384
438
  };
385
- }, [setTheme]);
439
+ }, []);
386
440
  const contextValue = useMemo(() => ({
387
- colors: activeTheme.colors,
388
- name: activeTheme.name,
441
+ theme: {
442
+ name: activeTheme.name,
443
+ colors: activeTheme.colors,
444
+ scheme: schemeOf(activeTheme.name),
445
+ },
446
+ preference,
389
447
  setTheme,
390
448
  isTransitioning,
391
- }), [activeTheme, setTheme, isTransitioning]);
392
- return (_jsx(Context.Provider, { value: contextValue, children: _jsxs(View, { ref: rootRef, style: ROOT_STYLE, collapsable: false, children: [children, _jsx(Animated.View, { style: ABSOLUTE_FILL, animatedProps: blockerProps }), _jsx(Animated.View, { style: [ABSOLUTE_FILL, overlayStyle], pointerEvents: "none", children: overlayUri != null ? (_jsx(Image, { source: overlaySource, style: ABSOLUTE_FILL, resizeMode: "cover", fadeDuration: 0, onLoad: onOverlayLoad, onError: onOverlayError })) : null })] }) }));
449
+ }), [activeTheme, preference, setTheme, isTransitioning]);
450
+ const overlayParamsForRender = overlayParams ?? DEFAULT_OVERLAY_PARAMS;
451
+ const handleInnerLayout = useCallback((e) => {
452
+ const { width, height } = e.nativeEvent.layout;
453
+ innerSizeRef.current = { width, height };
454
+ }, []);
455
+ return (_jsx(Context, { value: contextValue, children: _jsxs(View, { style: FLEX_FILL, collapsable: false, children: [_jsx(View, { ref: innerRef, style: FLEX_FILL, collapsable: false, onLayout: handleInnerLayout, children: children }), _jsx(Animated.View, { style: [ABSOLUTE_FILL, blockerStyle] }), _jsx(SkiaOverlay, { image: skImage, imageNew: skImageNew, progress: progress, params: overlayParamsForRender })] }) }));
393
456
  }
394
457
  return { Context, ThemeTransitionProvider };
395
458
  }