react-native-smooth-clip-view 0.2.9 → 0.4.0

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