react-native-smooth-clip-view 0.2.4 → 0.2.6

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 (40) hide show
  1. package/README.md +62 -25
  2. package/android/CMakeLists.txt +0 -1
  3. package/android/src/main/cpp/SmoothClipAndroid.h +5 -0
  4. package/android/src/main/cpp/SmoothClipBindings.cpp +28 -8
  5. package/android/src/main/cpp/SmoothClipRegistry.cpp +198 -189
  6. package/android/src/main/java/com/smoothclipview/ClipGeometryNormalizer.kt +61 -11
  7. package/android/src/main/java/com/smoothclipview/SmoothClipBindings.kt +20 -0
  8. package/android/src/main/java/com/smoothclipview/SmoothClipModule.kt +1 -0
  9. package/android/src/main/java/com/smoothclipview/SmoothClipView.kt +105 -34
  10. package/cpp/SmoothClipAnimationCurve.h +468 -0
  11. package/cpp/SmoothClipAnimationId.h +32 -0
  12. package/cpp/SmoothClipRegistry.h +11 -1
  13. package/cpp/SmoothClipVelocityTracker.h +32 -15
  14. package/ios/SmoothClipRegistry.mm +246 -97
  15. package/ios/SmoothClipTurboModule.cpp +4 -2
  16. package/ios/SmoothClipTurboModule.h +2 -1
  17. package/ios/SmoothClipView.mm +73 -16
  18. package/lib/module/NativeSmoothClipModule.js.map +1 -1
  19. package/lib/module/drivers.android.js +3 -1
  20. package/lib/module/drivers.android.js.map +1 -1
  21. package/lib/module/drivers.ios.js +3 -391
  22. package/lib/module/drivers.ios.js.map +1 -1
  23. package/lib/module/drivers.native.js +470 -0
  24. package/lib/module/drivers.native.js.map +1 -0
  25. package/lib/typescript/src/NativeSmoothClipModule.d.ts +1 -1
  26. package/lib/typescript/src/NativeSmoothClipModule.d.ts.map +1 -1
  27. package/lib/typescript/src/driverTypes.d.ts +6 -3
  28. package/lib/typescript/src/driverTypes.d.ts.map +1 -1
  29. package/lib/typescript/src/drivers.android.d.ts +2 -2
  30. package/lib/typescript/src/drivers.android.d.ts.map +1 -1
  31. package/lib/typescript/src/drivers.ios.d.ts +2 -4
  32. package/lib/typescript/src/drivers.ios.d.ts.map +1 -1
  33. package/lib/typescript/src/drivers.native.d.ts +5 -0
  34. package/lib/typescript/src/drivers.native.d.ts.map +1 -0
  35. package/package.json +1 -1
  36. package/src/NativeSmoothClipModule.ts +2 -1
  37. package/src/driverTypes.ts +6 -3
  38. package/src/drivers.android.ts +4 -2
  39. package/src/drivers.ios.ts +4 -687
  40. package/src/drivers.native.ts +805 -0
