motion-dom 12.7.3 → 12.7.5-alpha.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 (92) hide show
  1. package/dist/cjs/index.js +2946 -475
  2. package/dist/es/animation/AsyncMotionValueAnimation.mjs +178 -0
  3. package/dist/es/animation/GroupAnimation.mjs +6 -15
  4. package/dist/es/animation/JSAnimation.mjs +346 -0
  5. package/dist/es/animation/NativeAnimation.mjs +64 -67
  6. package/dist/es/animation/NativeAnimationExtended.mjs +65 -0
  7. package/dist/es/animation/NativeAnimationWrapper.mjs +14 -0
  8. package/dist/es/animation/drivers/driver-frameloop.mjs +17 -0
  9. package/dist/es/animation/generators/inertia.mjs +87 -0
  10. package/dist/es/animation/generators/keyframes.mjs +49 -0
  11. package/dist/es/animation/generators/spring/defaults.mjs +27 -0
  12. package/dist/es/animation/generators/spring/find.mjs +84 -0
  13. package/dist/es/animation/generators/spring/index.mjs +175 -0
  14. package/dist/es/animation/generators/utils/velocity.mjs +9 -0
  15. package/dist/es/animation/keyframes/DOMKeyframesResolver.mjs +131 -0
  16. package/dist/es/animation/keyframes/KeyframesResolver.mjs +156 -0
  17. package/dist/es/animation/keyframes/get-final.mjs +3 -4
  18. package/dist/es/animation/keyframes/offsets/default.mjs +9 -0
  19. package/dist/es/animation/keyframes/offsets/fill.mjs +12 -0
  20. package/dist/es/animation/keyframes/offsets/time.mjs +5 -0
  21. package/dist/es/animation/keyframes/utils/apply-px-defaults.mjs +11 -0
  22. package/dist/es/animation/keyframes/utils/fill-wildcards.mjs +7 -0
  23. package/dist/es/animation/keyframes/utils/is-none.mjs +15 -0
  24. package/dist/es/animation/keyframes/utils/make-none-animatable.mjs +30 -0
  25. package/dist/es/animation/keyframes/utils/unit-conversion.mjs +36 -0
  26. package/dist/es/animation/utils/WithPromise.mjs +28 -0
  27. package/dist/es/animation/utils/active-animations.mjs +9 -0
  28. package/dist/es/animation/utils/can-animate.mjs +42 -0
  29. package/dist/es/animation/utils/css-variables-conversion.mjs +41 -0
  30. package/dist/es/animation/utils/is-animatable.mjs +30 -0
  31. package/dist/es/animation/utils/is-css-variable.mjs +15 -0
  32. package/dist/es/animation/utils/replace-transition-type.mjs +18 -0
  33. package/dist/es/animation/waapi/easing/is-supported.mjs +1 -1
  34. package/dist/es/animation/waapi/easing/map-easing.mjs +5 -3
  35. package/dist/es/animation/waapi/start-waapi-animation.mjs +6 -4
  36. package/dist/es/animation/waapi/supports/waapi.mjs +39 -0
  37. package/dist/es/animation/waapi/utils/accelerated-values.mjs +14 -0
  38. package/dist/es/animation/waapi/utils/apply-generator.mjs +2 -1
  39. package/dist/es/animation/waapi/utils/unsupported-easing.mjs +18 -0
  40. package/dist/es/frameloop/batcher.mjs +2 -1
  41. package/dist/es/frameloop/order.mjs +1 -0
  42. package/dist/es/index.mjs +49 -2
  43. package/dist/es/render/dom/is-css-var.mjs +3 -0
  44. package/dist/es/render/dom/parse-transform.mjs +83 -0
  45. package/dist/es/render/dom/style-computed.mjs +10 -0
  46. package/dist/es/render/dom/style-set.mjs +9 -0
  47. package/dist/es/render/utils/keys-position.mjs +13 -0
  48. package/dist/es/render/utils/keys-transform.mjs +28 -0
  49. package/dist/es/scroll/observe.mjs +18 -0
  50. package/dist/es/stats/index.mjs +2 -0
  51. package/dist/es/utils/interpolate.mjs +74 -0
  52. package/dist/es/utils/mix/color.mjs +47 -0
  53. package/dist/es/utils/mix/complex.mjs +92 -0
  54. package/dist/es/utils/mix/immediate.mjs +5 -0
  55. package/dist/es/utils/mix/index.mjs +14 -0
  56. package/dist/es/utils/mix/number.mjs +26 -0
  57. package/dist/es/utils/mix/visibility.mjs +16 -0
  58. package/dist/es/value/index.mjs +3 -1
  59. package/dist/es/value/types/auto.mjs +9 -0
  60. package/dist/es/value/types/color/hex.mjs +40 -0
  61. package/dist/es/value/types/color/hsla-to-rgba.mjs +42 -0
  62. package/dist/es/value/types/color/hsla.mjs +22 -0
  63. package/dist/es/value/types/color/index.mjs +27 -0
  64. package/dist/es/value/types/color/rgba.mjs +25 -0
  65. package/dist/es/value/types/color/utils.mjs +29 -0
  66. package/dist/es/value/types/complex/filter.mjs +30 -0
  67. package/dist/es/value/types/complex/index.mjs +91 -0
  68. package/dist/es/value/types/dimensions.mjs +15 -0
  69. package/dist/es/value/types/int.mjs +8 -0
  70. package/dist/es/value/types/maps/defaults.mjs +30 -0
  71. package/dist/es/value/types/maps/number.mjs +51 -0
  72. package/dist/es/value/types/maps/transform.mjs +31 -0
  73. package/dist/es/value/types/numbers/index.mjs +17 -0
  74. package/dist/es/value/types/numbers/units.mjs +18 -0
  75. package/dist/es/value/types/test.mjs +6 -0
  76. package/dist/es/value/types/utils/animatable-none.mjs +15 -0
  77. package/dist/es/value/types/utils/color-regex.mjs +3 -0
  78. package/dist/es/value/types/utils/find.mjs +15 -0
  79. package/dist/es/value/types/utils/float-regex.mjs +3 -0
  80. package/dist/es/value/types/utils/get-as-type.mjs +10 -0
  81. package/dist/es/value/types/utils/is-nullish.mjs +5 -0
  82. package/dist/es/value/types/utils/sanitize.mjs +5 -0
  83. package/dist/es/value/types/utils/single-color-regex.mjs +3 -0
  84. package/dist/es/view/start.mjs +4 -3
  85. package/dist/index.d.ts +945 -444
  86. package/dist/motion-dom.dev.js +2945 -475
  87. package/dist/motion-dom.js +1 -1
  88. package/package.json +3 -3
  89. package/dist/es/animation/keyframes/hydrate.mjs +0 -26
  90. package/dist/es/animation/waapi/utils/attach-timeline.mjs +0 -6
  91. package/dist/es/render/dom/style.mjs +0 -15
  92. package/dist/es/utils/is-bezier-definition.mjs +0 -3
package/dist/cjs/index.js CHANGED
@@ -4,198 +4,1921 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var motionUtils = require('motion-utils');
6
6
 
