@rootnative/inertia 0.0.0-alpha.2 → 0.0.0-alpha.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.
package/dist/index.mjs CHANGED
@@ -1,1359 +1,23 @@
1
- import { Image, Pressable, ScrollView, Text, View, Platform } from 'react-native';
2
- import { createContext, forwardRef, useRef, useState, useEffect, useMemo, useContext, useCallback, Children, isValidElement } from 'react';
3
- import Animated, { useSharedValue, useAnimatedStyle, interpolateColor, reanimatedVersion, useReducedMotion, withSequence, LinearTransition, runOnJS, withRepeat, withTiming, withSpring, withDelay, withDecay, Easing, useAnimatedReaction, useDerivedValue, Extrapolation, useAnimatedScrollHandler, interpolate } from 'react-native-reanimated';
4
- import { jsx, Fragment } from 'react/jsx-runtime';
1
+ export { useGesture } from './chunk-W6IS4HAK.mjs';
2
+ import { MotionView } from './chunk-RJNR7CFN.mjs';
3
+ export { MotionView } from './chunk-RJNR7CFN.mjs';
4
+ import { MotionText } from './chunk-FSPQVLBF.mjs';
5
+ export { MotionText } from './chunk-FSPQVLBF.mjs';
6
+ import { MotionImage } from './chunk-UM3WVSKQ.mjs';
7
+ export { MotionImage } from './chunk-UM3WVSKQ.mjs';
8
+ import { MotionPressable } from './chunk-E4MDU4YV.mjs';
9
+ export { MotionPressable } from './chunk-E4MDU4YV.mjs';
10
+ import { MotionScrollView } from './chunk-KARV7QKF.mjs';
11
+ export { MotionScrollView } from './chunk-KARV7QKF.mjs';
12
+ export { Presence, createMotionComponent, usePresence } from './chunk-UXK4YCT6.mjs';
13
+ import { useShouldReduceMotion, resolveNamedTransition, useNamedTransitions, lookupNamedTransition } from './chunk-GJD4VVAS.mjs';
14
+ export { MotionConfig, resolveNamedTransition, useMotionConfig, useNamedTransitions, useShouldReduceMotion } from './chunk-GJD4VVAS.mjs';
15
+ import { stableSig, resolveTransition, springToReanimated } from './chunk-6FENLMCA.mjs';
16
+ export { buildReleaseAnimation, cubicBezier, ensureWorkletEasing, resolveAnimatableValue, resolveTransition } from './chunk-6FENLMCA.mjs';
17
+ import { useEffect, useMemo, useRef } from 'react';
18
+ import { useSharedValue, withSpring, useAnimatedReaction, useAnimatedStyle, interpolateColor, useDerivedValue, Extrapolation, useAnimatedScrollHandler, interpolate } from 'react-native-reanimated';
5
19
  import { isWorkletFunction } from 'react-native-worklets';
6
20
 