@@ -0,0 +1,805 @@
1
+ // The shared NATIVE driver: iOS and Android both execute this file, via the
2
+ // one-line re-exports in drivers.ios.ts / drivers.android.ts that Metro's
3
+ // platform resolution picks up from index.ts's `./drivers` import. Only the
4
+ // `./smoothClipNative` import below is platform-split. drivers.ts (no
5
+ // suffix) is the web/Reanimated fallback, not this driver's sibling.
6
+ import { useEffect, useRef } from 'react';
7
+ import { useSharedValue, type SharedValue } from 'react-native-reanimated';
8
+ import { isRNRuntime, scheduleOnRN, scheduleOnUI } from 'react-native-worklets';
9
+ import NativeSmoothClipModule from './smoothClipNative';
10
+ import type {
11
+ ClipReduceMotion,
12
+ KeyframedClipAnimation,
13
+ SmoothClipAnimation,
14
+ SmoothClipDriver,
15
+ SmoothClipDriverOptions,
16
+ SpringClipAnimation,
17
+ TimingClipAnimation,
18
+ } from './driverTypes';
19
+ import {
20
+ allocateDriverId,
21
+ attachDriverState,
22
+ createDriverState,
23
+ detachDriverState,
24
+ getDriverState,
25
+ setDriverState,
26
+ } from './driverState';
27
+ import {
28
+ completeNativeAnimation,
29
+ synchronizeNativeCompletion,
30
+ } from './nativeCompletion';
31
+ import {
32
+ clipPresentationEquals,
33
+ createClipPresentation,
34
+ isFiniteClipPresentation,
35
+ type ClipGeometry,
36
+ type SmoothClipPresentation,
37
+ } from './geometry';
38
+ import {
39
+ createReactRequest,
40
+ rejectDriverRequests,
41
+ resolveReactRequest,
42
+ } from './reactRequests';
43
+
44
+ const INTERACTIVE = 0;
45
+ const NATIVE = 1;
46
+
47
+ const setPresentationHostFunction = NativeSmoothClipModule.setClipPresentation;
48
+ const beginInteractionHostFunction = NativeSmoothClipModule.beginInteraction;
49
+
50
+ // The animate* host functions take one argument beyond the TurboModule spec:
51
+ // the Reanimated-rule start stamp in milliseconds (see animateOnUI). Android's
52
+ // JSI bindings read it as an optional trailing argument; the iOS TurboModule
53
+ // reads its declared parameters positionally and ignores extras, so the
54
+ // codegen spec stays untouched and both platforms take the same call. A
55
+ // narrower function is assignable to the widened type, so no cast is needed.
56
+ type WithStartStamp<F> = F extends (...args: infer A) => infer R
57
+ ? (...args: [...A, startedAtMs: number]) => R
58
+ : never;
59
+ const animateTimingHostFunction: WithStartStamp<
60
+ typeof NativeSmoothClipModule.animateTiming
61
+ > = NativeSmoothClipModule.animateTiming;
62
+ const animateSpringHostFunction: WithStartStamp<
63
+ typeof NativeSmoothClipModule.animateSpring
64
+ > = NativeSmoothClipModule.animateSpring;
65
+ const animateKeyframesHostFunction: WithStartStamp<
66
+ typeof NativeSmoothClipModule.animateKeyframes
67
+ > = NativeSmoothClipModule.animateKeyframes;
68
+ const rejectAnimationHostFunction = NativeSmoothClipModule.rejectAnimation;
69
+ const cancelAnimationHostFunction = NativeSmoothClipModule.cancelAnimation;
70
+ const destroyDriverHostFunction = NativeSmoothClipModule.destroyDriver;
71
+
72
+ // Workaround for react-native-worklets 0.10: the RN-side serialization cache
73
+ // hands out one remote-function registry id per function forever, but the
74
+ // registry entry is deleted as soon as any transient UI-side proxy of that
75
+ // function is garbage collected. A later scheduleOnRN for the same function
76
+ // then reads `undefined` from the registry and aborts in Value::getObject.
77
+ // Pinning one UI-side reference for the app lifetime keeps the proxy — and
78
+ // with it the registry entry — alive. Remove once worklets decouples registry
79
+ // cleanup from proxy lifetime.
80
+ scheduleOnUI((resolver: typeof resolveReactRequest) => {
81
+ 'worklet';
82
+ (globalThis as Record<string, unknown>).__smoothClipPinnedResolver = resolver;
83
+ }, resolveReactRequest);
84
+
85
+ function reduceMotionCode(value: ClipReduceMotion): number {
86
+ switch (value) {
87
+ case 'always':
88
+ return 1;
89
+ case 'never':
90
+ return 2;
91
+ default:
92
+ return 0;
93
+ }
94
+ }
95
+
96
+ function animationIsFinite(
97
+ target: SmoothClipPresentation,
98
+ animation: SmoothClipAnimation
99
+ ): boolean {
100
+ 'worklet';
101
+ if (
102
+ animation.from !== undefined &&
103
+ !isFiniteClipPresentation(animation.from)
104
+ ) {
105
+ // Silently dropping an invalid explicit start would re-open the exact
106
+ // stale-start handoff `from` exists to close — reject the whole call.
107
+ return false;
108
+ }
109
+ if (animation.type === 'timing') {
110
+ return (
111
+ Number.isFinite(animation.duration) &&
112
+ animation.controlPoints.every(Number.isFinite)
113
+ );
114
+ }
115
+ if (animation.type === 'spring') {
116
+ return [
117
+ animation.mass ?? 1,
118
+ animation.stiffness ?? 100,
119
+ animation.damping ?? 10,
120
+ animation.initialVelocity === 'inherit'
121
+ ? 0
122
+ : (animation.initialVelocity ?? 0),
123
+ ].every(Number.isFinite);
124
+ }
125
+ if (!Number.isFinite(animation.duration) || animation.frames.length < 2) {
126
+ return false;
127
+ }
128
+ let previousOffset = -1;
129
+ for (const frame of animation.frames) {
130
+ if (
131
+ !Number.isFinite(frame.offset) ||
132
+ frame.offset < 0 ||
133
+ frame.offset > 1 ||
134
+ frame.offset <= previousOffset ||
135
+ !isFiniteClipPresentation(frame.presentation)
136
+ ) {
137
+ return false;
138
+ }
139
+ previousOffset = frame.offset;
140
+ }
141
+ return (
142
+ animation.frames[0]?.offset === 0 &&
143
+ previousOffset === 1 &&
144
+ clipPresentationEquals(
145
+ animation.frames[animation.frames.length - 1]?.presentation ?? null,
146
+ target
147
+ )
148
+ );
149
+ }
150
+
151
+ function presentationFromNative(
152
+ values: ReadonlyArray<number>,
153
+ fallback: SmoothClipPresentation,
154
+ offset = 0
155
+ ): SmoothClipPresentation {
156
+ 'worklet';
157
+ if (values.length < offset + 7) return fallback;
158
+ const presentation = {
159
+ clip: {
160
+ x: values[offset] as number,
161
+ y: values[offset + 1] as number,
162
+ width: values[offset + 2] as number,
163
+ height: values[offset + 3] as number,
164
+ radius: values[offset + 4] as number,
165
+ },
166
+ contentTranslateX: values[offset + 5] as number,
167
+ contentTranslateY: values[offset + 6] as number,
168
+ };
169
+ return isFiniteClipPresentation(presentation) ? presentation : fallback;
170
+ }
171
+
172
+ function flattenedKeyframes(animation: KeyframedClipAnimation): number[] {
173
+ 'worklet';
174
+ const values: number[] = [];
175
+ for (const frame of animation.frames) {
176
+ const { clip, contentTranslateX, contentTranslateY } = frame.presentation;
177
+ values.push(
178
+ frame.offset,
179
+ clip.x,
180
+ clip.y,
181
+ clip.width,
182
+ clip.height,
183
+ clip.radius,
184
+ contentTranslateX,
185
+ contentTranslateY
186
+ );
187
+ }
188
+ return values;
189
+ }
190
+
191
+ function uiOnly(): never {
192
+ 'worklet';
193
+ throw new Error(
194
+ '[SmoothClipView] driver.ui methods must run on the UI runtime. Use driver.react from React code.'
195
+ );
196
+ }
197
+
198
+ export function useSmoothClipDriver(
199
+ initialValue: ClipGeometry | SmoothClipPresentation,
200
+ options: SmoothClipDriverOptions = {}
201
+ ): SmoothClipDriver {
202
+ const initialPresentation =
203
+ 'clip' in initialValue
204
+ ? initialValue
205
+ : createClipPresentation(initialValue);
206
+ const presentation = useSharedValue(initialPresentation);
207
+ const ownership = useSharedValue(INTERACTIVE);
208
+ const suppressDeliveries = useSharedValue(0);
209
+ const activeAnimationId = useSharedValue(0);
210
+ // Non-zero after a setScalars hot write: driver.presentation is then stale,
211
+ // so animateTo must start from the native registry's latest value instead
212
+ // of snapping back to the stale SharedValue.
213
+ const scalarsStale = useSharedValue(0);
214
+ // Non-zero between the effect cleanup's native teardown and the next effect
215
+ // run. Native cannot tell "this driver was never seeded" from "this driver
216
+ // was destroyed and erased" — both are a missing registry entry — so the
217
+ // animation entry points would happily create a fresh state for a call that
218
+ // arrives after the hook is gone, leaving a latch that no view starts and no
219
+ // destroy cancels. Only the UI side knows the difference, so it is decided
220
+ // here.
221
+ const disposed = useSharedValue(0);
222
+ const callbackRef = useRef(options.onAnimationComplete);
223
+ const driverRef = useRef<SmoothClipDriver | null>(null);
224
+ callbackRef.current = options.onAnimationComplete;
225
+
226
+ if (driverRef.current === null) {
227
+ const driverId = allocateDriverId();
228
+ const reduceMotion = reduceMotionCode(options.reduceMotion ?? 'system');
229
+
230
+ const seedPresentation = (next: SmoothClipPresentation) => {
231
+ 'worklet';
232
+ if (clipPresentationEquals(presentation.value, next)) return;
233
+ suppressDeliveries.value += 1;
234
+ presentation.value = next;
235
+ // The listener runs synchronously inside that assignment, so the credit
236
+ // is either spent by now or was never spendable. deliver() returns before
237
+ // the decrement whenever the value dedupes against `last` — which happens
238
+ // exactly when native already holds it, e.g. freezing a latch back to the
239
+ // value it started from. An unspent credit would then swallow the next
240
+ // real declarative write and leave native a geometry behind for good.
241
+ if (suppressDeliveries.value > 0) suppressDeliveries.value -= 1;
242
+ };
243
+
244
+ const beginOnUI = (): SmoothClipPresentation => {
245
+ 'worklet';
246
+ if (disposed.value !== 0) return presentation.value;
247
+ const current = presentationFromNative(
248
+ beginInteractionHostFunction(driverId),
249
+ presentation.value
250
+ );
251
+ activeAnimationId.value = 0;
252
+ ownership.value = INTERACTIVE;
253
+ scalarsStale.value = 0;
254
+ seedPresentation(current);
255
+ return current;
256
+ };
257
+
258
+ const setOnUI = (next: SmoothClipPresentation): void => {
259
+ 'worklet';
260
+ if (disposed.value !== 0 || !isFiniteClipPresentation(next)) return;
261
+ activeAnimationId.value = 0;
262
+ ownership.value = INTERACTIVE;
263
+ scalarsStale.value = 0;
264
+ const { clip, contentTranslateX, contentTranslateY } = next;
265
+ setPresentationHostFunction(
266
+ driverId,
267
+ clip.x,
268
+ clip.y,
269
+ clip.width,
270
+ clip.height,
271
+ clip.radius,
272
+ contentTranslateX,
273
+ contentTranslateY,
274
+ true,
275
+ false
276
+ );
277
+ seedPresentation(next);
278
+ };
279
+
280
+ const setScalarsOnUI = (
281
+ x: number,
282
+ y: number,
283
+ width: number,
284
+ height: number,
285
+ radius: number,
286
+ contentTranslateX: number,
287
+ contentTranslateY: number,
288
+ overridePendingAnimation = false
289
+ ): void => {
290
+ 'worklet';
291
+ if (
292
+ disposed.value !== 0 ||
293
+ !Number.isFinite(x) ||
294
+ !Number.isFinite(y) ||
295
+ !Number.isFinite(width) ||
296
+ !Number.isFinite(height) ||
297
+ !Number.isFinite(radius) ||
298
+ !Number.isFinite(contentTranslateX) ||
299
+ !Number.isFinite(contentTranslateY)
300
+ ) {
301
+ return;
302
+ }
303
+ if (activeAnimationId.value !== 0) activeAnimationId.value = 0;
304
+ if (ownership.value !== INTERACTIVE) ownership.value = INTERACTIVE;
305
+ if (scalarsStale.value === 0) scalarsStale.value = 1;
306
+ setPresentationHostFunction(
307
+ driverId,
308
+ x,
309
+ y,
310
+ width,
311
+ height,
312
+ radius,
313
+ contentTranslateX,
314
+ contentTranslateY,
315
+ true,
316
+ overridePendingAnimation
317
+ );
318
+ };
319
+
320
+ const animateOnUI = (
321
+ target: SmoothClipPresentation,
322
+ animation: SmoothClipAnimation
323
+ ): number => {
324
+ 'worklet';
325
+ if (
326
+ !isFiniteClipPresentation(target) ||
327
+ !animationIsFinite(target, animation)
328
+ ) {
329
+ return rejectAnimationHostFunction(driverId);
330
+ }
331
+ // Past the hook's cleanup the native entry is gone for good, and an
332
+ // interactive start here would recreate it as a latch nothing can ever
333
+ // start or cancel. Reject before any side effect — not via
334
+ // rejectAnimation, which would mint an id and a completion for a driver
335
+ // whose JS state is already detached. This is the "unsupported dispatch"
336
+ // arm of the documented 0 contract.
337
+ if (disposed.value !== 0) return 0;
338
+
339
+ const from = animation.from;
340
+ if (from !== undefined) {
341
+ // Fused hot write: exactly setScalars(from…) issued immediately
342
+ // before the handoff, so native's latest value — the animation
343
+ // start below — is the caller's explicit presentation. Also
344
+ // re-grabs from a running animation, which the implicit
345
+ // interactive-start path would silently skip.
346
+ setScalarsOnUI(
347
+ from.clip.x,
348
+ from.clip.y,
349
+ from.clip.width,
350
+ from.clip.height,
351
+ from.clip.radius,
352
+ from.contentTranslateX,
353
+ from.contentTranslateY,
354
+ true
355
+ );
356
+ }
357
+
358
+ // After a setScalars hot write the SharedValue no longer matches what
359
+ // is on screen; passing it as the start would snap the animation back.
360
+ // Without an interactive start, native resolves the start from its own
361
+ // latest value instead.
362
+ const scalarsWereStale = scalarsStale.value !== 0;
363
+ const hasInteractiveStart =
364
+ ownership.value === INTERACTIVE && !scalarsWereStale;
365
+ const start = presentation.value;
366
+ ownership.value = NATIVE;
367
+ presentation.value = target;
368
+ scalarsStale.value = 0;
369
+ const startClip = start.clip;
370
+ const targetClip = target.clip;
371
+ // Reanimated stamps a parallel animation's t0 on this same runtime as
372
+ // `__frameTimestamp || _getAnimationTimestamp()` (valueSetter.ts).
373
+ // Capturing the identical value here and handing it to the integrator
374
+ // keeps clip and content phase-locked in every branch — including a
375
+ // start issued from CALLBACK_INPUT (batched gesture moves), where the
376
+ // dispatching frame's stamp is EARLIER than the call: the native min()
377
+ // anchor alone would adopt that frame stamp while Reanimated, outside
378
+ // its rAF flush where __frameTimestamp is cleared, keeps the wall
379
+ // clock — a lead lasting the whole animation. NaN when the globals are
380
+ // absent (tests, non-worklets runtimes): native then falls back to its
381
+ // own clock plus the min() anchor, the pre-stamp behavior.
382
+ const workletGlobal = globalThis as {
383
+ __frameTimestamp?: number;
384
+ _getAnimationTimestamp?: () => number;
385
+ };
386
+ const startedAtMs =
387
+ workletGlobal.__frameTimestamp ||
388
+ (typeof workletGlobal._getAnimationTimestamp === 'function'
389
+ ? workletGlobal._getAnimationTimestamp()
390
+ : Number.NaN);
391
+ let animationId: number;
392
+
393
+ if (animation.type === 'timing') {
394
+ const [x1, y1, x2, y2] = animation.controlPoints;
395
+ animationId = animateTimingHostFunction(
396
+ driverId,
397
+ hasInteractiveStart,
398
+ startClip.x,
399
+ startClip.y,
400
+ startClip.width,
401
+ startClip.height,
402
+ startClip.radius,
403
+ start.contentTranslateX,
404
+ start.contentTranslateY,
405
+ targetClip.x,
406
+ targetClip.y,
407
+ targetClip.width,
408
+ targetClip.height,
409
+ targetClip.radius,
410
+ target.contentTranslateX,
411
+ target.contentTranslateY,
412
+ Math.max(0, animation.duration),
413
+ x1,
414
+ y1,
415
+ x2,
416
+ y2,
417
+ reduceMotion,
418
+ startedAtMs
419
+ );
420
+ } else if (animation.type === 'spring') {
421
+ const inheritVelocity =
422
+ animation.initialVelocity === undefined ||
423
+ animation.initialVelocity === 'inherit';
424
+ animationId = animateSpringHostFunction(
425
+ driverId,
426
+ hasInteractiveStart,
427
+ startClip.x,
428
+ startClip.y,
429
+ startClip.width,
430
+ startClip.height,
431
+ startClip.radius,
432
+ start.contentTranslateX,
433
+ start.contentTranslateY,
434
+ targetClip.x,
435
+ targetClip.y,
436
+ targetClip.width,
437
+ targetClip.height,
438
+ targetClip.radius,
439
+ target.contentTranslateX,
440
+ target.contentTranslateY,
441
+ Math.max(0.0001, animation.mass ?? 1),
442
+ Math.max(0.0001, animation.stiffness ?? 100),
443
+ Math.max(0, animation.damping ?? 10),
444
+ inheritVelocity ? 0 : (animation.initialVelocity as number),
445
+ inheritVelocity,
446
+ reduceMotion,
447
+ startedAtMs
448
+ );
449
+ } else {
450
+ animationId = animateKeyframesHostFunction(
451
+ driverId,
452
+ hasInteractiveStart,
453
+ startClip.x,
454
+ startClip.y,
455
+ startClip.width,
456
+ startClip.height,
457
+ startClip.radius,
458
+ start.contentTranslateX,
459
+ start.contentTranslateY,
460
+ targetClip.x,
461
+ targetClip.y,
462
+ targetClip.width,
463
+ targetClip.height,
464
+ targetClip.radius,
465
+ target.contentTranslateX,
466
+ target.contentTranslateY,
467
+ Math.max(0, animation.duration),
468
+ flattenedKeyframes(animation),
469
+ reduceMotion,
470
+ startedAtMs
471
+ );
472
+ }
473
+ if (animationId === 0) {
474
+ // The 0 sentinel: off-main, invalid-id, or otherwise unsupported
475
+ // dispatch. A missing driver is accepted when this call carries the
476
+ // authoritative interactive start above; a start-less missing-state
477
+ // request remains unsupported rather than inventing zero geometry.
478
+ // Validation failures never get here (they reject before any side
479
+ // effect with a fresh id and one finished:false completion).
480
+ ownership.value = INTERACTIVE;
481
+ presentation.value = start;
482
+ if (scalarsWereStale) scalarsStale.value = 1;
483
+ activeAnimationId.value = 0;
484
+ return rejectAnimationHostFunction(driverId);
485
+ }
486
+ activeAnimationId.value = animationId;
487
+ return animationId;
488
+ };
489
+
490
+ const cancelOnUI = (
491
+ animationId = 0,
492
+ behavior: 'current' | 'target' = 'current'
493
+ ): SmoothClipPresentation => {
494
+ 'worklet';
495
+ // Past the hook's cleanup the native entry is gone; the call would fail
496
+ // defined (handled=false) but it is the last driver.ui path that still
497
+ // crosses into native after the tombstone. Guard it like the rest.
498
+ if (disposed.value !== 0) return presentation.value;
499
+ const values = cancelAnimationHostFunction(
500
+ driverId,
501
+ animationId,
502
+ behavior === 'target' ? 1 : 0
503
+ );
504
+ if (values.length < 8 || values[0] !== 1) return presentation.value;
505
+ const current = presentationFromNative(values, presentation.value, 1);
506
+ activeAnimationId.value = 0;
507
+ ownership.value = INTERACTIVE;
508
+ scalarsStale.value = 0;
509
+ seedPresentation(current);
510
+ return current;
511
+ };
512
+
513
+ const driver: SmoothClipDriver = {
514
+ kind: 'hybrid',
515
+ presentation,
516
+ ui: {
517
+ beginInteraction() {
518
+ 'worklet';
519
+ if (isRNRuntime()) return uiOnly();
520
+ return beginOnUI();
521
+ },
522
+ set(next) {
523
+ 'worklet';
524
+ if (isRNRuntime()) return uiOnly();
525
+ setOnUI(next);
526
+ },
527
+ setScalars(
528
+ x,
529
+ y,
530
+ width,
531
+ height,
532
+ radius,
533
+ contentTranslateX,
534
+ contentTranslateY
535
+ ) {
536
+ 'worklet';
537
+ if (isRNRuntime()) return uiOnly();
538
+ setScalarsOnUI(
539
+ x,
540
+ y,
541
+ width,
542
+ height,
543
+ radius,
544
+ contentTranslateX,
545
+ contentTranslateY
546
+ );
547
+ },
548
+ animateTo(target, animation) {
549
+ 'worklet';
550
+ if (isRNRuntime()) return uiOnly();
551
+ return animateOnUI(target, animation);
552
+ },
553
+ cancel(animationId = 0, behavior = 'current') {
554
+ 'worklet';
555
+ if (isRNRuntime()) return uiOnly();
556
+ return cancelOnUI(animationId, behavior);
557
+ },
558
+ },
559
+ react: {
560
+ beginInteraction() {
561
+ const { requestId, promise } =
562
+ createReactRequest<SmoothClipPresentation>(driverId);
563
+ scheduleOnUI(() => {
564
+ 'worklet';
565
+ const result = beginOnUI();
566
+ scheduleOnRN(resolveReactRequest, driverId, requestId, result);
567
+ });
568
+ return promise;
569
+ },
570
+ set(next) {
571
+ const { requestId, promise } = createReactRequest<void>(driverId);
572
+ scheduleOnUI(() => {
573
+ 'worklet';
574
+ setOnUI(next);
575
+ scheduleOnRN(resolveReactRequest, driverId, requestId, undefined);
576
+ });
577
+ return promise;
578
+ },
579
+ animateTo(target, animation) {
580
+ const { requestId, promise } = createReactRequest<number>(
581
+ driverId,
582
+ true
583
+ );
584
+ scheduleOnUI(() => {
585
+ 'worklet';
586
+ const result = animateOnUI(target, animation);
587
+ scheduleOnRN(
588
+ resolveReactRequest,
589
+ driverId,
590
+ requestId,
591
+ result,
592
+ true
593
+ );
594
+ });
595
+ return promise;
596
+ },
597
+ cancel(animationId = 0, behavior = 'current') {
598
+ const { requestId, promise } =
599
+ createReactRequest<SmoothClipPresentation>(driverId, true);
600
+ scheduleOnUI(() => {
601
+ 'worklet';
602
+ const result = cancelOnUI(animationId, behavior);
603
+ scheduleOnRN(
604
+ resolveReactRequest,
605
+ driverId,
606
+ requestId,
607
+ result,
608
+ true
609
+ );
610
+ });
611
+ return promise;
612
+ },
613
+ },
614
+ };
615
+
616
+ setDriverState(
617
+ driver,
618
+ createDriverState(
619
+ driverId,
620
+ initialPresentation,
621
+ presentation,
622
+ callbackRef,
623
+ activeAnimationId,
624
+ ownership
625
+ )
626
+ );
627
+ driverRef.current = driver;
628
+ }
629
+
630
+ const driver = driverRef.current;
631
+
632
+ useEffect(() => {
633
+ const currentDriver = driverRef.current;
634
+ if (!currentDriver) return undefined;
635
+ const state = getDriverState(currentDriver);
636
+ const { driverId } = state;
637
+ // Re-attach on every effect run: StrictMode/<Activity> replay the effect
638
+ // after its cleanup detached this state and destroyed the native driver.
639
+ // The authoritative seed below recreates the native entry in that case.
640
+ attachDriverState(state);
641
+
642
+ const subscription = NativeSmoothClipModule.onClipAnimationComplete(
643
+ (result) => {
644
+ if (result.driverId !== driverId) return;
645
+ synchronizeNativeCompletion(
646
+ activeAnimationId,
647
+ ownership,
648
+ result.animationId,
649
+ result.finished
650
+ );
651
+ completeNativeAnimation(driverId, result.animationId, result.finished);
652
+ }
653
+ );
654
+
655
+ scheduleOnUI(
656
+ (
657
+ source: SharedValue<SmoothClipPresentation>,
658
+ listenerId: number,
659
+ nativeDriverId: number,
660
+ owner: SharedValue<number>,
661
+ suppressed: SharedValue<number>,
662
+ active: SharedValue<number>,
663
+ stale: SharedValue<number>,
664
+ gone: SharedValue<number>,
665
+ setter: typeof setPresentationHostFunction
666
+ ) => {
667
+ 'worklet';
668
+ // First, before the listener or the seed: this effect run owns the
669
+ // driver again, so a StrictMode/<Activity> replay must clear the
670
+ // previous cleanup's tombstone or every later write would be rejected.
671
+ gone.value = 0;
672
+ let last: SmoothClipPresentation | null = null;
673
+ const deliver = (next: SmoothClipPresentation) => {
674
+ if (
675
+ !isFiniteClipPresentation(next) ||
676
+ clipPresentationEquals(last, next)
677
+ ) {
678
+ return;
679
+ }
680
+ // Record `last` only for values native has actually observed:
681
+ // deliveries dropped during native ownership must stay eligible
682
+ // for re-delivery once interactive ownership returns.
683
+ if (owner.value !== INTERACTIVE) return;
684
+ if (suppressed.value > 0) {
685
+ suppressed.value -= 1;
686
+ last = next;
687
+ return;
688
+ }
689
+ last = next;
690
+ if (stale.value !== 0) stale.value = 0;
691
+ const { clip, contentTranslateX, contentTranslateY } = next;
692
+ setter(
693
+ nativeDriverId,
694
+ clip.x,
695
+ clip.y,
696
+ clip.width,
697
+ clip.height,
698
+ clip.radius,
699
+ contentTranslateX,
700
+ contentTranslateY,
701
+ false,
702
+ false
703
+ );
704
+ };
705
+ source.addListener(listenerId, deliver);
706
+ // Authoritative take-ownership seed. Creates the native entry before
707
+ // any view mounts on the ordinary path, and revives a driver destroyed
708
+ // by an effect-replay cleanup (StrictMode/<Activity>) on later runs.
709
+ // An animation worklet can win the scheduling race and create a latch
710
+ // first; Native ownership then marks that intent as newer, so this
711
+ // passive seed must not clear its active id or replay the target value.
712
+ const current = source.value;
713
+ if (owner.value === INTERACTIVE && isFiniteClipPresentation(current)) {
714
+ active.value = 0;
715
+ owner.value = INTERACTIVE;
716
+ stale.value = 0;
717
+ last = current;
718
+ setter(
719
+ nativeDriverId,
720
+ current.clip.x,
721
+ current.clip.y,
722
+ current.clip.width,
723
+ current.clip.height,
724
+ current.clip.radius,
725
+ current.contentTranslateX,
726
+ current.contentTranslateY,
727
+ true,
728
+ false
729
+ );
730
+ }
731
+ },
732
+ presentation,
733
+ driverId,
734
+ driverId,
735
+ ownership,
736
+ suppressDeliveries,
737
+ activeAnimationId,
738
+ scalarsStale,
739
+ disposed,
740
+ setPresentationHostFunction
741
+ );
742
+
743
+ return () => {
744
+ subscription.remove();
745
+ rejectDriverRequests(driverId);
746
+ detachDriverState(state);
747
+ scheduleOnUI(
748
+ (
749
+ source: SharedValue<SmoothClipPresentation>,
750
+ listenerId: number,
751
+ nativeDriverId: number,
752
+ owner: SharedValue<number>,
753
+ active: SharedValue<number>,
754
+ stale: SharedValue<number>,
755
+ suppressed: SharedValue<number>,
756
+ gone: SharedValue<number>,
757
+ destroy: typeof destroyDriverHostFunction
758
+ ) => {
759
+ 'worklet';
760
+ source.removeListener(listenerId);
761
+ destroy(nativeDriverId);
762
+ // StrictMode replays the effect with these same SharedValues. Reset
763
+ // the UI-side tombstone only after native teardown so the next setup
764
+ // can seed or animate without inheriting stale Native ownership.
765
+ active.value = 0;
766
+ owner.value = INTERACTIVE;
767
+ stale.value = 0;
768
+ // Defensive: seedPresentation now reclaims its own unspent credit at
769
+ // the point of issue, so this should already be 0. Kept because the
770
+ // failure mode — one declarative write silently dropped for the rest
771
+ // of the next hook's life — is invisible until someone reports a
772
+ // stale clip rect.
773
+ suppressed.value = 0;
774
+ // Last: the native entry is now erased, so until the next effect run
775
+ // clears this, any call that would recreate it is rejected instead.
776
+ gone.value = 1;
777
+ },
778
+ presentation,
779
+ driverId,
780
+ driverId,
781
+ ownership,
782
+ activeAnimationId,
783
+ scalarsStale,
784
+ suppressDeliveries,
785
+ disposed,
786
+ destroyDriverHostFunction
787
+ );
788
+ };
789
+ }, [
790
+ activeAnimationId,
791
+ disposed,
792
+ ownership,
793
+ presentation,
794
+ scalarsStale,
795
+ suppressDeliveries,
796
+ ]);
797
+
798
+ return driver;
799
+ }
800
+
801
+ export type {
802
+ KeyframedClipAnimation,
803
+ SpringClipAnimation,
804
+ TimingClipAnimation,
805
+ };