@solidnative-dev/animation 0.0.0-stage → 0.1.0-beta.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.
package/dist/index.js ADDED
@@ -0,0 +1,1604 @@
1
+ export const UI_WORKLET_PROTOCOL_VERSION = 0;
2
+ export const UI_WORKLET_MAX_INPUTS = 64;
3
+ export const UI_WORKLET_MAX_OUTPUTS = 64;
4
+ export const UI_WORKLET_MAX_EXPRESSION_DEPTH = 32;
5
+ export const UI_WORKLET_MAX_EXPRESSION_NODES = 512;
6
+ export const UI_WORKLET_MAX_TIMING_DURATION_MS = 60_000;
7
+ export const UI_WORKLET_MAX_TIMING_KEYFRAMES = 32;
8
+ export const UI_WORKLET_MAX_FRAME_INTERVAL_SAMPLES = 8_192;
9
+ export const UI_WORKLET_MIN_SPRING_MASS = 0.001;
10
+ export const UI_WORKLET_MAX_SPRING_MASS = 100;
11
+ export const UI_WORKLET_MIN_SPRING_STIFFNESS = 0.001;
12
+ export const UI_WORKLET_MAX_SPRING_STIFFNESS = 100_000;
13
+ export const UI_WORKLET_MAX_SPRING_DAMPING = 10_000;
14
+ export const UI_WORKLET_MAX_SPRING_INITIAL_VELOCITY = 100;
15
+ export const UI_WORKLET_MAX_SPRING_REST_SPEED = 100;
16
+ export const UI_WORKLET_MAX_SPRING_DURATION_MS = 60_000;
17
+ export const UI_WORKLET_MIN_DECAY_DECELERATION = 0.001;
18
+ export const UI_WORKLET_MAX_DECAY_DECELERATION = 1_000;
19
+ export const UI_WORKLET_MAX_DECAY_VELOCITY = 100_000;
20
+ export const UI_WORKLET_MAX_DECAY_VELOCITY_THRESHOLD = 10_000;
21
+ export const UI_WORKLET_MAX_DECAY_DURATION_MS = 60_000;
22
+ const IDENTIFIER_PATTERN = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
23
+ const BINARY_OPERATORS = new Set([
24
+ "add",
25
+ "subtract",
26
+ "multiply",
27
+ "divide",
28
+ "min",
29
+ "max",
30
+ ]);
31
+ const TIMING_EASINGS = new Set([
32
+ "linear",
33
+ "ease-in",
34
+ "ease-out",
35
+ "ease-in-out",
36
+ ]);
37
+ function objectRecord(value, context) {
38
+ if (value === null ||
39
+ typeof value !== "object" ||
40
+ Array.isArray(value) ||
41
+ Object.getPrototypeOf(value) !== Object.prototype) {
42
+ throw new TypeError(`${context} must be a plain object.`);
43
+ }
44
+ return value;
45
+ }
46
+ function exactKeys(record, keys, context) {
47
+ const allowed = new Set(keys);
48
+ for (const key of Object.keys(record)) {
49
+ if (!allowed.has(key)) {
50
+ throw new TypeError(`${context} contains unsupported field ${key}.`);
51
+ }
52
+ }
53
+ for (const key of keys) {
54
+ if (!(key in record)) {
55
+ throw new TypeError(`${context} is missing field ${key}.`);
56
+ }
57
+ }
58
+ }
59
+ function finiteNumber(value, context) {
60
+ if (typeof value !== "number" || !Number.isFinite(value)) {
61
+ throw new TypeError(`${context} must be a finite number.`);
62
+ }
63
+ return value;
64
+ }
65
+ function identifier(value, context) {
66
+ if (typeof value !== "string" || !IDENTIFIER_PATTERN.test(value)) {
67
+ throw new TypeError(`${context} must be an identifier of 1 to 64 ASCII characters.`);
68
+ }
69
+ return value;
70
+ }
71
+ function numericRange(value, context, strictlyAscending) {
72
+ if (!Array.isArray(value) || value.length !== 2) {
73
+ throw new TypeError(`${context} must contain exactly two numbers.`);
74
+ }
75
+ const lower = finiteNumber(value[0], `${context}[0]`);
76
+ const upper = finiteNumber(value[1], `${context}[1]`);
77
+ if (strictlyAscending && upper <= lower) {
78
+ throw new RangeError(`${context} must be strictly ascending.`);
79
+ }
80
+ return Object.freeze([lower, upper]);
81
+ }
82
+ function parseExpression(value, inputs, budget, depth, context) {
83
+ if (depth > UI_WORKLET_MAX_EXPRESSION_DEPTH) {
84
+ throw new RangeError(`${context} exceeds the maximum worklet expression depth of ${UI_WORKLET_MAX_EXPRESSION_DEPTH}.`);
85
+ }
86
+ budget.nodes++;
87
+ if (budget.nodes > UI_WORKLET_MAX_EXPRESSION_NODES) {
88
+ throw new RangeError(`The worklet graph exceeds ${UI_WORKLET_MAX_EXPRESSION_NODES} expression nodes.`);
89
+ }
90
+ const record = objectRecord(value, context);
91
+ const kind = record.kind;
92
+ if (kind === "constant") {
93
+ exactKeys(record, ["kind", "value"], context);
94
+ return Object.freeze({
95
+ kind,
96
+ value: finiteNumber(record.value, `${context}.value`),
97
+ });
98
+ }
99
+ if (kind === "input") {
100
+ exactKeys(record, ["kind", "name"], context);
101
+ const name = identifier(record.name, `${context}.name`);
102
+ if (!inputs.has(name)) {
103
+ throw new RangeError(`${context} references undeclared worklet input ${name}.`);
104
+ }
105
+ return Object.freeze({ kind, name });
106
+ }
107
+ if (kind === "binary") {
108
+ exactKeys(record, ["kind", "operator", "left", "right"], context);
109
+ if (typeof record.operator !== "string" ||
110
+ !BINARY_OPERATORS.has(record.operator)) {
111
+ throw new TypeError(`${context}.operator is unsupported.`);
112
+ }
113
+ return Object.freeze({
114
+ kind,
115
+ operator: record.operator,
116
+ left: parseExpression(record.left, inputs, budget, depth + 1, `${context}.left`),
117
+ right: parseExpression(record.right, inputs, budget, depth + 1, `${context}.right`),
118
+ });
119
+ }
120
+ if (kind === "abs" || kind === "negate") {
121
+ exactKeys(record, ["kind", "value"], context);
122
+ return Object.freeze({
123
+ kind,
124
+ value: parseExpression(record.value, inputs, budget, depth + 1, `${context}.value`),
125
+ });
126
+ }
127
+ if (kind === "clamp") {
128
+ exactKeys(record, ["kind", "value", "min", "max"], context);
129
+ const min = finiteNumber(record.min, `${context}.min`);
130
+ const max = finiteNumber(record.max, `${context}.max`);
131
+ if (max < min) {
132
+ throw new RangeError(`${context} clamp bounds must be ascending.`);
133
+ }
134
+ return Object.freeze({
135
+ kind,
136
+ value: parseExpression(record.value, inputs, budget, depth + 1, `${context}.value`),
137
+ min,
138
+ max,
139
+ });
140
+ }
141
+ if (kind === "interpolate") {
142
+ exactKeys(record, ["kind", "value", "inputRange", "outputRange", "extrapolate"], context);
143
+ if (record.extrapolate !== "clamp" && record.extrapolate !== "extend") {
144
+ throw new TypeError(`${context}.extrapolate must be clamp or extend.`);
145
+ }
146
+ return Object.freeze({
147
+ kind,
148
+ value: parseExpression(record.value, inputs, budget, depth + 1, `${context}.value`),
149
+ inputRange: numericRange(record.inputRange, `${context}.inputRange`, true),
150
+ outputRange: numericRange(record.outputRange, `${context}.outputRange`, false),
151
+ extrapolate: record.extrapolate,
152
+ });
153
+ }
154
+ throw new TypeError(`${context}.kind is unsupported.`);
155
+ }
156
+ /** Validates, clones, and deeply freezes an untrusted worklet graph. */
157
+ export function parseUIWorkletGraph(value) {
158
+ const record = objectRecord(value, "UI worklet graph");
159
+ exactKeys(record, ["protocolVersion", "inputs", "outputs"], "UI worklet graph");
160
+ if (record.protocolVersion !== UI_WORKLET_PROTOCOL_VERSION) {
161
+ throw new RangeError(`Unsupported UI worklet protocol version ${String(record.protocolVersion)}.`);
162
+ }
163
+ if (!Array.isArray(record.inputs)) {
164
+ throw new TypeError("UI worklet graph inputs must be an array.");
165
+ }
166
+ if (record.inputs.length > UI_WORKLET_MAX_INPUTS) {
167
+ throw new RangeError(`UI worklet graphs support at most ${UI_WORKLET_MAX_INPUTS} inputs.`);
168
+ }
169
+ const inputNames = new Set();
170
+ const inputs = record.inputs.map((value, index) => {
171
+ const context = `UI worklet input ${String(index)}`;
172
+ const input = objectRecord(value, context);
173
+ exactKeys(input, ["name", "initialValue"], context);
174
+ const name = identifier(input.name, `${context}.name`);
175
+ if (inputNames.has(name)) {
176
+ throw new RangeError(`Duplicate UI worklet input ${name}.`);
177
+ }
178
+ inputNames.add(name);
179
+ return Object.freeze({
180
+ name,
181
+ initialValue: finiteNumber(input.initialValue, `${context}.initialValue`),
182
+ });
183
+ });
184
+ if (!Array.isArray(record.outputs) || record.outputs.length === 0) {
185
+ throw new TypeError("UI worklet graph outputs must be a non-empty array.");
186
+ }
187
+ if (record.outputs.length > UI_WORKLET_MAX_OUTPUTS) {
188
+ throw new RangeError(`UI worklet graphs support at most ${UI_WORKLET_MAX_OUTPUTS} outputs.`);
189
+ }
190
+ const outputNames = new Set();
191
+ const budget = { nodes: 0 };
192
+ const outputs = record.outputs.map((value, index) => {
193
+ const context = `UI worklet output ${String(index)}`;
194
+ const output = objectRecord(value, context);
195
+ exactKeys(output, ["name", "expression"], context);
196
+ const name = identifier(output.name, `${context}.name`);
197
+ if (outputNames.has(name)) {
198
+ throw new RangeError(`Duplicate UI worklet output ${name}.`);
199
+ }
200
+ outputNames.add(name);
201
+ return Object.freeze({
202
+ name,
203
+ expression: parseExpression(output.expression, inputNames, budget, 1, `${context}.expression`),
204
+ });
205
+ });
206
+ return Object.freeze({
207
+ protocolVersion: UI_WORKLET_PROTOCOL_VERSION,
208
+ inputs: Object.freeze(inputs),
209
+ outputs: Object.freeze(outputs),
210
+ });
211
+ }
212
+ function workletOperand(value) {
213
+ return typeof value === "number" ? { kind: "constant", value } : value;
214
+ }
215
+ function binaryWorkletExpression(operator, left, right) {
216
+ return {
217
+ kind: "binary",
218
+ operator,
219
+ left: workletOperand(left),
220
+ right: workletOperand(right),
221
+ };
222
+ }
223
+ const UI_WORKLET_EXPRESSION_BUILDER = Object.freeze({
224
+ constant(value) {
225
+ return { kind: "constant", value };
226
+ },
227
+ add(left, right) {
228
+ return binaryWorkletExpression("add", left, right);
229
+ },
230
+ subtract(left, right) {
231
+ return binaryWorkletExpression("subtract", left, right);
232
+ },
233
+ multiply(left, right) {
234
+ return binaryWorkletExpression("multiply", left, right);
235
+ },
236
+ divide(left, right) {
237
+ return binaryWorkletExpression("divide", left, right);
238
+ },
239
+ min(left, right) {
240
+ return binaryWorkletExpression("min", left, right);
241
+ },
242
+ max(left, right) {
243
+ return binaryWorkletExpression("max", left, right);
244
+ },
245
+ abs(value) {
246
+ return { kind: "abs", value: workletOperand(value) };
247
+ },
248
+ negate(value) {
249
+ return { kind: "negate", value: workletOperand(value) };
250
+ },
251
+ clamp(value, min, max) {
252
+ return { kind: "clamp", value: workletOperand(value), min, max };
253
+ },
254
+ interpolate(value, inputRange, outputRange, extrapolate = "clamp") {
255
+ return {
256
+ kind: "interpolate",
257
+ value: workletOperand(value),
258
+ inputRange,
259
+ outputRange,
260
+ extrapolate,
261
+ };
262
+ },
263
+ });
264
+ export function createUIWorkletGraph(definitionOrInputs, defineOutputs) {
265
+ if (defineOutputs === undefined) {
266
+ return parseUIWorkletGraph(definitionOrInputs);
267
+ }
268
+ if (typeof defineOutputs !== "function") {
269
+ throw new TypeError("UI worklet outputs must be defined by a function.");
270
+ }
271
+ const initialInputs = objectRecord(definitionOrInputs, "UI worklet initial inputs");
272
+ const inputExpressions = {};
273
+ for (const name of Object.keys(initialInputs)) {
274
+ inputExpressions[name] = { kind: "input", name };
275
+ }
276
+ const definedOutputs = objectRecord(defineOutputs(Object.freeze(inputExpressions), UI_WORKLET_EXPRESSION_BUILDER), "UI worklet defined outputs");
277
+ const outputs = Object.entries(definedOutputs).map(([name, expression]) => ({
278
+ name,
279
+ expression: workletOperand(expression),
280
+ }));
281
+ return parseUIWorkletGraph({
282
+ protocolVersion: UI_WORKLET_PROTOCOL_VERSION,
283
+ inputs: Object.entries(initialInputs).map(([name, initialValue]) => ({
284
+ name,
285
+ initialValue,
286
+ })),
287
+ outputs,
288
+ });
289
+ }
290
+ /** Validates and freezes one bounded native timing request. */
291
+ export function parseUIWorkletTiming(value) {
292
+ const record = objectRecord(value, "UI worklet timing");
293
+ exactKeys(record, ["durationMilliseconds", "easing"], "UI worklet timing");
294
+ const durationMilliseconds = finiteNumber(record.durationMilliseconds, "UI worklet timing duration");
295
+ if (durationMilliseconds <= 0 ||
296
+ durationMilliseconds > UI_WORKLET_MAX_TIMING_DURATION_MS) {
297
+ throw new RangeError(`UI worklet timing duration must be greater than zero and at most ${UI_WORKLET_MAX_TIMING_DURATION_MS} milliseconds.`);
298
+ }
299
+ if (typeof record.easing !== "string" ||
300
+ !TIMING_EASINGS.has(record.easing)) {
301
+ throw new TypeError("UI worklet timing easing is unsupported.");
302
+ }
303
+ return Object.freeze({
304
+ durationMilliseconds,
305
+ easing: record.easing,
306
+ });
307
+ }
308
+ /** Validates and freezes one bounded analytical native spring. */
309
+ export function parseUIWorkletSpring(value) {
310
+ const record = objectRecord(value, "UI worklet spring");
311
+ exactKeys(record, [
312
+ "mass",
313
+ "stiffness",
314
+ "damping",
315
+ "initialVelocity",
316
+ "restSpeedThreshold",
317
+ "restDisplacementThreshold",
318
+ "maximumDurationMilliseconds",
319
+ ], "UI worklet spring");
320
+ const mass = finiteNumber(record.mass, "UI worklet spring mass");
321
+ const stiffness = finiteNumber(record.stiffness, "UI worklet spring stiffness");
322
+ const damping = finiteNumber(record.damping, "UI worklet spring damping");
323
+ const initialVelocity = finiteNumber(record.initialVelocity, "UI worklet spring initial velocity");
324
+ const restSpeedThreshold = finiteNumber(record.restSpeedThreshold, "UI worklet spring rest speed threshold");
325
+ const restDisplacementThreshold = finiteNumber(record.restDisplacementThreshold, "UI worklet spring rest displacement threshold");
326
+ const maximumDurationMilliseconds = finiteNumber(record.maximumDurationMilliseconds, "UI worklet spring maximum duration");
327
+ if (mass < UI_WORKLET_MIN_SPRING_MASS || mass > UI_WORKLET_MAX_SPRING_MASS) {
328
+ throw new RangeError(`UI worklet spring mass must be between ${UI_WORKLET_MIN_SPRING_MASS} and ${UI_WORKLET_MAX_SPRING_MASS}.`);
329
+ }
330
+ if (stiffness < UI_WORKLET_MIN_SPRING_STIFFNESS ||
331
+ stiffness > UI_WORKLET_MAX_SPRING_STIFFNESS) {
332
+ throw new RangeError(`UI worklet spring stiffness must be between ${UI_WORKLET_MIN_SPRING_STIFFNESS} and ${UI_WORKLET_MAX_SPRING_STIFFNESS}.`);
333
+ }
334
+ if (damping < 0 || damping > UI_WORKLET_MAX_SPRING_DAMPING) {
335
+ throw new RangeError(`UI worklet spring damping must be between zero and ${UI_WORKLET_MAX_SPRING_DAMPING}.`);
336
+ }
337
+ if (Math.abs(initialVelocity) > UI_WORKLET_MAX_SPRING_INITIAL_VELOCITY) {
338
+ throw new RangeError(`UI worklet spring initial velocity magnitude must be at most ${UI_WORKLET_MAX_SPRING_INITIAL_VELOCITY}.`);
339
+ }
340
+ if (restSpeedThreshold <= 0 ||
341
+ restSpeedThreshold > UI_WORKLET_MAX_SPRING_REST_SPEED) {
342
+ throw new RangeError(`UI worklet spring rest speed threshold must be greater than zero and at most ${UI_WORKLET_MAX_SPRING_REST_SPEED}.`);
343
+ }
344
+ if (restDisplacementThreshold <= 0 || restDisplacementThreshold >= 1) {
345
+ throw new RangeError("UI worklet spring rest displacement threshold must be greater than zero and less than one.");
346
+ }
347
+ if (maximumDurationMilliseconds <= 0 ||
348
+ maximumDurationMilliseconds > UI_WORKLET_MAX_SPRING_DURATION_MS) {
349
+ throw new RangeError(`UI worklet spring maximum duration must be greater than zero and at most ${UI_WORKLET_MAX_SPRING_DURATION_MS} milliseconds.`);
350
+ }
351
+ return Object.freeze({
352
+ mass,
353
+ stiffness,
354
+ damping,
355
+ initialVelocity,
356
+ restSpeedThreshold,
357
+ restDisplacementThreshold,
358
+ maximumDurationMilliseconds,
359
+ });
360
+ }
361
+ /** Validates and freezes one bounded analytical native velocity decay. */
362
+ export function parseUIWorkletDecay(value) {
363
+ const record = objectRecord(value, "UI worklet decay");
364
+ exactKeys(record, ["deceleration", "velocityThreshold", "maximumDurationMilliseconds"], "UI worklet decay");
365
+ const deceleration = finiteNumber(record.deceleration, "UI worklet decay deceleration");
366
+ const velocityThreshold = finiteNumber(record.velocityThreshold, "UI worklet decay velocity threshold");
367
+ const maximumDurationMilliseconds = finiteNumber(record.maximumDurationMilliseconds, "UI worklet decay maximum duration");
368
+ if (deceleration < UI_WORKLET_MIN_DECAY_DECELERATION ||
369
+ deceleration > UI_WORKLET_MAX_DECAY_DECELERATION) {
370
+ throw new RangeError(`UI worklet decay deceleration must be between ${UI_WORKLET_MIN_DECAY_DECELERATION} and ${UI_WORKLET_MAX_DECAY_DECELERATION} per second.`);
371
+ }
372
+ if (velocityThreshold <= 0 ||
373
+ velocityThreshold > UI_WORKLET_MAX_DECAY_VELOCITY_THRESHOLD) {
374
+ throw new RangeError(`UI worklet decay velocity threshold must be greater than zero and at most ${UI_WORKLET_MAX_DECAY_VELOCITY_THRESHOLD}.`);
375
+ }
376
+ if (maximumDurationMilliseconds <= 0 ||
377
+ maximumDurationMilliseconds > UI_WORKLET_MAX_DECAY_DURATION_MS) {
378
+ throw new RangeError(`UI worklet decay maximum duration must be greater than zero and at most ${UI_WORKLET_MAX_DECAY_DURATION_MS} milliseconds.`);
379
+ }
380
+ return Object.freeze({
381
+ deceleration,
382
+ velocityThreshold,
383
+ maximumDurationMilliseconds,
384
+ });
385
+ }
386
+ /** Validates and freezes one bounded native pan-to-input mapping. */
387
+ export function parseUIWorkletPanGesture(value, graphValue) {
388
+ const graph = parseUIWorkletGraph(graphValue);
389
+ const record = objectRecord(value, "UI worklet pan gesture");
390
+ const hasReleaseDecay = Object.prototype.hasOwnProperty.call(record, "releaseDecay");
391
+ exactKeys(record, [
392
+ "xInput",
393
+ "yInput",
394
+ "minX",
395
+ "maxX",
396
+ "minY",
397
+ "maxY",
398
+ ...(hasReleaseDecay ? ["releaseDecay"] : []),
399
+ ], "UI worklet pan gesture");
400
+ const xInput = identifier(record.xInput, "UI worklet pan xInput");
401
+ const yInput = identifier(record.yInput, "UI worklet pan yInput");
402
+ if (xInput === yInput) {
403
+ throw new RangeError("UI worklet pan inputs must be distinct.");
404
+ }
405
+ const inputs = new Set(graph.inputs.map((input) => input.name));
406
+ if (!inputs.has(xInput)) {
407
+ throw new RangeError(`Unknown UI worklet pan input ${xInput}.`);
408
+ }
409
+ if (!inputs.has(yInput)) {
410
+ throw new RangeError(`Unknown UI worklet pan input ${yInput}.`);
411
+ }
412
+ const minX = finiteNumber(record.minX, "UI worklet pan minX");
413
+ const maxX = finiteNumber(record.maxX, "UI worklet pan maxX");
414
+ const minY = finiteNumber(record.minY, "UI worklet pan minY");
415
+ const maxY = finiteNumber(record.maxY, "UI worklet pan maxY");
416
+ if (maxX < minX || maxY < minY) {
417
+ throw new RangeError("UI worklet pan bounds must be ascending.");
418
+ }
419
+ return Object.freeze({
420
+ xInput,
421
+ yInput,
422
+ minX,
423
+ maxX,
424
+ minY,
425
+ maxY,
426
+ ...(hasReleaseDecay
427
+ ? { releaseDecay: parseUIWorkletDecay(record.releaseDecay) }
428
+ : {}),
429
+ });
430
+ }
431
+ /** Reference easing semantics shared by deterministic and native hosts. */
432
+ export function evaluateUIWorkletTimingProgress(timingValue, elapsedMillisecondsValue) {
433
+ const timing = parseUIWorkletTiming(timingValue);
434
+ const elapsedMilliseconds = finiteNumber(elapsedMillisecondsValue, "UI worklet timing elapsed time");
435
+ if (elapsedMilliseconds < 0) {
436
+ throw new RangeError("UI worklet timing elapsed time must be non-negative.");
437
+ }
438
+ const progress = Math.min(1, elapsedMilliseconds / timing.durationMilliseconds);
439
+ switch (timing.easing) {
440
+ case "linear":
441
+ return progress;
442
+ case "ease-in":
443
+ return progress * progress;
444
+ case "ease-out":
445
+ return 1 - (1 - progress) * (1 - progress);
446
+ case "ease-in-out":
447
+ return progress < 0.5
448
+ ? 2 * progress * progress
449
+ : 1 - ((-2 * progress + 2) * (-2 * progress + 2)) / 2;
450
+ }
451
+ }
452
+ /**
453
+ * Analytical damped-harmonic-oscillator reference. Its result depends on
454
+ * elapsed time rather than the number of display callbacks.
455
+ */
456
+ export function evaluateUIWorkletSpring(springValue, elapsedMillisecondsValue) {
457
+ const spring = parseUIWorkletSpring(springValue);
458
+ const elapsedMilliseconds = finiteNumber(elapsedMillisecondsValue, "UI worklet spring elapsed time");
459
+ if (elapsedMilliseconds < 0) {
460
+ throw new RangeError("UI worklet spring elapsed time must be non-negative.");
461
+ }
462
+ if (elapsedMilliseconds >= spring.maximumDurationMilliseconds) {
463
+ return Object.freeze({ position: 1, velocity: 0, settled: true });
464
+ }
465
+ if (elapsedMilliseconds === 0) {
466
+ return Object.freeze({
467
+ position: 0,
468
+ velocity: spring.initialVelocity,
469
+ settled: false,
470
+ });
471
+ }
472
+ const elapsedSeconds = elapsedMilliseconds / 1_000;
473
+ const naturalFrequency = Math.sqrt(spring.stiffness / spring.mass);
474
+ const dampingRatio = spring.damping / (2 * Math.sqrt(spring.stiffness * spring.mass));
475
+ const initialDisplacement = -1;
476
+ let displacement;
477
+ let velocity;
478
+ if (dampingRatio < 1 - 1e-7) {
479
+ const dampedFrequency = naturalFrequency * Math.sqrt(1 - dampingRatio * dampingRatio);
480
+ const decay = Math.exp(-dampingRatio * naturalFrequency * elapsedSeconds);
481
+ const cosine = Math.cos(dampedFrequency * elapsedSeconds);
482
+ const sine = Math.sin(dampedFrequency * elapsedSeconds);
483
+ const sineCoefficient = (spring.initialVelocity +
484
+ dampingRatio * naturalFrequency * initialDisplacement) /
485
+ dampedFrequency;
486
+ const oscillation = initialDisplacement * cosine + sineCoefficient * sine;
487
+ displacement = decay * oscillation;
488
+ velocity =
489
+ decay *
490
+ (-dampingRatio * naturalFrequency * oscillation +
491
+ -initialDisplacement * dampedFrequency * sine +
492
+ sineCoefficient * dampedFrequency * cosine);
493
+ }
494
+ else if (dampingRatio <= 1 + 1e-7) {
495
+ const linearCoefficient = spring.initialVelocity + naturalFrequency * initialDisplacement;
496
+ const decay = Math.exp(-naturalFrequency * elapsedSeconds);
497
+ const linear = initialDisplacement + linearCoefficient * elapsedSeconds;
498
+ displacement = linear * decay;
499
+ velocity = (linearCoefficient - naturalFrequency * linear) * decay;
500
+ }
501
+ else {
502
+ const radical = Math.sqrt(dampingRatio * dampingRatio - 1);
503
+ const slowRoot = -naturalFrequency / (dampingRatio + radical);
504
+ const fastRoot = -naturalFrequency * (dampingRatio + radical);
505
+ const slowCoefficient = (spring.initialVelocity - fastRoot * initialDisplacement) /
506
+ (slowRoot - fastRoot);
507
+ const fastCoefficient = initialDisplacement - slowCoefficient;
508
+ const slowTerm = slowCoefficient * Math.exp(slowRoot * elapsedSeconds);
509
+ const fastTerm = fastCoefficient * Math.exp(fastRoot * elapsedSeconds);
510
+ displacement = slowTerm + fastTerm;
511
+ velocity = slowRoot * slowTerm + fastRoot * fastTerm;
512
+ }
513
+ const position = 1 + displacement;
514
+ if (!Number.isFinite(position) || !Number.isFinite(velocity)) {
515
+ throw new RangeError("UI worklet spring evaluation was not finite.");
516
+ }
517
+ const settled = Math.abs(displacement) <= spring.restDisplacementThreshold &&
518
+ Math.abs(velocity) <= spring.restSpeedThreshold;
519
+ return Object.freeze(settled
520
+ ? { position: 1, velocity: 0, settled: true }
521
+ : { position, velocity, settled: false });
522
+ }
523
+ /**
524
+ * Analytical exponential-decay reference for a complete velocity vector.
525
+ * `initialSpeedValue` is that vector's maximum absolute input velocity.
526
+ */
527
+ export function evaluateUIWorkletDecay(decayValue, initialSpeedValue, elapsedMillisecondsValue) {
528
+ const decay = parseUIWorkletDecay(decayValue);
529
+ const initialSpeed = finiteNumber(initialSpeedValue, "UI worklet decay initial speed");
530
+ const elapsedMilliseconds = finiteNumber(elapsedMillisecondsValue, "UI worklet decay elapsed time");
531
+ if (initialSpeed < 0 || initialSpeed > UI_WORKLET_MAX_DECAY_VELOCITY) {
532
+ throw new RangeError(`UI worklet decay initial speed must be between zero and ${UI_WORKLET_MAX_DECAY_VELOCITY}.`);
533
+ }
534
+ if (elapsedMilliseconds < 0) {
535
+ throw new RangeError("UI worklet decay elapsed time must be non-negative.");
536
+ }
537
+ const thresholdTimeSeconds = initialSpeed <= decay.velocityThreshold
538
+ ? 0
539
+ : Math.log(initialSpeed / decay.velocityThreshold) / decay.deceleration;
540
+ const terminalTimeSeconds = Math.min(thresholdTimeSeconds, decay.maximumDurationMilliseconds / 1_000);
541
+ const elapsedSeconds = elapsedMilliseconds / 1_000;
542
+ const settled = elapsedSeconds >= terminalTimeSeconds;
543
+ const evaluatedSeconds = settled ? terminalTimeSeconds : elapsedSeconds;
544
+ const velocityFactor = Math.exp(-decay.deceleration * evaluatedSeconds);
545
+ const displacementFactorSeconds = -Math.expm1(-decay.deceleration * evaluatedSeconds) / decay.deceleration;
546
+ if (!Number.isFinite(velocityFactor) ||
547
+ !Number.isFinite(displacementFactorSeconds)) {
548
+ throw new RangeError("UI worklet decay evaluation was not finite.");
549
+ }
550
+ return Object.freeze({
551
+ displacementFactorSeconds,
552
+ velocityFactor: settled ? 0 : velocityFactor,
553
+ speed: settled ? 0 : initialSpeed * velocityFactor,
554
+ settled,
555
+ });
556
+ }
557
+ function initialInputs(graph) {
558
+ const values = {};
559
+ for (const input of graph.inputs)
560
+ values[input.name] = input.initialValue;
561
+ return Object.freeze(values);
562
+ }
563
+ function completeInputs(graph, value) {
564
+ const record = objectRecord(value, "UI worklet inputs");
565
+ const expected = new Set(graph.inputs.map((input) => input.name));
566
+ for (const key of Object.keys(record)) {
567
+ if (!expected.has(key)) {
568
+ throw new RangeError(`Unknown UI worklet input ${key}.`);
569
+ }
570
+ }
571
+ const values = {};
572
+ for (const input of graph.inputs) {
573
+ if (!(input.name in record)) {
574
+ throw new TypeError(`UI worklet input ${input.name} is missing.`);
575
+ }
576
+ values[input.name] = finiteNumber(record[input.name], `UI worklet input ${input.name}`);
577
+ }
578
+ return Object.freeze(values);
579
+ }
580
+ function evaluateExpression(expression, inputs) {
581
+ if (expression.kind === "constant")
582
+ return expression.value;
583
+ if (expression.kind === "input")
584
+ return inputs[expression.name];
585
+ if (expression.kind === "abs") {
586
+ return Math.abs(evaluateExpression(expression.value, inputs));
587
+ }
588
+ if (expression.kind === "negate") {
589
+ return -evaluateExpression(expression.value, inputs);
590
+ }
591
+ if (expression.kind === "clamp") {
592
+ return Math.min(expression.max, Math.max(expression.min, evaluateExpression(expression.value, inputs)));
593
+ }
594
+ if (expression.kind === "interpolate") {
595
+ const input = evaluateExpression(expression.value, inputs);
596
+ let progress = (input - expression.inputRange[0]) /
597
+ (expression.inputRange[1] - expression.inputRange[0]);
598
+ if (expression.extrapolate === "clamp") {
599
+ progress = Math.min(1, Math.max(0, progress));
600
+ }
601
+ return (expression.outputRange[0] +
602
+ progress * (expression.outputRange[1] - expression.outputRange[0]));
603
+ }
604
+ const left = evaluateExpression(expression.left, inputs);
605
+ const right = evaluateExpression(expression.right, inputs);
606
+ switch (expression.operator) {
607
+ case "add":
608
+ return left + right;
609
+ case "subtract":
610
+ return left - right;
611
+ case "multiply":
612
+ return left * right;
613
+ case "divide":
614
+ if (right === 0)
615
+ throw new RangeError("UI worklet division by zero.");
616
+ return left / right;
617
+ case "min":
618
+ return Math.min(left, right);
619
+ case "max":
620
+ return Math.max(left, right);
621
+ }
622
+ }
623
+ /** Reference semantics used by native backends and deterministic tests. */
624
+ export function evaluateUIWorkletGraph(graphValue, inputValue) {
625
+ const graph = parseUIWorkletGraph(graphValue);
626
+ const inputs = completeInputs(graph, inputValue);
627
+ const outputs = {};
628
+ for (const output of graph.outputs) {
629
+ const value = evaluateExpression(output.expression, inputs);
630
+ if (!Number.isFinite(value)) {
631
+ throw new RangeError(`UI worklet output ${output.name} was not finite.`);
632
+ }
633
+ outputs[output.name] = value;
634
+ }
635
+ return Object.freeze(outputs);
636
+ }
637
+ function assertHost(value) {
638
+ if (value === null ||
639
+ typeof value !== "object" ||
640
+ value.protocolVersion !== UI_WORKLET_PROTOCOL_VERSION ||
641
+ typeof value.installGraph !== "function" ||
642
+ typeof value.updateGraphInputs !== "function" ||
643
+ typeof value.destroyGraph !== "function") {
644
+ throw new TypeError(`UI worklet host must implement protocol version ${UI_WORKLET_PROTOCOL_VERSION}.`);
645
+ }
646
+ }
647
+ function timestamp(value) {
648
+ const result = finiteNumber(value, "UI worklet timestamp");
649
+ if (result < 0) {
650
+ throw new RangeError("UI worklet timestamps must be non-negative.");
651
+ }
652
+ return result;
653
+ }
654
+ function readReduceMotionPreference(source) {
655
+ if (source === undefined)
656
+ return false;
657
+ const value = source();
658
+ if (value !== undefined && typeof value !== "boolean") {
659
+ throw new TypeError("UI worklet reduceMotion must return a boolean or undefined.");
660
+ }
661
+ return value === true;
662
+ }
663
+ /**
664
+ * Installs one validated graph and owns its input/cancellation boundary. This
665
+ * does not imply that the injected host executes on the UI thread.
666
+ */
667
+ export function createUIWorkletSession(host, graphValue, options = {}) {
668
+ assertHost(host);
669
+ const graph = parseUIWorkletGraph(graphValue);
670
+ const clock = options.clock ?? Date.now;
671
+ if (typeof clock !== "function") {
672
+ throw new TypeError("UI worklet session clock must be a function.");
673
+ }
674
+ if (options.reduceMotion !== undefined &&
675
+ typeof options.reduceMotion !== "function") {
676
+ throw new TypeError("UI worklet session reduceMotion must be a function.");
677
+ }
678
+ const handle = host.installGraph(graph);
679
+ if (!Number.isSafeInteger(handle) || handle <= 0) {
680
+ throw new TypeError("UI worklet hosts must allocate positive safe-integer handles.");
681
+ }
682
+ let currentInputs = initialInputs(graph);
683
+ let lastTimestamp = -Infinity;
684
+ let disposed = false;
685
+ let nativeInputsOwned = false;
686
+ const knownInputs = new Set(graph.inputs.map((input) => input.name));
687
+ function prepareInputFrame(changesValue, timestampValue) {
688
+ if (disposed)
689
+ throw new Error("The UI worklet session is disposed.");
690
+ if (nativeInputsOwned) {
691
+ throw new Error("The UI worklet input vector is owned by its native pan gesture.");
692
+ }
693
+ const changes = objectRecord(changesValue, "UI worklet input update");
694
+ const nextInputs = { ...currentInputs };
695
+ const changedKeys = Object.keys(changes);
696
+ for (const key of changedKeys) {
697
+ if (!knownInputs.has(key)) {
698
+ throw new RangeError(`Unknown UI worklet input ${key}.`);
699
+ }
700
+ nextInputs[key] = finiteNumber(changes[key], `UI worklet input ${key}`);
701
+ }
702
+ if (changedKeys.length === 0)
703
+ return undefined;
704
+ const nextTimestamp = timestamp(timestampValue === undefined ? clock() : timestampValue);
705
+ if (nextTimestamp < lastTimestamp) {
706
+ throw new RangeError("UI worklet input timestamps must be monotonic.");
707
+ }
708
+ return {
709
+ nextInputs: Object.freeze(nextInputs),
710
+ inputVector: Object.freeze(graph.inputs.map((input) => nextInputs[input.name])),
711
+ nextTimestamp,
712
+ };
713
+ }
714
+ function prepareDecayVelocityFrame(velocitiesValue, timestampValue) {
715
+ if (disposed)
716
+ throw new Error("The UI worklet session is disposed.");
717
+ if (nativeInputsOwned) {
718
+ throw new Error("The UI worklet input vector is owned by its native pan gesture.");
719
+ }
720
+ const velocities = objectRecord(velocitiesValue, "UI worklet decay velocities");
721
+ const velocityVector = new Array(graph.inputs.length).fill(0);
722
+ const changedKeys = Object.keys(velocities);
723
+ for (const key of changedKeys) {
724
+ if (!knownInputs.has(key)) {
725
+ throw new RangeError(`Unknown UI worklet decay input ${key}.`);
726
+ }
727
+ const velocity = finiteNumber(velocities[key], `UI worklet decay velocity ${key}`);
728
+ if (Math.abs(velocity) > UI_WORKLET_MAX_DECAY_VELOCITY) {
729
+ throw new RangeError(`UI worklet decay velocity magnitude must be at most ${UI_WORKLET_MAX_DECAY_VELOCITY}.`);
730
+ }
731
+ velocityVector[graph.inputs.findIndex((input) => input.name === key)] =
732
+ velocity;
733
+ }
734
+ if (changedKeys.length === 0)
735
+ return undefined;
736
+ const nextTimestamp = timestamp(timestampValue === undefined ? clock() : timestampValue);
737
+ if (nextTimestamp < lastTimestamp) {
738
+ throw new RangeError("UI worklet input timestamps must be monotonic.");
739
+ }
740
+ return {
741
+ velocityVector: Object.freeze(velocityVector),
742
+ nextTimestamp,
743
+ };
744
+ }
745
+ function prepareTimingKeyframes(keyframesValue, timestampValue) {
746
+ if (disposed)
747
+ throw new Error("The UI worklet session is disposed.");
748
+ if (nativeInputsOwned) {
749
+ throw new Error("The UI worklet input vector is owned by its native pan gesture.");
750
+ }
751
+ if (!Array.isArray(keyframesValue) ||
752
+ keyframesValue.length === 0 ||
753
+ keyframesValue.length > UI_WORKLET_MAX_TIMING_KEYFRAMES) {
754
+ throw new RangeError(`UI worklet timing keyframes must contain between 1 and ${UI_WORKLET_MAX_TIMING_KEYFRAMES} steps.`);
755
+ }
756
+ let nextInputs = currentInputs;
757
+ let totalDurationMilliseconds = 0;
758
+ const keyframes = keyframesValue.map((value, index) => {
759
+ const context = `UI worklet timing keyframe ${String(index)}`;
760
+ const record = objectRecord(value, context);
761
+ exactKeys(record, ["inputs", "timing"], context);
762
+ const changes = objectRecord(record.inputs, `${context}.inputs`);
763
+ const target = { ...nextInputs };
764
+ for (const key of Object.keys(changes)) {
765
+ if (!knownInputs.has(key)) {
766
+ throw new RangeError(`Unknown UI worklet input ${key}.`);
767
+ }
768
+ target[key] = finiteNumber(changes[key], `${context} input ${key}`);
769
+ }
770
+ const timing = parseUIWorkletTiming(record.timing);
771
+ totalDurationMilliseconds += timing.durationMilliseconds;
772
+ if (totalDurationMilliseconds > UI_WORKLET_MAX_TIMING_DURATION_MS) {
773
+ throw new RangeError(`UI worklet timing keyframes may last at most ${UI_WORKLET_MAX_TIMING_DURATION_MS} milliseconds in total.`);
774
+ }
775
+ nextInputs = Object.freeze(target);
776
+ return Object.freeze({
777
+ inputs: Object.freeze(graph.inputs.map((input) => nextInputs[input.name])),
778
+ timing,
779
+ });
780
+ });
781
+ const nextTimestamp = timestamp(timestampValue === undefined ? clock() : timestampValue);
782
+ if (nextTimestamp < lastTimestamp) {
783
+ throw new RangeError("UI worklet input timestamps must be monotonic.");
784
+ }
785
+ return {
786
+ keyframes: Object.freeze(keyframes),
787
+ finalInputs: nextInputs,
788
+ nextTimestamp,
789
+ };
790
+ }
791
+ function readSynchronizedInputVector(value) {
792
+ if (!Array.isArray(value) || value.length !== graph.inputs.length) {
793
+ throw new TypeError("UI worklet synchronization must return the complete frozen input vector.");
794
+ }
795
+ const inputs = {};
796
+ for (let index = 0; index < graph.inputs.length; index++) {
797
+ const input = graph.inputs[index];
798
+ inputs[input.name] = finiteNumber(value[index], `Synchronized UI worklet input ${input.name}`);
799
+ }
800
+ return Object.freeze(inputs);
801
+ }
802
+ const session = {
803
+ graph,
804
+ handle,
805
+ get disposed() {
806
+ return disposed;
807
+ },
808
+ get nativeInputsOwned() {
809
+ return nativeInputsOwned;
810
+ },
811
+ get inputs() {
812
+ return currentInputs;
813
+ },
814
+ update(changesValue, timestampValue) {
815
+ const frame = prepareInputFrame(changesValue, timestampValue);
816
+ if (frame === undefined)
817
+ return;
818
+ host.updateGraphInputs(handle, frame.inputVector, frame.nextTimestamp);
819
+ currentInputs = frame.nextInputs;
820
+ lastTimestamp = frame.nextTimestamp;
821
+ },
822
+ animate(changesValue, timingValue, timestampValue) {
823
+ const timing = parseUIWorkletTiming(timingValue);
824
+ const frame = prepareInputFrame(changesValue, timestampValue);
825
+ if (frame === undefined)
826
+ return;
827
+ if (readReduceMotionPreference(options.reduceMotion)) {
828
+ host.updateGraphInputs(handle, frame.inputVector, frame.nextTimestamp);
829
+ }
830
+ else {
831
+ const animateGraphInputs = host.animateGraphInputs;
832
+ if (typeof animateGraphInputs !== "function") {
833
+ throw new Error("The UI worklet host does not support native timings.");
834
+ }
835
+ animateGraphInputs.call(host, handle, frame.inputVector, frame.nextTimestamp, timing);
836
+ }
837
+ currentInputs = frame.nextInputs;
838
+ lastTimestamp = frame.nextTimestamp;
839
+ },
840
+ animateKeyframes(keyframesValue, timestampValue) {
841
+ const prepared = prepareTimingKeyframes(keyframesValue, timestampValue);
842
+ if (readReduceMotionPreference(options.reduceMotion)) {
843
+ host.updateGraphInputs(handle, prepared.keyframes[prepared.keyframes.length - 1].inputs, prepared.nextTimestamp);
844
+ }
845
+ else {
846
+ const animateGraphKeyframes = host.animateGraphKeyframes;
847
+ if (typeof animateGraphKeyframes !== "function") {
848
+ throw new Error("The UI worklet host does not support native timing keyframes.");
849
+ }
850
+ animateGraphKeyframes.call(host, handle, prepared.keyframes, prepared.nextTimestamp);
851
+ }
852
+ currentInputs = prepared.finalInputs;
853
+ lastTimestamp = prepared.nextTimestamp;
854
+ },
855
+ spring(changesValue, springValue, timestampValue) {
856
+ const spring = parseUIWorkletSpring(springValue);
857
+ const frame = prepareInputFrame(changesValue, timestampValue);
858
+ if (frame === undefined)
859
+ return;
860
+ if (readReduceMotionPreference(options.reduceMotion)) {
861
+ host.updateGraphInputs(handle, frame.inputVector, frame.nextTimestamp);
862
+ }
863
+ else {
864
+ const springGraphInputs = host.springGraphInputs;
865
+ if (typeof springGraphInputs !== "function") {
866
+ throw new Error("The UI worklet host does not support native springs.");
867
+ }
868
+ springGraphInputs.call(host, handle, frame.inputVector, frame.nextTimestamp, spring);
869
+ }
870
+ currentInputs = frame.nextInputs;
871
+ lastTimestamp = frame.nextTimestamp;
872
+ },
873
+ decay(velocitiesValue, decayValue, timestampValue) {
874
+ const decay = parseUIWorkletDecay(decayValue);
875
+ const frame = prepareDecayVelocityFrame(velocitiesValue, timestampValue);
876
+ if (frame === undefined)
877
+ return;
878
+ if (readReduceMotionPreference(options.reduceMotion)) {
879
+ host.updateGraphInputs(handle, Object.freeze(graph.inputs.map((input) => currentInputs[input.name])), frame.nextTimestamp);
880
+ }
881
+ else {
882
+ const decayGraphInputs = host.decayGraphInputs;
883
+ if (typeof decayGraphInputs !== "function") {
884
+ throw new Error("The UI worklet host does not support native decays.");
885
+ }
886
+ decayGraphInputs.call(host, handle, frame.velocityVector, frame.nextTimestamp, decay);
887
+ }
888
+ lastTimestamp = frame.nextTimestamp;
889
+ },
890
+ cancel(timestampValue) {
891
+ if (disposed)
892
+ throw new Error("The UI worklet session is disposed.");
893
+ const cancelGraphAnimation = host.cancelGraphAnimation;
894
+ if (typeof cancelGraphAnimation !== "function") {
895
+ throw new Error("The UI worklet host does not support native animation cancellation.");
896
+ }
897
+ const nextTimestamp = timestamp(timestampValue === undefined ? clock() : timestampValue);
898
+ if (nextTimestamp < lastTimestamp) {
899
+ throw new RangeError("UI worklet input timestamps must be monotonic.");
900
+ }
901
+ const frozenInputs = readSynchronizedInputVector(cancelGraphAnimation.call(host, handle, nextTimestamp));
902
+ currentInputs = frozenInputs;
903
+ lastTimestamp = nextTimestamp;
904
+ },
905
+ attachPanGesture(gestureValue) {
906
+ if (disposed)
907
+ throw new Error("The UI worklet session is disposed.");
908
+ if (nativeInputsOwned) {
909
+ throw new Error("The UI worklet session already owns a native pan.");
910
+ }
911
+ const attachPanGesture = host.attachPanGesture;
912
+ if (typeof attachPanGesture !== "function") {
913
+ throw new Error("The UI worklet host does not support native pan gestures.");
914
+ }
915
+ const gesture = parseUIWorkletPanGesture(gestureValue, graph);
916
+ const effectiveGesture = gesture.releaseDecay !== undefined &&
917
+ readReduceMotionPreference(options.reduceMotion)
918
+ ? Object.freeze({
919
+ xInput: gesture.xInput,
920
+ yInput: gesture.yInput,
921
+ minX: gesture.minX,
922
+ maxX: gesture.maxX,
923
+ minY: gesture.minY,
924
+ maxY: gesture.maxY,
925
+ })
926
+ : gesture;
927
+ attachPanGesture.call(host, handle, effectiveGesture);
928
+ nativeInputsOwned = true;
929
+ },
930
+ detachPanGesture(timestampValue) {
931
+ if (disposed)
932
+ throw new Error("The UI worklet session is disposed.");
933
+ if (!nativeInputsOwned) {
934
+ throw new Error("The UI worklet session does not own a native pan.");
935
+ }
936
+ const detachPanGesture = host.detachPanGesture;
937
+ if (typeof detachPanGesture !== "function") {
938
+ throw new Error("The UI worklet host does not support native pan detachment.");
939
+ }
940
+ const nextTimestamp = timestamp(timestampValue === undefined ? clock() : timestampValue);
941
+ if (nextTimestamp < lastTimestamp) {
942
+ throw new RangeError("UI worklet input timestamps must be monotonic.");
943
+ }
944
+ const frozenInputs = readSynchronizedInputVector(detachPanGesture.call(host, handle, nextTimestamp));
945
+ currentInputs = frozenInputs;
946
+ lastTimestamp = nextTimestamp;
947
+ nativeInputsOwned = false;
948
+ },
949
+ dispose() {
950
+ if (disposed)
951
+ return;
952
+ disposed = true;
953
+ host.destroyGraph(handle);
954
+ },
955
+ };
956
+ return Object.freeze(session);
957
+ }
958
+ function createMutableFrameStatistics() {
959
+ return {
960
+ frameCount: 0,
961
+ firstFrameTimeMilliseconds: 0,
962
+ lastFrameTimeMilliseconds: 0,
963
+ minimumFrameIntervalMilliseconds: 0,
964
+ maximumFrameIntervalMilliseconds: 0,
965
+ totalFrameIntervalMilliseconds: 0,
966
+ intervalSamples: [],
967
+ droppedIntervalSampleCount: 0,
968
+ };
969
+ }
970
+ function recordAnimationFrame(statistics, frameTimeMilliseconds) {
971
+ if (statistics.frameCount === 0) {
972
+ statistics.frameCount = 1;
973
+ statistics.firstFrameTimeMilliseconds = frameTimeMilliseconds;
974
+ statistics.lastFrameTimeMilliseconds = frameTimeMilliseconds;
975
+ return;
976
+ }
977
+ const interval = frameTimeMilliseconds - statistics.lastFrameTimeMilliseconds;
978
+ if (interval <= 0) {
979
+ throw new RangeError("UI worklet animation frame timestamps must be strictly increasing.");
980
+ }
981
+ statistics.frameCount++;
982
+ statistics.lastFrameTimeMilliseconds = frameTimeMilliseconds;
983
+ statistics.totalFrameIntervalMilliseconds += interval;
984
+ if (statistics.minimumFrameIntervalMilliseconds === 0 ||
985
+ interval < statistics.minimumFrameIntervalMilliseconds) {
986
+ statistics.minimumFrameIntervalMilliseconds = interval;
987
+ }
988
+ if (interval > statistics.maximumFrameIntervalMilliseconds) {
989
+ statistics.maximumFrameIntervalMilliseconds = interval;
990
+ }
991
+ if (statistics.intervalSamples.length < UI_WORKLET_MAX_FRAME_INTERVAL_SAMPLES) {
992
+ statistics.intervalSamples.push(interval);
993
+ }
994
+ else {
995
+ statistics.droppedIntervalSampleCount++;
996
+ }
997
+ }
998
+ function snapshotFrameStatistics(statistics) {
999
+ if (statistics === undefined || statistics.frameCount === 0)
1000
+ return undefined;
1001
+ const intervalCount = statistics.frameCount - 1;
1002
+ const samples = [...statistics.intervalSamples].sort((left, right) => left - right);
1003
+ const quantile = (value) => samples.length === 0
1004
+ ? 0
1005
+ : samples[Math.max(0, Math.ceil(samples.length * value) - 1)];
1006
+ return Object.freeze({
1007
+ frameCount: statistics.frameCount,
1008
+ intervalCount,
1009
+ sampledIntervalCount: samples.length,
1010
+ droppedIntervalSampleCount: statistics.droppedIntervalSampleCount,
1011
+ firstFrameTimeMilliseconds: statistics.firstFrameTimeMilliseconds,
1012
+ lastFrameTimeMilliseconds: statistics.lastFrameTimeMilliseconds,
1013
+ minimumFrameIntervalMilliseconds: statistics.minimumFrameIntervalMilliseconds,
1014
+ maximumFrameIntervalMilliseconds: statistics.maximumFrameIntervalMilliseconds,
1015
+ meanFrameIntervalMilliseconds: intervalCount === 0
1016
+ ? 0
1017
+ : statistics.totalFrameIntervalMilliseconds / intervalCount,
1018
+ p50FrameIntervalMilliseconds: quantile(0.5),
1019
+ p95FrameIntervalMilliseconds: quantile(0.95),
1020
+ p99FrameIntervalMilliseconds: quantile(0.99),
1021
+ });
1022
+ }
1023
+ /** Deterministic reference host; it is intentionally not a UI-thread backend. */
1024
+ export function createInMemoryUIWorkletHost() {
1025
+ const states = new Map();
1026
+ let nextHandle = 1;
1027
+ let lastFrameTime = -Infinity;
1028
+ function requireState(handle) {
1029
+ const state = states.get(handle);
1030
+ if (state === undefined) {
1031
+ throw new Error(`Unknown UI worklet graph handle ${String(handle)}.`);
1032
+ }
1033
+ return state;
1034
+ }
1035
+ function readInputVector(state, inputVector) {
1036
+ if (!Array.isArray(inputVector) ||
1037
+ inputVector.length !== state.graph.inputs.length) {
1038
+ throw new TypeError("UI worklet host input vectors must match the installed graph.");
1039
+ }
1040
+ const inputs = {};
1041
+ for (let index = 0; index < state.graph.inputs.length; index++) {
1042
+ const input = state.graph.inputs[index];
1043
+ inputs[input.name] = finiteNumber(inputVector[index], `UI worklet host input ${input.name}`);
1044
+ }
1045
+ return Object.freeze(inputs);
1046
+ }
1047
+ function requireMonotonicInputTimestamp(state, timestampValue) {
1048
+ const nextTimestamp = timestamp(timestampValue);
1049
+ if (state.timestamp !== undefined && nextTimestamp < state.timestamp) {
1050
+ throw new RangeError("UI worklet host timestamps must be monotonic.");
1051
+ }
1052
+ return nextTimestamp;
1053
+ }
1054
+ function readTimingKeyframes(state, values) {
1055
+ if (!Array.isArray(values) ||
1056
+ values.length === 0 ||
1057
+ values.length > UI_WORKLET_MAX_TIMING_KEYFRAMES) {
1058
+ throw new RangeError(`UI worklet host timing keyframes must contain between 1 and ${UI_WORKLET_MAX_TIMING_KEYFRAMES} steps.`);
1059
+ }
1060
+ let totalDurationMilliseconds = 0;
1061
+ const keyframes = values.map((value, index) => {
1062
+ const context = `UI worklet host timing keyframe ${String(index)}`;
1063
+ const record = objectRecord(value, context);
1064
+ exactKeys(record, ["inputs", "timing"], context);
1065
+ const to = readInputVector(state, record.inputs);
1066
+ const definition = parseUIWorkletTiming(record.timing);
1067
+ totalDurationMilliseconds += definition.durationMilliseconds;
1068
+ if (totalDurationMilliseconds > UI_WORKLET_MAX_TIMING_DURATION_MS) {
1069
+ throw new RangeError(`UI worklet timing keyframes may last at most ${UI_WORKLET_MAX_TIMING_DURATION_MS} milliseconds in total.`);
1070
+ }
1071
+ evaluateUIWorkletGraph(state.graph, to);
1072
+ return Object.freeze({ to, definition });
1073
+ });
1074
+ return {
1075
+ keyframes: Object.freeze(keyframes),
1076
+ totalDurationMilliseconds,
1077
+ };
1078
+ }
1079
+ function evaluateTimingKeyframes(timing, elapsedMilliseconds) {
1080
+ let remaining = Math.max(0, Math.min(elapsedMilliseconds, timing.totalDurationMilliseconds));
1081
+ let completedDurationMilliseconds = 0;
1082
+ let from = timing.from;
1083
+ for (const [index, keyframe] of timing.keyframes.entries()) {
1084
+ const last = index === timing.keyframes.length - 1;
1085
+ if (!last && remaining >= keyframe.definition.durationMilliseconds) {
1086
+ remaining -= keyframe.definition.durationMilliseconds;
1087
+ completedDurationMilliseconds +=
1088
+ keyframe.definition.durationMilliseconds;
1089
+ from = keyframe.to;
1090
+ continue;
1091
+ }
1092
+ const localProgress = evaluateUIWorkletTimingProgress(keyframe.definition, remaining);
1093
+ const inputs = {};
1094
+ for (const input of Object.keys(timing.from)) {
1095
+ inputs[input] =
1096
+ localProgress === 0
1097
+ ? from[input]
1098
+ : localProgress === 1
1099
+ ? keyframe.to[input]
1100
+ : from[input] * (1 - localProgress) +
1101
+ keyframe.to[input] * localProgress;
1102
+ }
1103
+ return {
1104
+ inputs: Object.freeze(inputs),
1105
+ progress: elapsedMilliseconds >= timing.totalDurationMilliseconds
1106
+ ? 1
1107
+ : (completedDurationMilliseconds +
1108
+ localProgress * keyframe.definition.durationMilliseconds) /
1109
+ timing.totalDurationMilliseconds,
1110
+ };
1111
+ }
1112
+ throw new Error("UI worklet timing keyframes are empty.");
1113
+ }
1114
+ const host = {
1115
+ protocolVersion: UI_WORKLET_PROTOCOL_VERSION,
1116
+ get activeGraphCount() {
1117
+ return states.size;
1118
+ },
1119
+ installGraph(graphValue) {
1120
+ const graph = parseUIWorkletGraph(graphValue);
1121
+ if (!Number.isSafeInteger(nextHandle)) {
1122
+ throw new RangeError("The UI worklet handle space is exhausted.");
1123
+ }
1124
+ const handle = nextHandle++;
1125
+ const inputs = initialInputs(graph);
1126
+ states.set(handle, {
1127
+ graph,
1128
+ inputs,
1129
+ outputs: evaluateUIWorkletGraph(graph, inputs),
1130
+ sequence: 0,
1131
+ timing: undefined,
1132
+ timingProgress: 0,
1133
+ timingFrameStatistics: undefined,
1134
+ spring: undefined,
1135
+ springPosition: undefined,
1136
+ springVelocity: undefined,
1137
+ springFrameStatistics: undefined,
1138
+ decay: undefined,
1139
+ decayElapsedMilliseconds: undefined,
1140
+ decaySpeed: undefined,
1141
+ decayFrameStatistics: undefined,
1142
+ pan: undefined,
1143
+ });
1144
+ return handle;
1145
+ },
1146
+ updateGraphInputs(handle, inputVector, timestampValue) {
1147
+ const state = requireState(handle);
1148
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1149
+ const inputs = readInputVector(state, inputVector);
1150
+ const outputs = evaluateUIWorkletGraph(state.graph, inputs);
1151
+ state.inputs = inputs;
1152
+ state.outputs = outputs;
1153
+ state.sequence++;
1154
+ state.timestamp = nextTimestamp;
1155
+ state.timing = undefined;
1156
+ state.timingProgress = 0;
1157
+ state.timingFrameStatistics = undefined;
1158
+ state.spring = undefined;
1159
+ state.springPosition = undefined;
1160
+ state.springVelocity = undefined;
1161
+ state.springFrameStatistics = undefined;
1162
+ state.decay = undefined;
1163
+ state.decayElapsedMilliseconds = undefined;
1164
+ state.decaySpeed = undefined;
1165
+ state.decayFrameStatistics = undefined;
1166
+ },
1167
+ animateGraphInputs(handle, inputVector, timestampValue, timingValue) {
1168
+ const state = requireState(handle);
1169
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1170
+ const inputs = readInputVector(state, inputVector);
1171
+ // Validate the complete target before changing the active timing.
1172
+ evaluateUIWorkletGraph(state.graph, inputs);
1173
+ const definition = parseUIWorkletTiming(timingValue);
1174
+ state.timing = {
1175
+ from: state.inputs,
1176
+ keyframes: Object.freeze([Object.freeze({ to: inputs, definition })]),
1177
+ totalDurationMilliseconds: definition.durationMilliseconds,
1178
+ };
1179
+ state.timestamp = nextTimestamp;
1180
+ state.timingProgress = 0;
1181
+ state.timingFrameStatistics = createMutableFrameStatistics();
1182
+ state.spring = undefined;
1183
+ state.springPosition = undefined;
1184
+ state.springVelocity = undefined;
1185
+ state.springFrameStatistics = undefined;
1186
+ state.decay = undefined;
1187
+ state.decayElapsedMilliseconds = undefined;
1188
+ state.decaySpeed = undefined;
1189
+ state.decayFrameStatistics = undefined;
1190
+ },
1191
+ animateGraphKeyframes(handle, keyframesValue, timestampValue) {
1192
+ const state = requireState(handle);
1193
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1194
+ // Parse and validate every terminal graph before replacing any driver.
1195
+ const keyframes = readTimingKeyframes(state, keyframesValue);
1196
+ state.timing = {
1197
+ from: state.inputs,
1198
+ ...keyframes,
1199
+ };
1200
+ state.timestamp = nextTimestamp;
1201
+ state.timingProgress = 0;
1202
+ state.timingFrameStatistics = createMutableFrameStatistics();
1203
+ state.spring = undefined;
1204
+ state.springPosition = undefined;
1205
+ state.springVelocity = undefined;
1206
+ state.springFrameStatistics = undefined;
1207
+ state.decay = undefined;
1208
+ state.decayElapsedMilliseconds = undefined;
1209
+ state.decaySpeed = undefined;
1210
+ state.decayFrameStatistics = undefined;
1211
+ },
1212
+ springGraphInputs(handle, inputVector, timestampValue, springValue) {
1213
+ const state = requireState(handle);
1214
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1215
+ const inputs = readInputVector(state, inputVector);
1216
+ // Validate the complete target before changing the active driver.
1217
+ evaluateUIWorkletGraph(state.graph, inputs);
1218
+ const definition = parseUIWorkletSpring(springValue);
1219
+ state.timing = undefined;
1220
+ state.timingProgress = 0;
1221
+ state.timingFrameStatistics = undefined;
1222
+ state.spring = {
1223
+ from: state.inputs,
1224
+ to: inputs,
1225
+ definition,
1226
+ };
1227
+ state.timestamp = nextTimestamp;
1228
+ state.springPosition = 0;
1229
+ state.springVelocity = definition.initialVelocity;
1230
+ state.springFrameStatistics = createMutableFrameStatistics();
1231
+ state.decay = undefined;
1232
+ state.decayElapsedMilliseconds = undefined;
1233
+ state.decaySpeed = undefined;
1234
+ state.decayFrameStatistics = undefined;
1235
+ },
1236
+ decayGraphInputs(handle, velocityVector, timestampValue, decayValue) {
1237
+ const state = requireState(handle);
1238
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1239
+ const velocities = readInputVector(state, velocityVector);
1240
+ let initialSpeed = 0;
1241
+ for (const velocity of Object.values(velocities)) {
1242
+ if (Math.abs(velocity) > UI_WORKLET_MAX_DECAY_VELOCITY) {
1243
+ throw new RangeError(`UI worklet decay velocity magnitude must be at most ${UI_WORKLET_MAX_DECAY_VELOCITY}.`);
1244
+ }
1245
+ initialSpeed = Math.max(initialSpeed, Math.abs(velocity));
1246
+ }
1247
+ const definition = parseUIWorkletDecay(decayValue);
1248
+ const terminal = evaluateUIWorkletDecay(definition, initialSpeed, definition.maximumDurationMilliseconds);
1249
+ const terminalInputs = {};
1250
+ for (const input of state.graph.inputs) {
1251
+ terminalInputs[input.name] =
1252
+ state.inputs[input.name] +
1253
+ velocities[input.name] * terminal.displacementFactorSeconds;
1254
+ }
1255
+ // Validate the bounded terminal vector before changing the active driver.
1256
+ evaluateUIWorkletGraph(state.graph, terminalInputs);
1257
+ state.timing = undefined;
1258
+ state.timingProgress = 0;
1259
+ state.timingFrameStatistics = undefined;
1260
+ state.spring = undefined;
1261
+ state.springPosition = undefined;
1262
+ state.springVelocity = undefined;
1263
+ state.springFrameStatistics = undefined;
1264
+ state.decay = {
1265
+ from: state.inputs,
1266
+ velocities,
1267
+ initialSpeed,
1268
+ definition,
1269
+ };
1270
+ state.timestamp = nextTimestamp;
1271
+ state.decayElapsedMilliseconds = 0;
1272
+ state.decaySpeed = initialSpeed;
1273
+ state.decayFrameStatistics = createMutableFrameStatistics();
1274
+ },
1275
+ cancelGraphAnimation(handle, timestampValue) {
1276
+ const state = requireState(handle);
1277
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1278
+ state.timestamp = nextTimestamp;
1279
+ state.timing = undefined;
1280
+ state.spring = undefined;
1281
+ if (state.springVelocity !== undefined)
1282
+ state.springVelocity = 0;
1283
+ state.decay = undefined;
1284
+ if (state.decaySpeed !== undefined)
1285
+ state.decaySpeed = 0;
1286
+ return Object.freeze(state.graph.inputs.map((input) => state.inputs[input.name]));
1287
+ },
1288
+ attachPanGesture(handle, gestureValue) {
1289
+ const state = requireState(handle);
1290
+ if (state.pan !== undefined) {
1291
+ throw new Error("The UI worklet graph already owns a native pan.");
1292
+ }
1293
+ const definition = parseUIWorkletPanGesture(gestureValue, state.graph);
1294
+ state.pan = {
1295
+ definition,
1296
+ active: false,
1297
+ originX: 0,
1298
+ originY: 0,
1299
+ sequence: 0,
1300
+ };
1301
+ },
1302
+ detachPanGesture(handle, timestampValue) {
1303
+ const state = requireState(handle);
1304
+ const nextTimestamp = requireMonotonicInputTimestamp(state, timestampValue);
1305
+ if (state.pan === undefined) {
1306
+ throw new Error("The UI worklet graph does not own a native pan.");
1307
+ }
1308
+ state.pan.active = false;
1309
+ state.pan = undefined;
1310
+ state.timing = undefined;
1311
+ state.spring = undefined;
1312
+ if (state.springVelocity !== undefined)
1313
+ state.springVelocity = 0;
1314
+ state.decay = undefined;
1315
+ if (state.decaySpeed !== undefined)
1316
+ state.decaySpeed = 0;
1317
+ state.timestamp = nextTimestamp;
1318
+ return Object.freeze(state.graph.inputs.map((input) => state.inputs[input.name]));
1319
+ },
1320
+ advanceFrame(frameTimeMillisecondsValue) {
1321
+ const frameTimeMilliseconds = timestamp(frameTimeMillisecondsValue);
1322
+ if (frameTimeMilliseconds < lastFrameTime) {
1323
+ throw new RangeError("UI worklet frame timestamps must be monotonic.");
1324
+ }
1325
+ lastFrameTime = frameTimeMilliseconds;
1326
+ for (const state of states.values()) {
1327
+ const timing = state.timing;
1328
+ if (timing !== undefined) {
1329
+ try {
1330
+ timing.startedAt ??= frameTimeMilliseconds;
1331
+ const sample = evaluateTimingKeyframes(timing, frameTimeMilliseconds - timing.startedAt);
1332
+ const outputs = evaluateUIWorkletGraph(state.graph, sample.inputs);
1333
+ const timingFrameStatistics = state.timingFrameStatistics ?? createMutableFrameStatistics();
1334
+ recordAnimationFrame(timingFrameStatistics, frameTimeMilliseconds);
1335
+ state.inputs = sample.inputs;
1336
+ state.outputs = outputs;
1337
+ state.sequence++;
1338
+ state.timingProgress = sample.progress;
1339
+ state.timingFrameStatistics = timingFrameStatistics;
1340
+ if (sample.progress === 1)
1341
+ state.timing = undefined;
1342
+ }
1343
+ catch (error) {
1344
+ state.timing = undefined;
1345
+ throw error;
1346
+ }
1347
+ continue;
1348
+ }
1349
+ const spring = state.spring;
1350
+ if (spring !== undefined) {
1351
+ try {
1352
+ spring.startedAt ??= frameTimeMilliseconds;
1353
+ const sample = evaluateUIWorkletSpring(spring.definition, frameTimeMilliseconds - spring.startedAt);
1354
+ const inputs = {};
1355
+ for (const input of state.graph.inputs) {
1356
+ const from = spring.from[input.name];
1357
+ const to = spring.to[input.name];
1358
+ inputs[input.name] = sample.settled
1359
+ ? to
1360
+ : from * (1 - sample.position) + to * sample.position;
1361
+ }
1362
+ const frozenInputs = Object.freeze(inputs);
1363
+ const outputs = evaluateUIWorkletGraph(state.graph, frozenInputs);
1364
+ const springFrameStatistics = state.springFrameStatistics ?? createMutableFrameStatistics();
1365
+ recordAnimationFrame(springFrameStatistics, frameTimeMilliseconds);
1366
+ state.inputs = frozenInputs;
1367
+ state.outputs = outputs;
1368
+ state.sequence++;
1369
+ state.springPosition = sample.position;
1370
+ state.springVelocity = sample.velocity;
1371
+ state.springFrameStatistics = springFrameStatistics;
1372
+ if (sample.settled)
1373
+ state.spring = undefined;
1374
+ }
1375
+ catch (error) {
1376
+ state.spring = undefined;
1377
+ throw error;
1378
+ }
1379
+ continue;
1380
+ }
1381
+ const decay = state.decay;
1382
+ if (decay === undefined)
1383
+ continue;
1384
+ try {
1385
+ decay.startedAt ??= frameTimeMilliseconds;
1386
+ const elapsedMilliseconds = frameTimeMilliseconds - decay.startedAt;
1387
+ const sample = evaluateUIWorkletDecay(decay.definition, decay.initialSpeed, elapsedMilliseconds);
1388
+ const inputs = {};
1389
+ for (const input of state.graph.inputs) {
1390
+ inputs[input.name] =
1391
+ decay.from[input.name] +
1392
+ decay.velocities[input.name] * sample.displacementFactorSeconds;
1393
+ }
1394
+ const frozenInputs = Object.freeze(inputs);
1395
+ const outputs = evaluateUIWorkletGraph(state.graph, frozenInputs);
1396
+ const decayFrameStatistics = state.decayFrameStatistics ?? createMutableFrameStatistics();
1397
+ recordAnimationFrame(decayFrameStatistics, frameTimeMilliseconds);
1398
+ state.inputs = frozenInputs;
1399
+ state.outputs = outputs;
1400
+ state.sequence++;
1401
+ state.decayElapsedMilliseconds = elapsedMilliseconds;
1402
+ state.decaySpeed = sample.speed;
1403
+ state.decayFrameStatistics = decayFrameStatistics;
1404
+ if (sample.settled)
1405
+ state.decay = undefined;
1406
+ }
1407
+ catch (error) {
1408
+ state.decay = undefined;
1409
+ throw error;
1410
+ }
1411
+ }
1412
+ },
1413
+ dispatchPanGesture(handle, phase, translationXValue, translationYValue, timestampValue, velocityXValue = 0, velocityYValue = 0) {
1414
+ const state = requireState(handle);
1415
+ const pan = state.pan;
1416
+ if (pan === undefined) {
1417
+ throw new Error("The UI worklet graph does not own a native pan.");
1418
+ }
1419
+ if (phase !== "begin" &&
1420
+ phase !== "change" &&
1421
+ phase !== "end" &&
1422
+ phase !== "cancel") {
1423
+ throw new TypeError("The UI worklet pan phase is unsupported.");
1424
+ }
1425
+ const translationX = finiteNumber(translationXValue, "UI worklet pan translationX");
1426
+ const translationY = finiteNumber(translationYValue, "UI worklet pan translationY");
1427
+ const velocityX = finiteNumber(velocityXValue, "UI worklet pan velocityX");
1428
+ const velocityY = finiteNumber(velocityYValue, "UI worklet pan velocityY");
1429
+ if (Math.abs(velocityX) > UI_WORKLET_MAX_DECAY_VELOCITY ||
1430
+ Math.abs(velocityY) > UI_WORKLET_MAX_DECAY_VELOCITY) {
1431
+ throw new RangeError(`UI worklet pan velocity magnitude must be at most ${UI_WORKLET_MAX_DECAY_VELOCITY}.`);
1432
+ }
1433
+ const nextTimestamp = timestamp(timestampValue);
1434
+ if (pan.timestamp !== undefined && nextTimestamp < pan.timestamp) {
1435
+ throw new RangeError("UI worklet pan timestamps must be monotonic.");
1436
+ }
1437
+ if (phase === "begin") {
1438
+ if (pan.active) {
1439
+ throw new Error("The UI worklet pan is already active.");
1440
+ }
1441
+ pan.active = true;
1442
+ pan.originX = state.inputs[pan.definition.xInput];
1443
+ pan.originY = state.inputs[pan.definition.yInput];
1444
+ pan.timestamp = nextTimestamp;
1445
+ state.timing = undefined;
1446
+ state.timingProgress = 0;
1447
+ state.spring = undefined;
1448
+ if (state.springPosition !== undefined)
1449
+ state.springPosition = 0;
1450
+ if (state.springVelocity !== undefined)
1451
+ state.springVelocity = 0;
1452
+ state.decay = undefined;
1453
+ if (state.decayElapsedMilliseconds !== undefined) {
1454
+ state.decayElapsedMilliseconds = 0;
1455
+ }
1456
+ if (state.decaySpeed !== undefined)
1457
+ state.decaySpeed = 0;
1458
+ return;
1459
+ }
1460
+ if (!pan.active) {
1461
+ throw new Error("The UI worklet pan is not active.");
1462
+ }
1463
+ if (phase === "cancel") {
1464
+ pan.active = false;
1465
+ pan.timestamp = nextTimestamp;
1466
+ return;
1467
+ }
1468
+ try {
1469
+ const inputs = { ...state.inputs };
1470
+ inputs[pan.definition.xInput] = Math.min(pan.definition.maxX, Math.max(pan.definition.minX, pan.originX + translationX));
1471
+ inputs[pan.definition.yInput] = Math.min(pan.definition.maxY, Math.max(pan.definition.minY, pan.originY + translationY));
1472
+ const frozenInputs = Object.freeze(inputs);
1473
+ const outputs = evaluateUIWorkletGraph(state.graph, frozenInputs);
1474
+ let releaseDecay;
1475
+ if (phase === "end" && pan.definition.releaseDecay !== undefined) {
1476
+ const velocities = {};
1477
+ for (const input of state.graph.inputs)
1478
+ velocities[input.name] = 0;
1479
+ velocities[pan.definition.xInput] = velocityX;
1480
+ velocities[pan.definition.yInput] = velocityY;
1481
+ const frozenVelocities = Object.freeze(velocities);
1482
+ const initialSpeed = Math.max(Math.abs(velocityX), Math.abs(velocityY));
1483
+ const definition = pan.definition.releaseDecay;
1484
+ const terminal = evaluateUIWorkletDecay(definition, initialSpeed, definition.maximumDurationMilliseconds);
1485
+ const terminalInputs = {};
1486
+ for (const input of state.graph.inputs) {
1487
+ terminalInputs[input.name] =
1488
+ frozenInputs[input.name] +
1489
+ frozenVelocities[input.name] *
1490
+ terminal.displacementFactorSeconds;
1491
+ }
1492
+ // Reject an invalid terminal graph before publishing the final pan.
1493
+ evaluateUIWorkletGraph(state.graph, terminalInputs);
1494
+ releaseDecay = {
1495
+ velocities: frozenVelocities,
1496
+ initialSpeed,
1497
+ definition,
1498
+ };
1499
+ }
1500
+ state.inputs = frozenInputs;
1501
+ state.outputs = outputs;
1502
+ state.sequence++;
1503
+ state.timing = undefined;
1504
+ state.timingProgress = 0;
1505
+ state.spring = undefined;
1506
+ if (state.springPosition !== undefined)
1507
+ state.springPosition = 0;
1508
+ if (state.springVelocity !== undefined)
1509
+ state.springVelocity = 0;
1510
+ state.decay =
1511
+ releaseDecay === undefined
1512
+ ? undefined
1513
+ : {
1514
+ from: frozenInputs,
1515
+ velocities: releaseDecay.velocities,
1516
+ initialSpeed: releaseDecay.initialSpeed,
1517
+ definition: releaseDecay.definition,
1518
+ };
1519
+ if (releaseDecay === undefined) {
1520
+ if (state.decayElapsedMilliseconds !== undefined) {
1521
+ state.decayElapsedMilliseconds = 0;
1522
+ }
1523
+ if (state.decaySpeed !== undefined)
1524
+ state.decaySpeed = 0;
1525
+ }
1526
+ else {
1527
+ state.decayElapsedMilliseconds = 0;
1528
+ state.decaySpeed = releaseDecay.initialSpeed;
1529
+ state.decayFrameStatistics = createMutableFrameStatistics();
1530
+ }
1531
+ pan.sequence++;
1532
+ pan.timestamp = nextTimestamp;
1533
+ if (phase === "end")
1534
+ pan.active = false;
1535
+ }
1536
+ catch (error) {
1537
+ pan.active = false;
1538
+ throw error;
1539
+ }
1540
+ },
1541
+ destroyGraph(handle) {
1542
+ if (!states.delete(handle)) {
1543
+ throw new Error(`Unknown UI worklet graph handle ${String(handle)}.`);
1544
+ }
1545
+ },
1546
+ snapshot(handle) {
1547
+ const state = states.get(handle);
1548
+ if (state === undefined) {
1549
+ throw new Error(`Unknown UI worklet graph handle ${String(handle)}.`);
1550
+ }
1551
+ const timingFrameStatistics = snapshotFrameStatistics(state.timingFrameStatistics);
1552
+ const springFrameStatistics = snapshotFrameStatistics(state.springFrameStatistics);
1553
+ const decayFrameStatistics = snapshotFrameStatistics(state.decayFrameStatistics);
1554
+ const base = {
1555
+ handle,
1556
+ sequence: state.sequence,
1557
+ inputs: Object.freeze({ ...state.inputs }),
1558
+ outputs: Object.freeze({ ...state.outputs }),
1559
+ timingActive: state.timing !== undefined,
1560
+ timingProgress: state.timingProgress,
1561
+ ...(timingFrameStatistics === undefined
1562
+ ? {}
1563
+ : { timingFrameStatistics }),
1564
+ ...(state.springPosition === undefined ||
1565
+ state.springVelocity === undefined
1566
+ ? {}
1567
+ : {
1568
+ springActive: state.spring !== undefined,
1569
+ springPosition: state.springPosition,
1570
+ springVelocity: state.springVelocity,
1571
+ ...(springFrameStatistics === undefined
1572
+ ? {}
1573
+ : { springFrameStatistics }),
1574
+ }),
1575
+ ...(state.decayElapsedMilliseconds === undefined ||
1576
+ state.decaySpeed === undefined
1577
+ ? {}
1578
+ : {
1579
+ decayActive: state.decay !== undefined,
1580
+ decayElapsedMilliseconds: state.decayElapsedMilliseconds,
1581
+ decaySpeed: state.decaySpeed,
1582
+ ...(decayFrameStatistics === undefined
1583
+ ? {}
1584
+ : { decayFrameStatistics }),
1585
+ }),
1586
+ };
1587
+ const gesture = state.pan === undefined
1588
+ ? {}
1589
+ : {
1590
+ gestureAttached: true,
1591
+ gestureActive: state.pan.active,
1592
+ gestureSequence: state.pan.sequence,
1593
+ ...(state.pan.timestamp === undefined
1594
+ ? {}
1595
+ : { gestureTimestamp: state.pan.timestamp }),
1596
+ };
1597
+ return Object.freeze(state.timestamp === undefined
1598
+ ? { ...base, ...gesture }
1599
+ : { ...base, timestamp: state.timestamp, ...gesture });
1600
+ },
1601
+ };
1602
+ return Object.freeze(host);
1603
+ }
1604
+ //# sourceMappingURL=index.js.map