7
- // src/motion/Image.tsx
8
-
9
- // src/transitions/sig.ts
10
- function stableSig(value) {
11
- if (value === void 0) return "";
12
- try {
13
- return stableStringify(value);
14
- } catch {
15
- return String(value);
16
- }
17
- }
18
- function stableStringify(v) {
19
- if (v === null || typeof v !== "object") {
20
- if (typeof v === "function" || v === void 0) return "null";
21
- return JSON.stringify(v);
22
- }
23
- if (Array.isArray(v)) {
24
- return "[" + v.map(stableStringify).join(",") + "]";
25
- }
26
- const obj = v;
27
- const keys = Object.keys(obj).sort();
28
- return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";
29
- }
30
- var DEFAULT_MOTION_CONFIG = {
31
- reducedMotion: "user",
32
- transitions: {}
33
- };
34
- var MotionConfigContext = createContext(
35
- DEFAULT_MOTION_CONFIG
36
- );
37
- function useMotionConfig() {
38
- return useContext(MotionConfigContext);
39
- }
40
- function useNamedTransitions() {
41
- return useMotionConfig().transitions;
42
- }
43
- function useShouldReduceMotion() {
44
- const { reducedMotion } = useMotionConfig();
45
- const osReduced = useReducedMotion();
46
- if (reducedMotion === "never") return false;
47
- if (reducedMotion === "always") return true;
48
- return osReduced;
49
- }
50
- function MotionConfig({
51
- reducedMotion,
52
- transitions,
53
- children
54
- }) {
55
- const parent = useMotionConfig();
56
- const transitionsSig = stableSig(transitions);
57
- const value = useMemo(
58
- () => ({
59
- reducedMotion: reducedMotion ?? parent.reducedMotion,
60
- transitions: transitions ? { ...parent.transitions, ...transitions } : parent.transitions
61
- }),
62
- // eslint-disable-next-line react-hooks/exhaustive-deps
63
- [reducedMotion, transitionsSig, parent]
64
- );
65
- return /* @__PURE__ */ jsx(MotionConfigContext.Provider, { value, children });
66
- }
67
-
68
- // src/transitions/keys.ts
69
- var TRANSITION_CONFIG_KEYS = /* @__PURE__ */ new Set([
70
- "type",
71
- "tension",
72
- "friction",
73
- "mass",
74
- "velocity",
75
- "restSpeedThreshold",
76
- "restDisplacementThreshold",
77
- "duration",
78
- "easing",
79
- "delay",
80
- "repeat",
81
- "deceleration",
82
- "clamp"
83
- ]);
84
- function isTopLevelTransition(t) {
85
- if (t === null || typeof t !== "object") return false;
86
- const keys = Object.keys(t);
87
- if (keys.length === 0) return false;
88
- return keys.every((k) => TRANSITION_CONFIG_KEYS.has(k));
89
- }
90
-
91
- // src/config/namedTransitions.ts
92
- var UNKNOWN_NAME_FALLBACK = { type: "spring" };
93
- function lookupNamedTransition(name, registry) {
94
- const cfg = registry[name];
95
- if (cfg) return cfg;
96
- if (__DEV__) {
97
- console.warn(
98
- `[inertia] Unknown transition name "${name}" \u2014 falling back to the default spring. Register it on a provider: <MotionConfig transitions={{ '${name}': { ... } }}>.`
99
- );
100
- }
101
- return UNKNOWN_NAME_FALLBACK;
102
- }
103
- function resolveNamedTransition(input, registry) {
104
- if (input === void 0) return void 0;
105
- if (typeof input === "string") return lookupNamedTransition(input, registry);
106
- return input;
107
- }
108
- function resolveNamedTransitionProp(transition, registry) {
109
- if (transition === void 0) return void 0;
110
- if (typeof transition === "string") {
111
- return lookupNamedTransition(transition, registry);
112
- }
113
- if (isTopLevelTransition(transition)) return transition;
114
- const map = transition;
115
- let out = null;
116
- for (const key in map) {
117
- const value = map[key];
118
- if (typeof value === "string") {
119
- if (out === null) out = { ...map };
120
- out[key] = lookupNamedTransition(value, registry);
121
- }
122
- }
123
- return out ?? transition;
124
- }
125
- var modality = "keyboard";
126
- var installed = false;
127
- function setKeyboard() {
128
- modality = "keyboard";
129
- }
130
- function setPointer() {
131
- modality = "pointer";
132
- }
133
- function ensureInstalled() {
134
- if (installed) return;
135
- if (Platform.OS !== "web") return;
136
- if (typeof document === "undefined") return;
137
- document.addEventListener("keydown", setKeyboard, true);
138
- document.addEventListener("mousedown", setPointer, true);
139
- document.addEventListener("pointerdown", setPointer, true);
140
- document.addEventListener("touchstart", setPointer, true);
141
- installed = true;
142
- }
143
- function isFocusVisible() {
144
- if (Platform.OS !== "web") return true;
145
- ensureInstalled();
146
- return modality === "keyboard";
147
- }
148
- function ensureWorkletEasing(easing) {
149
- if (!easing) return void 0;
150
- const fn = isEasingFactory(easing) ? easing.factory() : easing;
151
- if (isWorkletFunction(fn)) return fn;
152
- const wrapped = (t) => {
153
- "worklet";
154
- return fn(t);
155
- };
156
- return wrapped;
157
- }
158
- function isEasingFactory(value) {
159
- return typeof value === "object" && value !== null && "factory" in value && typeof value.factory === "function";
160
- }
161
-
162
- // src/transitions/spring.ts
163
- var DEFAULT_SPRING = {
164
- tension: 170,
165
- friction: 26,
166
- mass: 1
167
- };
168
- function springToReanimated(t) {
169
- "worklet";
170
- return {
171
- stiffness: t.tension ?? DEFAULT_SPRING.tension,
172
- damping: t.friction ?? DEFAULT_SPRING.friction,
173
- mass: t.mass ?? DEFAULT_SPRING.mass,
174
- velocity: t.velocity,
175
- restSpeedThreshold: t.restSpeedThreshold,
176
- restDisplacementThreshold: t.restDisplacementThreshold
177
- };
178
- }
179
-
180
- // src/layout/resolveLayout.ts
181
- function resolveLayoutTransition(layout) {
182
- if (!layout) return void 0;
183
- const cfg = layout === true ? { type: "spring" } : layout;
184
- if (cfg.type === "no-animation") return void 0;
185
- if (cfg.type === "timing") {
186
- let builder2 = LinearTransition.duration(cfg.duration ?? 300);
187
- const easing = ensureWorkletEasing(cfg.easing);
188
- if (easing) builder2 = builder2.easing(easing);
189
- if (cfg.delay) builder2 = builder2.delay(cfg.delay);
190
- return builder2;
191
- }
192
- const spring = cfg.type === "decay" ? { type: "spring" } : cfg;
193
- const { stiffness, damping, mass } = springToReanimated({
194
- ...DEFAULT_SPRING,
195
- ...spring
196
- });
197
- let builder = LinearTransition.springify().stiffness(stiffness).damping(damping).mass(mass);
198
- if ("delay" in spring && spring.delay) builder = builder.delay(spring.delay);
199
- return builder;
200
- }
201
-
202
- // src/layout/sharedRegistry.ts
203
- var REGISTRY = /* @__PURE__ */ new Map();
204
- var SHARED_LAYOUT_TTL_MS = 1e3;
205
- var now = () => Date.now();
206
- function registerLayout(id, rect) {
207
- REGISTRY.set(id, { rect, expiresAt: now() + SHARED_LAYOUT_TTL_MS });
208
- }
209
- function releaseLayout(id, rect) {
210
- REGISTRY.set(id, { rect, expiresAt: now() + SHARED_LAYOUT_TTL_MS });
211
- }
212
- function consumeLayout(id) {
213
- const entry = REGISTRY.get(id);
214
- if (!entry) return void 0;
215
- REGISTRY.delete(id);
216
- if (entry.expiresAt < now()) return void 0;
217
- return entry.rect;
218
- }
219
- function useSharedLayout(options) {
220
- const { layoutId, userRef, transition, shouldReduceMotion, userOnLayout } = options;
221
- const dx = useSharedValue(0);
222
- const dy = useSharedValue(0);
223
- const sx = useSharedValue(1);
224
- const sy = useSharedValue(1);
225
- const lastRectRef = useRef(null);
226
- const consumedRef = useRef(false);
227
- const transitionRef = useRef(transition);
228
- transitionRef.current = transition;
229
- const reducedMotionRef = useRef(shouldReduceMotion);
230
- reducedMotionRef.current = shouldReduceMotion;
231
- const setRef = useCallback(
232
- (node) => {
233
- if (typeof userRef === "function") userRef(node);
234
- else if (userRef) userRef.current = node;
235
- },
236
- [userRef]
237
- );
238
- const onLayout = useCallback(
239
- (event) => {
240
- userOnLayout?.(event);
241
- if (!layoutId) return;
242
- const { x, y, width, height } = event.nativeEvent.layout;
243
- const rect = { x, y, width, height };
244
- lastRectRef.current = rect;
245
- let source;
246
- if (!consumedRef.current) {
247
- consumedRef.current = true;
248
- source = consumeLayout(layoutId);
249
- }
250
- registerLayout(layoutId, rect);
251
- if (source) {
252
- applyFlip({
253
- source,
254
- target: rect,
255
- dx,
256
- dy,
257
- sx,
258
- sy,
259
- transition: transitionRef.current,
260
- shouldReduceMotion: reducedMotionRef.current
261
- });
262
- }
263
- },
264
- // dx/dy/sx/sy are stable refs from useSharedValue, but eslint's
265
- // exhaustive-deps would flag them — including them is harmless and
266
- // silences the warning.
267
- [layoutId, userOnLayout, dx, dy, sx, sy]
268
- );
269
- useEffect(() => {
270
- consumedRef.current = false;
271
- }, [layoutId]);
272
- useEffect(() => {
273
- return () => {
274
- if (!layoutId) return;
275
- const rect = lastRectRef.current;
276
- if (!rect) return;
277
- releaseLayout(layoutId, rect);
278
- };
279
- }, [layoutId]);
280
- return useMemo(
281
- () => ({
282
- flip: { dx, dy, sx, sy },
283
- setRef,
284
- onLayout
285
- }),
286
- [dx, dy, sx, sy, setRef, onLayout]
287
- );
288
- }
289
- function applyFlip(args) {
290
- const { source, target, dx, dy, sx, sy, transition, shouldReduceMotion } = args;
291
- const sourceCenterX = source.x + source.width / 2;
292
- const sourceCenterY = source.y + source.height / 2;
293
- const targetCenterX = target.x + target.width / 2;
294
- const targetCenterY = target.y + target.height / 2;
295
- const deltaX = sourceCenterX - targetCenterX;
296
- const deltaY = sourceCenterY - targetCenterY;
297
- const scaleX = target.width > 0 ? source.width / target.width : 1;
298
- const scaleY = target.height > 0 ? source.height / target.height : 1;
299
- if (shouldReduceMotion) {
300
- dx.value = 0;
301
- dy.value = 0;
302
- sx.value = 1;
303
- sy.value = 1;
304
- return;
305
- }
306
- if (transition?.type === "no-animation") {
307
- dx.value = 0;
308
- dy.value = 0;
309
- sx.value = 1;
310
- sy.value = 1;
311
- return;
312
- }
313
- if (transition?.type === "timing") {
314
- const duration = transition.duration ?? 300;
315
- dx.value = withSequence(
316
- withTiming(deltaX, { duration: 0 }),
317
- withTiming(0, { duration })
318
- );
319
- dy.value = withSequence(
320
- withTiming(deltaY, { duration: 0 }),
321
- withTiming(0, { duration })
322
- );
323
- sx.value = withSequence(
324
- withTiming(scaleX, { duration: 0 }),
325
- withTiming(1, { duration })
326
- );
327
- sy.value = withSequence(
328
- withTiming(scaleY, { duration: 0 }),
329
- withTiming(1, { duration })
330
- );
331
- return;
332
- }
333
- const springCfg = transition?.type === "spring" ? { ...DEFAULT_SPRING, ...transition } : { ...DEFAULT_SPRING };
334
- const springParams = springToReanimated(springCfg);
335
- dx.value = withSequence(
336
- withTiming(deltaX, { duration: 0 }),
337
- withSpring(0, springParams)
338
- );
339
- dy.value = withSequence(
340
- withTiming(deltaY, { duration: 0 }),
341
- withSpring(0, springParams)
342
- );
343
- sx.value = withSequence(
344
- withTiming(scaleX, { duration: 0 }),
345
- withSpring(1, springParams)
346
- );
347
- sy.value = withSequence(
348
- withTiming(scaleY, { duration: 0 }),
349
- withSpring(1, springParams)
350
- );
351
- }
352
- var PresenceContext = createContext(null);
353
- function usePresence() {
354
- return useContext(PresenceContext);
355
- }
356
- function Presence({ children }) {
357
- const incoming = useMemo(() => {
358
- const out = [];
359
- Children.forEach(children, (child) => {
360
- if (!isValidElement(child)) return;
361
- if (child.key === null) {
362
- if (__DEV__) {
363
- console.warn(
364
- "[inertia] <Presence> children must have a `key`. Skipping a keyless child."
365
- );
366
- }
367
- return;
368
- }
369
- out.push(child);
370
- });
371
- return out;
372
- }, [children]);
373
- const [exiting, setExiting] = useState(
374
- () => /* @__PURE__ */ new Map()
375
- );
376
- const prevIncomingRef = useRef(incoming);
377
- if (prevIncomingRef.current !== incoming) {
378
- const prev = prevIncomingRef.current;
379
- prevIncomingRef.current = incoming;
380
- const incomingKeys = new Set(incoming.map((el) => el.key));
381
- let next = null;
382
- const ensureMutable = () => {
383
- if (!next) next = new Map(exiting);
384
- return next;
385
- };
386
- for (const oldEl of prev) {
387
- const key = oldEl.key;
388
- if (!incomingKeys.has(key) && !exiting.has(key)) {
389
- ensureMutable().set(key, oldEl);
390
- }
391
- }
392
- for (const el of incoming) {
393
- const key = el.key;
394
- if (exiting.has(key)) {
395
- ensureMutable().delete(key);
396
- }
397
- }
398
- if (next) setExiting(next);
399
- }
400
- const handleRemove = useCallback((key) => {
401
- setExiting((prev) => {
402
- if (!prev.has(key)) return prev;
403
- const next = new Map(prev);
404
- next.delete(key);
405
- return next;
406
- });
407
- }, []);
408
- const renderList = [];
409
- for (const el of incoming) {
410
- renderList.push({
411
- key: el.key,
412
- element: el,
413
- isPresent: true
414
- });
415
- }
416
- for (const [key, el] of exiting) {
417
- if (!renderList.some((entry) => entry.key === key)) {
418
- renderList.push({ key, element: el, isPresent: false });
419
- }
420
- }
421
- return /* @__PURE__ */ jsx(Fragment, { children: renderList.map(({ key, element, isPresent }) => /* @__PURE__ */ jsx(
422
- PresenceItem,
423
- {
424
- itemKey: key,
425
- isPresent,
426
- onRemove: handleRemove,
427
- children: element
428
- },
429
- key
430
- )) });
431
- }
432
- function PresenceItem({
433
- itemKey,
434
- isPresent,
435
- onRemove,
436
- children
437
- }) {
438
- const value = useMemo(
439
- () => ({
440
- isPresent,
441
- safeToRemove: () => onRemove(itemKey)
442
- }),
443
- [isPresent, itemKey, onRemove]
444
- );
445
- return /* @__PURE__ */ jsx(PresenceContext.Provider, { value, children });
446
- }
447
- var DEFAULT_TIMING_DURATION = 250;
448
- function buildSpring(cfg, toValue, cb) {
449
- return withSpring(toValue, springToReanimated(cfg), cb);
450
- }
451
- function buildTiming(cfg, toValue, cb) {
452
- return withTiming(
453
- toValue,
454
- {
455
- duration: cfg.duration ?? DEFAULT_TIMING_DURATION,
456
- easing: ensureWorkletEasing(cfg.easing) ?? Easing.inOut(Easing.ease)
457
- },
458
- cb
459
- );
460
- }
461
- function buildDecay(cfg, cb) {
462
- return withDecay(
463
- {
464
- velocity: cfg.velocity ?? 0,
465
- deceleration: cfg.deceleration,
466
- clamp: cfg.clamp
467
- },
468
- cb
469
- );
470
- }
471
- function buildOne(cfg, toValue, cb) {
472
- if (cfg.type === "no-animation") {
473
- if (cb) cb(true, toValue);
474
- return toValue;
475
- }
476
- if (cfg.type === "decay") return buildDecay(cfg, cb);
477
- if (cfg.type === "timing") return buildTiming(cfg, toValue, cb);
478
- return buildSpring(cfg, toValue, cb);
479
- }
480
- function applyRepeat(animation, repeat) {
481
- if (repeat === void 0) return animation;
482
- if (repeat === "infinite") {
483
- return withRepeat(animation, -1, true);
484
- }
485
- if (typeof repeat === "number") {
486
- return withRepeat(animation, repeat, true);
487
- }
488
- const count = repeat.count === "infinite" ? -1 : repeat.count;
489
- const alternate = repeat.alternate ?? true;
490
- return withRepeat(animation, count, alternate);
491
- }
492
- function applyDelay(animation, delay) {
493
- if (!delay || delay <= 0) return animation;
494
- return withDelay(delay, animation);
495
- }
496
- function resolveTransition(config, toValue, callback) {
497
- const cfg = config ?? { type: "spring" };
498
- const base = buildOne(cfg, toValue, callback);
499
- const repeated = applyRepeat(base, repeatOf(cfg));
500
- return applyDelay(repeated, delayOf(cfg));
501
- }
502
- function repeatOf(cfg) {
503
- if (cfg.type === "no-animation" || cfg.type === "decay") return void 0;
504
- return cfg.repeat;
505
- }
506
- function stripRepeat(cfg) {
507
- if (!cfg) return cfg;
508
- if (cfg.type === "no-animation" || cfg.type === "decay") return cfg;
509
- if (cfg.repeat === void 0) return cfg;
510
- const next = { ...cfg };
511
- delete next.repeat;
512
- return next;
513
- }
514
- function delayOf(cfg) {
515
- if (cfg.type === "no-animation") return void 0;
516
- return cfg.delay;
517
- }
518
- function isStepObject(v) {
519
- return typeof v === "object" && v !== null && !Array.isArray(v) && "to" in v;
520
- }
521
- function resolveAnimatableValue(value, base, factory) {
522
- if (Array.isArray(value)) {
523
- const steps = value;
524
- const stepBase = stripRepeat(base);
525
- const animations = steps.map(
526
- (step2, i) => resolveStep(step2, stepBase, factory?.("step", i))
527
- );
528
- const seq = withSequence(...animations);
529
- return applyRepeat(seq, base ? repeatOf(base) : void 0);
530
- }
531
- const step = value;
532
- const cb = factory?.("animation", void 0);
533
- if (isStepObject(step)) {
534
- return resolveStep(step, base, cb);
535
- }
536
- return resolveTransition(base, step, cb);
537
- }
538
- function resolveStep(step, base, cb) {
539
- if (isStepObject(step)) {
540
- const { to, ...override } = step;
541
- const merged = mergeTransition(base, override);
542
- return resolveTransition(merged, to, cb);
543
- }
544
- return resolveTransition(base, step, cb);
545
- }
546
- function mergeTransition(base, override) {
547
- if (override.type && base && override.type !== base.type) {
548
- return override;
549
- }
550
- return { ...base ?? { type: "spring" }, ...override };
551
- }
552
- var CSS_KEYWORDS = {
553
- ease: [0.25, 0.1, 0.25, 1],
554
- "ease-in": [0.42, 0, 1, 1],
555
- "ease-out": [0, 0, 0.58, 1],
556
- "ease-in-out": [0.42, 0, 0.58, 1]
557
- };
558
- var CSS_FUNCTION = /^cubic-bezier\((.*)\)$/;
559
- function cubicBezier(first, y1, x2, y2) {
560
- if (typeof first === "string") return fromCss(first);
561
- return bezier(first, y1, x2, y2, void 0);
562
- }
563
- function fromCss(input) {
564
- const token = input.trim().toLowerCase();
565
- if (token === "linear") return Easing.linear;
566
- const keyword = CSS_KEYWORDS[token];
567
- if (keyword) return bezier(...keyword, input);
568
- const match = CSS_FUNCTION.exec(token);
569
- if (!match) {
570
- throw new Error(
571
- `[inertia] cubicBezier: unsupported easing token ${JSON.stringify(input)}. Expected four numbers, a 'cubic-bezier(x1, y1, x2, y2)' string, or one of the CSS keywords 'linear' | 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out'.`
572
- );
573
- }
574
- const parts = match[1].split(",").map((p) => Number(p.trim()));
575
- if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n))) {
576
- throw new Error(
577
- `[inertia] cubicBezier: could not parse ${JSON.stringify(input)} \u2014 expected exactly four finite numbers inside cubic-bezier(...).`
578
- );
579
- }
580
- return bezier(parts[0], parts[1], parts[2], parts[3], input);
581
- }
582
- function bezier(x1, y1, x2, y2, source) {
583
- const describe = () => source !== void 0 ? JSON.stringify(source) : `cubicBezier(${x1}, ${y1}, ${x2}, ${y2})`;
584
- for (const n of [x1, y1, x2, y2]) {
585
- if (typeof n !== "number" || !Number.isFinite(n)) {
586
- throw new Error(
587
- `[inertia] cubicBezier: ${describe()} \u2014 every control point must be a finite number.`
588
- );
589
- }
590
- }
591
- if (x1 < 0 || x1 > 1 || x2 < 0 || x2 > 1) {
592
- throw new Error(
593
- `[inertia] cubicBezier: ${describe()} \u2014 x1 and x2 must be within [0, 1] (got x1=${x1}, x2=${x2}).`
594
- );
595
- }
596
- return Easing.bezier(x1, y1, x2, y2);
597
- }
598
- var DEFAULT_TIMING_DURATION2 = 250;
599
- function buildReleaseAnimation(transition, toValue) {
600
- "worklet";
601
- if (transition.type === "no-animation") return toValue;
602
- if (transition.type === "decay") {
603
- const cfg = { velocity: transition.velocity ?? 0 };
604
- if (transition.deceleration !== void 0) {
605
- cfg.deceleration = transition.deceleration;
606
- }
607
- if (transition.clamp !== void 0) cfg.clamp = transition.clamp;
608
- return withDecay(cfg);
609
- }
610
- if (transition.type === "timing") {
611
- const e = transition.easing;
612
- const easingFn = e && typeof e === "object" && "factory" in e ? e.factory() : e ?? Easing.inOut(Easing.ease);
613
- return withTiming(toValue, {
614
- duration: transition.duration ?? DEFAULT_TIMING_DURATION2,
615
- easing: easingFn
616
- });
617
- }
618
- return withSpring(toValue, springToReanimated(transition));
619
- }
620
- var alreadyChecked = false;
621
- function ensureReanimatedInstalled() {
622
- if (!__DEV__ || alreadyChecked) return;
623
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "test") {
624
- return;
625
- }
626
- alreadyChecked = true;
627
- const version = reanimatedVersion;
628
- if (version) {
629
- const major = parseInt(version.split(".")[0] ?? "0", 10);
630
- if (major < 4) {
631
- console.error(
632
- `[inertia] react-native-reanimated v${version} is installed, but @rootnative/inertia requires v4.0.0 or later. Upgrade with \`pnpm add react-native-reanimated@^4\` (or your package manager's equivalent).`
633
- );
634
- return;
635
- }
636
- }
637
- const probe = function probe2() {
638
- "worklet";
639
- return 0;
640
- };
641
- if (typeof probe.__workletHash !== "number") {
642
- console.error(
643
- `[inertia] The Reanimated worklets babel plugin is not configured. Add \`'react-native-worklets/plugin'\` as the LAST entry in the \`plugins\` array of your \`babel.config.js\`, then restart Metro with a fresh cache: \`npx expo start -c\` or \`npx react-native start --reset-cache\`.`
644
- );
645
- }
646
- }
647
- var TRANSFORM_KEYS = [
648
- "translateX",
649
- "translateY",
650
- "scale",
651
- "scaleX",
652
- "scaleY",
653
- "rotate",
654
- "rotateX",
655
- "rotateY"
656
- ];
657
- var ROTATION_KEYS = /* @__PURE__ */ new Set(["rotate", "rotateX", "rotateY"]);
658
- var NUMERIC_TOP_LEVEL_KEYS = [
659
- "opacity",
660
- "width",
661
- "height",
662
- "borderRadius",
663
- "shadowOpacity",
664
- "shadowRadius",
665
- "elevation"
666
- ];
667
- var COLOR_KEYS = [
668
- "backgroundColor",
669
- "borderColor",
670
- "color",
671
- "tintColor",
672
- "shadowColor"
673
- ];
674
- var SHADOW_OFFSET_KEYS = ["shadowOffsetWidth", "shadowOffsetHeight"];
675
- var ALL_KEYS = [
676
- ...TRANSFORM_KEYS,
677
- ...NUMERIC_TOP_LEVEL_KEYS,
678
- ...COLOR_KEYS,
679
- ...SHADOW_OFFSET_KEYS
680
- ];
681
- var TRANSFORM_KEY_SET = new Set(TRANSFORM_KEYS);
682
- var COLOR_KEY_SET = new Set(COLOR_KEYS);
683
- var SHADOW_OFFSET_KEY_SET = new Set(SHADOW_OFFSET_KEYS);
684
- var GESTURE_LAYER_NAMES = [
685
- "hovered",
686
- "focused",
687
- "focusVisible",
688
- "pressed"
689
- ];
690
- var GESTURE_LAYER_NAME_SET = new Set(GESTURE_LAYER_NAMES);
691
- var EXITING_POINTER_EVENTS_STYLE = { pointerEvents: "none" };
692
- var DEFAULT_RESTING = {
693
- translateX: 0,
694
- translateY: 0,
695
- scale: 1,
696
- scaleX: 1,
697
- scaleY: 1,
698
- rotate: 0,
699
- rotateX: 0,
700
- rotateY: 0,
701
- opacity: 1,
702
- width: 0,
703
- height: 0,
704
- borderRadius: 0,
705
- shadowOpacity: 0,
706
- shadowRadius: 0,
707
- elevation: 0,
708
- // 'transparent' is the only safe universal default for colors: it works as
709
- // an initial seed for any color animation (no jarring opaque flash on mount
710
- // when `initial` is omitted) and rgba(0,0,0,0) interpolates cleanly into
711
- // any opaque target via Reanimated's color util.
712
- backgroundColor: "transparent",
713
- borderColor: "transparent",
714
- color: "transparent",
715
- tintColor: "transparent",
716
- shadowColor: "transparent",
717
- shadowOffsetWidth: 0,
718
- shadowOffsetHeight: 0
719
- };
720
- function transitionFor(prop, transition) {
721
- if (!transition) return void 0;
722
- if (typeof transition === "string") return void 0;
723
- if (isTopLevelTransition(transition)) return transition;
724
- if (GESTURE_LAYER_NAME_SET.has(prop)) return void 0;
725
- return transition[prop];
726
- }
727
- function gestureLayerTransitionFor(layer, transition) {
728
- if (!transition) return void 0;
729
- if (typeof transition === "string") return void 0;
730
- if (isTopLevelTransition(transition)) return transition;
731
- return transition[layer];
732
- }
733
- function createMotionComponent(Component) {
734
- ensureReanimatedInstalled();
735
- const AnimatedComponent = Animated.createAnimatedComponent(
736
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
737
- Component
738
- );
739
- const Motion2 = forwardRef(function Motion3(props, ref) {
740
- const {
741
- initial,
742
- animate,
743
- exit,
744
- transition: transitionProp,
745
- variants,
746
- controller,
747
- gesture,
748
- layout: layoutProp,
749
- layoutId,
750
- onAnimationEnd,
751
- style,
752
- onLayout: userOnLayout,
753
- ...rest
754
- } = props;
755
- const namedTransitions = useNamedTransitions();
756
- const transition = resolveNamedTransitionProp(
757
- transitionProp,
758
- namedTransitions
759
- );
760
- const layout = typeof layoutProp === "string" ? lookupNamedTransition(layoutProp, namedTransitions) : layoutProp;
761
- if (__DEV__ && typeof style === "function") {
762
- throw new Error(
763
- "[inertia] `style` must be a style object or array of style objects, not a function. The function-form `style={(state) => ...}` Pressable API is not supported \u2014 use `gesture.pressed` (or `gesture.focused`, etc.) to drive state-dependent styling instead."
764
- );
765
- }
766
- const presence = usePresence();
767
- const isExiting = presence !== null && presence.isPresent === false;
768
- const shouldReduceMotion = useShouldReduceMotion();
769
- const onAnimationEndRef = useRef(onAnimationEnd);
770
- onAnimationEndRef.current = onAnimationEnd;
771
- const variantKey = useControllerKey(controller);
772
- const resolvedAnimate = resolveAnimateInput(
773
- animate,
774
- variants,
775
- variantKey
776
- );
777
- const animateRecord = resolvedAnimate ?? {};
778
- const initialRecord = initial && initial !== false ? initial : void 0;
779
- const exitRecord = exit ? exit : void 0;
780
- const [pressed, setPressed] = useState(false);
781
- const [focused, setFocused] = useState(false);
782
- const [focusVisible, setFocusVisible] = useState(false);
783
- const [hovered, setHovered] = useState(false);
784
- const touched = /* @__PURE__ */ new Set();
785
- collectTouchedKeys(touched, animateRecord);
786
- if (initialRecord) collectTouchedKeys(touched, initialRecord);
787
- if (variants) {
788
- for (const variant of Object.values(variants)) {
789
- if (!variant) continue;
790
- collectTouchedKeys(touched, variant);
791
- }
792
- }
793
- if (gesture) {
794
- for (const subState of [
795
- gesture.pressed,
796
- gesture.focused,
797
- gesture.focusVisible,
798
- gesture.hovered
799
- ]) {
800
- if (!subState) continue;
801
- collectTouchedKeys(touched, subState);
802
- }
803
- }
804
- if (exitRecord) collectTouchedKeys(touched, exitRecord);
805
- const activeKeysRef = useRef(null);
806
- const hasTransformRef = useRef(false);
807
- const hasShadowOffsetRef = useRef(false);
808
- const prevActive = activeKeysRef.current;
809
- let grew = prevActive === null;
810
- if (!grew && prevActive) {
811
- for (const k of touched) {
812
- if (!prevActive.includes(k)) {
813
- grew = true;
814
- break;
815
- }
816
- }
817
- }
818
- if (grew) {
819
- const merged = new Set(prevActive ?? []);
820
- for (const k of touched) merged.add(k);
821
- activeKeysRef.current = ALL_KEYS.filter((k) => merged.has(k));
822
- hasTransformRef.current = activeKeysRef.current.some(
823
- (k) => TRANSFORM_KEY_SET.has(k)
824
- );
825
- hasShadowOffsetRef.current = activeKeysRef.current.some(
826
- (k) => SHADOW_OFFSET_KEY_SET.has(k)
827
- );
828
- }
829
- const sharedValues = useAnimatableSharedValues((key) => {
830
- if (SHADOW_OFFSET_KEY_SET.has(key)) {
831
- const axis = shadowOffsetAxisFor(key);
832
- if (initial === false) {
833
- return shadowOffsetAxisValue(animateRecord.shadowOffset, axis) ?? DEFAULT_RESTING[key];
834
- }
835
- return shadowOffsetAxisValue(
836
- initialRecord?.shadowOffset,
837
- axis
838
- ) ?? shadowOffsetAxisValue(animateRecord.shadowOffset, axis) ?? DEFAULT_RESTING[key];
839
- }
840
- if (initial === false) {
841
- const a = animateRecord[key];
842
- return restValue(a) ?? DEFAULT_RESTING[key];
843
- }
844
- return initialRecord?.[key] ?? restValue(animateRecord[key]) ?? DEFAULT_RESTING[key];
845
- });
846
- const pressedProgress = useSharedValue(0);
847
- const focusedProgress = useSharedValue(0);
848
- const focusVisibleProgress = useSharedValue(0);
849
- const hoveredProgress = useSharedValue(0);
850
- const gestureSV = useSharedValue(
851
- resolveGestureLayers(gesture)
852
- );
853
- const gestureTargetsSig = stableSig(gesture);
854
- useEffect(() => {
855
- gestureSV.value = resolveGestureLayers(gesture);
856
- }, [gestureTargetsSig]);
857
- const baseRecord = isExiting && exitRecord ? { ...animateRecord, ...exitRecord } : animateRecord;
858
- const baseSig = stableSig(baseRecord) + (isExiting ? "|exit" : "") + (shouldReduceMotion ? "|rm" : "");
859
- const transitionSig = stableSig(transition);
860
- const safeToRemoveRef = useRef(void 0);
861
- safeToRemoveRef.current = presence?.safeToRemove;
862
- useEffect(() => {
863
- if (isExiting && (!exitRecord || Object.keys(exitRecord).length === 0)) {
864
- safeToRemoveRef.current?.();
865
- return;
866
- }
867
- let pending = 0;
868
- let done = false;
869
- const onSettle = () => {
870
- if (done) return;
871
- pending--;
872
- if (pending <= 0) {
873
- done = true;
874
- if (isExiting) safeToRemoveRef.current?.();
875
- }
876
- };
877
- let transformPending = 0;
878
- for (const k of ALL_KEYS) {
879
- if (TRANSFORM_KEY_SET.has(k) && baseRecord[k] !== void 0) {
880
- transformPending++;
881
- }
882
- }
883
- const transformGroup = transformPending > 0 ? { remaining: transformPending } : void 0;
884
- for (const key of ALL_KEYS) {
885
- const target = SHADOW_OFFSET_KEY_SET.has(key) ? shadowOffsetAxisValue(
886
- baseRecord.shadowOffset,
887
- shadowOffsetAxisFor(key)
888
- ) : baseRecord[key];
889
- if (target === void 0) continue;
890
- const cfg = shouldReduceMotion ? { type: "no-animation" } : transitionFor(
891
- SHADOW_OFFSET_KEY_SET.has(key) ? "shadowOffset" : key,
892
- transition
893
- );
894
- if (isExiting) pending++;
895
- const factory = makeKeyCallbackFactory(
896
- key,
897
- sharedValues[key],
898
- targetEndValue(target),
899
- onAnimationEndRef,
900
- {
901
- stepCount: stepCountOf(target),
902
- totalIterations: totalIterationsOf(cfg)
903
- },
904
- isExiting ? onSettle : void 0,
905
- TRANSFORM_KEY_SET.has(key) ? transformGroup : void 0
906
- );
907
- sharedValues[key].value = resolveAnimatableValue(
908
- target,
909
- cfg,
910
- factory
911
- );
912
- }
913
- if (isExiting && pending === 0) {
914
- safeToRemoveRef.current?.();
915
- }
916
- }, [baseSig, transitionSig]);
917
- useGestureLayerProgress(
918
- pressedProgress,
919
- pressed,
920
- gesture?.pressed != null,
921
- "pressed",
922
- transition,
923
- isExiting,
924
- shouldReduceMotion
925
- );
926
- useGestureLayerProgress(
927
- focusedProgress,
928
- focused,
929
- gesture?.focused != null,
930
- "focused",
931
- transition,
932
- isExiting,
933
- shouldReduceMotion
934
- );
935
- useGestureLayerProgress(
936
- focusVisibleProgress,
937
- focusVisible,
938
- gesture?.focusVisible != null,
939
- "focusVisible",
940
- transition,
941
- isExiting,
942
- shouldReduceMotion
943
- );
944
- useGestureLayerProgress(
945
- hoveredProgress,
946
- hovered,
947
- gesture?.hovered != null,
948
- "hovered",
949
- transition,
950
- isExiting,
951
- shouldReduceMotion
952
- );
953
- const sharedLayout = useSharedLayout({
954
- layoutId,
955
- userRef: ref,
956
- transition: isTopLevelTransition(transition) ? transition : void 0,
957
- shouldReduceMotion,
958
- userOnLayout
959
- });
960
- const flip = sharedLayout.flip;
961
- const hasLayoutId = layoutId !== void 0;
962
- const animatedStyle = useAnimatedStyle(() => {
963
- const activeKeys = activeKeysRef.current;
964
- const hasTransform = hasTransformRef.current;
965
- const hasShadowOffset = hasShadowOffsetRef.current;
966
- const out = {};
967
- const transform = [];
968
- let shadowOffsetW = 0;
969
- let shadowOffsetH = 0;
970
- const ph = hoveredProgress.value;
971
- const pf = focusedProgress.value;
972
- const pfv = focusVisibleProgress.value;
973
- const pp = pressedProgress.value;
974
- const layers = gestureSV.value;
975
- const hoveredLayer = layers ? layers.hovered : null;
976
- const focusedLayer = layers ? layers.focused : null;
977
- const focusVisibleLayer = layers ? layers.focusVisible : null;
978
- const pressedLayer = layers ? layers.pressed : null;
979
- for (const key of activeKeys) {
980
- let v = sharedValues[key].value;
981
- const isColor = COLOR_KEY_SET.has(key);
982
- if (hoveredLayer && ph > 0 && hoveredLayer[key] !== void 0) {
983
- const t = hoveredLayer[key];
984
- v = isColor ? interpolateColor(ph, [0, 1], [v, t]) : v + (t - v) * ph;
985
- }
986
- if (focusedLayer && pf > 0 && focusedLayer[key] !== void 0) {
987
- const t = focusedLayer[key];
988
- v = isColor ? interpolateColor(pf, [0, 1], [v, t]) : v + (t - v) * pf;
989
- }
990
- if (focusVisibleLayer && pfv > 0 && focusVisibleLayer[key] !== void 0) {
991
- const t = focusVisibleLayer[key];
992
- v = isColor ? interpolateColor(pfv, [0, 1], [v, t]) : v + (t - v) * pfv;
993
- }
994
- if (pressedLayer && pp > 0 && pressedLayer[key] !== void 0) {
995
- const t = pressedLayer[key];
996
- v = isColor ? interpolateColor(pp, [0, 1], [v, t]) : v + (t - v) * pp;
997
- }
998
- if (TRANSFORM_KEY_SET.has(key)) {
999
- transform.push(
1000
- ROTATION_KEYS.has(key) ? { [key]: `${v}deg` } : { [key]: v }
1001
- );
1002
- } else if (key === "shadowOffsetWidth") {
1003
- shadowOffsetW = v;
1004
- } else if (key === "shadowOffsetHeight") {
1005
- shadowOffsetH = v;
1006
- } else {
1007
- out[key] = v;
1008
- }
1009
- }
1010
- if (hasLayoutId) {
1011
- transform.push({ translateX: flip.dx.value });
1012
- transform.push({ translateY: flip.dy.value });
1013
- transform.push({ scaleX: flip.sx.value });
1014
- transform.push({ scaleY: flip.sy.value });
1015
- }
1016
- if (hasTransform || hasLayoutId) out.transform = transform;
1017
- if (hasShadowOffset) {
1018
- out.shadowOffset = { width: shadowOffsetW, height: shadowOffsetH };
1019
- }
1020
- return out;
1021
- });
1022
- const mergedStyle = useMemo(
1023
- () => isExiting ? [style, animatedStyle, EXITING_POINTER_EVENTS_STYLE] : [style, animatedStyle],
1024
- [style, animatedStyle, isExiting]
1025
- );
1026
- const gestureHandlers = useGestureHandlers(
1027
- gesture,
1028
- rest,
1029
- setPressed,
1030
- setFocused,
1031
- setFocusVisible,
1032
- setHovered
1033
- );
1034
- const layoutSig = stableSig(layout);
1035
- const layoutTransition = useMemo(
1036
- () => shouldReduceMotion ? void 0 : resolveLayoutTransition(layout),
1037
- // eslint-disable-next-line react-hooks/exhaustive-deps
1038
- [layoutSig, shouldReduceMotion]
1039
- );
1040
- return /* @__PURE__ */ jsx(
1041
- AnimatedComponent,
1042
- {
1043
- ref: sharedLayout.setRef,
1044
- ...rest,
1045
- ...gestureHandlers,
1046
- onLayout: sharedLayout.onLayout,
1047
- layout: layoutTransition,
1048
- style: mergedStyle
1049
- }
1050
- );
1051
- });
1052
- Motion2.displayName = `Motion(${Component.displayName ?? Component.name ?? "Component"})`;
1053
- return Motion2;
1054
- }
1055
- function useAnimatableSharedValues(init) {
1056
- const translateX = useSharedValue(init("translateX"));
1057
- const translateY = useSharedValue(init("translateY"));
1058
- const scale = useSharedValue(init("scale"));
1059
- const scaleX = useSharedValue(init("scaleX"));
1060
- const scaleY = useSharedValue(init("scaleY"));
1061
- const rotate = useSharedValue(init("rotate"));
1062
- const rotateX = useSharedValue(init("rotateX"));
1063
- const rotateY = useSharedValue(init("rotateY"));
1064
- const opacity = useSharedValue(init("opacity"));
1065
- const width = useSharedValue(init("width"));
1066
- const height = useSharedValue(init("height"));
1067
- const borderRadius = useSharedValue(init("borderRadius"));
1068
- const shadowOpacity = useSharedValue(init("shadowOpacity"));
1069
- const shadowRadius = useSharedValue(init("shadowRadius"));
1070
- const elevation = useSharedValue(init("elevation"));
1071
- const backgroundColor = useSharedValue(
1072
- init("backgroundColor")
1073
- );
1074
- const borderColor = useSharedValue(init("borderColor"));
1075
- const color = useSharedValue(init("color"));
1076
- const tintColor = useSharedValue(init("tintColor"));
1077
- const shadowColor = useSharedValue(init("shadowColor"));
1078
- const shadowOffsetWidth = useSharedValue(
1079
- init("shadowOffsetWidth")
1080
- );
1081
- const shadowOffsetHeight = useSharedValue(
1082
- init("shadowOffsetHeight")
1083
- );
1084
- const ref = useRef(null);
1085
- if (ref.current === null) {
1086
- ref.current = {
1087
- translateX,
1088
- translateY,
1089
- scale,
1090
- scaleX,
1091
- scaleY,
1092
- rotate,
1093
- rotateX,
1094
- rotateY,
1095
- opacity,
1096
- width,
1097
- height,
1098
- borderRadius,
1099
- shadowOpacity,
1100
- shadowRadius,
1101
- elevation,
1102
- backgroundColor,
1103
- borderColor,
1104
- color,
1105
- tintColor,
1106
- shadowColor,
1107
- shadowOffsetWidth,
1108
- shadowOffsetHeight
1109
- };
1110
- }
1111
- return ref.current;
1112
- }
1113
- function makeKeyCallbackFactory(key, sharedValue, target, onAnimationEndRef, meta, onSettle, transformGroup) {
1114
- if (!onAnimationEndRef.current && !onSettle) return void 0;
1115
- const state = { iteration: 0 };
1116
- const isTransformKey = TRANSFORM_KEY_SET.has(key);
1117
- const dispatch = (rawPhase, step, finished, value) => {
1118
- const isLastIteration = state.iteration >= meta.totalIterations - 1;
1119
- let phase;
1120
- let isTerminal = false;
1121
- if (rawPhase === "step") {
1122
- const isLastInPass = step !== void 0 && step === meta.stepCount - 1;
1123
- if (!isLastInPass) {
1124
- phase = "step";
1125
- } else if (isLastIteration) {
1126
- phase = "animation";
1127
- isTerminal = true;
1128
- } else {
1129
- phase = "sequence";
1130
- }
1131
- } else if (isLastIteration) {
1132
- phase = "animation";
1133
- isTerminal = true;
1134
- } else {
1135
- phase = "repeat";
1136
- }
1137
- const reportedIteration = state.iteration;
1138
- if (phase === "sequence" || phase === "repeat") state.iteration++;
1139
- const fn = onAnimationEndRef.current;
1140
- if (fn) {
1141
- if (isTransformKey && transformGroup && phase === "animation") {
1142
- transformGroup.remaining--;
1143
- if (transformGroup.remaining <= 0) {
1144
- fn({
1145
- key: "transform",
1146
- finished,
1147
- value,
1148
- target,
1149
- phase,
1150
- step,
1151
- iteration: reportedIteration
1152
- });
1153
- }
1154
- } else {
1155
- fn({
1156
- key,
1157
- finished,
1158
- value,
1159
- target,
1160
- phase,
1161
- step,
1162
- iteration: reportedIteration
1163
- });
1164
- }
1165
- }
1166
- if (onSettle && isTerminal) onSettle();
1167
- };
1168
- return (rawPhase, step) => {
1169
- const cb = (finished) => {
1170
- "worklet";
1171
- runOnJS(dispatch)(rawPhase, step, !!finished, sharedValue.value);
1172
- };
1173
- return cb;
1174
- };
1175
- }
1176
- function shadowOffsetAxisFor(key) {
1177
- return key === "shadowOffsetWidth" ? "width" : "height";
1178
- }
1179
- function shadowOffsetAxisValue(source, axis) {
1180
- return source?.[axis];
1181
- }
1182
- function collectTouchedKeys(touched, record) {
1183
- for (const k of ALL_KEYS) {
1184
- if (k in record) touched.add(k);
1185
- }
1186
- if ("shadowOffset" in record && record.shadowOffset) {
1187
- const so = record.shadowOffset;
1188
- if (so.width !== void 0) touched.add("shadowOffsetWidth");
1189
- if (so.height !== void 0) touched.add("shadowOffsetHeight");
1190
- }
1191
- }
1192
- function stepCountOf(v) {
1193
- if (Array.isArray(v)) return v.length;
1194
- return 1;
1195
- }
1196
- function totalIterationsOf(cfg) {
1197
- if (!cfg || cfg.type === "no-animation" || cfg.type === "decay") return 1;
1198
- const r = cfg.repeat;
1199
- if (r === void 0) return 1;
1200
- if (r === "infinite") return Number.POSITIVE_INFINITY;
1201
- if (typeof r === "number") return r;
1202
- if (r.count === "infinite") return Number.POSITIVE_INFINITY;
1203
- return r.count;
1204
- }
1205
- function targetEndValue(v) {
1206
- if (v === void 0) return void 0;
1207
- if (typeof v === "number" || typeof v === "string") return v;
1208
- if (Array.isArray(v)) {
1209
- return v.length > 0 ? targetEndValue(v[v.length - 1]) : void 0;
1210
- }
1211
- if (typeof v === "object" && v !== null && "to" in v) {
1212
- const to = v.to;
1213
- return typeof to === "number" || typeof to === "string" ? to : void 0;
1214
- }
1215
- return void 0;
1216
- }
1217
- function useControllerKey(controller) {
1218
- const [, setTick] = useState(0);
1219
- useEffect(() => {
1220
- if (!controller) return;
1221
- const unsub = controller.subscribe(() => setTick((n) => n + 1));
1222
- return unsub;
1223
- }, [controller]);
1224
- return controller?.current;
1225
- }
1226
- function resolveAnimateInput(animate, variants, controllerKey) {
1227
- if (controllerKey !== void 0 && variants && controllerKey in variants) {
1228
- return variants[controllerKey];
1229
- }
1230
- if (typeof animate === "string") {
1231
- if (variants && animate in variants) return variants[animate];
1232
- if (__DEV__) {
1233
- console.warn(
1234
- `[inertia] animate="${animate}" but no matching variant. Did you forget to pass \`variants\`?`
1235
- );
1236
- }
1237
- return void 0;
1238
- }
1239
- return animate;
1240
- }
1241
- function restValue(v) {
1242
- if (v === void 0) return void 0;
1243
- if (typeof v === "number" || typeof v === "string") return v;
1244
- if (Array.isArray(v)) {
1245
- return v.length > 0 ? restValue(v[0]) : void 0;
1246
- }
1247
- if (typeof v === "object" && v !== null && "to" in v) {
1248
- const to = v.to;
1249
- return typeof to === "number" || typeof to === "string" ? to : void 0;
1250
- }
1251
- return void 0;
1252
- }
1253
- function resolveGestureLayers(gesture) {
1254
- if (!gesture) return null;
1255
- const out = {};
1256
- for (const layer of GESTURE_LAYER_NAMES) {
1257
- const subState = gesture[layer];
1258
- if (!subState) continue;
1259
- const resolved = {};
1260
- for (const key of ALL_KEYS) {
1261
- if (SHADOW_OFFSET_KEY_SET.has(key)) {
1262
- const axis = shadowOffsetAxisFor(key);
1263
- const so = subState.shadowOffset;
1264
- const v = shadowOffsetAxisValue(so, axis);
1265
- if (v !== void 0) resolved[key] = v;
1266
- continue;
1267
- }
1268
- const raw = subState[key];
1269
- if (raw === void 0) continue;
1270
- const t = targetEndValue(raw);
1271
- if (t !== void 0) resolved[key] = t;
1272
- }
1273
- out[layer] = resolved;
1274
- }
1275
- return out;
1276
- }
1277
- function useGestureLayerProgress(progress, active, declared, layer, transition, isExiting, shouldReduceMotion) {
1278
- const layerCfgSig = stableSig(gestureLayerTransitionFor(layer, transition));
1279
- useEffect(() => {
1280
- if (!declared) return;
1281
- if (isExiting) {
1282
- progress.value = 0;
1283
- return;
1284
- }
1285
- const target = active ? 1 : 0;
1286
- const cfg = shouldReduceMotion ? { type: "no-animation" } : gestureLayerTransitionFor(layer, transition) ?? { type: "spring" };
1287
- progress.value = resolveTransition(cfg, target);
1288
- }, [active, declared, isExiting, shouldReduceMotion, layerCfgSig]);
1289
- }
1290
- function useGestureHandlers(gesture, rest, setPressed, setFocused, setFocusVisible, setHovered) {
1291
- const hasPressed = gesture?.pressed ? 1 : 0;
1292
- const hasFocused = gesture?.focused ? 1 : 0;
1293
- const hasFocusVisible = gesture?.focusVisible ? 1 : 0;
1294
- const hasHovered = gesture?.hovered ? 1 : 0;
1295
- return useMemo(() => {
1296
- if (!gesture) return {};
1297
- const handlers = {};
1298
- if (gesture.pressed) {
1299
- handlers.onTouchStart = compose(rest.onTouchStart, () => setPressed(true));
1300
- handlers.onTouchEnd = compose(rest.onTouchEnd, () => setPressed(false));
1301
- handlers.onTouchCancel = compose(
1302
- rest.onTouchCancel,
1303
- () => setPressed(false)
1304
- );
1305
- handlers.onPressIn = compose(rest.onPressIn, () => setPressed(true));
1306
- handlers.onPressOut = compose(rest.onPressOut, () => setPressed(false));
1307
- }
1308
- if (gesture.focused || gesture.focusVisible) {
1309
- handlers.onFocus = compose(rest.onFocus, () => {
1310
- if (gesture.focused) setFocused(true);
1311
- if (gesture.focusVisible && isFocusVisible()) setFocusVisible(true);
1312
- });
1313
- handlers.onBlur = compose(rest.onBlur, () => {
1314
- if (gesture.focused) setFocused(false);
1315
- if (gesture.focusVisible) setFocusVisible(false);
1316
- });
1317
- }
1318
- if (gesture.hovered) {
1319
- handlers.onMouseEnter = compose(rest.onMouseEnter, () => setHovered(true));
1320
- handlers.onMouseLeave = compose(
1321
- rest.onMouseLeave,
1322
- () => setHovered(false)
1323
- );
1324
- }
1325
- return handlers;
1326
- }, [
1327
- hasPressed,
1328
- hasFocused,
1329
- hasFocusVisible,
1330
- hasHovered,
1331
- rest.onTouchStart,
1332
- rest.onTouchEnd,
1333
- rest.onTouchCancel,
1334
- rest.onPressIn,
1335
- rest.onPressOut,
1336
- rest.onFocus,
1337
- rest.onBlur,
1338
- rest.onMouseEnter,
1339
- rest.onMouseLeave
1340
- ]);
1341
- }
1342
- function compose(user, ours) {
1343
- if (typeof user !== "function") return ours;
1344
- return (event) => {
1345
- user(event);
1346
- ours(event);
1347
- };
1348
- }
1349
-
1350
- // src/motion/Image.tsx
1351
- var MotionImage = createMotionComponent(Image);
1352
- var MotionPressable = createMotionComponent(Pressable);
1353
- var MotionScrollView = createMotionComponent(ScrollView);
1354
- var MotionText = createMotionComponent(Text);
1355
- var MotionView = createMotionComponent(View);
1356
-
1357
21
  // src/motion/index.ts