7
- const supportsScrollTimeline = /* @__PURE__ */ motionUtils.memo(() => window.ScrollTimeline !== undefined);
7
+ const stepsOrder = [
8
+ "setup", // Compute
9
+ "read", // Read
10
+ "resolveKeyframes", // Write/Read/Write/Read
11
+ "update", // Compute
12
+ "preRender", // Compute
13
+ "render", // Write
14
+ "postRender", // Compute
15
+ ];
16
+
17
+ const statsBuffer = {
18
+ value: null,
19
+ addProjectionMetrics: null,
20
+ };
21
+
22
+ function createRenderStep(runNextFrame, stepName) {
23
+ /**
24
+ * We create and reuse two queues, one to queue jobs for the current frame
25
+ * and one for the next. We reuse to avoid triggering GC after x frames.
26
+ */
27
+ let thisFrame = new Set();
28
+ let nextFrame = new Set();
29
+ /**
30
+ * Track whether we're currently processing jobs in this step. This way
31
+ * we can decide whether to schedule new jobs for this frame or next.
32
+ */
33
+ let isProcessing = false;
34
+ let flushNextFrame = false;
35
+ /**
36
+ * A set of processes which were marked keepAlive when scheduled.
37
+ */
38
+ const toKeepAlive = new WeakSet();
39
+ let latestFrameData = {
40
+ delta: 0.0,
41
+ timestamp: 0.0,
42
+ isProcessing: false,
43
+ };
44
+ let numCalls = 0;
45
+ function triggerCallback(callback) {
46
+ if (toKeepAlive.has(callback)) {
47
+ step.schedule(callback);
48
+ runNextFrame();
49
+ }
50
+ numCalls++;
51
+ callback(latestFrameData);
52
+ }
53
+ const step = {
54
+ /**
55
+ * Schedule a process to run on the next frame.
56
+ */
57
+ schedule: (callback, keepAlive = false, immediate = false) => {
58
+ const addToCurrentFrame = immediate && isProcessing;
59
+ const queue = addToCurrentFrame ? thisFrame : nextFrame;
60
+ if (keepAlive)
61
+ toKeepAlive.add(callback);
62
+ if (!queue.has(callback))
63
+ queue.add(callback);
64
+ return callback;
65
+ },
66
+ /**
67
+ * Cancel the provided callback from running on the next frame.
68
+ */
69
+ cancel: (callback) => {
70
+ nextFrame.delete(callback);
71
+ toKeepAlive.delete(callback);
72
+ },
73
+ /**
74
+ * Execute all schedule callbacks.
75
+ */
76
+ process: (frameData) => {
77
+ latestFrameData = frameData;
78
+ /**
79
+ * If we're already processing we've probably been triggered by a flushSync
80
+ * inside an existing process. Instead of executing, mark flushNextFrame
81
+ * as true and ensure we flush the following frame at the end of this one.
82
+ */
83
+ if (isProcessing) {
84
+ flushNextFrame = true;
85
+ return;
86
+ }
87
+ isProcessing = true;
88
+ [thisFrame, nextFrame] = [nextFrame, thisFrame];
89
+ // Execute this frame
90
+ thisFrame.forEach(triggerCallback);
91
+ /**
92
+ * If we're recording stats then
93
+ */
94
+ if (stepName && statsBuffer.value) {
95
+ statsBuffer.value.frameloop[stepName].push(numCalls);
96
+ }
97
+ numCalls = 0;
98
+ // Clear the frame so no callbacks remain. This is to avoid
99
+ // memory leaks should this render step not run for a while.
100
+ thisFrame.clear();
101
+ isProcessing = false;
102
+ if (flushNextFrame) {
103
+ flushNextFrame = false;
104
+ step.process(frameData);
105
+ }
106
+ },
107
+ };
108
+ return step;
109
+ }
110
+
111
+ const maxElapsed = 40;
112
+ function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
113
+ let runNextFrame = false;
114
+ let useDefaultElapsed = true;
115
+ const state = {
116
+ delta: 0.0,
117
+ timestamp: 0.0,
118
+ isProcessing: false,
119
+ };
120
+ const flagRunNextFrame = () => (runNextFrame = true);
121
+ const steps = stepsOrder.reduce((acc, key) => {
122
+ acc[key] = createRenderStep(flagRunNextFrame, allowKeepAlive ? key : undefined);
123
+ return acc;
124
+ }, {});
125
+ const { setup, read, resolveKeyframes, update, preRender, render, postRender, } = steps;
126
+ const processBatch = () => {
127
+ const timestamp = motionUtils.MotionGlobalConfig.useManualTiming
128
+ ? state.timestamp
129
+ : performance.now();
130
+ runNextFrame = false;
131
+ if (!motionUtils.MotionGlobalConfig.useManualTiming) {
132
+ state.delta = useDefaultElapsed
133
+ ? 1000 / 60
134
+ : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
135
+ }
136
+ state.timestamp = timestamp;
137
+ state.isProcessing = true;
138
+ // Unrolled render loop for better per-frame performance
139
+ setup.process(state);
140
+ read.process(state);
141
+ resolveKeyframes.process(state);
142
+ update.process(state);
143
+ preRender.process(state);
144
+ render.process(state);
145
+ postRender.process(state);
146
+ state.isProcessing = false;
147
+ if (runNextFrame && allowKeepAlive) {
148
+ useDefaultElapsed = false;
149
+ scheduleNextBatch(processBatch);
150
+ }
151
+ };
152
+ const wake = () => {
153
+ runNextFrame = true;
154
+ useDefaultElapsed = true;
155
+ if (!state.isProcessing) {
156
+ scheduleNextBatch(processBatch);
157
+ }
158
+ };
159
+ const schedule = stepsOrder.reduce((acc, key) => {
160
+ const step = steps[key];
161
+ acc[key] = (process, keepAlive = false, immediate = false) => {
162
+ if (!runNextFrame)
163
+ wake();
164
+ return step.schedule(process, keepAlive, immediate);
165
+ };
166
+ return acc;
167
+ }, {});
168
+ const cancel = (process) => {
169
+ for (let i = 0; i < stepsOrder.length; i++) {
170
+ steps[stepsOrder[i]].cancel(process);
171
+ }
172
+ };
173
+ return { schedule, cancel, state, steps };
174
+ }
175
+
176
+ const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps, } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : motionUtils.noop, true);
177
+
178
+ let now;
179
+ function clearTime() {
180
+ now = undefined;
181
+ }
182
+ /**
183
+ * An eventloop-synchronous alternative to performance.now().
184
+ *
185
+ * Ensures that time measurements remain consistent within a synchronous context.
186
+ * Usually calling performance.now() twice within the same synchronous context
187
+ * will return different values which isn't useful for animations when we're usually
188
+ * trying to sync animations to the same frame.
189
+ */
190
+ const time = {
191
+ now: () => {
192
+ if (now === undefined) {
193
+ time.set(frameData.isProcessing || motionUtils.MotionGlobalConfig.useManualTiming
194
+ ? frameData.timestamp
195
+ : performance.now());
196
+ }
197
+ return now;
198
+ },
199
+ set: (newTime) => {
200
+ now = newTime;
201
+ queueMicrotask(clearTime);
202
+ },
203
+ };
204
+
205
+ const activeAnimations = {
206
+ layout: 0,
207
+ mainThread: 0,
208
+ waapi: 0,
209
+ };
210
+
211
+ const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
212
+ const isCSSVariableName =
213
+ /*@__PURE__*/ checkStringStartsWith("--");
214
+ const startsAsVariableToken =
215
+ /*@__PURE__*/ checkStringStartsWith("var(--");
216
+ const isCSSVariableToken = (value) => {
217
+ const startsWithToken = startsAsVariableToken(value);
218
+ if (!startsWithToken)
219
+ return false;
220
+ // Ensure any comments are stripped from the value as this can harm performance of the regex.
221
+ return singleCssVariableRegex.test(value.split("/*")[0].trim());
222
+ };
223
+ const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;
224
+
225
+ const number = {
226
+ test: (v) => typeof v === "number",
227
+ parse: parseFloat,
228
+ transform: (v) => v,
229
+ };
230
+ const alpha = {
231
+ ...number,
232
+ transform: (v) => motionUtils.clamp(0, 1, v),
233
+ };
234
+ const scale = {
235
+ ...number,
236
+ default: 1,
237
+ };
238
+
239
+ // If this number is a decimal, make it just five decimal places
240
+ // to avoid exponents
241
+ const sanitize = (v) => Math.round(v * 100000) / 100000;
242
+
243
+ const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu;
244
+
245
+ function isNullish(v) {
246
+ return v == null;
247
+ }
248
+
249
+ const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;
250
+
251
+ /**
252
+ * Returns true if the provided string is a color, ie rgba(0,0,0,0) or #000,
253
+ * but false if a number or multiple colors
254
+ */
255
+ const isColorString = (type, testProp) => (v) => {
256
+ return Boolean((typeof v === "string" &&
257
+ singleColorRegex.test(v) &&
258
+ v.startsWith(type)) ||
259
+ (testProp &&
260
+ !isNullish(v) &&
261
+ Object.prototype.hasOwnProperty.call(v, testProp)));
262
+ };
263
+ const splitColor = (aName, bName, cName) => (v) => {
264
+ if (typeof v !== "string")
265
+ return v;
266
+ const [a, b, c, alpha] = v.match(floatRegex);
267
+ return {
268
+ [aName]: parseFloat(a),
269
+ [bName]: parseFloat(b),
270
+ [cName]: parseFloat(c),
271
+ alpha: alpha !== undefined ? parseFloat(alpha) : 1,
272
+ };
273
+ };
274
+
275
+ const clampRgbUnit = (v) => motionUtils.clamp(0, 255, v);
276
+ const rgbUnit = {
277
+ ...number,
278
+ transform: (v) => Math.round(clampRgbUnit(v)),
279
+ };
280
+ const rgba = {
281
+ test: /*@__PURE__*/ isColorString("rgb", "red"),
282
+ parse: /*@__PURE__*/ splitColor("red", "green", "blue"),
283
+ transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" +
284
+ rgbUnit.transform(red) +
285
+ ", " +
286
+ rgbUnit.transform(green) +
287
+ ", " +
288
+ rgbUnit.transform(blue) +
289
+ ", " +
290
+ sanitize(alpha.transform(alpha$1)) +
291
+ ")",
292
+ };
293
+
294
+ function parseHex(v) {
295
+ let r = "";
296
+ let g = "";
297
+ let b = "";
298
+ let a = "";
299
+ // If we have 6 characters, ie #FF0000
300
+ if (v.length > 5) {
301
+ r = v.substring(1, 3);
302
+ g = v.substring(3, 5);
303
+ b = v.substring(5, 7);
304
+ a = v.substring(7, 9);
305
+ // Or we have 3 characters, ie #F00
306
+ }
307
+ else {
308
+ r = v.substring(1, 2);
309
+ g = v.substring(2, 3);
310
+ b = v.substring(3, 4);
311
+ a = v.substring(4, 5);
312
+ r += r;
313
+ g += g;
314
+ b += b;
315
+ a += a;
316
+ }
317
+ return {
318
+ red: parseInt(r, 16),
319
+ green: parseInt(g, 16),
320
+ blue: parseInt(b, 16),
321
+ alpha: a ? parseInt(a, 16) / 255 : 1,
322
+ };
323
+ }
324
+ const hex = {
325
+ test: /*@__PURE__*/ isColorString("#"),
326
+ parse: parseHex,
327
+ transform: rgba.transform,
328
+ };
329
+
330
+ /*#__NO_SIDE_EFFECTS__*/
331
+ const createUnitType = (unit) => ({
332
+ test: (v) => typeof v === "string" && v.endsWith(unit) && v.split(" ").length === 1,
333
+ parse: parseFloat,
334
+ transform: (v) => `${v}${unit}`,
335
+ });
336
+ const degrees = /*@__PURE__*/ createUnitType("deg");
337
+ const percent = /*@__PURE__*/ createUnitType("%");
338
+ const px = /*@__PURE__*/ createUnitType("px");
339
+ const vh = /*@__PURE__*/ createUnitType("vh");
340
+ const vw = /*@__PURE__*/ createUnitType("vw");
341
+ const progressPercentage = /*@__PURE__*/ (() => ({
342
+ ...percent,
343
+ parse: (v) => percent.parse(v) / 100,
344
+ transform: (v) => percent.transform(v * 100),
345
+ }))();
346
+
347
+ const hsla = {
348
+ test: /*@__PURE__*/ isColorString("hsl", "hue"),
349
+ parse: /*@__PURE__*/ splitColor("hue", "saturation", "lightness"),
350
+ transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
351
+ return ("hsla(" +
352
+ Math.round(hue) +
353
+ ", " +
354
+ percent.transform(sanitize(saturation)) +
355
+ ", " +
356
+ percent.transform(sanitize(lightness)) +
357
+ ", " +
358
+ sanitize(alpha.transform(alpha$1)) +
359
+ ")");
360
+ },
361
+ };
362
+
363
+ const color = {
364
+ test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
365
+ parse: (v) => {
366
+ if (rgba.test(v)) {
367
+ return rgba.parse(v);
368
+ }
369
+ else if (hsla.test(v)) {
370
+ return hsla.parse(v);
371
+ }
372
+ else {
373
+ return hex.parse(v);
374
+ }
375
+ },
376
+ transform: (v) => {
377
+ return typeof v === "string"
378
+ ? v
379
+ : v.hasOwnProperty("red")
380
+ ? rgba.transform(v)
381
+ : hsla.transform(v);
382
+ },
383
+ };
384
+
385
+ const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;
386
+
387
+ function test(v) {
388
+ return (isNaN(v) &&
389
+ typeof v === "string" &&
390
+ (v.match(floatRegex)?.length || 0) +
391
+ (v.match(colorRegex)?.length || 0) >
392
+ 0);
393
+ }
394
+ const NUMBER_TOKEN = "number";
395
+ const COLOR_TOKEN = "color";
396
+ const VAR_TOKEN = "var";
397
+ const VAR_FUNCTION_TOKEN = "var(";
398
+ const SPLIT_TOKEN = "${}";
399
+ // this regex consists of the `singleCssVariableRegex|rgbHSLValueRegex|digitRegex`
400
+ const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;
401
+ function analyseComplexValue(value) {
402
+ const originalValue = value.toString();
403
+ const values = [];
404
+ const indexes = {
405
+ color: [],
406
+ number: [],
407
+ var: [],
408
+ };
409
+ const types = [];
410
+ let i = 0;
411
+ const tokenised = originalValue.replace(complexRegex, (parsedValue) => {
412
+ if (color.test(parsedValue)) {
413
+ indexes.color.push(i);
414
+ types.push(COLOR_TOKEN);
415
+ values.push(color.parse(parsedValue));
416
+ }
417
+ else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) {
418
+ indexes.var.push(i);
419
+ types.push(VAR_TOKEN);
420
+ values.push(parsedValue);
421
+ }
422
+ else {
423
+ indexes.number.push(i);
424
+ types.push(NUMBER_TOKEN);
425
+ values.push(parseFloat(parsedValue));
426
+ }
427
+ ++i;
428
+ return SPLIT_TOKEN;
429
+ });
430
+ const split = tokenised.split(SPLIT_TOKEN);
431
+ return { values, split, indexes, types };
432
+ }
433
+ function parseComplexValue(v) {
434
+ return analyseComplexValue(v).values;
435
+ }
436
+ function createTransformer(source) {
437
+ const { split, types } = analyseComplexValue(source);
438
+ const numSections = split.length;
439
+ return (v) => {
440
+ let output = "";
441
+ for (let i = 0; i < numSections; i++) {
442
+ output += split[i];
443
+ if (v[i] !== undefined) {
444
+ const type = types[i];
445
+ if (type === NUMBER_TOKEN) {
446
+ output += sanitize(v[i]);
447
+ }
448
+ else if (type === COLOR_TOKEN) {
449
+ output += color.transform(v[i]);
450
+ }
451
+ else {
452
+ output += v[i];
453
+ }
454
+ }
455
+ }
456
+ return output;
457
+ };
458
+ }
459
+ const convertNumbersToZero = (v) => typeof v === "number" ? 0 : v;
460
+ function getAnimatableNone$1(v) {
461
+ const parsed = parseComplexValue(v);
462
+ const transformer = createTransformer(v);
463
+ return transformer(parsed.map(convertNumbersToZero));
464
+ }
465
+ const complex = {
466
+ test,
467
+ parse: parseComplexValue,
468
+ createTransformer,
469
+ getAnimatableNone: getAnimatableNone$1,
470
+ };
471
+
472
+ // Adapted from https://gist.github.com/mjackson/5311256
473
+ function hueToRgb(p, q, t) {
474
+ if (t < 0)
475
+ t += 1;
476
+ if (t > 1)
477
+ t -= 1;
478
+ if (t < 1 / 6)
479
+ return p + (q - p) * 6 * t;
480
+ if (t < 1 / 2)
481
+ return q;
482
+ if (t < 2 / 3)
483
+ return p + (q - p) * (2 / 3 - t) * 6;
484
+ return p;
485
+ }
486
+ function hslaToRgba({ hue, saturation, lightness, alpha }) {
487
+ hue /= 360;
488
+ saturation /= 100;
489
+ lightness /= 100;
490
+ let red = 0;
491
+ let green = 0;
492
+ let blue = 0;
493
+ if (!saturation) {
494
+ red = green = blue = lightness;
495
+ }
496
+ else {
497
+ const q = lightness < 0.5
498
+ ? lightness * (1 + saturation)
499
+ : lightness + saturation - lightness * saturation;
500
+ const p = 2 * lightness - q;
501
+ red = hueToRgb(p, q, hue + 1 / 3);
502
+ green = hueToRgb(p, q, hue);
503
+ blue = hueToRgb(p, q, hue - 1 / 3);
504
+ }
505
+ return {
506
+ red: Math.round(red * 255),
507
+ green: Math.round(green * 255),
508
+ blue: Math.round(blue * 255),
509
+ alpha,
510
+ };
511
+ }
512
+
513
+ function mixImmediate(a, b) {
514
+ return (p) => (p > 0 ? b : a);
515
+ }
516
+
517
+ /*
518
+ Value in range from progress
519
+
520
+ Given a lower limit and an upper limit, we return the value within
521
+ that range as expressed by progress (usually a number from 0 to 1)
522
+
523
+ So progress = 0.5 would change
524
+
525
+ from -------- to
526
+
527
+ to
528
+
529
+ from ---- to
530
+
531
+ E.g. from = 10, to = 20, progress = 0.5 => 15
532
+
533
+ @param [number]: Lower limit of range
534
+ @param [number]: Upper limit of range
535
+ @param [number]: The progress between lower and upper limits expressed 0-1
536
+ @return [number]: Value as calculated from progress within range (not limited within range)
537
+ */
538
+ const mixNumber$1 = (from, to, progress) => {
539
+ return from + (to - from) * progress;
540
+ };
541
+
542
+ // Linear color space blending
543
+ // Explained https://www.youtube.com/watch?v=LKnqECcg6Gw
544
+ // Demonstrated http://codepen.io/osublake/pen/xGVVaN
545
+ const mixLinearColor = (from, to, v) => {
546
+ const fromExpo = from * from;
547
+ const expo = v * (to * to - fromExpo) + fromExpo;
548
+ return expo < 0 ? 0 : Math.sqrt(expo);
549
+ };
550
+ const colorTypes = [hex, rgba, hsla];
551
+ const getColorType = (v) => colorTypes.find((type) => type.test(v));
552
+ function asRGBA(color) {
553
+ const type = getColorType(color);
554
+ motionUtils.warning(Boolean(type), `'${color}' is not an animatable color. Use the equivalent color code instead.`);
555
+ if (!Boolean(type))
556
+ return false;
557
+ let model = type.parse(color);
558
+ if (type === hsla) {
559
+ // TODO Remove this cast - needed since Motion's stricter typing
560
+ model = hslaToRgba(model);
561
+ }
562
+ return model;
563
+ }
564
+ const mixColor = (from, to) => {
565
+ const fromRGBA = asRGBA(from);
566
+ const toRGBA = asRGBA(to);
567
+ if (!fromRGBA || !toRGBA) {
568
+ return mixImmediate(from, to);
569
+ }
570
+ const blended = { ...fromRGBA };
571
+ return (v) => {
572
+ blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v);
573
+ blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v);
574
+ blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v);
575
+ blended.alpha = mixNumber$1(fromRGBA.alpha, toRGBA.alpha, v);
576
+ return rgba.transform(blended);
577
+ };
578
+ };
579
+
580
+ const invisibleValues = new Set(["none", "hidden"]);
581
+ /**
582
+ * Returns a function that, when provided a progress value between 0 and 1,
583
+ * will return the "none" or "hidden" string only when the progress is that of
584
+ * the origin or target.
585
+ */
586
+ function mixVisibility(origin, target) {
587
+ if (invisibleValues.has(origin)) {
588
+ return (p) => (p <= 0 ? origin : target);
589
+ }
590
+ else {
591
+ return (p) => (p >= 1 ? target : origin);
592
+ }
593
+ }
594
+
595
+ function mixNumber(a, b) {
596
+ return (p) => mixNumber$1(a, b, p);
597
+ }
598
+ function getMixer(a) {
599
+ if (typeof a === "number") {
600
+ return mixNumber;
601
+ }
602
+ else if (typeof a === "string") {
603
+ return isCSSVariableToken(a)
604
+ ? mixImmediate
605
+ : color.test(a)
606
+ ? mixColor
607
+ : mixComplex;
608
+ }
609
+ else if (Array.isArray(a)) {
610
+ return mixArray;
611
+ }
612
+ else if (typeof a === "object") {
613
+ return color.test(a) ? mixColor : mixObject;
614
+ }
615
+ return mixImmediate;
616
+ }
617
+ function mixArray(a, b) {
618
+ const output = [...a];
619
+ const numValues = output.length;
620
+ const blendValue = a.map((v, i) => getMixer(v)(v, b[i]));
621
+ return (p) => {
622
+ for (let i = 0; i < numValues; i++) {
623
+ output[i] = blendValue[i](p);
624
+ }
625
+ return output;
626
+ };
627
+ }
628
+ function mixObject(a, b) {
629
+ const output = { ...a, ...b };
630
+ const blendValue = {};
631
+ for (const key in output) {
632
+ if (a[key] !== undefined && b[key] !== undefined) {
633
+ blendValue[key] = getMixer(a[key])(a[key], b[key]);
634
+ }
635
+ }
636
+ return (v) => {
637
+ for (const key in blendValue) {
638
+ output[key] = blendValue[key](v);
639
+ }
640
+ return output;
641
+ };
642
+ }
643
+ function matchOrder(origin, target) {
644
+ const orderedOrigin = [];
645
+ const pointers = { color: 0, var: 0, number: 0 };
646
+ for (let i = 0; i < target.values.length; i++) {
647
+ const type = target.types[i];
648
+ const originIndex = origin.indexes[type][pointers[type]];
649
+ const originValue = origin.values[originIndex] ?? 0;
650
+ orderedOrigin[i] = originValue;
651
+ pointers[type]++;
652
+ }
653
+ return orderedOrigin;
654
+ }
655
+ const mixComplex = (origin, target) => {
656
+ const template = complex.createTransformer(target);
657
+ const originStats = analyseComplexValue(origin);
658
+ const targetStats = analyseComplexValue(target);
659
+ const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length &&
660
+ originStats.indexes.color.length === targetStats.indexes.color.length &&
661
+ originStats.indexes.number.length >= targetStats.indexes.number.length;
662
+ if (canInterpolate) {
663
+ if ((invisibleValues.has(origin) &&
664
+ !targetStats.values.length) ||
665
+ (invisibleValues.has(target) &&
666
+ !originStats.values.length)) {
667
+ return mixVisibility(origin, target);
668
+ }
669
+ return motionUtils.pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);
670
+ }
671
+ else {
672
+ motionUtils.warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`);
673
+ return mixImmediate(origin, target);
674
+ }
675
+ };
676
+
677
+ function mix(from, to, p) {
678
+ if (typeof from === "number" &&
679
+ typeof to === "number" &&
680
+ typeof p === "number") {
681
+ return mixNumber$1(from, to, p);
682
+ }
683
+ const mixer = getMixer(from);
684
+ return mixer(from, to);
685
+ }
686
+
687
+ const frameloopDriver = (update) => {
688
+ const passTimestamp = ({ timestamp }) => update(timestamp);
689
+ return {
690
+ start: () => frame.update(passTimestamp, true),
691
+ stop: () => cancelFrame(passTimestamp),
692
+ /**
693
+ * If we're processing this frame we can use the
694
+ * framelocked timestamp to keep things in sync.
695
+ */
696
+ now: () => (frameData.isProcessing ? frameData.timestamp : time.now()),
697
+ };
698
+ };
699
+
700
+ const generateLinearEasing = (easing, duration, // as milliseconds
701
+ resolution = 10 // as milliseconds
702
+ ) => {
703
+ let points = "";
704
+ const numPoints = Math.max(Math.round(duration / resolution), 2);
705
+ for (let i = 0; i < numPoints; i++) {
706
+ points += easing(i / (numPoints - 1)) + ", ";
707
+ }
708
+ return `linear(${points.substring(0, points.length - 2)})`;
709
+ };
710
+
711
+ /**
712
+ * Implement a practical max duration for keyframe generation
713
+ * to prevent infinite loops
714
+ */
715
+ const maxGeneratorDuration = 20000;
716
+ function calcGeneratorDuration(generator) {
717
+ let duration = 0;
718
+ const timeStep = 50;
719
+ let state = generator.next(duration);
720
+ while (!state.done && duration < maxGeneratorDuration) {
721
+ duration += timeStep;
722
+ state = generator.next(duration);
723
+ }
724
+ return duration >= maxGeneratorDuration ? Infinity : duration;
725
+ }
726
+
727
+ /**
728
+ * Create a progress => progress easing function from a generator.
729
+ */
730
+ function createGeneratorEasing(options, scale = 100, createGenerator) {
731
+ const generator = createGenerator({ ...options, keyframes: [0, scale] });
732
+ const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
733
+ return {
734
+ type: "keyframes",
735
+ ease: (progress) => {
736
+ return generator.next(duration * progress).value / scale;
737
+ },
738
+ duration: motionUtils.millisecondsToSeconds(duration),
739
+ };
740
+ }
741
+
742
+ const velocitySampleDuration = 5; // ms
743
+ function calcGeneratorVelocity(resolveValue, t, current) {
744
+ const prevT = Math.max(t - velocitySampleDuration, 0);
745
+ return motionUtils.velocityPerSecond(current - resolveValue(prevT), t - prevT);
746
+ }
747
+
748
+ const springDefaults = {
749
+ // Default spring physics
750
+ stiffness: 100,
751
+ damping: 10,
752
+ mass: 1.0,
753
+ velocity: 0.0,
754
+ // Default duration/bounce-based options
755
+ duration: 800, // in ms
756
+ bounce: 0.3,
757
+ visualDuration: 0.3, // in seconds
758
+ // Rest thresholds
759
+ restSpeed: {
760
+ granular: 0.01,
761
+ default: 2,
762
+ },
763
+ restDelta: {
764
+ granular: 0.005,
765
+ default: 0.5,
766
+ },
767
+ // Limits
768
+ minDuration: 0.01, // in seconds
769
+ maxDuration: 10.0, // in seconds
770
+ minDamping: 0.05,
771
+ maxDamping: 1,
772
+ };
773
+
774
+ const safeMin = 0.001;
775
+ function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass, }) {
776
+ let envelope;
777
+ let derivative;
778
+ motionUtils.warning(duration <= motionUtils.secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less");
779
+ let dampingRatio = 1 - bounce;
780
+ /**
781
+ * Restrict dampingRatio and duration to within acceptable ranges.
782
+ */
783
+ dampingRatio = motionUtils.clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio);
784
+ duration = motionUtils.clamp(springDefaults.minDuration, springDefaults.maxDuration, motionUtils.millisecondsToSeconds(duration));
785
+ if (dampingRatio < 1) {
786
+ /**
787
+ * Underdamped spring
788
+ */
789
+ envelope = (undampedFreq) => {
790
+ const exponentialDecay = undampedFreq * dampingRatio;
791
+ const delta = exponentialDecay * duration;
792
+ const a = exponentialDecay - velocity;
793
+ const b = calcAngularFreq(undampedFreq, dampingRatio);
794
+ const c = Math.exp(-delta);
795
+ return safeMin - (a / b) * c;
796
+ };
797
+ derivative = (undampedFreq) => {
798
+ const exponentialDecay = undampedFreq * dampingRatio;
799
+ const delta = exponentialDecay * duration;
800
+ const d = delta * velocity + velocity;
801
+ const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;
802
+ const f = Math.exp(-delta);
803
+ const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);
804
+ const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;
805
+ return (factor * ((d - e) * f)) / g;
806
+ };
807
+ }
808
+ else {
809
+ /**
810
+ * Critically-damped spring
811
+ */
812
+ envelope = (undampedFreq) => {
813
+ const a = Math.exp(-undampedFreq * duration);
814
+ const b = (undampedFreq - velocity) * duration + 1;
815
+ return -safeMin + a * b;
816
+ };
817
+ derivative = (undampedFreq) => {
818
+ const a = Math.exp(-undampedFreq * duration);
819
+ const b = (velocity - undampedFreq) * (duration * duration);
820
+ return a * b;
821
+ };
822
+ }
823
+ const initialGuess = 5 / duration;
824
+ const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
825
+ duration = motionUtils.secondsToMilliseconds(duration);
826
+ if (isNaN(undampedFreq)) {
827
+ return {
828
+ stiffness: springDefaults.stiffness,
829
+ damping: springDefaults.damping,
830
+ duration,
831
+ };
832
+ }
833
+ else {
834
+ const stiffness = Math.pow(undampedFreq, 2) * mass;
835
+ return {
836
+ stiffness,
837
+ damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
838
+ duration,
839
+ };
840
+ }
841
+ }
842
+ const rootIterations = 12;
843
+ function approximateRoot(envelope, derivative, initialGuess) {
844
+ let result = initialGuess;
845
+ for (let i = 1; i < rootIterations; i++) {
846
+ result = result - envelope(result) / derivative(result);
847
+ }
848
+ return result;
849
+ }
850
+ function calcAngularFreq(undampedFreq, dampingRatio) {
851
+ return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
852
+ }
853
+
854
+ const durationKeys = ["duration", "bounce"];
855
+ const physicsKeys = ["stiffness", "damping", "mass"];
856
+ function isSpringType(options, keys) {
857
+ return keys.some((key) => options[key] !== undefined);
858
+ }
859
+ function getSpringOptions(options) {
860
+ let springOptions = {
861
+ velocity: springDefaults.velocity,
862
+ stiffness: springDefaults.stiffness,
863
+ damping: springDefaults.damping,
864
+ mass: springDefaults.mass,
865
+ isResolvedFromDuration: false,
866
+ ...options,
867
+ };
868
+ // stiffness/damping/mass overrides duration/bounce
869
+ if (!isSpringType(options, physicsKeys) &&
870
+ isSpringType(options, durationKeys)) {
871
+ if (options.visualDuration) {
872
+ const visualDuration = options.visualDuration;
873
+ const root = (2 * Math.PI) / (visualDuration * 1.2);
874
+ const stiffness = root * root;
875
+ const damping = 2 *
876
+ motionUtils.clamp(0.05, 1, 1 - (options.bounce || 0)) *
877
+ Math.sqrt(stiffness);
878
+ springOptions = {
879
+ ...springOptions,
880
+ mass: springDefaults.mass,
881
+ stiffness,
882
+ damping,
883
+ };
884
+ }
885
+ else {
886
+ const derived = findSpring(options);
887
+ springOptions = {
888
+ ...springOptions,
889
+ ...derived,
890
+ mass: springDefaults.mass,
891
+ };
892
+ springOptions.isResolvedFromDuration = true;
893
+ }
894
+ }
895
+ return springOptions;
896
+ }
897
+ function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {
898
+ const options = typeof optionsOrVisualDuration !== "object"
899
+ ? {
900
+ visualDuration: optionsOrVisualDuration,
901
+ keyframes: [0, 1],
902
+ bounce,
903
+ }
904
+ : optionsOrVisualDuration;
905
+ let { restSpeed, restDelta } = options;
906
+ const origin = options.keyframes[0];
907
+ const target = options.keyframes[options.keyframes.length - 1];
908
+ /**
909
+ * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
910
+ * to reduce GC during animation.
911
+ */
912
+ const state = { done: false, value: origin };
913
+ const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration, } = getSpringOptions({
914
+ ...options,
915
+ velocity: -motionUtils.millisecondsToSeconds(options.velocity || 0),
916
+ });
917
+ const initialVelocity = velocity || 0.0;
918
+ const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
919
+ const initialDelta = target - origin;
920
+ const undampedAngularFreq = motionUtils.millisecondsToSeconds(Math.sqrt(stiffness / mass));
921
+ /**
922
+ * If we're working on a granular scale, use smaller defaults for determining
923
+ * when the spring is finished.
924
+ *
925
+ * These defaults have been selected emprically based on what strikes a good
926
+ * ratio between feeling good and finishing as soon as changes are imperceptible.
927
+ */
928
+ const isGranularScale = Math.abs(initialDelta) < 5;
929
+ restSpeed || (restSpeed = isGranularScale
930
+ ? springDefaults.restSpeed.granular
931
+ : springDefaults.restSpeed.default);
932
+ restDelta || (restDelta = isGranularScale
933
+ ? springDefaults.restDelta.granular
934
+ : springDefaults.restDelta.default);
935
+ let resolveSpring;
936
+ if (dampingRatio < 1) {
937
+ const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
938
+ // Underdamped spring
939
+ resolveSpring = (t) => {
940
+ const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
941
+ return (target -
942
+ envelope *
943
+ (((initialVelocity +
944
+ dampingRatio * undampedAngularFreq * initialDelta) /
945
+ angularFreq) *
946
+ Math.sin(angularFreq * t) +
947
+ initialDelta * Math.cos(angularFreq * t)));
948
+ };
949
+ }
950
+ else if (dampingRatio === 1) {
951
+ // Critically damped spring
952
+ resolveSpring = (t) => target -
953
+ Math.exp(-undampedAngularFreq * t) *
954
+ (initialDelta +
955
+ (initialVelocity + undampedAngularFreq * initialDelta) * t);
956
+ }
957
+ else {
958
+ // Overdamped spring
959
+ const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
960
+ resolveSpring = (t) => {
961
+ const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
962
+ // When performing sinh or cosh values can hit Infinity so we cap them here
963
+ const freqForT = Math.min(dampedAngularFreq * t, 300);
964
+ return (target -
965
+ (envelope *
966
+ ((initialVelocity +
967
+ dampingRatio * undampedAngularFreq * initialDelta) *
968
+ Math.sinh(freqForT) +
969
+ dampedAngularFreq *
970
+ initialDelta *
971
+ Math.cosh(freqForT))) /
972
+ dampedAngularFreq);
973
+ };
974
+ }
975
+ const generator = {
976
+ calculatedDuration: isResolvedFromDuration ? duration || null : null,
977
+ next: (t) => {
978
+ const current = resolveSpring(t);
979
+ if (!isResolvedFromDuration) {
980
+ let currentVelocity = 0.0;
981
+ /**
982
+ * We only need to calculate velocity for under-damped springs
983
+ * as over- and critically-damped springs can't overshoot, so
984
+ * checking only for displacement is enough.
985
+ */
986
+ if (dampingRatio < 1) {
987
+ currentVelocity =
988
+ t === 0
989
+ ? motionUtils.secondsToMilliseconds(initialVelocity)
990
+ : calcGeneratorVelocity(resolveSpring, t, current);
991
+ }
992
+ const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;
993
+ const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta;
994
+ state.done =
995
+ isBelowVelocityThreshold && isBelowDisplacementThreshold;
996
+ }
997
+ else {
998
+ state.done = t >= duration;
999
+ }
1000
+ state.value = state.done ? target : current;
1001
+ return state;
1002
+ },
1003
+ toString: () => {
1004
+ const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
1005
+ const easing = generateLinearEasing((progress) => generator.next(calculatedDuration * progress).value, calculatedDuration, 30);
1006
+ return calculatedDuration + "ms " + easing;
1007
+ },
1008
+ toTransition: () => { },
1009
+ };
1010
+ return generator;
1011
+ }
1012
+ spring.applyToOptions = (options) => {
1013
+ const generatorOptions = createGeneratorEasing(options, 100, spring);
1014
+ options.ease = generatorOptions.ease;
1015
+ options.duration = motionUtils.secondsToMilliseconds(generatorOptions.duration);
1016
+ options.type = "keyframes";
1017
+ return options;
1018
+ };
1019
+
1020
+ function inertia({ keyframes, velocity = 0.0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed, }) {
1021
+ const origin = keyframes[0];
1022
+ const state = {
1023
+ done: false,
1024
+ value: origin,
1025
+ };
1026
+ const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);
1027
+ const nearestBoundary = (v) => {
1028
+ if (min === undefined)
1029
+ return max;
1030
+ if (max === undefined)
1031
+ return min;
1032
+ return Math.abs(min - v) < Math.abs(max - v) ? min : max;
1033
+ };
1034
+ let amplitude = power * velocity;
1035
+ const ideal = origin + amplitude;
1036
+ const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
1037
+ /**
1038
+ * If the target has changed we need to re-calculate the amplitude, otherwise
1039
+ * the animation will start from the wrong position.
1040
+ */
1041
+ if (target !== ideal)
1042
+ amplitude = target - origin;
1043
+ const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);
1044
+ const calcLatest = (t) => target + calcDelta(t);
1045
+ const applyFriction = (t) => {
1046
+ const delta = calcDelta(t);
1047
+ const latest = calcLatest(t);
1048
+ state.done = Math.abs(delta) <= restDelta;
1049
+ state.value = state.done ? target : latest;
1050
+ };
1051
+ /**
1052
+ * Ideally this would resolve for t in a stateless way, we could
1053
+ * do that by always precalculating the animation but as we know
1054
+ * this will be done anyway we can assume that spring will
1055
+ * be discovered during that.
1056
+ */
1057
+ let timeReachedBoundary;
1058
+ let spring$1;
1059
+ const checkCatchBoundary = (t) => {
1060
+ if (!isOutOfBounds(state.value))
1061
+ return;
1062
+ timeReachedBoundary = t;
1063
+ spring$1 = spring({
1064
+ keyframes: [state.value, nearestBoundary(state.value)],
1065
+ velocity: calcGeneratorVelocity(calcLatest, t, state.value), // TODO: This should be passing * 1000
1066
+ damping: bounceDamping,
1067
+ stiffness: bounceStiffness,
1068
+ restDelta,
1069
+ restSpeed,
1070
+ });
1071
+ };
1072
+ checkCatchBoundary(0);
1073
+ return {
1074
+ calculatedDuration: null,
1075
+ next: (t) => {
1076
+ /**
1077
+ * We need to resolve the friction to figure out if we need a
1078
+ * spring but we don't want to do this twice per frame. So here
1079
+ * we flag if we updated for this frame and later if we did
1080
+ * we can skip doing it again.
1081
+ */
1082
+ let hasUpdatedFrame = false;
1083
+ if (!spring$1 && timeReachedBoundary === undefined) {
1084
+ hasUpdatedFrame = true;
1085
+ applyFriction(t);
1086
+ checkCatchBoundary(t);
1087
+ }
1088
+ /**
1089
+ * If we have a spring and the provided t is beyond the moment the friction
1090
+ * animation crossed the min/max boundary, use the spring.
1091
+ */
1092
+ if (timeReachedBoundary !== undefined && t >= timeReachedBoundary) {
1093
+ return spring$1.next(t - timeReachedBoundary);
1094
+ }
1095
+ else {
1096
+ !hasUpdatedFrame && applyFriction(t);
1097
+ return state;
1098
+ }
1099
+ },
1100
+ };
1101
+ }
8
1102
 
9
- class GroupAnimation {
10
- constructor(animations) {
11
- // Bound to accomodate common `return animation.stop` pattern
12
- this.stop = () => this.runAll("stop");
13
- this.animations = animations.filter(Boolean);
1103
+ function createMixers(output, ease, customMixer) {
1104
+ const mixers = [];
1105
+ const mixerFactory = customMixer || motionUtils.MotionGlobalConfig.mix || mix;
1106
+ const numMixers = output.length - 1;
1107
+ for (let i = 0; i < numMixers; i++) {
1108
+ let mixer = mixerFactory(output[i], output[i + 1]);
1109
+ if (ease) {
1110
+ const easingFunction = Array.isArray(ease) ? ease[i] || motionUtils.noop : ease;
1111
+ mixer = motionUtils.pipe(easingFunction, mixer);
1112
+ }
1113
+ mixers.push(mixer);
1114
+ }
1115
+ return mixers;
1116
+ }
1117
+ /**
1118
+ * Create a function that maps from a numerical input array to a generic output array.
1119
+ *
1120
+ * Accepts:
1121
+ * - Numbers
1122
+ * - Colors (hex, hsl, hsla, rgb, rgba)
1123
+ * - Complex (combinations of one or more numbers or strings)
1124
+ *
1125
+ * ```jsx
1126
+ * const mixColor = interpolate([0, 1], ['#fff', '#000'])
1127
+ *
1128
+ * mixColor(0.5) // 'rgba(128, 128, 128, 1)'
1129
+ * ```
1130
+ *
1131
+ * TODO Revist this approach once we've moved to data models for values,
1132
+ * probably not needed to pregenerate mixer functions.
1133
+ *
1134
+ * @public
1135
+ */
1136
+ function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {
1137
+ const inputLength = input.length;
1138
+ motionUtils.invariant(inputLength === output.length, "Both input and output ranges must be the same length");
1139
+ /**
1140
+ * If we're only provided a single input, we can just make a function
1141
+ * that returns the output.
1142
+ */
1143
+ if (inputLength === 1)
1144
+ return () => output[0];
1145
+ if (inputLength === 2 && output[0] === output[1])
1146
+ return () => output[1];
1147
+ const isZeroDeltaRange = input[0] === input[1];
1148
+ // If input runs highest -> lowest, reverse both arrays
1149
+ if (input[0] > input[inputLength - 1]) {
1150
+ input = [...input].reverse();
1151
+ output = [...output].reverse();
1152
+ }
1153
+ const mixers = createMixers(output, ease, mixer);
1154
+ const numMixers = mixers.length;
1155
+ const interpolator = (v) => {
1156
+ if (isZeroDeltaRange && v < input[0])
1157
+ return output[0];
1158
+ let i = 0;
1159
+ if (numMixers > 1) {
1160
+ for (; i < input.length - 2; i++) {
1161
+ if (v < input[i + 1])
1162
+ break;
1163
+ }
1164
+ }
1165
+ const progressInRange = motionUtils.progress(input[i], input[i + 1], v);
1166
+ return mixers[i](progressInRange);
1167
+ };
1168
+ return isClamp
1169
+ ? (v) => interpolator(motionUtils.clamp(input[0], input[inputLength - 1], v))
1170
+ : interpolator;
1171
+ }
1172
+
1173
+ function fillOffset(offset, remaining) {
1174
+ const min = offset[offset.length - 1];
1175
+ for (let i = 1; i <= remaining; i++) {
1176
+ const offsetProgress = motionUtils.progress(0, remaining, i);
1177
+ offset.push(mixNumber$1(min, 1, offsetProgress));
1178
+ }
1179
+ }
1180
+
1181
+ function defaultOffset(arr) {
1182
+ const offset = [0];
1183
+ fillOffset(offset, arr.length - 1);
1184
+ return offset;
1185
+ }
1186
+
1187
+ function convertOffsetToTimes(offset, duration) {
1188
+ return offset.map((o) => o * duration);
1189
+ }
1190
+
1191
+ function defaultEasing(values, easing) {
1192
+ return values.map(() => easing || motionUtils.easeInOut).splice(0, values.length - 1);
1193
+ }
1194
+ function keyframes({ duration = 300, keyframes: keyframeValues, times, ease = "easeInOut", }) {
1195
+ /**
1196
+ * Easing functions can be externally defined as strings. Here we convert them
1197
+ * into actual functions.
1198
+ */
1199
+ const easingFunctions = motionUtils.isEasingArray(ease)
1200
+ ? ease.map(motionUtils.easingDefinitionToFunction)
1201
+ : motionUtils.easingDefinitionToFunction(ease);
1202
+ /**
1203
+ * This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
1204
+ * to reduce GC during animation.
1205
+ */
1206
+ const state = {
1207
+ done: false,
1208
+ value: keyframeValues[0],
1209
+ };
1210
+ /**
1211
+ * Create a times array based on the provided 0-1 offsets
1212
+ */
1213
+ const absoluteTimes = convertOffsetToTimes(
1214
+ // Only use the provided offsets if they're the correct length
1215
+ // TODO Maybe we should warn here if there's a length mismatch
1216
+ times && times.length === keyframeValues.length
1217
+ ? times
1218
+ : defaultOffset(keyframeValues), duration);
1219
+ const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {
1220
+ ease: Array.isArray(easingFunctions)
1221
+ ? easingFunctions
1222
+ : defaultEasing(keyframeValues, easingFunctions),
1223
+ });
1224
+ return {
1225
+ calculatedDuration: duration,
1226
+ next: (t) => {
1227
+ state.value = mapTimeToKeyframe(t);
1228
+ state.done = t >= duration;
1229
+ return state;
1230
+ },
1231
+ };
1232
+ }
1233
+
1234
+ const isNotNull = (value) => value !== null;
1235
+ function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) {
1236
+ const resolvedKeyframes = keyframes.filter(isNotNull);
1237
+ const useFirstKeyframe = speed < 0 || (repeat && repeatType !== "loop" && repeat % 2 === 1);
1238
+ const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;
1239
+ return !index || finalKeyframe === undefined
1240
+ ? resolvedKeyframes[index]
1241
+ : finalKeyframe;
1242
+ }
1243
+
1244
+ const transitionTypeMap = {
1245
+ decay: inertia,
1246
+ inertia,
1247
+ tween: keyframes,
1248
+ keyframes: keyframes,
1249
+ spring,
1250
+ };
1251
+ function replaceTransitionType(transition) {
1252
+ if (typeof transition.type === "string") {
1253
+ transition.type = transitionTypeMap[transition.type];
1254
+ }
1255
+ }
1256
+
1257
+ class WithPromise {
1258
+ constructor() {
1259
+ this.count = 0;
1260
+ this.updateFinished();
14
1261
  }
15
1262
  get finished() {
16
- return Promise.all(this.animations.map((animation) => animation.finished));
1263
+ return this._finished;
1264
+ }
1265
+ updateFinished() {
1266
+ this.count++;
1267
+ this._finished = new Promise((resolve) => {
1268
+ this.resolve = resolve;
1269
+ });
1270
+ }
1271
+ notifyFinished() {
1272
+ this.resolve();
17
1273
  }
18
1274
  /**
19
- * TODO: Filter out cancelled or stopped animations before returning
1275
+ * Allows the animation to be awaited.
1276
+ *
1277
+ * @deprecated Use `finished` instead.
20
1278
  */
21
- getAll(propName) {
22
- return this.animations[0][propName];
1279
+ then(onResolve, onReject) {
1280
+ return this.finished.then(onResolve, onReject);
23
1281
  }
24
- setAll(propName, newValue) {
25
- for (let i = 0; i < this.animations.length; i++) {
26
- this.animations[i][propName] = newValue;
1282
+ }
1283
+
1284
+ const percentToProgress = (percent) => percent / 100;
1285
+ class JSAnimation extends WithPromise {
1286
+ constructor(options) {
1287
+ super();
1288
+ this.state = "idle";
1289
+ this.startTime = null;
1290
+ this.isStopped = false;
1291
+ /**
1292
+ * The current time of the animation.
1293
+ */
1294
+ this.currentTime = 0;
1295
+ /**
1296
+ * The time at which the animation was paused.
1297
+ */
1298
+ this.holdTime = null;
1299
+ /**
1300
+ * Playback speed as a factor. 0 would be stopped, -1 reverse and 2 double speed.
1301
+ */
1302
+ this.playbackSpeed = 1;
1303
+ /**
1304
+ * This method is bound to the instance to fix a pattern where
1305
+ * animation.stop is returned as a reference from a useEffect.
1306
+ */
1307
+ this.stop = () => {
1308
+ const { motionValue } = this.options;
1309
+ if (motionValue && motionValue.updatedAt !== time.now()) {
1310
+ this.tick(time.now());
1311
+ }
1312
+ this.isStopped = true;
1313
+ if (this.state === "idle")
1314
+ return;
1315
+ this.teardown();
1316
+ const { onStop } = this.options;
1317
+ onStop && onStop();
1318
+ };
1319
+ activeAnimations.mainThread++;
1320
+ this.options = options;
1321
+ this.initAnimation();
1322
+ this.play();
1323
+ if (options.autoplay === false)
1324
+ this.pause();
1325
+ }
1326
+ initAnimation() {
1327
+ const { options } = this;
1328
+ replaceTransitionType(options);
1329
+ const { type = keyframes, repeat = 0, repeatDelay = 0, repeatType, velocity = 0, } = options;
1330
+ let { keyframes: keyframes$1 } = options;
1331
+ const generatorFactory = type || keyframes;
1332
+ if (process.env.NODE_ENV !== "production" &&
1333
+ generatorFactory !== keyframes) {
1334
+ motionUtils.invariant(keyframes$1.length <= 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`);
1335
+ }
1336
+ if (generatorFactory !== keyframes &&
1337
+ typeof keyframes$1[0] !== "number") {
1338
+ this.mixKeyframes = motionUtils.pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1]));
1339
+ keyframes$1 = [0, 100];
1340
+ }
1341
+ const generator = generatorFactory({ ...options, keyframes: keyframes$1 });
1342
+ /**
1343
+ * If we have a mirror repeat type we need to create a second generator that outputs the
1344
+ * mirrored (not reversed) animation and later ping pong between the two generators.
1345
+ */
1346
+ if (repeatType === "mirror") {
1347
+ this.mirroredGenerator = generatorFactory({
1348
+ ...options,
1349
+ keyframes: [...keyframes$1].reverse(),
1350
+ velocity: -velocity,
1351
+ });
1352
+ }
1353
+ /**
1354
+ * If duration is undefined and we have repeat options,
1355
+ * we need to calculate a duration from the generator.
1356
+ *
1357
+ * We set it to the generator itself to cache the duration.
1358
+ * Any timeline resolver will need to have already precalculated
1359
+ * the duration by this step.
1360
+ */
1361
+ if (generator.calculatedDuration === null) {
1362
+ generator.calculatedDuration = calcGeneratorDuration(generator);
1363
+ }
1364
+ const { calculatedDuration } = generator;
1365
+ this.calculatedDuration = calculatedDuration;
1366
+ this.resolvedDuration = calculatedDuration + repeatDelay;
1367
+ this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay;
1368
+ this.generator = generator;
1369
+ }
1370
+ updateTime(timestamp) {
1371
+ const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed;
1372
+ // Update currentTime
1373
+ if (this.holdTime !== null) {
1374
+ this.currentTime = this.holdTime;
1375
+ }
1376
+ else {
1377
+ // Rounding the time because floating point arithmetic is not always accurate, e.g. 3000.367 - 1000.367 =
1378
+ // 2000.0000000000002. This is a problem when we are comparing the currentTime with the duration, for
1379
+ // example.
1380
+ this.currentTime = animationTime;
27
1381
  }
28
1382
  }
