@wireai/activation 0.14.1 → 0.14.3

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.
@@ -1,4 +1,3 @@
1
- import { BlurView } from "expo-blur";
2
1
  import React, { useEffect, useMemo } from "react";
3
2
  import {
4
3
  Pressable,
@@ -7,7 +6,12 @@ import {
7
6
  useWindowDimensions,
8
7
  View,
9
8
  } from "react-native";
10
- import Animated, {
9
+
10
+ import { useOnboardingTheme } from "../theme/ThemeContext";
11
+ import { resolveBlurView } from "./expoBlur";
12
+ import { GestureHint } from "./GestureHint";
13
+ import {
14
+ Animated,
11
15
  FadeIn,
12
16
  FadeOut,
13
17
  useAnimatedProps,
@@ -17,14 +21,9 @@ import Animated, {
17
21
  withRepeat,
18
22
  withSequence,
19
23
  withTiming,
20
- } from "react-native-reanimated";
21
-
22
- import { useOnboardingTheme } from "../theme/ThemeContext";
23
- import { GestureHint } from "./GestureHint";
24
+ } from "./reanimated";
24
25
  import type { GestureKind, Placement, TargetRect } from "./types";
25
26
 
26
- const AnimatedBlurView = Animated.createAnimatedComponent(BlurView);
27
-
28
27
  const BLUR_INTENSITY = 26;
29
28
  const FADE_MS = 280;
30
29
  /** Breathing room between the highlighted element and the glowing ring. */
@@ -51,13 +50,25 @@ export interface SpotlightOverlayProps {
51
50
  }
52
51
 
53
52
  /**
54
- * A single coachmark step: the whole screen is frosted with an animated blur,
55
- * and a bright pulsing ring + tooltip point at one measured target. Mounted at
56
- * the app root (above the tab bar) via CoachmarkOverlayHost.
53
+ * A single coachmark step: the whole screen is frosted with an animated blur
54
+ * (or a plain dimmed scrim when the optional `expo-blur` peer is absent), and a
55
+ * bright pulsing ring + tooltip point at one measured target. Mounted at the app
56
+ * root (above the tab bar) via CoachmarkOverlayHost.
57
57
  *
58
58
  * Performance: one BlurView (mounted only while a step is visible), the ring
59
- * glow is a single reanimated view, and all animation runs on the UI thread.
60
- * Reduce Motion drops the pulse.
59
+ * glow is a single animated view, and with `react-native-reanimated` installed
60
+ * every animation runs on the UI thread. Reduce Motion drops the pulse.
61
+ *
62
+ * BOTH native peers are OPTIONAL, and each is resolved through a guarded lazy
63
+ * require, so the subpath never carries a static top-level import of either:
64
+ * • `expo-blur` (`expoBlur.ts`) — absent, the frost drops to an equivalent
65
+ * dimmed scrim. The animated component is built once, on first use.
66
+ * • `react-native-reanimated` (`reanimated.ts`) — absent, the overlay renders
67
+ * STATICALLY at its resting frame: the ring sits at scale 1 (no pulse), the
68
+ * blur at full BLUR_INTENSITY (no fade-in), and the whole overlay appears
69
+ * and leaves without the fade. Nothing moves; everything renders.
70
+ * A missing decoration must never blank a tour, so the ring, tooltip, copy and
71
+ * gestures are identical in all four combinations.
61
72
  */
62
73
  const SpotlightOverlayComponent: React.FC<SpotlightOverlayProps> = ({
63
74
  message,
@@ -76,6 +87,14 @@ const SpotlightOverlayComponent: React.FC<SpotlightOverlayProps> = ({
76
87
  const accent = accentColor ?? theme.colors.primary;
77
88
  const accentText = accentTextColor ?? theme.colors.onPrimary;
78
89
 
90
+ // Resolve the optional `expo-blur` peer and build its animated component ONCE, on first render,
91
+ // instead of at module scope — so merely importing this file (and thus the coachmarks subpath)
92
+ // never needs the peer. `null` = the peer is absent → the scrim path renders instead.
93
+ const AnimatedBlurView = useMemo(() => {
94
+ const BlurView = resolveBlurView();
95
+ return BlurView ? Animated.createAnimatedComponent(BlurView) : null;
96
+ }, []);
97
+
79
98
  // Tap / double-tap steps show ONLY the ring + tooltip — no gesture glyph. The
80
99
  // pulsing highlight ring already reads as "tap here", so an extra glyph is
81
100
  // noise. Every app inherits this centrally, with no config change.
@@ -138,11 +157,20 @@ const SpotlightOverlayComponent: React.FC<SpotlightOverlayProps> = ({
138
157
  entering={FadeIn.duration(FADE_MS)}
139
158
  exiting={FadeOut.duration(FADE_MS)}
140
159
  >
141
- <AnimatedBlurView
142
- tint="dark"
143
- animatedProps={blurAnimatedProps}
144
- style={StyleSheet.absoluteFill}
145
- />
160
+ {AnimatedBlurView ? (
161
+ <AnimatedBlurView
162
+ tint="dark"
163
+ animatedProps={blurAnimatedProps}
164
+ style={StyleSheet.absoluteFill}
165
+ />
166
+ ) : (
167
+ // `expo-blur` absent → a plain dimmed scrim stands in for the frost. Same dark backdrop
168
+ // the tour reads against, so the ring, tooltip and gestures behave identically.
169
+ <Animated.View
170
+ style={[StyleSheet.absoluteFill, styles.scrim]}
171
+ pointerEvents="none"
172
+ />
173
+ )}
146
174
 
147
175
  {/* Tap-the-backdrop to move on (dismisses the tour on the last step). */}
148
176
  <Pressable
@@ -210,6 +238,11 @@ const styles = StyleSheet.create({
210
238
  zIndex: 9999,
211
239
  elevation: 9999,
212
240
  },
241
+ // Fallback backdrop when `expo-blur` is absent. A structural dim (not a brand token), tuned to
242
+ // read like the dark blur at BLUR_INTENSITY so the ring + tooltip keep the same contrast.
243
+ scrim: {
244
+ backgroundColor: "rgba(0, 0, 0, 0.55)",
245
+ },
213
246
  ring: {
214
247
  position: "absolute",
215
248
  borderWidth: 2.5,
@@ -0,0 +1,135 @@
1
+ /**
2
+ * expoBlur — resolve `expo-blur`'s `BlurView`, lazily and optionally.
3
+ *
4
+ * ── WHY THIS DOES NOT BREAK THE NO-NATIVE-DEPENDENCY POLICY ──────────────────────────────
5
+ *
6
+ * `expo-blur` is an OPTIONAL peer of the coachmarks subpath. The spotlight overlay frosts the
7
+ * screen with it WHEN it is installed, and degrades to a plain dimmed scrim when it is not — the
8
+ * ring, tooltip and gestures behave identically either way (see SpotlightOverlay). So a host that
9
+ * never installs `expo-blur` can still run the guided tour, and the free tier that must load under
10
+ * Expo Go is not forced into a native module it cannot take.
11
+ *
12
+ * Before this file, `SpotlightOverlay` did `import { BlurView } from "expo-blur"` at module scope,
13
+ * and `coachmarks/index.ts` re-exports the overlay with no wildcard escape — so importing ANYTHING
14
+ * from `@wireai/activation/coachmarks`, even `setCoachmarkStorage`, dragged the peer in and a host
15
+ * without it hit a Metro resolution failure. This resolver removes that static edge.
16
+ *
17
+ * ── THE SPECIFIER MUST BE A STRING LITERAL, INSIDE A TRY/CATCH ───────────────────────────
18
+ *
19
+ * This follows `icons/expoIcons.ts` exactly, and its header carries the full autopsy. In short:
20
+ *
21
+ * • Metro collects dependencies STATICALLY, matching a call whose callee is literally the
22
+ * identifier `require` and whose argument is a STRING LITERAL. A variable specifier
23
+ * (`const req = require; req(name)`) is collected NOWHERE, so the module never enters the
24
+ * bundle — and the aliased `require` is Metro's own numeric-id-keyed `metroRequire`, which can
25
+ * never resolve a package-name string. That shape shipped broken once; do not restore it.
26
+ * • The call sitting inside a TRY/CATCH is literally how Metro marks the dependency `isOptional`:
27
+ * when the peer is absent Metro puts `null` in the dependencyMap and the require throws "Cannot
28
+ * find module" straight into the catch below. Do NOT "simplify" the try/catch away — it is what
29
+ * keeps the peer optional, not just tidy. (`withWireOnboarding` in metro/index.js adds a
30
+ * stub-to-empty-module safety net for hosts that disable Metro's `allowOptionalDependencies`.)
31
+ */
32
+ import type { ComponentType } from "react";
33
+
34
+ // Metro injects a module-scoped `require`; it is ABSENT in a pure-ESM runtime (the kit's own
35
+ // tests run under `node --test` as ESM). Declared locally so this type-checks without ambient
36
+ // Node types; the `typeof` guard keeps the reference ESM-safe.
37
+ declare const require: ((id: string) => unknown) | undefined;
38
+
39
+ /** A `require`-like resolver. Injectable in tests; production uses the guarded literal require. */
40
+ export type OptionalRequire = (moduleName: string) => unknown;
41
+
42
+ /** The minimal prop shape the overlay uses from `expo-blur`'s `BlurView`. */
43
+ export type BlurViewComponent = ComponentType<{
44
+ intensity?: number;
45
+ tint?: "light" | "dark" | "default";
46
+ style?: unknown;
47
+ children?: unknown;
48
+ }>;
49
+
50
+ /**
51
+ * The production resolver. The specifier is a LITERAL so Metro collects it (see the header); the
52
+ * `moduleName` parameter exists only to keep the `OptionalRequire` seam shape, so anything other
53
+ * than the one module this file owns resolves to undefined.
54
+ */
55
+ const runtimeRequire: OptionalRequire = (moduleName) => {
56
+ if (moduleName !== "expo-blur") return undefined;
57
+ if (typeof require !== "function") return undefined;
58
+ try {
59
+ return require("expo-blur");
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ };
64
+
65
+ /**
66
+ * TEST-ONLY seam. `SpotlightOverlay`'s public props are frozen, so it cannot take a `requireModule`
67
+ * the way `WireIcon` does — this lets a component render exercise the PRESENT path without the
68
+ * native peer installed. Production never sets it; `runtimeRequire` is the only resolver.
69
+ */
70
+ let testRequire: OptionalRequire | undefined;
71
+ export const __setBlurRequireForTests = (fn: OptionalRequire | undefined): void => {
72
+ testRequire = fn;
73
+ cached = undefined;
74
+ };
75
+
76
+ /** Read a module's `default` (Expo modules are consumed as default exports) or the namespace. */
77
+ const interop = (mod: unknown): Record<string, unknown> | undefined => {
78
+ if (!mod || typeof mod !== "object") return undefined;
79
+ const ns = mod as Record<string, unknown>;
80
+ // `expo-blur` exposes `BlurView` as a NAMED export; prefer the namespace when it already carries
81
+ // it, and only fall back to `default` for a CJS-interop wrapper.
82
+ if (ns.BlurView) return ns;
83
+ const def = (mod as { default?: unknown }).default;
84
+ if (def && typeof def === "object") return def as Record<string, unknown>;
85
+ return ns;
86
+ };
87
+
88
+ /**
89
+ * Narrow an unknown export to something mountable. `BlurView` is a real React component (function
90
+ * or class across versions), and React.memo / forwardRef wrappers are objects carrying `$$typeof`.
91
+ * Reject anything else rather than handing the reconciler a non-component.
92
+ */
93
+ const asComponent = (value: unknown): BlurViewComponent | undefined => {
94
+ if (typeof value === "function") return value as BlurViewComponent;
95
+ if (value && typeof value === "object" && "$$typeof" in (value as object)) {
96
+ return value as BlurViewComponent;
97
+ }
98
+ return undefined;
99
+ };
100
+
101
+ /**
102
+ * Module-level memo. `null` = "we looked and it is not there" (distinct from "not looked yet"),
103
+ * so an absent peer costs exactly one failed require per process, not one per overlay mount.
104
+ */
105
+ let cached: BlurViewComponent | null | undefined;
106
+
107
+ /** Reset the memo. TEST-ONLY seam — production never calls it. */
108
+ export const resetBlurModuleCache = (): void => {
109
+ cached = undefined;
110
+ };
111
+
112
+ /**
113
+ * Resolve the `BlurView` component, or undefined when the peer is absent/unresolvable.
114
+ * Never throws: an absent blur must degrade to a plain scrim, never break the tour.
115
+ *
116
+ * `requireModule` is injectable so tests can exercise BOTH the found and absent paths without
117
+ * installing the native peer (same convention as `resolveIconFamily` / `detectAppVersion`).
118
+ */
119
+ export const resolveBlurView = (
120
+ requireModule: OptionalRequire = testRequire ?? runtimeRequire,
121
+ ): BlurViewComponent | undefined => {
122
+ try {
123
+ if (cached === undefined || requireModule !== runtimeRequire) {
124
+ const resolved = interop(requireModule("expo-blur"));
125
+ const component = resolved ? asComponent(resolved.BlurView) : undefined;
126
+ // Don't poison the module memo from an injected test require.
127
+ if (requireModule === runtimeRequire) cached = component ?? null;
128
+ return component;
129
+ }
130
+ if (cached === null) return undefined;
131
+ return cached;
132
+ } catch {
133
+ return undefined;
134
+ }
135
+ };
@@ -2,8 +2,13 @@
2
2
  * @wireai/activation/coachmarks — the performance-first guided-tour engine.
3
3
  *
4
4
  * Subpath entry, kept OUT of the main barrel so the core kit stays dependency-
5
- * free: importing this pulls in the optional peers `react-native-reanimated` and
6
- * `expo-blur`. The app declares WHERE things anchor (useCoachmarkAnchor) and
5
+ * free. Importing this pulls in NO native peer: `react-native-reanimated` and
6
+ * `expo-blur` are both OPTIONAL and both reached through guarded lazy requires
7
+ * (`reanimated.ts`, `expoBlur.ts`). Installed, you get UI-thread animation and a
8
+ * frosted spotlight; absent, the tour still renders — statically, and with a
9
+ * plain dimmed scrim instead of the frost. (This doc used to say the subpath
10
+ * "pulls in" both peers, which was true until 0.14.2 / 0.14.3 removed the static
11
+ * imports.) The app declares WHERE things anchor (useCoachmarkAnchor) and
7
12
  * WHICH tour plays (useCoachmarkTour); the kit owns the animation, measuring,
8
13
  * blur, ring, gesture hand, and one-overlay-at-a-time queue.
9
14
  *
@@ -0,0 +1,342 @@
1
+ /**
2
+ * reanimated — resolve `react-native-reanimated`, lazily and optionally.
3
+ *
4
+ * ── WHY THIS DOES NOT BREAK THE NO-NATIVE-DEPENDENCY POLICY ──────────────────────────────
5
+ *
6
+ * `react-native-reanimated` is an OPTIONAL peer of the coachmarks subpath. `SpotlightOverlay` and
7
+ * `GestureHint` animate with it WHEN it is installed, and fall back to a STATIC render of the same
8
+ * visual when it is not — same ring, same tooltip, same glyph, same copy, same gestures, just
9
+ * without motion. So a host that never installs it can still run the guided tour and the feature
10
+ * showcase, and an Expo Go / Lite build is not forced into a native module it cannot take.
11
+ *
12
+ * Before this file, both components did `import Animated, { … } from "react-native-reanimated"` at
13
+ * module scope, and `coachmarks/index.ts` re-exports them with no wildcard escape — so importing
14
+ * ANYTHING from `@wireai/activation/coachmarks` (even `setCoachmarkStorage`) dragged the peer in,
15
+ * and a host without it hit a Metro resolution failure. `@wireai/activation/showcase` inherited the
16
+ * same edge through `GestureHint`. This resolver removes it. Same class as the 0.14.2 `expo-blur`
17
+ * fix (`expoBlur.ts`), same shape, one size up.
18
+ *
19
+ * ── THE SPECIFIER MUST BE A STRING LITERAL, INSIDE A TRY/CATCH ───────────────────────────
20
+ *
21
+ * This follows `icons/expoIcons.ts` and `coachmarks/expoBlur.ts` exactly, and expoIcons' header
22
+ * carries the full autopsy. In short: Metro collects dependencies STATICALLY, matching a call whose
23
+ * callee is literally the identifier `require` and whose argument is literally a string — an
24
+ * aliased callee (`const req = require; req(name)`) or a variable specifier is collected NOWHERE,
25
+ * so the module never enters the bundle (that shape shipped broken in 0.8.0). And the call sitting
26
+ * inside a TRY/CATCH is literally how Metro marks the dependency `isOptional`, which is what lets
27
+ * an absent peer degrade instead of failing the build. Do NOT "simplify" either half away.
28
+ *
29
+ * ── WHY THE EXPORTS ARE BARE FUNCTIONS WITH THE PEER'S OWN NAMES ─────────────────────────
30
+ *
31
+ * The call sites import `useAnimatedStyle` / `useAnimatedProps` / `withTiming` … from HERE instead
32
+ * of from the peer, and call them unqualified, exactly as before. That is load-bearing, not style:
33
+ * reanimated's Babel plugin decides what to workletize by the CALLEE NAME (`react-native-worklets`
34
+ * `plugin/index.js` → `reanimatedFunctionHooks` / `reanimatedFunctionArgsToWorkletize`; it reads
35
+ * `callee.name`, or `callee.property.name` for a member call, and never checks which module the
36
+ * name came from). Keeping the names identical keeps every worklet in `SpotlightOverlay` and
37
+ * `GestureHint` workletized byte-for-byte on a host that HAS the peer. Rename them and the
38
+ * animations silently stop running on the UI thread.
39
+ *
40
+ * ── THE DEGRADE: THE FINAL FRAME, NOT A DEAD ONE ─────────────────────────────────────────
41
+ *
42
+ * The shim resolves every animation to its RESTING value — `withTiming(to)` is `to`,
43
+ * `withSequence(a, b)` is `b`, `withRepeat(x)` is `x` — so a component lands on the pose it would
44
+ * have settled into anyway (ring at scale 1, glyph at full opacity, blur at BLUR_INTENSITY) rather
45
+ * than on frame zero, which for the blur would have meant a fully transparent overlay. Shared
46
+ * values are state-backed so a write from an effect actually reaches the next render; reanimated's
47
+ * own values do not need this because they drive the UI thread directly. The kit's own
48
+ * AccessibilityInfo-backed `useReducedMotion` stands in for the peer's, so the reduce-motion
49
+ * contract in ai_rules/rules/performance.md §3 holds with or without the peer.
50
+ *
51
+ * This is also what `ai_rules/rules/frequent_rules.md` #1 prescribes: when the kit needs motion
52
+ * without the optional peer, it uses core React Native, never Reanimated.
53
+ */
54
+ import {
55
+ createElement,
56
+ forwardRef,
57
+ useReducer,
58
+ useRef,
59
+ type ComponentType,
60
+ type ReactNode,
61
+ } from "react";
62
+ import { View, type ViewProps, type ViewStyle } from "react-native";
63
+
64
+ import { useReducedMotion as useOsReducedMotion } from "../motion/useReducedMotion";
65
+
66
+ // Metro injects a module-scoped `require`; it is ABSENT in a pure-ESM runtime (the kit's own tests
67
+ // run under `node --test` as ESM). Declared locally so this type-checks without ambient Node types;
68
+ // the `typeof` guard keeps the reference ESM-safe.
69
+ declare const require: ((id: string) => unknown) | undefined;
70
+
71
+ /** A `require`-like resolver. Injectable in tests; production uses the guarded literal require. */
72
+ export type OptionalRequire = (moduleName: string) => unknown;
73
+
74
+ /** A reanimated shared value, narrowed to the one member the kit uses. */
75
+ export interface SharedValue<T> {
76
+ value: T;
77
+ }
78
+
79
+ /** Props `Animated.View` accepts on top of a plain View (layout-animation descriptors). */
80
+ export interface AnimatedViewProps extends ViewProps {
81
+ entering?: unknown;
82
+ exiting?: unknown;
83
+ children?: ReactNode;
84
+ }
85
+
86
+ /** A component built by `createAnimatedComponent`: its own props plus reanimated's driven props. */
87
+ export type AnimatedComponent<P> = ComponentType<P & { animatedProps?: object }>;
88
+
89
+ /** The slice of reanimated the coachmark surfaces actually use. */
90
+ export interface ReanimatedApi {
91
+ /** True when the real peer resolved; false when this is the static fallback. */
92
+ present: boolean;
93
+ View: ComponentType<AnimatedViewProps>;
94
+ createAnimatedComponent: <P extends object>(component: ComponentType<P>) => AnimatedComponent<P>;
95
+ useSharedValue: <T>(initial: T) => SharedValue<T>;
96
+ useAnimatedStyle: (factory: () => ViewStyle) => ViewStyle;
97
+ useAnimatedProps: <P extends object>(factory: () => P) => P;
98
+ useReducedMotion: () => boolean;
99
+ withTiming: (toValue: number, config?: object) => number;
100
+ withRepeat: (animation: number, count?: number, reverse?: boolean) => number;
101
+ withSequence: (...animations: number[]) => number;
102
+ withDelay: (ms: number, animation: number) => number;
103
+ /** The `entering` / `exiting` descriptors, or undefined when the peer is absent. */
104
+ fadeIn: (durationMs: number) => unknown;
105
+ fadeOut: (durationMs: number) => unknown;
106
+ }
107
+
108
+ /**
109
+ * The production resolver. The specifier is a LITERAL so Metro collects it (see the header); the
110
+ * `moduleName` parameter exists only to keep the `OptionalRequire` seam shape, so anything other
111
+ * than the one module this file owns resolves to undefined.
112
+ */
113
+ const runtimeRequire: OptionalRequire = (moduleName) => {
114
+ if (moduleName !== "react-native-reanimated") return undefined;
115
+ if (typeof require !== "function") return undefined;
116
+ try {
117
+ return require("react-native-reanimated");
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ };
122
+
123
+ /**
124
+ * TEST-ONLY seam. `SpotlightOverlay` / `GestureHint` have frozen public props, so neither can take
125
+ * a `requireModule` the way `WireIcon` does — this lets a component render exercise the PRESENT
126
+ * path. Production never sets it; `runtimeRequire` is the only resolver.
127
+ */
128
+ let testRequire: OptionalRequire | undefined;
129
+ export const __setReanimatedRequireForTests = (fn: OptionalRequire | undefined): void => {
130
+ testRequire = fn;
131
+ cached = undefined;
132
+ };
133
+
134
+ // ── the static fallback ───────────────────────────────────────────────────────
135
+
136
+ /**
137
+ * A shared value that re-renders its owner on write. Reanimated's own value drives the UI thread
138
+ * and deliberately does NOT re-render; here the render IS the only output, so a value written from
139
+ * an effect (`intensity.value = withTiming(26)`) has to reach it or the overlay would sit on frame
140
+ * zero forever — a fully transparent blur. The box identity is stable for the component's lifetime,
141
+ * exactly like the real one, so it stays safe in a dependency list.
142
+ */
143
+ const useStaticSharedValue = <T,>(initial: T): SharedValue<T> => {
144
+ const [, bump] = useReducer((n: number): number => n + 1, 0);
145
+ const box = useRef<SharedValue<T> | null>(null);
146
+ if (box.current === null) {
147
+ let current = initial;
148
+ box.current = {
149
+ get value(): T {
150
+ return current;
151
+ },
152
+ set value(next: T) {
153
+ if (Object.is(next, current)) return;
154
+ current = next;
155
+ bump();
156
+ },
157
+ };
158
+ }
159
+ return box.current;
160
+ };
161
+
162
+ /** Run a worklet body on the JS side. It must never throw into the render — degrade, don't crash. */
163
+ const runWorklet = <R extends object>(factory: () => R, fallback: R): R => {
164
+ try {
165
+ return factory() ?? fallback;
166
+ } catch {
167
+ return fallback;
168
+ }
169
+ };
170
+
171
+ /** `Animated.View` without the peer: a plain View, with the layout-animation props dropped. */
172
+ const StaticAnimatedView = forwardRef<View, AnimatedViewProps>(function StaticAnimatedView(
173
+ { entering: _entering, exiting: _exiting, children, ...rest },
174
+ ref,
175
+ ) {
176
+ return createElement(View, { ...rest, ref }, children);
177
+ });
178
+
179
+ /**
180
+ * `createAnimatedComponent` without the peer. The wrapper MERGES `animatedProps` into the real
181
+ * props, because that object is the only carrier for values the worklet would have driven (the
182
+ * spotlight's blur `intensity`). Built once per wrapped component at the call site's `useMemo`, so
183
+ * the returned type identity is stable and React never remounts the subtree.
184
+ */
185
+ const staticCreateAnimatedComponent = <P extends object>(
186
+ component: ComponentType<P>,
187
+ ): AnimatedComponent<P> =>
188
+ function StaticAnimatedComponent({ animatedProps, ...rest }) {
189
+ return createElement(component, { ...(rest as P), ...(animatedProps as object) });
190
+ };
191
+
192
+ /**
193
+ * The peer-absent API. Every animation resolves to its RESTING value, so components render the
194
+ * frame they would have settled on. Nothing here schedules work, allocates a native module, or
195
+ * throws.
196
+ */
197
+ const staticApi: ReanimatedApi = {
198
+ present: false,
199
+ View: StaticAnimatedView,
200
+ createAnimatedComponent: staticCreateAnimatedComponent,
201
+ useSharedValue: useStaticSharedValue,
202
+ useAnimatedStyle: (factory) => runWorklet(factory, {}),
203
+ useAnimatedProps: (factory) => runWorklet(factory, {} as never),
204
+ useReducedMotion: useOsReducedMotion,
205
+ withTiming: (toValue) => toValue,
206
+ withRepeat: (animation) => animation,
207
+ withSequence: (...animations) => animations[animations.length - 1] ?? 0,
208
+ withDelay: (_ms, animation) => animation,
209
+ fadeIn: () => undefined,
210
+ fadeOut: () => undefined,
211
+ };
212
+
213
+ // ── the real peer ─────────────────────────────────────────────────────────────
214
+
215
+ const isFunction = (value: unknown): boolean => typeof value === "function";
216
+
217
+ /** A React component is a function, or an object carrying `$$typeof` (memo / forwardRef). */
218
+ const isComponent = (value: unknown): boolean =>
219
+ typeof value === "function" || (!!value && typeof value === "object" && "$$typeof" in value);
220
+
221
+ /**
222
+ * Build the API from a resolved module namespace, or undefined when it is not the module we expect.
223
+ *
224
+ * The hooks are NAMED exports; `View` and `createAnimatedComponent` live on the DEFAULT export (the
225
+ * `Animated` object). A CJS interop wrapper puts everything one level down under `default`, so both
226
+ * are looked up on the namespace first and the default second. EVERY member is verified before the
227
+ * namespace is accepted: a partial module must degrade to the static fallback, never crash halfway
228
+ * through a render.
229
+ */
230
+ const fromModule = (mod: unknown): ReanimatedApi | undefined => {
231
+ if (!mod || typeof mod !== "object") return undefined;
232
+ const ns = mod as Record<string, unknown>;
233
+ const def =
234
+ ns.default && typeof ns.default === "object"
235
+ ? (ns.default as Record<string, unknown>)
236
+ : undefined;
237
+ const pick = (name: string): unknown => ns[name] ?? def?.[name];
238
+
239
+ const view = def?.View ?? ns.View;
240
+ const createAnimated = def?.createAnimatedComponent ?? ns.createAnimatedComponent;
241
+ const hooks = {
242
+ useSharedValue: pick("useSharedValue"),
243
+ useAnimatedStyle: pick("useAnimatedStyle"),
244
+ useAnimatedProps: pick("useAnimatedProps"),
245
+ useReducedMotion: pick("useReducedMotion"),
246
+ withTiming: pick("withTiming"),
247
+ withRepeat: pick("withRepeat"),
248
+ withSequence: pick("withSequence"),
249
+ withDelay: pick("withDelay"),
250
+ };
251
+ const fadeIn = pick("FadeIn");
252
+ const fadeOut = pick("FadeOut");
253
+
254
+ if (!isComponent(view) || !isFunction(createAnimated)) return undefined;
255
+ if (Object.values(hooks).some((member) => !isFunction(member))) return undefined;
256
+ if (!fadeIn || !fadeOut) return undefined;
257
+
258
+ // The single narrowing seam. Everything above proved the members exist and are callable; the peer
259
+ // is untyped here (it is resolved through `unknown`), so the cast happens once, at the boundary,
260
+ // and the exported signatures above are the contract from here on.
261
+ const api = {
262
+ present: true,
263
+ View: view,
264
+ createAnimatedComponent: createAnimated,
265
+ ...hooks,
266
+ fadeIn: (durationMs: number) => (fadeIn as { duration: (ms: number) => unknown }).duration(durationMs),
267
+ fadeOut: (durationMs: number) => (fadeOut as { duration: (ms: number) => unknown }).duration(durationMs),
268
+ } as unknown as ReanimatedApi;
269
+ return api;
270
+ };
271
+
272
+ /**
273
+ * Module-level memo. Holds the RESOLVED api (real or static), so an absent peer costs exactly one
274
+ * failed require per process, not one per mount — and, more importantly, so the implementation can
275
+ * never change between two renders of the same component, which would break the rules of hooks.
276
+ */
277
+ let cached: ReanimatedApi | undefined;
278
+
279
+ /** Reset the memo. TEST-ONLY seam — production never calls it. */
280
+ export const resetReanimatedModuleCache = (): void => {
281
+ cached = undefined;
282
+ };
283
+
284
+ /**
285
+ * Resolve the reanimated API, or the static fallback when the peer is absent/unresolvable.
286
+ * Never throws and never returns undefined: an absent animation library must degrade to a still
287
+ * frame, never break the tour.
288
+ */
289
+ export const resolveReanimated = (
290
+ requireModule: OptionalRequire = testRequire ?? runtimeRequire,
291
+ ): ReanimatedApi => {
292
+ try {
293
+ if (cached === undefined || requireModule !== runtimeRequire) {
294
+ const resolved = fromModule(requireModule("react-native-reanimated")) ?? staticApi;
295
+ // Don't poison the module memo from an injected test require.
296
+ if (requireModule === runtimeRequire) cached = resolved;
297
+ return resolved;
298
+ }
299
+ return cached;
300
+ } catch {
301
+ return staticApi;
302
+ }
303
+ };
304
+
305
+ // ── the call-site surface: the peer's own names, resolved lazily ──────────────
306
+ //
307
+ // Each one delegates on every call, so nothing is resolved at import time. `api()` is memoized, so
308
+ // the delegation is a property read.
309
+
310
+ const api = (): ReanimatedApi => resolveReanimated();
311
+
312
+ /**
313
+ * The `Animated` namespace, with `View` behind a getter so merely importing this module never
314
+ * touches the peer. The component identity it returns is stable (the peer's own `Animated.View`, or
315
+ * the module-level `StaticAnimatedView`), so React never remounts the tree under it.
316
+ */
317
+ export const Animated: {
318
+ readonly View: ComponentType<AnimatedViewProps>;
319
+ createAnimatedComponent: <P extends object>(component: ComponentType<P>) => AnimatedComponent<P>;
320
+ } = {
321
+ get View() {
322
+ return api().View;
323
+ },
324
+ createAnimatedComponent: (component) => api().createAnimatedComponent(component),
325
+ };
326
+
327
+ /** Layout-animation descriptors. `.duration()` is the only builder the kit uses. */
328
+ export const FadeIn = { duration: (durationMs: number): unknown => api().fadeIn(durationMs) };
329
+ export const FadeOut = { duration: (durationMs: number): unknown => api().fadeOut(durationMs) };
330
+
331
+ export const useSharedValue = <T,>(initial: T): SharedValue<T> => api().useSharedValue(initial);
332
+ export const useAnimatedStyle = (factory: () => ViewStyle): ViewStyle =>
333
+ api().useAnimatedStyle(factory);
334
+ export const useAnimatedProps = <P extends object>(factory: () => P): P =>
335
+ api().useAnimatedProps(factory);
336
+ export const useReducedMotion = (): boolean => api().useReducedMotion();
337
+ export const withTiming = (toValue: number, config?: object): number =>
338
+ api().withTiming(toValue, config);
339
+ export const withRepeat = (animation: number, count?: number, reverse?: boolean): number =>
340
+ api().withRepeat(animation, count, reverse);
341
+ export const withSequence = (...animations: number[]): number => api().withSequence(...animations);
342
+ export const withDelay = (ms: number, animation: number): number => api().withDelay(ms, animation);