1358
22
  var Motion = {
1359
23
  View: MotionView,
@@ -1441,51 +105,6 @@ function useColorTransition(progress, range, options) {
1441
105
  return { [key]: interpolateColor(progress.value, [0, 1], [from, to]) };
1442
106
  });
1443
107
  }
1444
- function useGesture(transition) {
1445
- const pressed = useSharedValue(0);
1446
- const focused = useSharedValue(0);
1447
- const focusVisible = useSharedValue(0);
1448
- const hovered = useSharedValue(0);
1449
- const shouldReduceMotion = useShouldReduceMotion();
1450
- const resolved = resolveNamedTransitionProp(transition, useNamedTransitions());
1451
- const setLayer = useCallback(
1452
- (sv, layer, target) => {
1453
- const cfg = shouldReduceMotion ? { type: "no-animation" } : layerTransition(layer, resolved) ?? { type: "spring" };
1454
- sv.value = resolveTransition(cfg, target);
1455
- },
1456
- // The transition is intentionally read on every call rather than cooked
1457
- // into the dep array — a fresh literal each render would otherwise
1458
- // rebuild the handler bag and break composing consumers that key off
1459
- // handler identity. `transition` is read inside the callback closure;
1460
- // shared values are stable so the only dep that matters is the reduce-
1461
- // motion flag.
1462
- // eslint-disable-next-line react-hooks/exhaustive-deps
1463
- [shouldReduceMotion]
1464
- );
1465
- const handlers = useMemo(
1466
- () => ({
1467
- onPressIn: () => setLayer(pressed, "pressed", 1),
1468
- onPressOut: () => setLayer(pressed, "pressed", 0),
1469
- onHoverIn: () => setLayer(hovered, "hovered", 1),
1470
- onHoverOut: () => setLayer(hovered, "hovered", 0),
1471
- onFocus: () => {
1472
- setLayer(focused, "focused", 1);
1473
- if (isFocusVisible()) setLayer(focusVisible, "focusVisible", 1);
1474
- },
1475
- onBlur: () => {
1476
- setLayer(focused, "focused", 0);
1477
- setLayer(focusVisible, "focusVisible", 0);
1478
- }
1479
- }),
1480
- [setLayer, pressed, focused, focusVisible, hovered]
1481
- );
1482
- return { pressed, focused, focusVisible, hovered, handlers };
1483
- }
1484
- function layerTransition(layer, transition) {
1485
- if (!transition) return void 0;
1486
- if (isTopLevelTransition(transition)) return transition;
1487
- return transition[layer];
1488
- }
1489
108
  function useMotionValue(initial) {
1490
109
  return useSharedValue(initial);
1491
110
  }
@@ -1624,4 +243,4 @@ function useVariants(variants, initial) {
1624
243
  }, []);
1625
244
  }
1626
245
 
1627
- export { Motion, MotionConfig, MotionImage, MotionPressable, MotionScrollView, MotionText, MotionView, Presence, buildReleaseAnimation, createMotionComponent, cubicBezier, ensureWorkletEasing, resolveAnimatableValue, resolveNamedTransition, resolveTransition, useAnimation, useBooleanSpring, useColorTransition, useGesture, useMotionConfig, useMotionValue, useNamedTransitions, usePresence, useScroll, useShadow, useShouldReduceMotion, useSpring, useTransform, useVariants };
246
+ export { Motion, useAnimation, useBooleanSpring, useColorTransition, useMotionValue, useScroll, useShadow, useSpring, useTransform, useVariants };