29
- attachTimeline(timeline, fallback) {
30
- const subscriptions = this.animations.map((animation) => {
31
- if (supportsScrollTimeline() && animation.attachTimeline) {
32
- return animation.attachTimeline(timeline);
1383
+ tick(timestamp, sample = false) {
1384
+ const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration, } = this;
1385
+ if (this.startTime === null)
1386
+ return generator.next(0);
1387
+ const { delay = 0, keyframes, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe, } = this.options;
1388
+ /**
1389
+ * requestAnimationFrame timestamps can come through as lower than
1390
+ * the startTime as set by performance.now(). Here we prevent this,
1391
+ * though in the future it could be possible to make setting startTime
1392
+ * a pending operation that gets resolved here.
1393
+ */
1394
+ if (this.speed > 0) {
1395
+ this.startTime = Math.min(this.startTime, timestamp);
1396
+ }
1397
+ else if (this.speed < 0) {
1398
+ this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);
1399
+ }
1400
+ if (sample) {
1401
+ this.currentTime = timestamp;
1402
+ }
1403
+ else {
1404
+ this.updateTime(timestamp);
1405
+ }
1406
+ // Rebase on delay
1407
+ const timeWithoutDelay = this.currentTime - delay * (this.playbackSpeed >= 0 ? 1 : -1);
1408
+ const isInDelayPhase = this.playbackSpeed >= 0
1409
+ ? timeWithoutDelay < 0
1410
+ : timeWithoutDelay > totalDuration;
1411
+ this.currentTime = Math.max(timeWithoutDelay, 0);
1412
+ // If this animation has finished, set the current time to the total duration.
1413
+ if (this.state === "finished" && this.holdTime === null) {
1414
+ this.currentTime = totalDuration;
1415
+ }
1416
+ let elapsed = this.currentTime;
1417
+ let frameGenerator = generator;
1418
+ if (repeat) {
1419
+ /**
1420
+ * Get the current progress (0-1) of the animation. If t is >
1421
+ * than duration we'll get values like 2.5 (midway through the
1422
+ * third iteration)
1423
+ */
1424
+ const progress = Math.min(this.currentTime, totalDuration) / resolvedDuration;
1425
+ /**
1426
+ * Get the current iteration (0 indexed). For instance the floor of
1427
+ * 2.5 is 2.
1428
+ */
1429
+ let currentIteration = Math.floor(progress);
1430
+ /**
1431
+ * Get the current progress of the iteration by taking the remainder
1432
+ * so 2.5 is 0.5 through iteration 2
1433
+ */
1434
+ let iterationProgress = progress % 1.0;
1435
+ /**
1436
+ * If iteration progress is 1 we count that as the end
1437
+ * of the previous iteration.
1438
+ */
1439
+ if (!iterationProgress && progress >= 1) {
1440
+ iterationProgress = 1;
33
1441
  }
34
- else if (typeof fallback === "function") {
35
- return fallback(animation);
1442
+ iterationProgress === 1 && currentIteration--;
1443
+ currentIteration = Math.min(currentIteration, repeat + 1);
1444
+ /**
1445
+ * Reverse progress if we're not running in "normal" direction
1446
+ */
1447
+ const isOddIteration = Boolean(currentIteration % 2);
1448
+ if (isOddIteration) {
1449
+ if (repeatType === "reverse") {
1450
+ iterationProgress = 1 - iterationProgress;
1451
+ if (repeatDelay) {
1452
+ iterationProgress -= repeatDelay / resolvedDuration;
1453
+ }
1454
+ }
1455
+ else if (repeatType === "mirror") {
1456
+ frameGenerator = mirroredGenerator;
1457
+ }
36
1458
  }
37
- });
38
- return () => {
39
- subscriptions.forEach((cancel, i) => {
40
- cancel && cancel();
41
- this.animations[i].stop();
42
- });
43
- };
1459
+ elapsed = motionUtils.clamp(0, 1, iterationProgress) * resolvedDuration;
1460
+ }
1461
+ /**
1462
+ * If we're in negative time, set state as the initial keyframe.
1463
+ * This prevents delay: x, duration: 0 animations from finishing
1464
+ * instantly.
1465
+ */
1466
+ const state = isInDelayPhase
1467
+ ? { done: false, value: keyframes[0] }
1468
+ : frameGenerator.next(elapsed);
1469
+ if (mixKeyframes) {
1470
+ state.value = mixKeyframes(state.value);
1471
+ }
1472
+ let { done } = state;
1473
+ if (!isInDelayPhase && calculatedDuration !== null) {
1474
+ done =
1475
+ this.playbackSpeed >= 0
1476
+ ? this.currentTime >= totalDuration
1477
+ : this.currentTime <= 0;
1478
+ }
1479
+ const isAnimationFinished = this.holdTime === null &&
1480
+ (this.state === "finished" || (this.state === "running" && done));
1481
+ // TODO: The exception for inertia could be cleaner here
1482
+ if (isAnimationFinished && type !== inertia) {
1483
+ state.value = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
1484
+ }
1485
+ if (onUpdate) {
1486
+ onUpdate(state.value);
1487
+ }
1488
+ if (isAnimationFinished) {
1489
+ this.finish();
1490
+ }
1491
+ return state;
1492
+ }
1493
+ /**
1494
+ * Allows the returned animation to be awaited or promise-chained. Currently
1495
+ * resolves when the animation finishes at all but in a future update could/should
1496
+ * reject if its cancels.
1497
+ */
1498
+ then(resolve, reject) {
1499
+ return this.finished.then(resolve, reject);
1500
+ }
1501
+ get duration() {
1502
+ return motionUtils.millisecondsToSeconds(this.calculatedDuration);
44
1503
  }
45
1504
  get time() {
46
- return this.getAll("time");
1505
+ return motionUtils.millisecondsToSeconds(this.currentTime);
47
1506
  }
48
- set time(time) {
49
- this.setAll("time", time);
1507
+ set time(newTime) {
1508
+ newTime = motionUtils.secondsToMilliseconds(newTime);
1509
+ this.currentTime = newTime;
1510
+ if (this.startTime === null ||
1511
+ this.holdTime !== null ||
1512
+ this.playbackSpeed === 0) {
1513
+ this.holdTime = newTime;
1514
+ }
1515
+ else if (this.driver) {
1516
+ this.startTime = this.driver.now() - newTime / this.playbackSpeed;
1517
+ }
50
1518
  }
51
1519
  get speed() {
52
- return this.getAll("speed");
1520
+ return this.playbackSpeed;
53
1521
  }
54
- set speed(speed) {
55
- this.setAll("speed", speed);
1522
+ set speed(newSpeed) {
1523
+ this.updateTime(time.now());
1524
+ const hasChanged = this.playbackSpeed !== newSpeed;
1525
+ this.playbackSpeed = newSpeed;
1526
+ if (hasChanged) {
1527
+ this.time = motionUtils.millisecondsToSeconds(this.currentTime);
1528
+ }
56
1529
  }
57
- get startTime() {
58
- return this.getAll("startTime");
1530
+ play() {
1531
+ if (this.isStopped)
1532
+ return;
1533
+ const { driver = frameloopDriver, onPlay, startTime } = this.options;
1534
+ if (!this.driver) {
1535
+ this.driver = driver((timestamp) => this.tick(timestamp));
1536
+ }
1537
+ onPlay && onPlay();
1538
+ const now = this.driver.now();
1539
+ if (this.holdTime !== null) {
1540
+ this.startTime = now - this.holdTime;
1541
+ }
1542
+ else if (this.state === "finished") {
1543
+ console.log("JSAnimation updateFinished");
1544
+ this.updateFinished();
1545
+ this.startTime = now;
1546
+ }
1547
+ else if (!this.startTime) {
1548
+ this.startTime = startTime ?? now;
1549
+ }
1550
+ if (this.state === "finished" && this.speed < 0) {
1551
+ this.startTime += this.calculatedDuration;
1552
+ }
1553
+ this.holdTime = null;
1554
+ /**
1555
+ * Set playState to running only after we've used it in
1556
+ * the previous logic.
1557
+ */
1558
+ this.state = "running";
1559
+ this.driver.start();
59
1560
  }
60
- get duration() {
61
- let max = 0;
62
- for (let i = 0; i < this.animations.length; i++) {
63
- max = Math.max(max, this.animations[i].duration);
1561
+ pause() {
1562
+ this.state = "paused";
1563
+ this.updateTime(time.now());
1564
+ this.holdTime = this.currentTime;
1565
+ }
1566
+ complete() {
1567
+ if (this.state !== "running") {
1568
+ this.play();
64
1569
  }
65
- return max;
1570
+ this.state = "finished";
1571
+ this.holdTime = null;
66
1572
  }
67
- runAll(methodName) {
68
- this.animations.forEach((controls) => controls[methodName]());
1573
+ finish() {
1574
+ this.notifyFinished();
1575
+ this.teardown();
1576
+ this.state = "finished";
1577
+ const { onComplete } = this.options;
1578
+ onComplete && onComplete();
69
1579
  }
70
- flatten() {
71
- this.runAll("flatten");
1580
+ cancel() {
1581
+ this.holdTime = null;
1582
+ this.startTime = 0;
1583
+ this.tick(0);
1584
+ this.teardown();
72
1585
  }
73
- play() {
74
- this.runAll("play");
1586
+ teardown() {
1587
+ this.state = "idle";
1588
+ this.stopDriver();
1589
+ this.startTime = this.holdTime = null;
1590
+ activeAnimations.mainThread--;
75
1591
  }
76
- pause() {
77
- this.runAll("pause");
1592
+ stopDriver() {
1593
+ if (!this.driver)
1594
+ return;
1595
+ this.driver.stop();
1596
+ this.driver = undefined;
78
1597
  }
79
- cancel() {
80
- this.runAll("cancel");
1598
+ sample(sampleTime) {
1599
+ this.startTime = 0;
1600
+ return this.tick(sampleTime, true);
81
1601
  }
82
- complete() {
83
- this.runAll("complete");
1602
+ attachTimeline(timeline) {
1603
+ this.pause();
1604
+ if (this.options.allowFlatten) {
1605
+ this.options.type = "keyframes";
1606
+ this.options.ease = "linear";
1607
+ this.initAnimation();
1608
+ }
1609
+ return timeline.observe(this);
84
1610
  }
85
1611
  }
1612
+ // Legacy function support
1613
+ function animateValue(options) {
1614
+ return new JSAnimation(options);
1615
+ }
86
1616
 
87
- class GroupAnimationWithThen extends GroupAnimation {
88
- then(onResolve, _onReject) {
89
- return this.finished.finally(onResolve).then(() => { });
1617
+ function fillWildcards(keyframes) {
1618
+ for (let i = 1; i < keyframes.length; i++) {
1619
+ keyframes[i] ?? (keyframes[i] = keyframes[i - 1]);
90
1620
  }
91
1621
  }
92
1622
 
93
- const isCSSVar = (name) => name.startsWith("--");
94
- const style$1 = {
95
- set: (element, name, value) => {
96
- isCSSVar(name)
97
- ? element.style.setProperty(name, value)
98
- : (element.style[name] = value);
99
- },
100
- get: (element, name) => {
101
- return isCSSVar(name)
102
- ? element.style.getPropertyValue(name)
103
- : element.style[name];
104
- },
1623
+ const radToDeg = (rad) => (rad * 180) / Math.PI;
1624
+ const rotate = (v) => {
1625
+ const angle = radToDeg(Math.atan2(v[1], v[0]));
1626
+ return rebaseAngle(angle);
105
1627
  };
106
-
107
- const isNotNull = (value) => value !== null;
108
- function getFinalKeyframe(keyframes, { repeat, repeatType = "loop" }, finalKeyframe) {
109
- const resolvedKeyframes = keyframes.filter(isNotNull);
110
- const index = repeat && repeatType !== "loop" && repeat % 2 === 1
111
- ? 0
112
- : resolvedKeyframes.length - 1;
113
- return !index || finalKeyframe === undefined
114
- ? resolvedKeyframes[index]
115
- : finalKeyframe;
1628
+ const matrix2dParsers = {
1629
+ x: 4,
1630
+ y: 5,
1631
+ translateX: 4,
1632
+ translateY: 5,
1633
+ scaleX: 0,
1634
+ scaleY: 3,
1635
+ scale: (v) => (Math.abs(v[0]) + Math.abs(v[3])) / 2,
1636
+ rotate,
1637
+ rotateZ: rotate,
1638
+ skewX: (v) => radToDeg(Math.atan(v[1])),
1639
+ skewY: (v) => radToDeg(Math.atan(v[2])),
1640
+ skew: (v) => (Math.abs(v[1]) + Math.abs(v[2])) / 2,
1641
+ };
1642
+ const rebaseAngle = (angle) => {
1643
+ angle = angle % 360;
1644
+ if (angle < 0)
1645
+ angle += 360;
1646
+ return angle;
1647
+ };
1648
+ const rotateZ = rotate;
1649
+ const scaleX = (v) => Math.sqrt(v[0] * v[0] + v[1] * v[1]);
1650
+ const scaleY = (v) => Math.sqrt(v[4] * v[4] + v[5] * v[5]);
1651
+ const matrix3dParsers = {
1652
+ x: 12,
1653
+ y: 13,
1654
+ z: 14,
1655
+ translateX: 12,
1656
+ translateY: 13,
1657
+ translateZ: 14,
1658
+ scaleX,
1659
+ scaleY,
1660
+ scale: (v) => (scaleX(v) + scaleY(v)) / 2,
1661
+ rotateX: (v) => rebaseAngle(radToDeg(Math.atan2(v[6], v[5]))),
1662
+ rotateY: (v) => rebaseAngle(radToDeg(Math.atan2(-v[2], v[0]))),
1663
+ rotateZ,
1664
+ rotate: rotateZ,
1665
+ skewX: (v) => radToDeg(Math.atan(v[4])),
1666
+ skewY: (v) => radToDeg(Math.atan(v[1])),
1667
+ skew: (v) => (Math.abs(v[1]) + Math.abs(v[4])) / 2,
1668
+ };
1669
+ function defaultTransformValue(name) {
1670
+ return name.includes("scale") ? 1 : 0;
116
1671
  }
117
-
118
- const supportsPartialKeyframes = /*@__PURE__*/ motionUtils.memo(() => {
119
- try {
120
- document.createElement("div").animate({ opacity: [1] });
1672
+ function parseValueFromTransform(transform, name) {
1673
+ if (!transform || transform === "none") {
1674
+ return defaultTransformValue(name);
121
1675
  }
122
- catch (e) {
123
- return false;
1676
+ const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);
1677
+ let parsers;
1678
+ let match;
1679
+ if (matrix3dMatch) {
1680
+ parsers = matrix3dParsers;
1681
+ match = matrix3dMatch;
124
1682
  }
125
- return true;
126
- });
127
-
128
- const pxValues = new Set([
129
- // Border props
130
- "borderWidth",
131
- "borderTopWidth",
132
- "borderRightWidth",
133
- "borderBottomWidth",
134
- "borderLeftWidth",
135
- "borderRadius",
136
- "radius",
137
- "borderTopLeftRadius",
138
- "borderTopRightRadius",
139
- "borderBottomRightRadius",
140
- "borderBottomLeftRadius",
141
- // Positioning props
142
- "width",
143
- "maxWidth",
144
- "height",
145
- "maxHeight",
146
- "top",
147
- "right",
148
- "bottom",
149
- "left",
150
- // Spacing props
151
- "padding",
152
- "paddingTop",
153
- "paddingRight",
154
- "paddingBottom",
155
- "paddingLeft",
156
- "margin",
157
- "marginTop",
158
- "marginRight",
159
- "marginBottom",
160
- "marginLeft",
161
- // Misc
162
- "backgroundPositionX",
163
- "backgroundPositionY",
164
- ]);
1683
+ else {
1684
+ const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u);
1685
+ parsers = matrix2dParsers;
1686
+ match = matrix2dMatch;
1687
+ }
1688
+ if (!match) {
1689
+ return defaultTransformValue(name);
1690
+ }
1691
+ const valueParser = parsers[name];
1692
+ const values = match[1].split(",").map(convertTransformToNumber);
1693
+ return typeof valueParser === "function"
1694
+ ? valueParser(values)
1695
+ : values[valueParser];
1696
+ }
1697
+ const readTransformValue = (instance, name) => {
1698
+ const { transform = "none" } = getComputedStyle(instance);
1699
+ return parseValueFromTransform(transform, name);
1700
+ };
1701
+ function convertTransformToNumber(value) {
1702
+ return parseFloat(value.trim());
1703
+ }
1704
+
1705
+ /**
1706
+ * Generate a list of every possible transform key.
1707
+ */
1708
+ const transformPropOrder = [
1709
+ "transformPerspective",
1710
+ "x",
1711
+ "y",
1712
+ "z",
1713
+ "translateX",
1714
+ "translateY",
1715
+ "translateZ",
1716
+ "scale",
1717
+ "scaleX",
1718
+ "scaleY",
1719
+ "rotate",
1720
+ "rotateX",
1721
+ "rotateY",
1722
+ "rotateZ",
1723
+ "skew",
1724
+ "skewX",
1725
+ "skewY",
1726
+ ];
1727
+ /**
1728
+ * A quick lookup for transform props.
1729
+ */
1730
+ const transformProps = /*@__PURE__*/ (() => new Set(transformPropOrder))();
165
1731
 
166
- function hydrateKeyframes(element, name, keyframes, pseudoElement) {
167
- if (!Array.isArray(keyframes)) {
168
- keyframes = [keyframes];
1732
+ const isNumOrPxType = (v) => v === number || v === px;
1733
+ const transformKeys = new Set(["x", "y", "z"]);
1734
+ const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));
1735
+ function removeNonTranslationalTransform(visualElement) {
1736
+ const removedTransforms = [];
1737
+ nonTranslationalTransformKeys.forEach((key) => {
1738
+ const value = visualElement.getValue(key);
1739
+ if (value !== undefined) {
1740
+ removedTransforms.push([key, value.get()]);
1741
+ value.set(key.startsWith("scale") ? 1 : 0);
1742
+ }
1743
+ });
1744
+ return removedTransforms;
1745
+ }
1746
+ const positionalValues = {
1747
+ // Dimensions
1748
+ width: ({ x }, { paddingLeft = "0", paddingRight = "0" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),
1749
+ height: ({ y }, { paddingTop = "0", paddingBottom = "0" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),
1750
+ top: (_bbox, { top }) => parseFloat(top),
1751
+ left: (_bbox, { left }) => parseFloat(left),
1752
+ bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),
1753
+ right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),
1754
+ // Transform
1755
+ x: (_bbox, { transform }) => parseValueFromTransform(transform, "x"),
1756
+ y: (_bbox, { transform }) => parseValueFromTransform(transform, "y"),
1757
+ };
1758
+ // Alias translate longform names
1759
+ positionalValues.translateX = positionalValues.x;
1760
+ positionalValues.translateY = positionalValues.y;
1761
+
1762
+ const toResolve = new Set();
1763
+ let isScheduled = false;
1764
+ let anyNeedsMeasurement = false;
1765
+ let isForced = false;
1766
+ function measureAllKeyframes() {
1767
+ if (anyNeedsMeasurement) {
1768
+ const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement);
1769
+ const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element));
1770
+ const transformsToRestore = new Map();
1771
+ /**
1772
+ * Write pass
1773
+ * If we're measuring elements we want to remove bounding box-changing transforms.
1774
+ */
1775
+ elementsToMeasure.forEach((element) => {
1776
+ const removedTransforms = removeNonTranslationalTransform(element);
1777
+ if (!removedTransforms.length)
1778
+ return;
1779
+ transformsToRestore.set(element, removedTransforms);
1780
+ element.render();
1781
+ });
1782
+ // Read
1783
+ resolversToMeasure.forEach((resolver) => resolver.measureInitialState());
1784
+ // Write
1785
+ elementsToMeasure.forEach((element) => {
1786
+ element.render();
1787
+ const restore = transformsToRestore.get(element);
1788
+ if (restore) {
1789
+ restore.forEach(([key, value]) => {
1790
+ element.getValue(key)?.set(value);
1791
+ });
1792
+ }
1793
+ });
1794
+ // Read
1795
+ resolversToMeasure.forEach((resolver) => resolver.measureEndState());
1796
+ // Write
1797
+ resolversToMeasure.forEach((resolver) => {
1798
+ if (resolver.suspendedScrollY !== undefined) {
1799
+ window.scrollTo(0, resolver.suspendedScrollY);
1800
+ }
1801
+ });
169
1802
  }
170
- for (let i = 0; i < keyframes.length; i++) {
171
- if (keyframes[i] === null) {
172
- keyframes[i] =
173
- i === 0 && !pseudoElement
174
- ? style$1.get(element, name)
175
- : keyframes[i - 1];
1803
+ anyNeedsMeasurement = false;
1804
+ isScheduled = false;
1805
+ toResolve.forEach((resolver) => resolver.complete(isForced));
1806
+ toResolve.clear();
1807
+ }
1808
+ function readAllKeyframes() {
1809
+ toResolve.forEach((resolver) => {
1810
+ resolver.readKeyframes();
1811
+ if (resolver.needsMeasurement) {
1812
+ anyNeedsMeasurement = true;
176
1813
  }
177
- if (typeof keyframes[i] === "number" && pxValues.has(name)) {
178
- keyframes[i] = keyframes[i] + "px";
1814
+ });
1815
+ }
1816
+ function flushKeyframeResolvers() {
1817
+ isForced = true;
1818
+ readAllKeyframes();
1819
+ measureAllKeyframes();
1820
+ isForced = false;
1821
+ }
1822
+ class KeyframeResolver {
1823
+ constructor(unresolvedKeyframes, onComplete, name, motionValue, element, isAsync = false) {
1824
+ /**
1825
+ * Track whether this resolver has completed. Once complete, it never
1826
+ * needs to attempt keyframe resolution again.
1827
+ */
1828
+ this.isComplete = false;
1829
+ /**
1830
+ * Track whether this resolver is async. If it is, it'll be added to the
1831
+ * resolver queue and flushed in the next frame. Resolvers that aren't going
1832
+ * to trigger read/write thrashing don't need to be async.
1833
+ */
1834
+ this.isAsync = false;
1835
+ /**
1836
+ * Track whether this resolver needs to perform a measurement
1837
+ * to resolve its keyframes.
1838
+ */
1839
+ this.needsMeasurement = false;
1840
+ /**
1841
+ * Track whether this resolver is currently scheduled to resolve
1842
+ * to allow it to be cancelled and resumed externally.
1843
+ */
1844
+ this.isScheduled = false;
1845
+ this.unresolvedKeyframes = [...unresolvedKeyframes];
1846
+ this.onComplete = onComplete;
1847
+ this.name = name;
1848
+ this.motionValue = motionValue;
1849
+ this.element = element;
1850
+ this.isAsync = isAsync;
1851
+ }
1852
+ scheduleResolve() {
1853
+ this.isScheduled = true;
1854
+ if (this.isAsync) {
1855
+ toResolve.add(this);
1856
+ if (!isScheduled) {
1857
+ isScheduled = true;
1858
+ frame.read(readAllKeyframes);
1859
+ frame.resolveKeyframes(measureAllKeyframes);
1860
+ }
1861
+ }
1862
+ else {
1863
+ this.readKeyframes();
1864
+ this.complete();
1865
+ }
1866
+ }
1867
+ readKeyframes() {
1868
+ const { unresolvedKeyframes, name, element, motionValue } = this;
1869
+ // If initial keyframe is null we need to read it from the DOM
1870
+ if (unresolvedKeyframes[0] === null) {
1871
+ const currentValue = motionValue?.get();
1872
+ // TODO: This doesn't work if the final keyframe is a wildcard
1873
+ const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
1874
+ if (currentValue !== undefined) {
1875
+ unresolvedKeyframes[0] = currentValue;
1876
+ }
1877
+ else if (element && name) {
1878
+ const valueAsRead = element.readValue(name, finalKeyframe);
1879
+ if (valueAsRead !== undefined && valueAsRead !== null) {
1880
+ unresolvedKeyframes[0] = valueAsRead;
1881
+ }
1882
+ }
1883
+ if (unresolvedKeyframes[0] === undefined) {
1884
+ unresolvedKeyframes[0] = finalKeyframe;
1885
+ }
1886
+ if (motionValue && currentValue === undefined) {
1887
+ motionValue.set(unresolvedKeyframes[0]);
1888
+ }
179
1889
  }
1890
+ fillWildcards(unresolvedKeyframes);
180
1891
  }
181
- if (!pseudoElement && !supportsPartialKeyframes() && keyframes.length < 2) {
182
- keyframes.unshift(style$1.get(element, name));
1892
+ setFinalKeyframe() { }
1893
+ measureInitialState() { }
1894
+ renderEndStyles() { }
1895
+ measureEndState() { }
1896
+ complete(isForced = false) {
1897
+ this.isComplete = true;
1898
+ this.onComplete(this.unresolvedKeyframes, this.finalKeyframe, isForced);
1899
+ toResolve.delete(this);
1900
+ }
1901
+ cancel() {
1902
+ if (!this.isComplete) {
1903
+ this.isScheduled = false;
1904
+ toResolve.delete(this);
1905
+ }
1906
+ }
1907
+ resume() {
1908
+ if (!this.isComplete)
1909
+ this.scheduleResolve();
183
1910
  }
184
- return keyframes;
185
1911
  }
186
1912
 
187
- const activeAnimations = {
188
- layout: 0,
189
- mainThread: 0,
190
- waapi: 0,
191
- };
1913
+ const isCSSVar = (name) => name.startsWith("--");
192
1914
 
193
- const statsBuffer = {
194
- value: null,
195
- addProjectionMetrics: null,
196
- };
1915
+ function setStyle(element, name, value) {
1916
+ isCSSVar(name)
1917
+ ? element.style.setProperty(name, value)
1918
+ : (element.style[name] = value);
1919
+ }
197
1920
 
198
- const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number";
1921
+ const supportsScrollTimeline = /* @__PURE__ */ motionUtils.memo(() => window.ScrollTimeline !== undefined);
199
1922
 
200
1923
  /**
201
1924
  * Add the ability for test suites to manually set support flags
@@ -220,17 +1943,6 @@ const supportsLinearEasing = /*@__PURE__*/ memoSupports(() => {
220
1943
  return true;
221
1944
  }, "linearEasing");
222
1945
 
223
- const generateLinearEasing = (easing, duration, // as milliseconds
224
- resolution = 10 // as milliseconds
225
- ) => {
226
- let points = "";
227
- const numPoints = Math.max(Math.round(duration / resolution), 2);
228
- for (let i = 0; i < numPoints; i++) {
229
- points += easing(i / (numPoints - 1)) + ", ";
230
- }
231
- return `linear(${points.substring(0, points.length - 2)})`;
232
- };
233
-
234
1946
  const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
235
1947
 
236
1948
  const supportedWaapiEasing = {
@@ -249,10 +1961,12 @@ function mapEasingToNativeEasing(easing, duration) {
249
1961
  if (!easing) {
250
1962
  return undefined;
251
1963
  }
252
- else if (typeof easing === "function" && supportsLinearEasing()) {
253
- return generateLinearEasing(easing, duration);
1964
+ else if (typeof easing === "function") {
1965
+ return supportsLinearEasing()
1966
+ ? generateLinearEasing(easing, duration)
1967
+ : "ease-out";
254
1968
  }
255
- else if (isBezierDefinition(easing)) {
1969
+ else if (motionUtils.isBezierDefinition(easing)) {
256
1970
  return cubicBezierAsString(easing);
257
1971
  }
258
1972
  else if (Array.isArray(easing)) {
@@ -264,7 +1978,7 @@ function mapEasingToNativeEasing(easing, duration) {
264
1978
  }
265
1979
  }
266
1980
 
267
- function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duration = 300, repeat = 0, repeatType = "loop", ease = "easeInOut", times, } = {}, pseudoElement = undefined) {
1981
+ function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duration = 300, repeat = 0, repeatType = "loop", ease = "easeOut", times, } = {}, pseudoElement = undefined) {
268
1982
  const keyframeOptions = {
269
1983
  [valueName]: keyframes,
270
1984
  };
@@ -279,15 +1993,17 @@ function startWaapiAnimation(element, valueName, keyframes, { delay = 0, duratio
279
1993
  if (statsBuffer.value) {
280
1994
  activeAnimations.waapi++;
281
1995
  }
282
- const animation = element.animate(keyframeOptions, {
1996
+ const options = {
283
1997
  delay,
284
1998
  duration,
285
1999
  easing: !Array.isArray(easing) ? easing : "linear",
286
2000
  fill: "both",
287
2001
  iterations: repeat + 1,
288
2002
  direction: repeatType === "reverse" ? "alternate" : "normal",
289
- pseudoElement,
290
- });
2003
+ };
2004
+ if (pseudoElement)
2005
+ options.pseudoElement = pseudoElement;
2006
+ const animation = element.animate(keyframeOptions, options);
291
2007
  if (statsBuffer.value) {
292
2008
  animation.finished.finally(() => {
293
2009
  activeAnimations.waapi--;
@@ -301,7 +2017,7 @@ function isGenerator(type) {
301
2017
  }
302
2018
 
303
2019
  function applyGeneratorOptions({ type, ...options }) {
304
- if (isGenerator(type)) {
2020
+ if (isGenerator(type) && supportsLinearEasing()) {
305
2021
  return type.applyToOptions(options);
306
2022
  }
307
2023
  else {
@@ -311,62 +2027,476 @@ function applyGeneratorOptions({ type, ...options }) {
311
2027
  return options;
312
2028
  }
313
2029
 
314
- const animationMaps = new WeakMap();
315
- const animationMapKey = (name, pseudoElement) => `${name}:${pseudoElement}`;
316
- function getAnimationMap(element) {
317
- const map = animationMaps.get(element) || new Map();
318
- animationMaps.set(element, map);
319
- return map;
320
- }
321
2030
  /**
322
2031
  * NativeAnimation implements AnimationPlaybackControls for the browser's Web Animations API.
323
2032
  */
324
- class NativeAnimation {
2033
+ class NativeAnimation extends WithPromise {
325
2034
  constructor(options) {
326
- /**
327
- * If we already have an animation, we don't need to instantiate one
328
- * and can just use this as a controls interface.
329
- */
330
- if ("animation" in options) {
331
- this.animation = options.animation;
2035
+ super();
2036
+ this.finishedTime = null;
2037
+ this.isStopped = false;
2038
+ if (!options)
332
2039
  return;
333
- }
334
- const { element, name, keyframes: unresolvedKeyframes, pseudoElement, allowFlatten = false, } = options;
335
- let { transition } = options;
2040
+ const { element, name, keyframes, pseudoElement, allowFlatten = false, finalKeyframe, } = options;
336
2041
  this.isPseudoElement = Boolean(pseudoElement);
337
2042
  this.allowFlatten = allowFlatten;
338
- /**
339
- * Stop any existing animations on the element before reading existing keyframes.
340
- *
341
- * TODO: Check for VisualElement before using animation state. This is a fallback
342
- * for mini animate(). Do this when implementing NativeAnimationExtended.
343
- */
344
- const animationMap = getAnimationMap(element);
345
- const key = animationMapKey(name, pseudoElement || "");
346
- const currentAnimation = animationMap.get(key);
347
- currentAnimation && currentAnimation.stop();
348
- /**
349
- * TODO: If these keyframes aren't correctly hydrated then we want to throw
350
- * run an instant animation.
351
- */
352
- const keyframes = hydrateKeyframes(element, name, unresolvedKeyframes, pseudoElement);
353
- motionUtils.invariant(typeof transition.type !== "string", `animateMini doesn't support "type" as a string. Did you mean to import { spring } from "motion"?`);
354
- transition = applyGeneratorOptions(transition);
2043
+ this.options = options;
2044
+ motionUtils.invariant(typeof options.type !== "string", `animateMini doesn't support "type" as a string. Did you mean to import { spring } from "motion"?`);
2045
+ const transition = applyGeneratorOptions(options);
355
2046
  this.animation = startWaapiAnimation(element, name, keyframes, transition, pseudoElement);
356
2047
  if (transition.autoplay === false) {
357
2048
  this.animation.pause();
358
2049
  }
359
- this.removeAnimation = () => animationMap.delete(key);
360
2050
  this.animation.onfinish = () => {
2051
+ this.finishedTime = this.time;
361
2052
  if (!pseudoElement) {
362
- style$1.set(element, name, getFinalKeyframe(keyframes, transition));
363
- this.cancel();
2053
+ const keyframe = getFinalKeyframe(keyframes, this.options, finalKeyframe, this.speed);
2054
+ if (this.updateMotionValue) {
2055
+ this.updateMotionValue(keyframe);
2056
+ }
2057
+ else {
2058
+ /**
2059
+ * If we can, we want to commit the final style as set by the user,
2060
+ * rather than the computed keyframe value supplied by the animation.
2061
+ */
2062
+ setStyle(element, name, keyframe);
2063
+ }
2064
+ this.animation.cancel();
2065
+ }
2066
+ this.notifyFinished();
2067
+ };
2068
+ }
2069
+ play() {
2070
+ if (this.isStopped)
2071
+ return;
2072
+ this.animation.play();
2073
+ if (this.state === "finished") {
2074
+ this.updateFinished();
2075
+ }
2076
+ }
2077
+ pause() {
2078
+ this.animation.pause();
2079
+ }
2080
+ complete() {
2081
+ this.animation.finish?.();
2082
+ }
2083
+ cancel() {
2084
+ try {
2085
+ this.animation.cancel();
2086
+ }
2087
+ catch (e) { }
2088
+ }
2089
+ stop() {
2090
+ if (this.isStopped)
2091
+ return;
2092
+ this.isStopped = true;
2093
+ const { state } = this;
2094
+ if (state === "idle" || state === "finished") {
2095
+ return;
2096
+ }
2097
+ if (this.updateMotionValue) {
2098
+ this.updateMotionValue();
2099
+ }
2100
+ else {
2101
+ this.commitStyles();
2102
+ }
2103
+ if (!this.isPseudoElement)
2104
+ this.cancel();
2105
+ }
2106
+ /**
2107
+ * WAAPI doesn't natively have any interruption capabilities.
2108
+ *
2109
+ * In this method, we commit styles back to the DOM before cancelling
2110
+ * the animation.
2111
+ *
2112
+ * This is designed to be overridden by NativeAnimationExtended, which
2113
+ * will create a renderless JS animation and sample it twice to calculate
2114
+ * its current value, "previous" value, and therefore allow
2115
+ * Motion to also correctly calculate velocity for any subsequent animation
2116
+ * while deferring the commit until the next animation frame.
2117
+ */
2118
+ commitStyles() {
2119
+ if (!this.isPseudoElement) {
2120
+ this.animation.commitStyles?.();
2121
+ }
2122
+ }
2123
+ get duration() {
2124
+ const duration = this.animation.effect?.getComputedTiming?.().duration || 0;
2125
+ return motionUtils.millisecondsToSeconds(Number(duration));
2126
+ }
2127
+ get time() {
2128
+ return motionUtils.millisecondsToSeconds(Number(this.animation.currentTime) || 0);
2129
+ }
2130
+ set time(newTime) {
2131
+ this.finishedTime = null;
2132
+ this.animation.currentTime = motionUtils.secondsToMilliseconds(newTime);
2133
+ }
2134
+ /**
2135
+ * The playback speed of the animation.
2136
+ * 1 = normal speed, 2 = double speed, 0.5 = half speed.
2137
+ */
2138
+ get speed() {
2139
+ return this.animation.playbackRate;
2140
+ }
2141
+ set speed(newSpeed) {
2142
+ // Allow backwards playback after finishing
2143
+ if (newSpeed < 0)
2144
+ this.finishedTime = null;
2145
+ this.animation.playbackRate = newSpeed;
2146
+ }
2147
+ get state() {
2148
+ return this.finishedTime !== null
2149
+ ? "finished"
2150
+ : this.animation.playState;
2151
+ }
2152
+ get startTime() {
2153
+ return Number(this.animation.startTime);
2154
+ }
2155
+ set startTime(newStartTime) {
2156
+ this.animation.startTime = newStartTime;
2157
+ }
2158
+ /**
2159
+ * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
2160
+ */
2161
+ attachTimeline({ timeline, observe }) {
2162
+ if (this.allowFlatten) {
2163
+ this.animation.effect?.updateTiming({ easing: "linear" });
2164
+ }
2165
+ this.animation.onfinish = null;
2166
+ if (supportsScrollTimeline()) {
2167
+ this.animation.timeline = timeline;
2168
+ return motionUtils.noop;
2169
+ }
2170
+ else {
2171
+ return observe(this);
2172
+ }
2173
+ }
2174
+ }
2175
+
2176
+ const unsupportedEasingFunctions = {
2177
+ anticipate: motionUtils.anticipate,
2178
+ backInOut: motionUtils.backInOut,
2179
+ circInOut: motionUtils.circInOut,
2180
+ };
2181
+ function isUnsupportedEase(key) {
2182
+ return key in unsupportedEasingFunctions;
2183
+ }
2184
+ function replaceStringEasing(transition) {
2185
+ if (typeof transition.ease === "string" &&
2186
+ isUnsupportedEase(transition.ease)) {
2187
+ transition.ease = unsupportedEasingFunctions[transition.ease];
2188
+ }
2189
+ }
2190
+
2191
+ /**
2192
+ * 10ms is chosen here as it strikes a balance between smooth
2193
+ * results (more than one keyframe per frame at 60fps) and
2194
+ * keyframe quantity.
2195
+ */
2196
+ const sampleDelta = 10; //ms
2197
+ class NativeAnimationExtended extends NativeAnimation {
2198
+ constructor(options) {
2199
+ /**
2200
+ * The base NativeAnimation function only supports a subset
2201
+ * of Motion easings, and WAAPI also only supports some
2202
+ * easing functions via string/cubic-bezier definitions.
2203
+ *
2204
+ * This function replaces those unsupported easing functions
2205
+ * with a JS easing function. This will later get compiled
2206
+ * to a linear() easing function.
2207
+ */
2208
+ replaceStringEasing(options);
2209
+ /**
2210
+ * Ensure we replace the transition type with a generator function
2211
+ * before passing to WAAPI.
2212
+ *
2213
+ * TODO: Does this have a better home? It could be shared with
2214
+ * JSAnimation.
2215
+ */
2216
+ replaceTransitionType(options);
2217
+ super(options);
2218
+ if (options.startTime) {
2219
+ this.startTime = options.startTime;
2220
+ }
2221
+ this.options = options;
2222
+ }
2223
+ /**
2224
+ * WAAPI doesn't natively have any interruption capabilities.
2225
+ *
2226
+ * Rather than read commited styles back out of the DOM, we can
2227
+ * create a renderless JS animation and sample it twice to calculate
2228
+ * its current value, "previous" value, and therefore allow
2229
+ * Motion to calculate velocity for any subsequent animation.
2230
+ */
2231
+ updateMotionValue(value) {
2232
+ const { motionValue, onUpdate, onComplete, element, ...options } = this.options;
2233
+ if (!motionValue)
2234
+ return;
2235
+ if (value !== undefined) {
2236
+ motionValue.set(value);
2237
+ return;
2238
+ }
2239
+ const sampleAnimation = new JSAnimation({
2240
+ ...options,
2241
+ autoplay: false,
2242
+ });
2243
+ const sampleTime = motionUtils.secondsToMilliseconds(this.finishedTime ?? this.time);
2244
+ motionValue.setWithVelocity(sampleAnimation.sample(sampleTime - sampleDelta).value, sampleAnimation.sample(sampleTime).value, sampleDelta);
2245
+ sampleAnimation.stop();
2246
+ }
2247
+ }
2248
+
2249
+ /**
2250
+ * Check if a value is animatable. Examples:
2251
+ *
2252
+ * ✅: 100, "100px", "#fff"
2253
+ * ❌: "block", "url(2.jpg)"
2254
+ * @param value
2255
+ *
2256
+ * @internal
2257
+ */
2258
+ const isAnimatable = (value, name) => {
2259
+ // If the list of keys tat might be non-animatable grows, replace with Set
2260
+ if (name === "zIndex")
2261
+ return false;
2262
+ // If it's a number or a keyframes array, we can animate it. We might at some point
2263
+ // need to do a deep isAnimatable check of keyframes, or let Popmotion handle this,
2264
+ // but for now lets leave it like this for performance reasons
2265
+ if (typeof value === "number" || Array.isArray(value))
2266
+ return true;
2267
+ if (typeof value === "string" && // It's animatable if we have a string
2268
+ (complex.test(value) || value === "0") && // And it contains numbers and/or colors
2269
+ !value.startsWith("url(") // Unless it starts with "url("
2270
+ ) {
2271
+ return true;
2272
+ }
2273
+ return false;
2274
+ };
2275
+
2276
+ function hasKeyframesChanged(keyframes) {
2277
+ const current = keyframes[0];
2278
+ if (keyframes.length === 1)
2279
+ return true;
2280
+ for (let i = 0; i < keyframes.length; i++) {
2281
+ if (keyframes[i] !== current)
2282
+ return true;
2283
+ }
2284
+ }
2285
+ function canAnimate(keyframes, name, type, velocity) {
2286
+ /**
2287
+ * Check if we're able to animate between the start and end keyframes,
2288
+ * and throw a warning if we're attempting to animate between one that's
2289
+ * animatable and another that isn't.
2290
+ */
2291
+ const originKeyframe = keyframes[0];
2292
+ if (originKeyframe === null)
2293
+ return false;
2294
+ /**
2295
+ * These aren't traditionally animatable but we do support them.
2296
+ * In future we could look into making this more generic or replacing
2297
+ * this function with mix() === mixImmediate
2298
+ */
2299
+ if (name === "display" || name === "visibility")
2300
+ return true;
2301
+ const targetKeyframe = keyframes[keyframes.length - 1];
2302
+ const isOriginAnimatable = isAnimatable(originKeyframe, name);
2303
+ const isTargetAnimatable = isAnimatable(targetKeyframe, name);
2304
+ motionUtils.warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". ${originKeyframe} is not an animatable value - to enable this animation set ${originKeyframe} to a value animatable to ${targetKeyframe} via the \`style\` property.`);
2305
+ // Always skip if any of these are true
2306
+ if (!isOriginAnimatable || !isTargetAnimatable) {
2307
+ return false;
2308
+ }
2309
+ return (hasKeyframesChanged(keyframes) ||
2310
+ ((type === "spring" || isGenerator(type)) && velocity));
2311
+ }
2312
+
2313
+ /**
2314
+ * A list of values that can be hardware-accelerated.
2315
+ */
2316
+ const acceleratedValues$1 = new Set([
2317
+ "opacity",
2318
+ "clipPath",
2319
+ "filter",
2320
+ "transform",
2321
+ // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved
2322
+ // or until we implement support for linear() easing.
2323
+ // "background-color"
2324
+ ]);
2325
+ const supportsWaapi = /*@__PURE__*/ motionUtils.memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
2326
+ function supportsBrowserAnimation(options) {
2327
+ const { motionValue, name, repeatDelay, repeatType, damping, type } = options;
2328
+ if (!motionValue ||
2329
+ !motionValue.owner ||
2330
+ !(motionValue.owner.current instanceof HTMLElement)) {
2331
+ return false;
2332
+ }
2333
+ const { onUpdate, transformTemplate } = motionValue.owner.getProps();
2334
+ return (supportsWaapi() &&
2335
+ name &&
2336
+ acceleratedValues$1.has(name) &&
2337
+ (name !== "transform" || !transformTemplate) &&
2338
+ /**
2339
+ * If we're outputting values to onUpdate then we can't use WAAPI as there's
2340
+ * no way to read the value from WAAPI every frame.
2341
+ */
2342
+ !onUpdate &&
2343
+ !repeatDelay &&
2344
+ repeatType !== "mirror" &&
2345
+ damping !== 0 &&
2346
+ type !== "inertia");
2347
+ }
2348
+
2349
+ /**
2350
+ * Maximum time allowed between an animation being created and it being
2351
+ * resolved for us to use the latter as the start time.
2352
+ *
2353
+ * This is to ensure that while we prefer to "start" an animation as soon
2354
+ * as it's triggered, we also want to avoid a visual jump if there's a big delay
2355
+ * between these two moments.
2356
+ */
2357
+ const MAX_RESOLVE_DELAY = 40;
2358
+ class AsyncMotionValueAnimation extends WithPromise {
2359
+ constructor({ autoplay = true, delay = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", keyframes, name, motionValue, element, ...options }) {
2360
+ super();
2361
+ /**
2362
+ * Bound to support return animation.stop pattern
2363
+ */
2364
+ this.stop = () => {
2365
+ if (this._animation) {
2366
+ this._animation.stop();
2367
+ this.stopTimeline?.();
2368
+ }
2369
+ else {
2370
+ this.keyframeResolver?.cancel();
364
2371
  }
365
2372
  };
2373
+ this.createdAt = time.now();
2374
+ const optionsWithDefaults = {
2375
+ autoplay,
2376
+ delay,
2377
+ type,
2378
+ repeat,
2379
+ repeatDelay,
2380
+ repeatType,
2381
+ name,
2382
+ motionValue,
2383
+ element,
2384
+ ...options,
2385
+ };
2386
+ const KeyframeResolver$1 = element?.KeyframeResolver || KeyframeResolver;
2387
+ this.keyframeResolver = new KeyframeResolver$1(keyframes, (resolvedKeyframes, finalKeyframe, forced) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe, optionsWithDefaults, !forced), name, motionValue, element);
2388
+ this.keyframeResolver?.scheduleResolve();
2389
+ }
2390
+ onKeyframesResolved(keyframes, finalKeyframe, options, sync) {
2391
+ this.keyframeResolver = undefined;
2392
+ const { name, type, velocity, delay, isHandoff, onUpdate, onComplete } = options;
2393
+ this.resolvedAt = time.now();
2394
+ /**
2395
+ * If we can't animate this value with the resolved keyframes
2396
+ * then we should complete it immediately.
2397
+ */
2398
+ if (!canAnimate(keyframes, name, type, velocity)) {
2399
+ if (motionUtils.MotionGlobalConfig.instantAnimations || !delay) {
2400
+ onUpdate?.(getFinalKeyframe(keyframes, options, finalKeyframe));
2401
+ }
2402
+ keyframes[0] = keyframes[keyframes.length - 1];
2403
+ options.duration = 0;
2404
+ options.repeat = 0;
2405
+ }
2406
+ /**
2407
+ * Resolve startTime for the animation.
2408
+ *
2409
+ * This method uses the createdAt and resolvedAt to calculate the
2410
+ * animation startTime. *Ideally*, we would use the createdAt time as t=0
2411
+ * as the following frame would then be the first frame of the animation in
2412
+ * progress, which would feel snappier.
2413
+ *
2414
+ * However, if there's a delay (main thread work) between the creation of
2415
+ * the animation and the first commited frame, we prefer to use resolvedAt
2416
+ * to avoid a sudden jump into the animation.
2417
+ */
2418
+ const startTime = sync
2419
+ ? !this.resolvedAt
2420
+ ? this.createdAt
2421
+ : this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY
2422
+ ? this.resolvedAt
2423
+ : this.createdAt
2424
+ : undefined;
2425
+ const resolvedOptions = {
2426
+ startTime,
2427
+ finalKeyframe,
2428
+ ...options,
2429
+ keyframes,
2430
+ };
366
2431
  /**
367
- * TODO: Check for VisualElement before using animation state.
2432
+ * Animate via WAAPI if possible. If this is a handoff animation, the optimised animation will be running via
2433
+ * WAAPI. Therefore, this animation must be JS to ensure it runs "under" the
2434
+ * optimised animation.
368
2435
  */
369
- animationMap.set(key, this);
2436
+ const animation = !isHandoff && supportsBrowserAnimation(resolvedOptions)
2437
+ ? new NativeAnimationExtended({
2438
+ ...resolvedOptions,
2439
+ element: resolvedOptions.motionValue.owner.current,
2440
+ })
2441
+ : new JSAnimation(resolvedOptions);
2442
+ animation.finished
2443
+ .then(() => {
2444
+ onComplete?.();
2445
+ this.notifyFinished();
2446
+ })
2447
+ .catch(motionUtils.noop);
2448
+ if (this.pendingTimeline) {
2449
+ this.stopTimeline = animation.attachTimeline(this.pendingTimeline);
2450
+ this.pendingTimeline = undefined;
2451
+ }
2452
+ this._animation = animation;
2453
+ }
2454
+ get finished() {
2455
+ if (!this._animation) {
2456
+ return this._finished;
2457
+ }
2458
+ else {
2459
+ return this.animation.finished;
2460
+ }
2461
+ }
2462
+ then(onResolve, _onReject) {
2463
+ return this.finished.finally(onResolve).then(() => { });
2464
+ }
2465
+ get animation() {
2466
+ if (!this._animation) {
2467
+ flushKeyframeResolvers();
2468
+ }
2469
+ return this._animation;
2470
+ }
2471
+ get duration() {
2472
+ return this.animation.duration;
2473
+ }
2474
+ get time() {
2475
+ return this.animation.time;
2476
+ }
2477
+ set time(newTime) {
2478
+ this.animation.time = newTime;
2479
+ }
2480
+ get speed() {
2481
+ return this.animation.speed;
2482
+ }
2483
+ get state() {
2484
+ return this.animation.state;
2485
+ }
2486
+ set speed(newSpeed) {
2487
+ this.animation.speed = newSpeed;
2488
+ }
2489
+ get startTime() {
2490
+ return this.animation.startTime;
2491
+ }
2492
+ attachTimeline(timeline) {
2493
+ if (this._animation) {
2494
+ this.stopTimeline = this.animation.attachTimeline(timeline);
2495
+ }
2496
+ else {
2497
+ this.pendingTimeline = timeline;
2498
+ }
2499
+ return () => this.stop();
370
2500
  }
371
2501
  play() {
372
2502
  this.animation.play();
@@ -375,90 +2505,145 @@ class NativeAnimation {
375
2505
  this.animation.pause();
376
2506
  }
377
2507
  complete() {
378
- this.animation.finish();
2508
+ console.log("async animation complete");
2509
+ this.animation.complete();
379
2510
  }
380
2511
  cancel() {
381
- try {
382
- this.animation.cancel();
383
- }
384
- catch (e) { }
385
- this.removeAnimation();
2512
+ this.animation.cancel();
386
2513
  }
387
- stop() {
388
- const { state } = this;
389
- if (state === "idle" || state === "finished") {
390
- return;
391
- }
392
- this.commitStyles();
393
- this.cancel();
2514
+ }
2515
+
2516
+ class GroupAnimation {
2517
+ constructor(animations) {
2518
+ // Bound to accomadate common `return animation.stop` pattern
2519
+ this.stop = () => this.runAll("stop");
2520
+ this.animations = animations.filter(Boolean);
2521
+ }
2522
+ get finished() {
2523
+ return Promise.all(this.animations.map((animation) => animation.finished));
394
2524
  }
395
2525
  /**
396
- * WAAPI doesn't natively have any interruption capabilities.
397
- *
398
- * In this method, we commit styles back to the DOM before cancelling
399
- * the animation.
400
- *
401
- * This is designed to be overridden by NativeAnimationExtended, which
402
- * will create a renderless JS animation and sample it twice to calculate
403
- * its current value, "previous" value, and therefore allow
404
- * Motion to also correctly calculate velocity for any subsequent animation
405
- * while deferring the commit until the next animation frame.
2526
+ * TODO: Filter out cancelled or stopped animations before returning
406
2527
  */
407
- commitStyles() {
408
- if (!this.isPseudoElement) {
409
- this.animation.commitStyles?.();
2528
+ getAll(propName) {
2529
+ return this.animations[0][propName];
2530
+ }
2531
+ setAll(propName, newValue) {
2532
+ for (let i = 0; i < this.animations.length; i++) {
2533
+ this.animations[i][propName] = newValue;
410
2534
  }
411
2535
  }
412
- get duration() {
413
- const duration = this.animation.effect?.getComputedTiming().duration || 0;
414
- return motionUtils.millisecondsToSeconds(Number(duration));
2536
+ attachTimeline(timeline) {
2537
+ const subscriptions = this.animations.map((animation) => animation.attachTimeline(timeline));
2538
+ return () => {
2539
+ subscriptions.forEach((cancel, i) => {
2540
+ cancel && cancel();
2541
+ this.animations[i].stop();
2542
+ });
2543
+ };
415
2544
  }
416
2545
  get time() {
417
- return motionUtils.millisecondsToSeconds(Number(this.animation.currentTime) || 0);
2546
+ return this.getAll("time");
418
2547
  }
419
- set time(newTime) {
420
- this.animation.currentTime = motionUtils.secondsToMilliseconds(newTime);
2548
+ set time(time) {
2549
+ this.setAll("time", time);
421
2550
  }
422
- /**
423
- * The playback speed of the animation.
424
- * 1 = normal speed, 2 = double speed, 0.5 = half speed.
425
- */
426
2551
  get speed() {
427
- return this.animation.playbackRate;
2552
+ return this.getAll("speed");
428
2553
  }
429
- set speed(newSpeed) {
430
- this.animation.playbackRate = newSpeed;
2554
+ set speed(speed) {
2555
+ this.setAll("speed", speed);
431
2556
  }
432
2557
  get state() {
433
- return this.animation.playState;
2558
+ return this.getAll("state");
434
2559
  }
435
2560
  get startTime() {
436
- return Number(this.animation.startTime);
437
- }
438
- get finished() {
439
- return this.animation.finished;
2561
+ return this.getAll("startTime");
440
2562
  }
441
- flatten() {
442
- if (this.allowFlatten) {
443
- this.animation.effect?.updateTiming({ easing: "linear" });
2563
+ get duration() {
2564
+ let max = 0;
2565
+ for (let i = 0; i < this.animations.length; i++) {
2566
+ max = Math.max(max, this.animations[i].duration);
444
2567
  }
2568
+ return max;
445
2569
  }
446
- /**
447
- * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
448
- */
449
- attachTimeline(timeline) {
450
- this.animation.timeline = timeline;
451
- this.animation.onfinish = null;
452
- return motionUtils.noop;
2570
+ runAll(methodName) {
2571
+ this.animations.forEach((controls) => controls[methodName]());
453
2572
  }
454
- /**
455
- * Allows the animation to be awaited.
456
- *
457
- * @deprecated Use `finished` instead.
458
- */
459
- then(onResolve, onReject) {
460
- return this.finished.then(onResolve).catch(onReject);
2573
+ play() {
2574
+ this.runAll("play");
2575
+ }
2576
+ pause() {
2577
+ this.runAll("pause");
2578
+ }
2579
+ cancel() {
2580
+ this.runAll("cancel");
2581
+ }
2582
+ complete() {
2583
+ this.runAll("complete");
2584
+ }
2585
+ }
2586
+
2587
+ class GroupAnimationWithThen extends GroupAnimation {
2588
+ then(onResolve, _onReject) {
2589
+ return this.finished.finally(onResolve).then(() => { });
2590
+ }
2591
+ }
2592
+
2593
+ class NativeAnimationWrapper extends NativeAnimation {
2594
+ constructor(animation) {
2595
+ super();
2596
+ this.animation = animation;
2597
+ animation.onfinish = () => {
2598
+ this.finishedTime = this.time;
2599
+ this.notifyFinished();
2600
+ };
2601
+ }
2602
+ }
2603
+
2604
+ const animationMaps = new WeakMap();
2605
+ const animationMapKey = (name, pseudoElement = "") => `${name}:${pseudoElement}`;
2606
+ function getAnimationMap(element) {
2607
+ const map = animationMaps.get(element) || new Map();
2608
+ animationMaps.set(element, map);
2609
+ return map;
2610
+ }
2611
+
2612
+ /**
2613
+ * Parse Framer's special CSS variable format into a CSS token and a fallback.
2614
+ *
2615
+ * ```
2616
+ * `var(--foo, #fff)` => [`--foo`, '#fff']
2617
+ * ```
2618
+ *
2619
+ * @param current
2620
+ */
2621
+ const splitCSSVariableRegex =
2622
+ // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words
2623
+ /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;
2624
+ function parseCSSVariable(current) {
2625
+ const match = splitCSSVariableRegex.exec(current);
2626
+ if (!match)
2627
+ return [,];
2628
+ const [, token1, token2, fallback] = match;
2629
+ return [`--${token1 ?? token2}`, fallback];
2630
+ }
2631
+ const maxDepth = 4;
2632
+ function getVariableValue(current, element, depth = 1) {
2633
+ motionUtils.invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`);
2634
+ const [token, fallback] = parseCSSVariable(current);
2635
+ // No CSS variable detected
2636
+ if (!token)
2637
+ return;
2638
+ // Attempt to read this CSS variable off the element
2639
+ const resolved = window.getComputedStyle(element).getPropertyValue(token);
2640
+ if (resolved) {
2641
+ const trimmed = resolved.trim();
2642
+ return motionUtils.isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
461
2643
  }
2644
+ return isCSSVariableToken(fallback)
2645
+ ? getVariableValue(fallback, element, depth + 1)
2646
+ : fallback;
462
2647
  }
463
2648
 
464
2649
  function getValueTransition(transition, key) {
@@ -467,244 +2652,415 @@ function getValueTransition(transition, key) {
467
2652
  transition);
468
2653
  }
469
2654
 
2655
+ const positionalKeys = new Set([
2656
+ "width",
2657
+ "height",
2658
+ "top",
2659
+ "left",
2660
+ "right",
2661
+ "bottom",
2662
+ ...transformPropOrder,
2663
+ ]);
2664
+
470
2665
  /**
471
- * Implement a practical max duration for keyframe generation
472
- * to prevent infinite loops
2666
+ * ValueType for "auto"
473
2667
  */
474
- const maxGeneratorDuration = 20000;
475
- function calcGeneratorDuration(generator) {
476
- let duration = 0;
477
- const timeStep = 50;
478
- let state = generator.next(duration);
479
- while (!state.done && duration < maxGeneratorDuration) {
480
- duration += timeStep;
481
- state = generator.next(duration);
482
- }
483
- return duration >= maxGeneratorDuration ? Infinity : duration;
484
- }
2668
+ const auto = {
2669
+ test: (v) => v === "auto",
2670
+ parse: (v) => v,
2671
+ };
485
2672
 
486
2673
  /**
487
- * Create a progress => progress easing function from a generator.
2674
+ * Tests a provided value against a ValueType
488
2675
  */
489
- function createGeneratorEasing(options, scale = 100, createGenerator) {
490
- const generator = createGenerator({ ...options, keyframes: [0, scale] });
491
- const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
492
- return {
493
- type: "keyframes",
494
- ease: (progress) => {
495
- return generator.next(duration * progress).value / scale;
496
- },
497
- duration: motionUtils.millisecondsToSeconds(duration),
498
- };
499
- }
2676
+ const testValueType = (v) => (type) => type.test(v);
500
2677
 
501
- function isWaapiSupportedEasing(easing) {
502
- return Boolean((typeof easing === "function" && supportsLinearEasing()) ||
503
- !easing ||
504
- (typeof easing === "string" &&
505
- (easing in supportedWaapiEasing || supportsLinearEasing())) ||
506
- isBezierDefinition(easing) ||
507
- (Array.isArray(easing) && easing.every(isWaapiSupportedEasing)));
2678
+ /**
2679
+ * A list of value types commonly used for dimensions
2680
+ */
2681
+ const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];
2682
+ /**
2683
+ * Tests a dimensional value against the list of dimension ValueTypes
2684
+ */
2685
+ const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));
2686
+
2687
+ function isNone(value) {
2688
+ if (typeof value === "number") {
2689
+ return value === 0;
2690
+ }
2691
+ else if (value !== null) {
2692
+ return value === "none" || value === "0" || motionUtils.isZeroValueString(value);
2693
+ }
2694
+ else {
2695
+ return true;
2696
+ }
508
2697
  }
509
2698
 
510
- function attachTimeline(animation, timeline) {
511
- animation.timeline = timeline;
512
- animation.onfinish = null;
2699
+ /**
2700
+ * Properties that should default to 1 or 100%
2701
+ */
2702
+ const maxDefaults = new Set(["brightness", "contrast", "saturate", "opacity"]);
2703
+ function applyDefaultFilter(v) {
2704
+ const [name, value] = v.slice(0, -1).split("(");
2705
+ if (name === "drop-shadow")
2706
+ return v;
2707
+ const [number] = value.match(floatRegex) || [];
2708
+ if (!number)
2709
+ return v;
2710
+ const unit = value.replace(number, "");
2711
+ let defaultValue = maxDefaults.has(name) ? 1 : 0;
2712
+ if (number !== value)
2713
+ defaultValue *= 100;
2714
+ return name + "(" + defaultValue + unit + ")";
513
2715
  }
2716
+ const functionRegex = /\b([a-z-]*)\(.*?\)/gu;
2717
+ const filter = {
2718
+ ...complex,
2719
+ getAnimatableNone: (v) => {
2720
+ const functions = v.match(functionRegex);
2721
+ return functions ? functions.map(applyDefaultFilter).join(" ") : v;
2722
+ },
2723
+ };
514
2724
 
515
- const stepsOrder = [
516
- "read", // Read
517
- "resolveKeyframes", // Write/Read/Write/Read
518
- "update", // Compute
519
- "preRender", // Compute
520
- "render", // Write
521
- "postRender", // Compute
522
- ];
2725
+ const int = {
2726
+ ...number,
2727
+ transform: Math.round,
2728
+ };
523
2729
 
524
- function createRenderStep(runNextFrame, stepName) {
525
- /**
526
- * We create and reuse two queues, one to queue jobs for the current frame
527
- * and one for the next. We reuse to avoid triggering GC after x frames.
528
- */
529
- let thisFrame = new Set();
530
- let nextFrame = new Set();
531
- /**
532
- * Track whether we're currently processing jobs in this step. This way
533
- * we can decide whether to schedule new jobs for this frame or next.
534
- */
535
- let isProcessing = false;
536
- let flushNextFrame = false;
537
- /**
538
- * A set of processes which were marked keepAlive when scheduled.
539
- */
540
- const toKeepAlive = new WeakSet();
541
- let latestFrameData = {
542
- delta: 0.0,
543
- timestamp: 0.0,
544
- isProcessing: false,
545
- };
546
- let numCalls = 0;
547
- function triggerCallback(callback) {
548
- if (toKeepAlive.has(callback)) {
549
- step.schedule(callback);
550
- runNextFrame();
2730
+ const transformValueTypes = {
2731
+ rotate: degrees,
2732
+ rotateX: degrees,
2733
+ rotateY: degrees,
2734
+ rotateZ: degrees,
2735
+ scale,
2736
+ scaleX: scale,
2737
+ scaleY: scale,
2738
+ scaleZ: scale,
2739
+ skew: degrees,
2740
+ skewX: degrees,
2741
+ skewY: degrees,
2742
+ distance: px,
2743
+ translateX: px,
2744
+ translateY: px,
2745
+ translateZ: px,
2746
+ x: px,
2747
+ y: px,
2748
+ z: px,
2749
+ perspective: px,
2750
+ transformPerspective: px,
2751
+ opacity: alpha,
2752
+ originX: progressPercentage,
2753
+ originY: progressPercentage,
2754
+ originZ: px,
2755
+ };
2756
+
2757
+ const numberValueTypes = {
2758
+ // Border props
2759
+ borderWidth: px,
2760
+ borderTopWidth: px,
2761
+ borderRightWidth: px,
2762
+ borderBottomWidth: px,
2763
+ borderLeftWidth: px,
2764
+ borderRadius: px,
2765
+ radius: px,
2766
+ borderTopLeftRadius: px,
2767
+ borderTopRightRadius: px,
2768
+ borderBottomRightRadius: px,
2769
+ borderBottomLeftRadius: px,
2770
+ // Positioning props
2771
+ width: px,
2772
+ maxWidth: px,
2773
+ height: px,
2774
+ maxHeight: px,
2775
+ top: px,
2776
+ right: px,
2777
+ bottom: px,
2778
+ left: px,
2779
+ // Spacing props
2780
+ padding: px,
2781
+ paddingTop: px,
2782
+ paddingRight: px,
2783
+ paddingBottom: px,
2784
+ paddingLeft: px,
2785
+ margin: px,
2786
+ marginTop: px,
2787
+ marginRight: px,
2788
+ marginBottom: px,
2789
+ marginLeft: px,
2790
+ // Misc
2791
+ backgroundPositionX: px,
2792
+ backgroundPositionY: px,
2793
+ ...transformValueTypes,
2794
+ zIndex: int,
2795
+ size: px,
2796
+ // SVG
2797
+ fillOpacity: alpha,
2798
+ strokeOpacity: alpha,
2799
+ numOctaves: int,
2800
+ };
2801
+
2802
+ /**
2803
+ * A map of default value types for common values
2804
+ */
2805
+ const defaultValueTypes = {
2806
+ ...numberValueTypes,
2807
+ // Color props
2808
+ color,
2809
+ backgroundColor: color,
2810
+ outlineColor: color,
2811
+ fill: color,
2812
+ stroke: color,
2813
+ // Border props
2814
+ borderColor: color,
2815
+ borderTopColor: color,
2816
+ borderRightColor: color,
2817
+ borderBottomColor: color,
2818
+ borderLeftColor: color,
2819
+ filter,
2820
+ WebkitFilter: filter,
2821
+ };
2822
+ /**
2823
+ * Gets the default ValueType for the provided value key
2824
+ */
2825
+ const getDefaultValueType = (key) => defaultValueTypes[key];
2826
+
2827
+ function getAnimatableNone(key, value) {
2828
+ let defaultValueType = getDefaultValueType(key);
2829
+ if (defaultValueType !== filter)
2830
+ defaultValueType = complex;
2831
+ // If value is not recognised as animatable, ie "one", create an animatable version origin based on the target
2832
+ return defaultValueType.getAnimatableNone
2833
+ ? defaultValueType.getAnimatableNone(value)
2834
+ : undefined;
2835
+ }
2836
+
2837
+ /**
2838
+ * If we encounter keyframes like "none" or "0" and we also have keyframes like
2839
+ * "#fff" or "200px 200px" we want to find a keyframe to serve as a template for
2840
+ * the "none" keyframes. In this case "#fff" or "200px 200px" - then these get turned into
2841
+ * zero equivalents, i.e. "#fff0" or "0px 0px".
2842
+ */
2843
+ const invalidTemplates = new Set(["auto", "none", "0"]);
2844
+ function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) {
2845
+ let i = 0;
2846
+ let animatableTemplate = undefined;
2847
+ while (i < unresolvedKeyframes.length && !animatableTemplate) {
2848
+ const keyframe = unresolvedKeyframes[i];
2849
+ if (typeof keyframe === "string" &&
2850
+ !invalidTemplates.has(keyframe) &&
2851
+ analyseComplexValue(keyframe).values.length) {
2852
+ animatableTemplate = unresolvedKeyframes[i];
551
2853
  }
552
- numCalls++;
553
- callback(latestFrameData);
2854
+ i++;
554
2855
  }
555
- const step = {
2856
+ if (animatableTemplate && name) {
2857
+ for (const noneIndex of noneKeyframeIndexes) {
2858
+ unresolvedKeyframes[noneIndex] = getAnimatableNone(name, animatableTemplate);
2859
+ }
2860
+ }
2861
+ }
2862
+
2863
+ class DOMKeyframesResolver extends KeyframeResolver {
2864
+ constructor(unresolvedKeyframes, onComplete, name, motionValue, element) {
2865
+ super(unresolvedKeyframes, onComplete, name, motionValue, element, true);
2866
+ }
2867
+ readKeyframes() {
2868
+ const { unresolvedKeyframes, element, name } = this;
2869
+ if (!element || !element.current)
2870
+ return;
2871
+ super.readKeyframes();
556
2872
  /**
557
- * Schedule a process to run on the next frame.
2873
+ * If any keyframe is a CSS variable, we need to find its value by sampling the element
558
2874
  */
559
- schedule: (callback, keepAlive = false, immediate = false) => {
560
- const addToCurrentFrame = immediate && isProcessing;
561
- const queue = addToCurrentFrame ? thisFrame : nextFrame;
562
- if (keepAlive)
563
- toKeepAlive.add(callback);
564
- if (!queue.has(callback))
565
- queue.add(callback);
566
- return callback;
567
- },
2875
+ for (let i = 0; i < unresolvedKeyframes.length; i++) {
2876
+ let keyframe = unresolvedKeyframes[i];
2877
+ if (typeof keyframe === "string") {
2878
+ keyframe = keyframe.trim();
2879
+ if (isCSSVariableToken(keyframe)) {
2880
+ const resolved = getVariableValue(keyframe, element.current);
2881
+ if (resolved !== undefined) {
2882
+ unresolvedKeyframes[i] = resolved;
2883
+ }
2884
+ if (i === unresolvedKeyframes.length - 1) {
2885
+ this.finalKeyframe = keyframe;
2886
+ }
2887
+ }
2888
+ }
2889
+ }
568
2890
  /**
569
- * Cancel the provided callback from running on the next frame.
2891
+ * Resolve "none" values. We do this potentially twice - once before and once after measuring keyframes.
2892
+ * This could be seen as inefficient but it's a trade-off to avoid measurements in more situations, which
2893
+ * have a far bigger performance impact.
570
2894
  */
571
- cancel: (callback) => {
572
- nextFrame.delete(callback);
573
- toKeepAlive.delete(callback);
574
- },
2895
+ this.resolveNoneKeyframes();
575
2896
  /**
576
- * Execute all schedule callbacks.
2897
+ * Check to see if unit type has changed. If so schedule jobs that will
2898
+ * temporarily set styles to the destination keyframes.
2899
+ * Skip if we have more than two keyframes or this isn't a positional value.
2900
+ * TODO: We can throw if there are multiple keyframes and the value type changes.
577
2901
  */
578
- process: (frameData) => {
579
- latestFrameData = frameData;
580
- /**
581
- * If we're already processing we've probably been triggered by a flushSync
582
- * inside an existing process. Instead of executing, mark flushNextFrame
583
- * as true and ensure we flush the following frame at the end of this one.
584
- */
585
- if (isProcessing) {
586
- flushNextFrame = true;
587
- return;
2902
+ if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) {
2903
+ return;
2904
+ }
2905
+ const [origin, target] = unresolvedKeyframes;
2906
+ const originType = findDimensionValueType(origin);
2907
+ const targetType = findDimensionValueType(target);
2908
+ /**
2909
+ * Either we don't recognise these value types or we can animate between them.
2910
+ */
2911
+ if (originType === targetType)
2912
+ return;
2913
+ /**
2914
+ * If both values are numbers or pixels, we can animate between them by
2915
+ * converting them to numbers.
2916
+ */
2917
+ if (isNumOrPxType(originType) && isNumOrPxType(targetType)) {
2918
+ for (let i = 0; i < unresolvedKeyframes.length; i++) {
2919
+ const value = unresolvedKeyframes[i];
2920
+ if (typeof value === "string") {
2921
+ unresolvedKeyframes[i] = parseFloat(value);
2922
+ }
588
2923
  }
589
- isProcessing = true;
590
- [thisFrame, nextFrame] = [nextFrame, thisFrame];
591
- // Execute this frame
592
- thisFrame.forEach(triggerCallback);
2924
+ }
2925
+ else {
593
2926
  /**
594
- * If we're recording stats then
2927
+ * Else, the only way to resolve this is by measuring the element.
595
2928
  */
596
- if (stepName && statsBuffer.value) {
597
- statsBuffer.value.frameloop[stepName].push(numCalls);
598
- }
599
- numCalls = 0;
600
- // Clear the frame so no callbacks remain. This is to avoid
601
- // memory leaks should this render step not run for a while.
602
- thisFrame.clear();
603
- isProcessing = false;
604
- if (flushNextFrame) {
605
- flushNextFrame = false;
606
- step.process(frameData);
2929
+ this.needsMeasurement = true;
2930
+ }
2931
+ }
2932
+ resolveNoneKeyframes() {
2933
+ const { unresolvedKeyframes, name } = this;
2934
+ const noneKeyframeIndexes = [];
2935
+ for (let i = 0; i < unresolvedKeyframes.length; i++) {
2936
+ if (unresolvedKeyframes[i] === null ||
2937
+ isNone(unresolvedKeyframes[i])) {
2938
+ noneKeyframeIndexes.push(i);
607
2939
  }
608
- },
609
- };
610
- return step;
611
- }
612
-
613
- const maxElapsed = 40;
614
- function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
615
- let runNextFrame = false;
616
- let useDefaultElapsed = true;
617
- const state = {
618
- delta: 0.0,
619
- timestamp: 0.0,
620
- isProcessing: false,
621
- };
622
- const flagRunNextFrame = () => (runNextFrame = true);
623
- const steps = stepsOrder.reduce((acc, key) => {
624
- acc[key] = createRenderStep(flagRunNextFrame, allowKeepAlive ? key : undefined);
625
- return acc;
626
- }, {});
627
- const { read, resolveKeyframes, update, preRender, render, postRender } = steps;
628
- const processBatch = () => {
629
- const timestamp = motionUtils.MotionGlobalConfig.useManualTiming
630
- ? state.timestamp
631
- : performance.now();
632
- runNextFrame = false;
633
- if (!motionUtils.MotionGlobalConfig.useManualTiming) {
634
- state.delta = useDefaultElapsed
635
- ? 1000 / 60
636
- : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
637
2940
  }
638
- state.timestamp = timestamp;
639
- state.isProcessing = true;
640
- // Unrolled render loop for better per-frame performance
641
- read.process(state);
642
- resolveKeyframes.process(state);
643
- update.process(state);
644
- preRender.process(state);
645
- render.process(state);
646
- postRender.process(state);
647
- state.isProcessing = false;
648
- if (runNextFrame && allowKeepAlive) {
649
- useDefaultElapsed = false;
650
- scheduleNextBatch(processBatch);
2941
+ if (noneKeyframeIndexes.length) {
2942
+ makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name);
651
2943
  }
652
- };
653
- const wake = () => {
654
- runNextFrame = true;
655
- useDefaultElapsed = true;
656
- if (!state.isProcessing) {
657
- scheduleNextBatch(processBatch);
2944
+ }
2945
+ measureInitialState() {
2946
+ const { element, unresolvedKeyframes, name } = this;
2947
+ if (!element || !element.current)
2948
+ return;
2949
+ if (name === "height") {
2950
+ this.suspendedScrollY = window.pageYOffset;
658
2951
  }
659
- };
660
- const schedule = stepsOrder.reduce((acc, key) => {
661
- const step = steps[key];
662
- acc[key] = (process, keepAlive = false, immediate = false) => {
663
- if (!runNextFrame)
664
- wake();
665
- return step.schedule(process, keepAlive, immediate);
666
- };
667
- return acc;
668
- }, {});
669
- const cancel = (process) => {
670
- for (let i = 0; i < stepsOrder.length; i++) {
671
- steps[stepsOrder[i]].cancel(process);
2952
+ this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));
2953
+ unresolvedKeyframes[0] = this.measuredOrigin;
2954
+ // Set final key frame to measure after next render
2955
+ const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
2956
+ if (measureKeyframe !== undefined) {
2957
+ element.getValue(name, measureKeyframe).jump(measureKeyframe, false);
672
2958
  }
673
- };
674
- return { schedule, cancel, state, steps };
2959
+ }
2960
+ measureEndState() {
2961
+ const { element, name, unresolvedKeyframes } = this;
2962
+ if (!element || !element.current)
2963
+ return;
2964
+ const value = element.getValue(name);
2965
+ value && value.jump(this.measuredOrigin, false);
2966
+ const finalKeyframeIndex = unresolvedKeyframes.length - 1;
2967
+ const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex];
2968
+ unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current));
2969
+ if (finalKeyframe !== null && this.finalKeyframe === undefined) {
2970
+ this.finalKeyframe = finalKeyframe;
2971
+ }
2972
+ // If we removed transform values, reapply them before the next render
2973
+ if (this.removedTransforms?.length) {
2974
+ this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
2975
+ element
2976
+ .getValue(unsetTransformName)
2977
+ .set(unsetTransformValue);
2978
+ });
2979
+ }
2980
+ this.resolveNoneKeyframes();
2981
+ }
675
2982
  }
676
2983
 
677
- const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps, } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : motionUtils.noop, true);
2984
+ const pxValues = new Set([
2985
+ // Border props
2986
+ "borderWidth",
2987
+ "borderTopWidth",
2988
+ "borderRightWidth",
2989
+ "borderBottomWidth",
2990
+ "borderLeftWidth",
2991
+ "borderRadius",
2992
+ "radius",
2993
+ "borderTopLeftRadius",
2994
+ "borderTopRightRadius",
2995
+ "borderBottomRightRadius",
2996
+ "borderBottomLeftRadius",
2997
+ // Positioning props
2998
+ "width",
2999
+ "maxWidth",
3000
+ "height",
3001
+ "maxHeight",
3002
+ "top",
3003
+ "right",
3004
+ "bottom",
3005
+ "left",
3006
+ // Spacing props
3007
+ "padding",
3008
+ "paddingTop",
3009
+ "paddingRight",
3010
+ "paddingBottom",
3011
+ "paddingLeft",
3012
+ "margin",
3013
+ "marginTop",
3014
+ "marginRight",
3015
+ "marginBottom",
3016
+ "marginLeft",
3017
+ // Misc
3018
+ "backgroundPositionX",
3019
+ "backgroundPositionY",
3020
+ ]);
678
3021
 
679
- const { schedule: microtask, cancel: cancelMicrotask } =
680
- /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
3022
+ function applyPxDefaults(keyframes, name) {
3023
+ for (let i = 0; i < keyframes.length; i++) {
3024
+ if (typeof keyframes[i] === "number" && pxValues.has(name)) {
3025
+ keyframes[i] = keyframes[i] + "px";
3026
+ }
3027
+ }
3028
+ }
681
3029
 
682
- let now;
683
- function clearTime() {
684
- now = undefined;
3030
+ function isWaapiSupportedEasing(easing) {
3031
+ return Boolean((typeof easing === "function" && supportsLinearEasing()) ||
3032
+ !easing ||
3033
+ (typeof easing === "string" &&
3034
+ (easing in supportedWaapiEasing || supportsLinearEasing())) ||
3035
+ motionUtils.isBezierDefinition(easing) ||
3036
+ (Array.isArray(easing) && easing.every(isWaapiSupportedEasing)));
685
3037
  }
3038
+
3039
+ const supportsPartialKeyframes = /*@__PURE__*/ motionUtils.memo(() => {
3040
+ try {
3041
+ document.createElement("div").animate({ opacity: [1] });
3042
+ }
3043
+ catch (e) {
3044
+ return false;
3045
+ }
3046
+ return true;
3047
+ });
3048
+
686
3049
  /**
687
- * An eventloop-synchronous alternative to performance.now().
688
- *
689
- * Ensures that time measurements remain consistent within a synchronous context.
690
- * Usually calling performance.now() twice within the same synchronous context
691
- * will return different values which isn't useful for animations when we're usually
692
- * trying to sync animations to the same frame.
3050
+ * A list of values that can be hardware-accelerated.
693
3051
  */
694
- const time = {
695
- now: () => {
696
- if (now === undefined) {
697
- time.set(frameData.isProcessing || motionUtils.MotionGlobalConfig.useManualTiming
698
- ? frameData.timestamp
699
- : performance.now());
700
- }
701
- return now;
702
- },
703
- set: (newTime) => {
704
- now = newTime;
705
- queueMicrotask(clearTime);
706
- },
707
- };
3052
+ const acceleratedValues = new Set([
3053
+ "opacity",
3054
+ "clipPath",
3055
+ "filter",
3056
+ "transform",
3057
+ // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved
3058
+ // or until we implement support for linear() easing.
3059
+ // "background-color"
3060
+ ]);
3061
+
3062
+ const { schedule: microtask, cancel: cancelMicrotask } =
3063
+ /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
708
3064
 
709
3065
  const isDragging = {
710
3066
  x: false,
@@ -956,6 +3312,28 @@ function press(targetOrSelector, onPressStart, options = {}) {
956
3312
  return cancelEvents;
957
3313
  }
958
3314
 
3315
+ function getComputedStyle$1(element, name) {
3316
+ const computedStyle = window.getComputedStyle(element);
3317
+ return isCSSVar(name)
3318
+ ? computedStyle.getPropertyValue(name)
3319
+ : computedStyle[name];
3320
+ }
3321
+
3322
+ function observeTimeline(update, timeline) {
3323
+ let prevProgress;
3324
+ const onFrame = () => {
3325
+ const { currentTime } = timeline;
3326
+ const percentage = currentTime === null ? 0 : currentTime.value;
3327
+ const progress = percentage / 100;
3328
+ if (prevProgress !== progress) {
3329
+ update(progress);
3330
+ }
3331
+ prevProgress = progress;
3332
+ };
3333
+ frame.update(onFrame, true);
3334
+ return () => cancelFrame(onFrame);
3335
+ }
3336
+
959
3337
  function record() {
960
3338
  const { value } = statsBuffer;
961
3339
  if (value === null) {
@@ -998,6 +3376,7 @@ function reportStats() {
998
3376
  cancelFrame(record);
999
3377
  const summary = {
1000
3378
  frameloop: {
3379
+ setup: summarise(value.frameloop.setup),
1001
3380
  rate: summarise(value.frameloop.rate),
1002
3381
  read: summarise(value.frameloop.read),
1003
3382
  resolveKeyframes: summarise(value.frameloop.resolveKeyframes),
@@ -1035,6 +3414,7 @@ function recordStats() {
1035
3414
  const newStatsBuffer = statsBuffer;
1036
3415
  newStatsBuffer.value = {
1037
3416
  frameloop: {
3417
+ setup: [],
1038
3418
  rate: [],
1039
3419
  read: [],
1040
3420
  resolveKeyframes: [],
@@ -1092,7 +3472,7 @@ class MotionValue {
1092
3472
  * This will be replaced by the build step with the latest version number.
1093
3473
  * When MotionValues are provided to motion components, warn if versions are mixed.
1094
3474
  */
1095
- this.version = "12.7.3";
3475
+ this.version = "12.7.5-alpha.0";
1096
3476
  /**
1097
3477
  * Tracks whether this value can output a velocity. Currently this is only true
1098
3478
  * if the value is numerical, but we might be able to widen the scope here and support
@@ -1236,6 +3616,8 @@ class MotionValue {
1236
3616
  * @public
1237
3617
  */
1238
3618
  set(v, render = true) {
3619
+ if (v === "none")
3620
+ console.trace();
1239
3621
  if (!render || !this.passiveEffect) {
1240
3622
  this.updateAndNotify(v, render);
1241
3623
  }
@@ -1370,6 +3752,24 @@ function motionValue(init, options) {
1370
3752
  return new MotionValue(init, options);
1371
3753
  }
1372
3754
 
3755
+ /**
3756
+ * A list of all ValueTypes
3757
+ */
3758
+ const valueTypes = [...dimensionValueTypes, color, complex];
3759
+ /**
3760
+ * Tests a value against the list of ValueTypes
3761
+ */
3762
+ const findValueType = (v) => valueTypes.find(testValueType(v));
3763
+
3764
+ /**
3765
+ * Provided a value and a ValueType, returns the value as that value type.
3766
+ */
3767
+ const getValueAsType = (value, type) => {
3768
+ return type && typeof value === "number"
3769
+ ? type.transform(value)
3770
+ : value;
3771
+ };
3772
+
1373
3773
  function chooseLayerType(valueName) {
1374
3774
  if (valueName === "layout")
1375
3775
  return "group";
@@ -1508,11 +3908,11 @@ function startViewAnimation(builder) {
1508
3908
  valueOptions.duration && (valueOptions.duration = motionUtils.secondsToMilliseconds(valueOptions.duration));
1509
3909
  valueOptions.delay && (valueOptions.delay = motionUtils.secondsToMilliseconds(valueOptions.delay));
1510
3910
  const animation = new NativeAnimation({
3911
+ ...valueOptions,
1511
3912
  element: document.documentElement,
1512
3913
  name: valueName,
1513
3914
  pseudoElement: `::view-transition-${type}(${target})`,
1514
3915
  keyframes: valueKeyframes,
1515
- transition: valueOptions,
1516
3916
  });
1517
3917
  animations.push(animation);
1518
3918
  }
@@ -1553,14 +3953,14 @@ function startViewAnimation(builder) {
1553
3953
  duration: animationTransition.duration,
1554
3954
  easing,
1555
3955
  });
1556
- animations.push(new NativeAnimation({ animation }));
3956
+ animations.push(new NativeAnimationWrapper(animation));
1557
3957
  }
1558
3958
  else if (hasOpacity(targetDefinition, "enter") &&
1559
3959
  hasOpacity(targetDefinition, "exit") &&
1560
3960
  effect
1561
3961
  .getKeyframes()
1562
3962
  .some((keyframe) => keyframe.mixBlendMode)) {
1563
- animations.push(new NativeAnimation({ animation }));
3963
+ animations.push(new NativeAnimationWrapper(animation));
1564
3964
  }
1565
3965
  else {
1566
3966
  animation.cancel();
@@ -1697,48 +4097,119 @@ const cancelSync = stepsOrder.reduce((acc, key) => {
1697
4097
  return acc;
1698
4098
  }, {});
1699
4099
 
4100
+ exports.AsyncMotionValueAnimation = AsyncMotionValueAnimation;
4101
+ exports.DOMKeyframesResolver = DOMKeyframesResolver;
1700
4102
  exports.GroupAnimation = GroupAnimation;
1701
4103
  exports.GroupAnimationWithThen = GroupAnimationWithThen;
4104
+ exports.JSAnimation = JSAnimation;
4105
+ exports.KeyframeResolver = KeyframeResolver;
1702
4106
  exports.MotionValue = MotionValue;
1703
4107
  exports.NativeAnimation = NativeAnimation;
4108
+ exports.NativeAnimationExtended = NativeAnimationExtended;
4109
+ exports.NativeAnimationWrapper = NativeAnimationWrapper;
1704
4110
  exports.ViewTransitionBuilder = ViewTransitionBuilder;
4111
+ exports.acceleratedValues = acceleratedValues;
1705
4112
  exports.activeAnimations = activeAnimations;
4113
+ exports.alpha = alpha;
4114
+ exports.analyseComplexValue = analyseComplexValue;
4115
+ exports.animateValue = animateValue;
1706
4116
  exports.animateView = animateView;
1707
- exports.attachTimeline = attachTimeline;
4117
+ exports.animationMapKey = animationMapKey;
4118
+ exports.applyPxDefaults = applyPxDefaults;
1708
4119
  exports.calcGeneratorDuration = calcGeneratorDuration;
1709
4120
  exports.cancelFrame = cancelFrame;
1710
4121
  exports.cancelMicrotask = cancelMicrotask;
1711
4122
  exports.cancelSync = cancelSync;
1712
4123
  exports.collectMotionValues = collectMotionValues;
4124
+ exports.color = color;
4125
+ exports.complex = complex;
4126
+ exports.convertOffsetToTimes = convertOffsetToTimes;
1713
4127
  exports.createGeneratorEasing = createGeneratorEasing;
1714
4128
  exports.createRenderBatcher = createRenderBatcher;
1715
4129
  exports.cubicBezierAsString = cubicBezierAsString;
4130
+ exports.defaultEasing = defaultEasing;
4131
+ exports.defaultOffset = defaultOffset;
4132
+ exports.defaultValueTypes = defaultValueTypes;
4133
+ exports.degrees = degrees;
4134
+ exports.dimensionValueTypes = dimensionValueTypes;
4135
+ exports.fillOffset = fillOffset;
4136
+ exports.fillWildcards = fillWildcards;
4137
+ exports.findDimensionValueType = findDimensionValueType;
4138
+ exports.findValueType = findValueType;
4139
+ exports.flushKeyframeResolvers = flushKeyframeResolvers;
1716
4140
  exports.frame = frame;
1717
4141
  exports.frameData = frameData;
1718
4142
  exports.frameSteps = frameSteps;
1719
4143
  exports.generateLinearEasing = generateLinearEasing;
4144
+ exports.getAnimatableNone = getAnimatableNone;
4145
+ exports.getAnimationMap = getAnimationMap;
4146
+ exports.getComputedStyle = getComputedStyle$1;
4147
+ exports.getDefaultValueType = getDefaultValueType;
4148
+ exports.getMixer = getMixer;
4149
+ exports.getValueAsType = getValueAsType;
1720
4150
  exports.getValueTransition = getValueTransition;
4151
+ exports.getVariableValue = getVariableValue;
4152
+ exports.hex = hex;
1721
4153
  exports.hover = hover;
1722
- exports.isBezierDefinition = isBezierDefinition;
4154
+ exports.hsla = hsla;
4155
+ exports.hslaToRgba = hslaToRgba;
4156
+ exports.inertia = inertia;
4157
+ exports.interpolate = interpolate;
4158
+ exports.invisibleValues = invisibleValues;
4159
+ exports.isCSSVariableName = isCSSVariableName;
4160
+ exports.isCSSVariableToken = isCSSVariableToken;
1723
4161
  exports.isDragActive = isDragActive;
1724
4162
  exports.isDragging = isDragging;
1725
4163
  exports.isGenerator = isGenerator;
1726
4164
  exports.isNodeOrChild = isNodeOrChild;
1727
4165
  exports.isPrimaryPointer = isPrimaryPointer;
1728
4166
  exports.isWaapiSupportedEasing = isWaapiSupportedEasing;
4167
+ exports.keyframes = keyframes;
1729
4168
  exports.mapEasingToNativeEasing = mapEasingToNativeEasing;
1730
4169
  exports.maxGeneratorDuration = maxGeneratorDuration;
1731
4170
  exports.microtask = microtask;
4171
+ exports.mix = mix;
4172
+ exports.mixArray = mixArray;
4173
+ exports.mixColor = mixColor;
4174
+ exports.mixComplex = mixComplex;
4175
+ exports.mixImmediate = mixImmediate;
4176
+ exports.mixLinearColor = mixLinearColor;
4177
+ exports.mixNumber = mixNumber$1;
4178
+ exports.mixObject = mixObject;
4179
+ exports.mixVisibility = mixVisibility;
1732
4180
  exports.motionValue = motionValue;
4181
+ exports.number = number;
4182
+ exports.numberValueTypes = numberValueTypes;
4183
+ exports.observeTimeline = observeTimeline;
4184
+ exports.parseCSSVariable = parseCSSVariable;
4185
+ exports.parseValueFromTransform = parseValueFromTransform;
4186
+ exports.percent = percent;
4187
+ exports.positionalKeys = positionalKeys;
1733
4188
  exports.press = press;
4189
+ exports.progressPercentage = progressPercentage;
4190
+ exports.px = px;
4191
+ exports.readTransformValue = readTransformValue;
1734
4192
  exports.recordStats = recordStats;
1735
4193
  exports.resolveElements = resolveElements;
4194
+ exports.rgbUnit = rgbUnit;
4195
+ exports.rgba = rgba;
4196
+ exports.scale = scale;
1736
4197
  exports.setDragLock = setDragLock;
4198
+ exports.setStyle = setStyle;
4199
+ exports.spring = spring;
1737
4200
  exports.startWaapiAnimation = startWaapiAnimation;
1738
4201
  exports.statsBuffer = statsBuffer;
1739
4202
  exports.supportedWaapiEasing = supportedWaapiEasing;
4203
+ exports.supportsBrowserAnimation = supportsBrowserAnimation;
1740
4204
  exports.supportsFlags = supportsFlags;
1741
4205
  exports.supportsLinearEasing = supportsLinearEasing;
4206
+ exports.supportsPartialKeyframes = supportsPartialKeyframes;
1742
4207
  exports.supportsScrollTimeline = supportsScrollTimeline;
1743
4208
  exports.sync = sync;
4209
+ exports.testValueType = testValueType;
1744
4210
  exports.time = time;
4211
+ exports.transformPropOrder = transformPropOrder;
4212
+ exports.transformProps = transformProps;
4213
+ exports.transformValueTypes = transformValueTypes;
4214
+ exports.vh = vh;
4215
+ exports.vw = vw;