motion 10.5.0-alpha.1 → 10.5.0-alpha.5

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.
@@ -4,6 +4,815 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Motion = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
+ const data = new WeakMap();
8
+ function getAnimationData(element) {
9
+ if (!data.has(element)) {
10
+ data.set(element, {
11
+ transforms: [],
12
+ animations: {},
13
+ generators: {},
14
+ prevGeneratorState: {},
15
+ });
16
+ }
17
+ return data.get(element);
18
+ }
19
+
20
+ function addUniqueItem(array, item) {
21
+ array.indexOf(item) === -1 && array.push(item);
22
+ }
23
+ function removeItem(arr, item) {
24
+ const index = arr.indexOf(item);
25
+ index > -1 && arr.splice(index, 1);
26
+ }
27
+
28
+ const noop = () => { };
29
+ const noopReturn = (v) => v;
30
+
31
+ /**
32
+ * A list of all transformable axes. We'll use this list to generated a version
33
+ * of each axes for each transform.
34
+ */
35
+ const axes = ["", "X", "Y", "Z"];
36
+ /**
37
+ * An ordered array of each transformable value. By default, transform values
38
+ * will be sorted to this order.
39
+ */
40
+ const order = ["translate", "scale", "rotate", "skew"];
41
+ const transformAlias = {
42
+ x: "translateX",
43
+ y: "translateY",
44
+ z: "translateZ",
45
+ };
46
+ const rotation = {
47
+ syntax: "<angle>",
48
+ initialValue: "0deg",
49
+ toDefaultUnit: (v) => v + "deg",
50
+ };
51
+ const baseTransformProperties = {
52
+ translate: {
53
+ syntax: "<length-percentage>",
54
+ initialValue: "0px",
55
+ toDefaultUnit: (v) => v + "px",
56
+ },
57
+ rotate: rotation,
58
+ scale: {
59
+ syntax: "<number>",
60
+ initialValue: 1,
61
+ toDefaultUnit: noopReturn,
62
+ },
63
+ skew: rotation,
64
+ };
65
+ const transformDefinitions = new Map();
66
+ const asTransformCssVar = (name) => `--motion-${name}`;
67
+ /**
68
+ * Generate a list of every possible transform key
69
+ */
70
+ const transforms = ["x", "y", "z"];
71
+ order.forEach((name) => {
72
+ axes.forEach((axis) => {
73
+ transforms.push(name + axis);
74
+ transformDefinitions.set(asTransformCssVar(name + axis), baseTransformProperties[name]);
75
+ });
76
+ });
77
+ /**
78
+ * A function to use with Array.sort to sort transform keys by their default order.
79
+ */
80
+ const compareTransformOrder = (a, b) => transforms.indexOf(a) - transforms.indexOf(b);
81
+ /**
82
+ * Provide a quick way to check if a string is the name of a transform
83
+ */
84
+ const transformLookup = new Set(transforms);
85
+ const isTransform = (name) => transformLookup.has(name);
86
+ const addTransformToElement = (element, name) => {
87
+ // Map x to translateX etc
88
+ if (transformAlias[name])
89
+ name = transformAlias[name];
90
+ const { transforms } = getAnimationData(element);
91
+ addUniqueItem(transforms, name);
92
+ element.style.transform = buildTransformTemplate(transforms);
93
+ };
94
+ const buildTransformTemplate = (transforms) => transforms
95
+ .sort(compareTransformOrder)
96
+ .reduce(transformListToString, "")
97
+ .trim();
98
+ const transformListToString = (template, name) => `${template} ${name}(var(${asTransformCssVar(name)}))`;
99
+
100
+ const isCssVar = (name) => name.startsWith("--");
101
+ const registeredProperties = new Set();
102
+ function registerCssVariable(name) {
103
+ if (registeredProperties.has(name))
104
+ return;
105
+ registeredProperties.add(name);
106
+ try {
107
+ const { syntax, initialValue } = transformDefinitions.has(name)
108
+ ? transformDefinitions.get(name)
109
+ : {};
110
+ CSS.registerProperty({
111
+ name,
112
+ inherits: false,
113
+ syntax,
114
+ initialValue,
115
+ });
116
+ }
117
+ catch (e) { }
118
+ }
119
+
120
+ const ms = (seconds) => seconds * 1000;
121
+
122
+ const isNumber = (value) => typeof value === "number";
123
+
124
+ const isCubicBezier = (easing) => Array.isArray(easing) && isNumber(easing[0]);
125
+ const isEasingList = (easing) => Array.isArray(easing) && !isNumber(easing[0]);
126
+ const isCustomEasing = (easing) => typeof easing === "object" &&
127
+ Boolean(easing.createAnimation);
128
+ const convertEasing = (easing) => isCubicBezier(easing) ? cubicBezierAsString(easing) : easing;
129
+ const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
130
+
131
+ const testAnimation = (keyframes) => document.createElement("div").animate(keyframes, { duration: 0.001 });
132
+ const featureTests = {
133
+ cssRegisterProperty: () => typeof CSS !== "undefined" &&
134
+ Object.hasOwnProperty.call(CSS, "registerProperty"),
135
+ waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"),
136
+ partialKeyframes: () => {
137
+ try {
138
+ testAnimation({ opacity: [1] });
139
+ }
140
+ catch (e) {
141
+ return false;
142
+ }
143
+ return true;
144
+ },
145
+ finished: () => Boolean(testAnimation({ opacity: [0, 1] }).finished),
146
+ };
147
+ const results = {};
148
+ const supports = {};
149
+ for (const key in featureTests) {
150
+ supports[key] = () => {
151
+ if (results[key] === undefined)
152
+ results[key] = featureTests[key]();
153
+ return results[key];
154
+ };
155
+ }
156
+
157
+ const cssVariableRenderer = (element, name) => (latest) => element.style.setProperty(name, latest);
158
+ const styleRenderer = (element, name) => (latest) => (element.style[name] = latest);
159
+
160
+ const defaults = {
161
+ duration: 0.3,
162
+ delay: 0,
163
+ endDelay: 0,
164
+ repeat: 0,
165
+ easing: "ease",
166
+ };
167
+
168
+ /*
169
+ Bezier function generator
170
+
171
+ This has been modified from Gaëtan Renaudeau's BezierEasing
172
+ https://github.com/gre/bezier-easing/blob/master/src/index.js
173
+ https://github.com/gre/bezier-easing/blob/master/LICENSE
174
+
175
+ I've removed the newtonRaphsonIterate algo because in benchmarking it
176
+ wasn't noticiably faster than binarySubdivision, indeed removing it
177
+ usually improved times, depending on the curve.
178
+
179
+ I also removed the lookup table, as for the added bundle size and loop we're
180
+ only cutting ~4 or so subdivision iterations. I bumped the max iterations up
181
+ to 12 to compensate and this still tended to be faster for no perceivable
182
+ loss in accuracy.
183
+
184
+ Usage
185
+ const easeOut = cubicBezier(.17,.67,.83,.67);
186
+ const x = easeOut(0.5); // returns 0.627...
187
+ */
188
+ // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
189
+ const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) * t;
190
+ const subdivisionPrecision = 0.0000001;
191
+ const subdivisionMaxIterations = 12;
192
+ function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
193
+ let currentX;
194
+ let currentT;
195
+ let i = 0;
196
+ do {
197
+ currentT = lowerBound + (upperBound - lowerBound) / 2.0;
198
+ currentX = calcBezier(currentT, mX1, mX2) - x;
199
+ if (currentX > 0.0) {
200
+ upperBound = currentT;
201
+ }
202
+ else {
203
+ lowerBound = currentT;
204
+ }
205
+ } while (Math.abs(currentX) > subdivisionPrecision &&
206
+ ++i < subdivisionMaxIterations);
207
+ return currentT;
208
+ }
209
+ function cubicBezier(mX1, mY1, mX2, mY2) {
210
+ // If this is a linear gradient, return linear easing
211
+ if (mX1 === mY1 && mX2 === mY2)
212
+ return noopReturn;
213
+ const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
214
+ // If animation is at start/end, return t without easing
215
+ return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
216
+ }
217
+
218
+ const clamp = (min, max, v) => Math.min(Math.max(v, min), max);
219
+
220
+ const steps = (steps, direction = "end") => (progress) => {
221
+ progress =
222
+ direction === "end" ? Math.min(progress, 0.999) : Math.max(progress, 0.001);
223
+ const expanded = progress * steps;
224
+ const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
225
+ return clamp(0, 1, rounded / steps);
226
+ };
227
+
228
+ const namedEasings = {
229
+ ease: cubicBezier(0.25, 0.1, 0.25, 1.0),
230
+ "ease-in": cubicBezier(0.42, 0.0, 1.0, 1.0),
231
+ "ease-in-out": cubicBezier(0.42, 0.0, 0.58, 1.0),
232
+ "ease-out": cubicBezier(0.0, 0.0, 0.58, 1.0),
233
+ };
234
+ const functionArgsRegex = /\((.*?)\)/;
235
+ function getEasingFunction(definition) {
236
+ // If already an easing function, return
237
+ if (typeof definition === "function")
238
+ return definition;
239
+ // If an easing curve definition, return bezier function
240
+ if (Array.isArray(definition))
241
+ return cubicBezier(...definition);
242
+ // If we have a predefined easing function, return
243
+ if (namedEasings[definition])
244
+ return namedEasings[definition];
245
+ // If this is a steps function, attempt to create easing curve
246
+ if (definition.startsWith("steps")) {
247
+ const args = functionArgsRegex.exec(definition);
248
+ if (args) {
249
+ const argsArray = args[1].split(",");
250
+ return steps(parseFloat(argsArray[0]), argsArray[1].trim());
251
+ }
252
+ }
253
+ return noopReturn;
254
+ }
255
+
256
+ /*
257
+ Value in range from progress
258
+
259
+ Given a lower limit and an upper limit, we return the value within
260
+ that range as expressed by progress (usually a number from 0 to 1)
261
+
262
+ So progress = 0.5 would change
263
+
264
+ from -------- to
265
+
266
+ to
267
+
268
+ from ---- to
269
+
270
+ E.g. from = 10, to = 20, progress = 0.5 => 15
271
+
272
+ @param [number]: Lower limit of range
273
+ @param [number]: Upper limit of range
274
+ @param [number]: The progress between lower and upper limits expressed 0-1
275
+ @return [number]: Value as calculated from progress within range (not limited within range)
276
+ */
277
+ const mix = (from, to, progress) => -progress * from + progress * to + from;
278
+
279
+ /*
280
+ Progress within given range
281
+
282
+ Given a lower limit and an upper limit, we return the progress
283
+ (expressed as a number 0-1) represented by the given value.
284
+
285
+ @param [number]: Lower limit
286
+ @param [number]: Upper limit
287
+ @param [number]: Value to find progress within given range
288
+ @return [number]: Progress of value within range as expressed 0-1
289
+ */
290
+ const progress = (from, to, value) => {
291
+ return to - from === 0 ? 1 : (value - from) / (to - from);
292
+ };
293
+
294
+ const wrap = (min, max, v) => {
295
+ const rangeSize = max - min;
296
+ return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
297
+ };
298
+
299
+ function getEasingForSegment(easing, i) {
300
+ return isEasingList(easing)
301
+ ? easing[wrap(0, easing.length, i)]
302
+ : easing;
303
+ }
304
+
305
+ function fillOffset(offset, remaining) {
306
+ const min = offset[offset.length - 1];
307
+ for (let i = 1; i <= remaining; i++) {
308
+ const offsetProgress = progress(0, remaining, i);
309
+ offset.push(mix(min, 1, offsetProgress));
310
+ }
311
+ }
312
+ function defaultOffset(length) {
313
+ const offset = [0];
314
+ fillOffset(offset, length - 1);
315
+ return offset;
316
+ }
317
+
318
+ const clampProgress = (p) => Math.min(1, Math.max(p, 0));
319
+ function slowInterpolateNumbers(output, input = defaultOffset(output.length), easing = noopReturn) {
320
+ const length = output.length;
321
+ /**
322
+ * If the input length is lower than the output we
323
+ * fill the input to match. This currently assumes the input
324
+ * is an animation progress value so is a good candidate for
325
+ * moving outside the function.
326
+ */
327
+ const remainder = length - input.length;
328
+ remainder > 0 && fillOffset(input, remainder);
329
+ return (t) => {
330
+ let i = 0;
331
+ for (; i < length - 2; i++) {
332
+ if (t < input[i + 1])
333
+ break;
334
+ }
335
+ let progressInRange = clampProgress(progress(input[i], input[i + 1], t));
336
+ const segmentEasing = getEasingForSegment(easing, i);
337
+ progressInRange = segmentEasing(progressInRange);
338
+ return mix(output[i], output[i + 1], progressInRange);
339
+ };
340
+ }
341
+
342
+ class NumberAnimation {
343
+ constructor(output, keyframes = [0, 1], { easing = defaults.easing, duration = defaults.duration, delay = defaults.delay, endDelay = defaults.endDelay, repeat = defaults.repeat, offset, direction = "normal", } = {}) {
344
+ this.startTime = 0;
345
+ this.rate = 1;
346
+ this.t = 0;
347
+ this.cancelTimestamp = 0;
348
+ this.playState = "idle";
349
+ this.finished = new Promise((resolve, reject) => {
350
+ this.resolve = resolve;
351
+ this.reject = reject;
352
+ });
353
+ const totalDuration = duration * (repeat + 1);
354
+ /**
355
+ * We don't currently support custom easing (spring, glide etc) in NumberAnimation
356
+ * (although this is completely possible), so this will have been hydrated by
357
+ * animateStyle.
358
+ */
359
+ if (isCustomEasing(easing))
360
+ easing = "ease";
361
+ const interpolate = slowInterpolateNumbers(keyframes, offset, isEasingList(easing)
362
+ ? easing.map(getEasingFunction)
363
+ : getEasingFunction(easing));
364
+ this.tick = (timestamp) => {
365
+ var _a;
366
+ if (this.pauseTime)
367
+ timestamp = this.pauseTime;
368
+ let t = (timestamp - this.startTime) * this.rate;
369
+ this.t = t;
370
+ // Convert to seconds
371
+ t /= 1000;
372
+ // Rebase on delay
373
+ t = Math.max(t - delay, 0);
374
+ /**
375
+ * If this animation has finished, set the current time
376
+ * to the total duration.
377
+ */
378
+ if (this.playState === "finished")
379
+ t = totalDuration;
380
+ /**
381
+ * Get the current progress (0-1) of the animation. If t is >
382
+ * than duration we'll get values like 2.5 (midway through the
383
+ * third iteration)
384
+ */
385
+ const progress = t / duration;
386
+ // TODO progress += iterationStart
387
+ /**
388
+ * Get the current iteration (0 indexed). For instance the floor of
389
+ * 2.5 is 2.
390
+ */
391
+ let currentIteration = Math.floor(progress);
392
+ /**
393
+ * Get the current progress of the iteration by taking the remainder
394
+ * so 2.5 is 0.5 through iteration 2
395
+ */
396
+ let iterationProgress = progress % 1.0;
397
+ if (!iterationProgress && progress >= 1) {
398
+ iterationProgress = 1;
399
+ }
400
+ /**
401
+ * If iteration progress is 1 we count that as the end
402
+ * of the previous iteration.
403
+ */
404
+ iterationProgress === 1 && currentIteration--;
405
+ /**
406
+ * Reverse progress if we're not running in "normal" direction
407
+ */
408
+ const iterationIsOdd = currentIteration % 2;
409
+ if (direction === "reverse" ||
410
+ (direction === "alternate" && iterationIsOdd) ||
411
+ (direction === "alternate-reverse" && !iterationIsOdd)) {
412
+ iterationProgress = 1 - iterationProgress;
413
+ }
414
+ const latest = interpolate(t >= totalDuration ? 1 : Math.min(iterationProgress, 1));
415
+ output(latest);
416
+ const isAnimationFinished = this.playState === "finished" || t >= totalDuration + endDelay;
417
+ if (isAnimationFinished) {
418
+ this.playState = "finished";
419
+ (_a = this.resolve) === null || _a === void 0 ? void 0 : _a.call(this, latest);
420
+ }
421
+ else if (this.playState !== "idle") {
422
+ requestAnimationFrame(this.tick);
423
+ }
424
+ };
425
+ this.play();
426
+ }
427
+ play() {
428
+ const now = performance.now();
429
+ this.playState = "running";
430
+ if (this.pauseTime) {
431
+ this.startTime = now - (this.pauseTime - this.startTime);
432
+ }
433
+ else if (!this.startTime) {
434
+ this.startTime = now;
435
+ }
436
+ this.pauseTime = undefined;
437
+ requestAnimationFrame(this.tick);
438
+ }
439
+ pause() {
440
+ this.playState = "paused";
441
+ this.pauseTime = performance.now();
442
+ }
443
+ finish() {
444
+ this.playState = "finished";
445
+ this.tick(0);
446
+ }
447
+ cancel() {
448
+ var _a;
449
+ this.playState = "idle";
450
+ this.tick(this.cancelTimestamp);
451
+ (_a = this.reject) === null || _a === void 0 ? void 0 : _a.call(this, false);
452
+ }
453
+ reverse() {
454
+ this.rate *= -1;
455
+ }
456
+ commitStyles() {
457
+ this.cancelTimestamp = performance.now();
458
+ }
459
+ get currentTime() {
460
+ return this.t;
461
+ }
462
+ set currentTime(t) {
463
+ if (this.pauseTime || this.rate === 0) {
464
+ this.pauseTime = t;
465
+ }
466
+ else {
467
+ this.startTime = performance.now() - t / this.rate;
468
+ }
469
+ }
470
+ get playbackRate() {
471
+ return this.rate;
472
+ }
473
+ set playbackRate(rate) {
474
+ this.rate = rate;
475
+ }
476
+ }
477
+
478
+ function hydrateKeyframes(keyframes, readInitialValue) {
479
+ for (let i = 0; i < keyframes.length; i++) {
480
+ if (keyframes[i] === null) {
481
+ keyframes[i] = i ? keyframes[i - 1] : readInitialValue();
482
+ }
483
+ }
484
+ return keyframes;
485
+ }
486
+ const keyframesList = (keyframes) => Array.isArray(keyframes) ? keyframes : [keyframes];
487
+
488
+ function getStyleName(key) {
489
+ if (transformAlias[key])
490
+ key = transformAlias[key];
491
+ return isTransform(key) ? asTransformCssVar(key) : key;
492
+ }
493
+
494
+ const style = {
495
+ get: (element, name) => {
496
+ name = getStyleName(name);
497
+ let value = isCssVar(name)
498
+ ? element.style.getPropertyValue(name)
499
+ : getComputedStyle(element)[name];
500
+ if (!value && value !== 0) {
501
+ const definition = transformDefinitions.get(name);
502
+ if (definition)
503
+ value = definition.initialValue;
504
+ }
505
+ return value;
506
+ },
507
+ };
508
+
509
+ function stopAnimation(animation) {
510
+ if (!animation)
511
+ return;
512
+ // Suppress error thrown by WAAPI
513
+ try {
514
+ /**
515
+ * commitStyles has overhead so we only want to commit and cancel
516
+ */
517
+ animation.playState !== "finished" && animation.commitStyles();
518
+ animation.cancel();
519
+ }
520
+ catch (e) { }
521
+ }
522
+
523
+ function animateStyle(element, key, keyframesDefinition, options = {}) {
524
+ let animation;
525
+ let { duration = defaults.duration, delay = defaults.delay, endDelay = defaults.endDelay, repeat = defaults.repeat, easing = defaults.easing, direction, offset, allowWebkitAcceleration = false, } = options;
526
+ const data = getAnimationData(element);
527
+ let canAnimateNatively = supports.waapi();
528
+ let render = noop;
529
+ const valueIsTransform = isTransform(key);
530
+ /**
531
+ * If this is an individual transform, we need to map its
532
+ * key to a CSS variable and update the element's transform style
533
+ */
534
+ valueIsTransform && addTransformToElement(element, key);
535
+ const name = getStyleName(key);
536
+ /**
537
+ * Get definition of value, this will be used to convert numerical
538
+ * keyframes into the default value type.
539
+ */
540
+ const definition = transformDefinitions.get(name);
541
+ /**
542
+ * Stop the current animation, if any. Because this will trigger
543
+ * commitStyles (DOM writes) and we might later trigger DOM reads,
544
+ * this is fired now and we return a factory function to create
545
+ * the actual animation that can get called in batch,
546
+ */
547
+ stopAnimation(data.animations[name]);
548
+ /**
549
+ * Batchable factory function containing all DOM reads.
550
+ */
551
+ return () => {
552
+ const readInitialValue = () => { var _a, _b; return (_b = (_a = style.get(element, name)) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition.initialValue) !== null && _b !== void 0 ? _b : 0; };
553
+ /**
554
+ * Replace null values with the previous keyframe value, or read
555
+ * it from the DOM if it's the first keyframe.
556
+ */
557
+ let keyframes = hydrateKeyframes(keyframesList(keyframesDefinition), readInitialValue);
558
+ if (isCustomEasing(easing)) {
559
+ const custom = easing.createAnimation(keyframes, readInitialValue, valueIsTransform, name, data);
560
+ easing = custom.easing;
561
+ if (custom.keyframes !== undefined)
562
+ keyframes = custom.keyframes;
563
+ if (custom.duration !== undefined)
564
+ duration = custom.duration;
565
+ }
566
+ /**
567
+ * If this is a CSS variable we need to register it with the browser
568
+ * before it can be animated natively. We also set it with setProperty
569
+ * rather than directly onto the element.style object.
570
+ */
571
+ if (isCssVar(name)) {
572
+ render = cssVariableRenderer(element, name);
573
+ if (supports.cssRegisterProperty()) {
574
+ registerCssVariable(name);
575
+ }
576
+ else {
577
+ canAnimateNatively = false;
578
+ }
579
+ }
580
+ else {
581
+ render = styleRenderer(element, name);
582
+ }
583
+ /**
584
+ * If we can animate this value with WAAPI, do so. Currently this only
585
+ * feature detects CSS.registerProperty but could check WAAPI too.
586
+ */
587
+ if (canAnimateNatively) {
588
+ /**
589
+ * Convert numbers to default value types. Currently this only supports
590
+ * transforms but it could also support other value types.
591
+ */
592
+ if (definition) {
593
+ keyframes = keyframes.map((value) => isNumber(value) ? definition.toDefaultUnit(value) : value);
594
+ }
595
+ /**
596
+ * If this browser doesn't support partial/implicit keyframes we need to
597
+ * explicitly provide one.
598
+ */
599
+ if (!supports.partialKeyframes() && keyframes.length === 1) {
600
+ keyframes.unshift(readInitialValue());
601
+ }
602
+ const animationOptions = {
603
+ delay: ms(delay),
604
+ duration: ms(duration),
605
+ endDelay: ms(endDelay),
606
+ easing: !isEasingList(easing) ? convertEasing(easing) : undefined,
607
+ direction,
608
+ iterations: repeat + 1,
609
+ fill: "both",
610
+ };
611
+ animation = element.animate({
612
+ [name]: keyframes,
613
+ offset,
614
+ easing: isEasingList(easing) ? easing.map(convertEasing) : undefined,
615
+ }, animationOptions);
616
+ /**
617
+ * Polyfill finished Promise in browsers that don't support it
618
+ */
619
+ if (!animation.finished) {
620
+ animation.finished = new Promise((resolve, reject) => {
621
+ animation.onfinish = resolve;
622
+ animation.oncancel = reject;
623
+ });
624
+ }
625
+ const target = keyframes[keyframes.length - 1];
626
+ animation.finished
627
+ .then(() => {
628
+ // Apply styles to target
629
+ render(target);
630
+ // Ensure fill modes don't persist
631
+ animation.cancel();
632
+ })
633
+ .catch(noop);
634
+ /**
635
+ * This forces Webkit to run animations on the main thread by exploiting
636
+ * this condition:
637
+ * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099
638
+ *
639
+ * This fixes Webkit's timing bugs, like accelerated animations falling
640
+ * out of sync with main thread animations and massive delays in starting
641
+ * accelerated animations in WKWebView.
642
+ */
643
+ if (!allowWebkitAcceleration)
644
+ animation.playbackRate = 1.000001;
645
+ /**
646
+ * If we can't animate the value natively then we can fallback to the numbers-only
647
+ * polyfill for transforms. All keyframes must be numerical.
648
+ */
649
+ }
650
+ else if (valueIsTransform && keyframes.every(isNumber)) {
651
+ /**
652
+ * If we only have a single keyframe, we need to create an initial keyframe by reading
653
+ * the current value from the DOM.
654
+ */
655
+ if (keyframes.length === 1) {
656
+ keyframes.unshift(parseFloat(readInitialValue()));
657
+ }
658
+ if (definition) {
659
+ const applyStyle = render;
660
+ render = (v) => applyStyle(definition.toDefaultUnit(v));
661
+ }
662
+ animation = new NumberAnimation(render, keyframes, Object.assign(Object.assign({}, options), { duration,
663
+ easing }));
664
+ }
665
+ else {
666
+ const target = keyframes[keyframes.length - 1];
667
+ render(definition && isNumber(target)
668
+ ? definition.toDefaultUnit(target)
669
+ : target);
670
+ }
671
+ data.animations[name] = animation;
672
+ /**
673
+ * When an animation finishes, delete the reference to the previous animation.
674
+ */
675
+ animation === null || animation === void 0 ? void 0 : animation.finished.then(() => {
676
+ data.animations[name] = undefined;
677
+ data.generators[name] = undefined;
678
+ data.prevGeneratorState[name] = undefined;
679
+ }).catch(noop);
680
+ return animation;
681
+ };
682
+ }
683
+
684
+ const getOptions = (options, key) =>
685
+ /**
686
+ * TODO: Make test for this
687
+ * Always return a new object otherwise delay is overwritten by results of stagger
688
+ * and this results in no stagger
689
+ */
690
+ options[key] ? Object.assign(Object.assign({}, options), options[key]) : Object.assign({}, options);
691
+
692
+ function resolveElements(elements, selectorCache) {
693
+ var _a;
694
+ if (typeof elements === "string") {
695
+ if (selectorCache) {
696
+ (_a = selectorCache[elements]) !== null && _a !== void 0 ? _a : (selectorCache[elements] = document.querySelectorAll(elements));
697
+ elements = selectorCache[elements];
698
+ }
699
+ else {
700
+ elements = document.querySelectorAll(elements);
701
+ }
702
+ }
703
+ else if (elements instanceof Element) {
704
+ elements = [elements];
705
+ }
706
+ return Array.from(elements);
707
+ }
708
+
709
+ const createAnimation = (factory) => factory();
710
+ const createAnimations = (animationFactory, duration) => new Proxy({
711
+ animations: animationFactory.map(createAnimation).filter(Boolean),
712
+ duration,
713
+ }, controls);
714
+ /**
715
+ * TODO:
716
+ * Currently this returns the first animation, ideally it would return
717
+ * the first active animation.
718
+ */
719
+ const getActiveAnimation = (state) => state.animations[0];
720
+ const controls = {
721
+ get: (target, key) => {
722
+ var _a, _b;
723
+ switch (key) {
724
+ case "duration":
725
+ return target.duration;
726
+ case "currentTime":
727
+ let time = ((_a = getActiveAnimation(target)) === null || _a === void 0 ? void 0 : _a[key]) || 0;
728
+ return time ? time / 1000 : 0;
729
+ case "playbackRate":
730
+ return (_b = getActiveAnimation(target)) === null || _b === void 0 ? void 0 : _b[key];
731
+ case "finished":
732
+ if (!target.finished) {
733
+ target.finished = Promise.all(target.animations.map(selectFinished)).catch(noop);
734
+ }
735
+ return target.finished;
736
+ case "stop":
737
+ return () => target.animations.forEach(stopAnimation);
738
+ default:
739
+ return () => target.animations.forEach((animation) => animation[key]());
740
+ }
741
+ },
742
+ set: (target, key, value) => {
743
+ switch (key) {
744
+ case "currentTime":
745
+ value = ms(value);
746
+ case "currentTime":
747
+ case "playbackRate":
748
+ for (let i = 0; i < target.animations.length; i++) {
749
+ target.animations[i][key] = value;
750
+ }
751
+ return true;
752
+ }
753
+ return false;
754
+ },
755
+ };
756
+ const selectFinished = (animation) => animation.finished;
757
+
758
+ function stagger(duration = 0.1, { start = 0, from = 0, easing } = {}) {
759
+ return (i, total) => {
760
+ const fromIndex = isNumber(from) ? from : getFromIndex(from, total);
761
+ const distance = Math.abs(fromIndex - i);
762
+ let delay = duration * distance;
763
+ if (easing) {
764
+ const maxDelay = total * i;
765
+ const easingFunction = getEasingFunction(easing);
766
+ delay = easingFunction(delay / maxDelay) * maxDelay;
767
+ }
768
+ return start + delay;
769
+ };
770
+ }
771
+ function getFromIndex(from, total) {
772
+ if (from === "first") {
773
+ return 0;
774
+ }
775
+ else {
776
+ const lastIndex = total - 1;
777
+ return from === "last" ? lastIndex : lastIndex / 2;
778
+ }
779
+ }
780
+ function resolveOption(option, i, total) {
781
+ return typeof option === "function"
782
+ ? option(i, total)
783
+ : option;
784
+ }
785
+
786
+ function animate(elements, keyframes, options = {}) {
787
+ var _a;
788
+ elements = resolveElements(elements);
789
+ const numElements = elements.length;
790
+ /**
791
+ * Create and start new animations
792
+ */
793
+ const animationFactories = [];
794
+ for (let i = 0; i < numElements; i++) {
795
+ const element = elements[i];
796
+ for (const key in keyframes) {
797
+ const valueOptions = getOptions(options, key);
798
+ valueOptions.delay = resolveOption(valueOptions.delay, i, numElements);
799
+ const animation = animateStyle(element, key, keyframes[key], valueOptions);
800
+ animationFactories.push(animation);
801
+ }
802
+ }
803
+ return createAnimations(animationFactories,
804
+ /**
805
+ * TODO:
806
+ * If easing is set to spring or glide, duration will be dynamically
807
+ * generated. Ideally we would dynamically generate this from
808
+ * animation.effect.getComputedTiming().duration but this isn't
809
+ * supported in iOS13 or our number polyfill. Perhaps it's possible
810
+ * to Proxy animations returned from animateStyle that has duration
811
+ * as a getter.
812
+ */
813
+ (_a = options.duration) !== null && _a !== void 0 ? _a : defaults.duration);
814
+ }
815
+
7
816
  /*! *****************************************************************************
8
817
  Copyright (c) Microsoft Corporation.
9
818
 
@@ -31,9 +840,846 @@
31
840
  return t;
32
841
  }
33
842
 
34
- function animate(_a) {
35
- var props = __rest(_a, []);
36
- console.log(props);
843
+ var invariant = function () { };
844
+ {
845
+ invariant = function (check, message) {
846
+ if (!check) {
847
+ throw new Error(message);
848
+ }
849
+ };
850
+ }
851
+
852
+ function calcNextTime(current, next, prev, labels) {
853
+ var _a;
854
+ if (isNumber(next)) {
855
+ return next;
856
+ }
857
+ else if (next.startsWith("-") || next.startsWith("+")) {
858
+ return Math.max(0, current + parseFloat(next));
859
+ }
860
+ else if (next === "<") {
861
+ return prev;
862
+ }
863
+ else {
864
+ return (_a = labels.get(next)) !== null && _a !== void 0 ? _a : current;
865
+ }
866
+ }
867
+
868
+ function eraseKeyframes(sequence, startTime, endTime) {
869
+ for (let i = 0; i < sequence.length; i++) {
870
+ const keyframe = sequence[i];
871
+ if (keyframe.at > startTime && keyframe.at < endTime) {
872
+ removeItem(sequence, keyframe);
873
+ // If we remove this item we have to push the pointer back one
874
+ i--;
875
+ }
876
+ }
877
+ }
878
+ function addKeyframes(sequence, keyframes, easing, offset, startTime, endTime) {
879
+ /**
880
+ * Erase every existing value between currentTime and targetTime,
881
+ * this will essentially splice this timeline into any currently
882
+ * defined ones.
883
+ */
884
+ eraseKeyframes(sequence, startTime, endTime);
885
+ for (let i = 0; i < keyframes.length; i++) {
886
+ sequence.push({
887
+ value: keyframes[i],
888
+ at: mix(startTime, endTime, offset[i]),
889
+ easing: getEasingForSegment(easing, i),
890
+ });
891
+ }
892
+ }
893
+
894
+ function compareByTime(a, b) {
895
+ if (a.at === b.at) {
896
+ return a.value === null ? 1 : -1;
897
+ }
898
+ else {
899
+ return a.at - b.at;
900
+ }
901
+ }
902
+
903
+ function timeline(definition, options = {}) {
904
+ var _a, _b;
905
+ const animationDefinitions = createAnimationsFromTimeline(definition, options);
906
+ /**
907
+ * Create and start animations
908
+ */
909
+ const animationFactories = animationDefinitions
910
+ .map((definition) => animateStyle(...definition))
911
+ .filter(Boolean);
912
+ return createAnimations(animationFactories,
913
+ // Get the duration from the first animation definition
914
+ (_b = (_a = animationDefinitions[0]) === null || _a === void 0 ? void 0 : _a[3].duration) !== null && _b !== void 0 ? _b : defaults.duration);
915
+ }
916
+ function createAnimationsFromTimeline(definition, _a = {}) {
917
+ var { defaultOptions = {} } = _a, timelineOptions = __rest(_a, ["defaultOptions"]);
918
+ const animationDefinitions = [];
919
+ const elementSequences = new Map();
920
+ const elementCache = {};
921
+ const timeLabels = new Map();
922
+ let prevTime = 0;
923
+ let currentTime = 0;
924
+ let totalDuration = 0;
925
+ /**
926
+ * Build the timeline by mapping over the definition array and converting
927
+ * the definitions into keyframes and offsets with absolute time values.
928
+ * These will later get converted into relative offsets in a second pass.
929
+ */
930
+ for (let i = 0; i < definition.length; i++) {
931
+ const [elementDefinition, keyframes, options = {}] = definition[i];
932
+ /**
933
+ * If a relative or absolute time value has been specified we need to resolve
934
+ * it in relation to the currentTime.
935
+ */
936
+ if (options.at !== undefined) {
937
+ currentTime = calcNextTime(currentTime, options.at, prevTime, timeLabels);
938
+ }
939
+ /**
940
+ * Keep track of the maximum duration in this definition. This will be
941
+ * applied to currentTime once the definition has been parsed.
942
+ */
943
+ let maxDuration = 0;
944
+ /**
945
+ * Find all the elements specified in the definition and parse value
946
+ * keyframes from their timeline definitions.
947
+ */
948
+ const elements = resolveElements(elementDefinition, elementCache);
949
+ const numElements = elements.length;
950
+ for (let elementIndex = 0; elementIndex < numElements; elementIndex++) {
951
+ const element = elements[elementIndex];
952
+ const elementSequence = getElementSequence(element, elementSequences);
953
+ for (const key in keyframes) {
954
+ const valueSequence = getValueSequence(key, elementSequence);
955
+ let valueKeyframes = keyframesList(keyframes[key]);
956
+ const valueOptions = getOptions(options, key);
957
+ let { duration = defaultOptions.duration || defaults.duration, easing = defaultOptions.easing || defaults.easing, } = valueOptions;
958
+ if (isCustomEasing(easing)) {
959
+ const valueIsTransform = isTransform(key);
960
+ invariant(valueKeyframes.length === 2 || !valueIsTransform, "spring must be provided 2 keyframes within timeline");
961
+ const custom = easing.createAnimation(valueKeyframes,
962
+ // TODO We currently only support explicit keyframes
963
+ // so this doesn't currently read from the DOM
964
+ () => "0", valueIsTransform);
965
+ easing = custom.easing;
966
+ if (custom.keyframes !== undefined)
967
+ valueKeyframes = custom.keyframes;
968
+ if (custom.duration !== undefined)
969
+ duration = custom.duration;
970
+ }
971
+ const delay = resolveOption(options.delay, elementIndex, numElements) || 0;
972
+ const startTime = currentTime + delay;
973
+ const targetTime = startTime + duration;
974
+ /**
975
+ *
976
+ */
977
+ let { offset = defaultOffset(valueKeyframes.length) } = valueOptions;
978
+ /**
979
+ * If there's only one offset of 0, fill in a second with length 1
980
+ *
981
+ * TODO: Ensure there's a test that covers this removal
982
+ */
983
+ if (offset.length === 1 && offset[0] === 0) {
984
+ offset[1] = 1;
985
+ }
986
+ /**
987
+ * Fill out if offset if fewer offsets than keyframes
988
+ */
989
+ const remainder = length - valueKeyframes.length;
990
+ remainder > 0 && fillOffset(offset, remainder);
991
+ /**
992
+ * If only one value has been set, ie [1], push a null to the start of
993
+ * the keyframe array. This will let us mark a keyframe at this point
994
+ * that will later be hydrated with the previous value.
995
+ */
996
+ valueKeyframes.length === 1 && valueKeyframes.unshift(null);
997
+ /**
998
+ * Add keyframes, mapping offsets to absolute time.
999
+ */
1000
+ addKeyframes(valueSequence, valueKeyframes, easing, offset, startTime, targetTime);
1001
+ maxDuration = Math.max(delay + duration, maxDuration);
1002
+ totalDuration = Math.max(targetTime, totalDuration);
1003
+ }
1004
+ }
1005
+ prevTime = currentTime;
1006
+ currentTime += maxDuration;
1007
+ }
1008
+ /**
1009
+ * For every element and value combination create a new animation.
1010
+ */
1011
+ elementSequences.forEach((valueSequences, element) => {
1012
+ for (const key in valueSequences) {
1013
+ const valueSequence = valueSequences[key];
1014
+ /**
1015
+ * Arrange all the keyframes in ascending time order.
1016
+ */
1017
+ valueSequence.sort(compareByTime);
1018
+ const keyframes = [];
1019
+ const valueOffset = [];
1020
+ const valueEasing = [];
1021
+ /**
1022
+ * For each keyframe, translate absolute times into
1023
+ * relative offsets based on the total duration of the timeline.
1024
+ */
1025
+ for (let i = 0; i < valueSequence.length; i++) {
1026
+ const { at, value, easing } = valueSequence[i];
1027
+ keyframes.push(value);
1028
+ valueOffset.push(progress(0, totalDuration, at));
1029
+ valueEasing.push(easing || defaults.easing);
1030
+ }
1031
+ /**
1032
+ * If the first keyframe doesn't land on offset: 0
1033
+ * provide one by duplicating the initial keyframe. This ensures
1034
+ * it snaps to the first keyframe when the animation starts.
1035
+ */
1036
+ if (valueOffset[0] !== 0) {
1037
+ valueOffset.unshift(0);
1038
+ keyframes.unshift(keyframes[0]);
1039
+ valueEasing.unshift("linear");
1040
+ }
1041
+ /**
1042
+ * If the last keyframe doesn't land on offset: 1
1043
+ * provide one with a null wildcard value. This will ensure it
1044
+ * stays static until the end of the animation.
1045
+ */
1046
+ if (valueOffset[valueOffset.length - 1] !== 1) {
1047
+ valueOffset.push(1);
1048
+ keyframes.push(null);
1049
+ }
1050
+ animationDefinitions.push([
1051
+ element,
1052
+ key,
1053
+ keyframes,
1054
+ Object.assign(Object.assign(Object.assign({}, defaultOptions), { duration: totalDuration, easing: valueEasing, offset: valueOffset }), timelineOptions),
1055
+ ]);
1056
+ }
1057
+ });
1058
+ return animationDefinitions;
1059
+ }
1060
+ function getElementSequence(element, sequences) {
1061
+ !sequences.has(element) && sequences.set(element, {});
1062
+ return sequences.get(element);
1063
+ }
1064
+ function getValueSequence(name, sequences) {
1065
+ if (!sequences[name])
1066
+ sequences[name] = [];
1067
+ return sequences[name];
1068
+ }
1069
+
1070
+ /*
1071
+ Convert velocity into velocity per second
1072
+
1073
+ @param [number]: Unit per frame
1074
+ @param [number]: Frame duration in ms
1075
+ */
1076
+ function velocityPerSecond(velocity, frameDuration) {
1077
+ return frameDuration ? velocity * (1000 / frameDuration) : 0;
1078
+ }
1079
+
1080
+ function hasReachedTarget(origin, target, current) {
1081
+ return ((origin < target && current >= target) ||
1082
+ (origin > target && current <= target));
1083
+ }
1084
+
1085
+ const defaultStiffness = 100.0;
1086
+ const defaultDamping = 10.0;
1087
+ const defaultMass = 1.0;
1088
+ const calcDampingRatio = (stiffness = defaultStiffness, damping = defaultDamping, mass = defaultMass) => damping / (2 * Math.sqrt(stiffness * mass));
1089
+ const calcAngularFreq = (undampedFreq, dampingRatio) => undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
1090
+ const createSpringGenerator = ({ stiffness = defaultStiffness, damping = defaultDamping, mass = defaultMass, from = 0, to = 1, velocity = 0.0, restSpeed = 2, restDistance = 0.5, } = {}) => {
1091
+ velocity = velocity ? velocity / 1000 : 0.0;
1092
+ const state = {
1093
+ done: false,
1094
+ value: from,
1095
+ target: to,
1096
+ velocity,
1097
+ hasReachedTarget: false,
1098
+ };
1099
+ const dampingRatio = calcDampingRatio(stiffness, damping, mass);
1100
+ const initialDelta = to - from;
1101
+ const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000;
1102
+ const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
1103
+ let resolveSpring;
1104
+ if (dampingRatio < 1) {
1105
+ // Underdamped spring (bouncy)
1106
+ resolveSpring = (t) => to -
1107
+ Math.exp(-dampingRatio * undampedAngularFreq * t) *
1108
+ (((-velocity + dampingRatio * undampedAngularFreq * initialDelta) /
1109
+ angularFreq) *
1110
+ Math.sin(angularFreq * t) +
1111
+ initialDelta * Math.cos(angularFreq * t));
1112
+ }
1113
+ else {
1114
+ // Critically damped spring
1115
+ resolveSpring = (t) => to -
1116
+ Math.exp(-undampedAngularFreq * t) *
1117
+ (initialDelta + (velocity + undampedAngularFreq * initialDelta) * t);
1118
+ }
1119
+ return {
1120
+ next: (t) => {
1121
+ state.value = resolveSpring(t);
1122
+ state.velocity =
1123
+ t === 0 ? velocity : calcVelocity(resolveSpring, t, state.value);
1124
+ const isBelowVelocityThreshold = Math.abs(state.velocity) <= restSpeed;
1125
+ const isBelowDisplacementThreshold = Math.abs(to - state.value) <= restDistance;
1126
+ state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold;
1127
+ state.hasReachedTarget = hasReachedTarget(from, to, state.value);
1128
+ return state;
1129
+ },
1130
+ };
1131
+ };
1132
+ const sampleT = 5; // ms
1133
+ function calcVelocity(resolveValue, t, current) {
1134
+ const prevT = Math.max(t - sampleT, 0);
1135
+ return velocityPerSecond(current - resolveValue(prevT), 5);
1136
+ }
1137
+
1138
+ const timeStep = 10;
1139
+ const maxDuration = 10000;
1140
+ function pregenerateKeyframes(generator) {
1141
+ let overshootDuration = undefined;
1142
+ let timestamp = timeStep;
1143
+ let state = generator.next(0);
1144
+ const keyframes = [state.value];
1145
+ while (!state.done && timestamp < maxDuration) {
1146
+ state = generator.next(timestamp);
1147
+ keyframes.push(state.done ? state.target : state.value);
1148
+ if (overshootDuration === undefined && state.hasReachedTarget) {
1149
+ overshootDuration = timestamp;
1150
+ }
1151
+ timestamp += timeStep;
1152
+ }
1153
+ const duration = timestamp - timeStep;
1154
+ /**
1155
+ * If generating an animation that didn't actually move,
1156
+ * generate a second keyframe so we have an origin and target.
1157
+ */
1158
+ if (keyframes.length === 1)
1159
+ keyframes.push(state.value);
1160
+ return {
1161
+ keyframes,
1162
+ duration: duration / 1000,
1163
+ overshootDuration: (overshootDuration !== null && overshootDuration !== void 0 ? overshootDuration : duration) / 1000,
1164
+ };
1165
+ }
1166
+
1167
+ function createGeneratorEasing(createGenerator) {
1168
+ const keyframesCache = new WeakMap();
1169
+ return (options = {}) => {
1170
+ const generatorCache = new Map();
1171
+ const getGenerator = (from = 0, to = 100, velocity = 0, isScale = false) => {
1172
+ const key = `${from}-${to}-${velocity}-${isScale}`;
1173
+ if (!generatorCache.has(key)) {
1174
+ generatorCache.set(key, createGenerator(Object.assign({ from,
1175
+ to,
1176
+ velocity, restSpeed: isScale ? 0.05 : 2, restDistance: isScale ? 0.01 : 0.5 }, options)));
1177
+ }
1178
+ return generatorCache.get(key);
1179
+ };
1180
+ const getKeyframes = (generator) => {
1181
+ if (!keyframesCache.has(generator)) {
1182
+ keyframesCache.set(generator, pregenerateKeyframes(generator));
1183
+ }
1184
+ return keyframesCache.get(generator);
1185
+ };
1186
+ return {
1187
+ createAnimation: (keyframes, getOrigin, canUseGenerator, name, data) => {
1188
+ let settings;
1189
+ let generator;
1190
+ const numKeyframes = keyframes.length;
1191
+ let shouldUseGenerator = canUseGenerator &&
1192
+ numKeyframes <= 2 &&
1193
+ keyframes.every(isNumberOrNull);
1194
+ if (shouldUseGenerator) {
1195
+ const prevMotionState = name && data && data.prevGeneratorState[name];
1196
+ const velocity = prevMotionState &&
1197
+ (numKeyframes === 1 ||
1198
+ (numKeyframes === 2 && keyframes[0] === null))
1199
+ ? prevMotionState.velocity
1200
+ : 0;
1201
+ const target = keyframes[numKeyframes - 1];
1202
+ const unresolvedOrigin = numKeyframes === 1 ? null : keyframes[0];
1203
+ const origin = unresolvedOrigin === null
1204
+ ? prevMotionState
1205
+ ? prevMotionState.value
1206
+ : parseFloat(getOrigin())
1207
+ : unresolvedOrigin;
1208
+ generator = getGenerator(origin, target, velocity, name === null || name === void 0 ? void 0 : name.includes("scale"));
1209
+ const keyframesMetadata = getKeyframes(generator);
1210
+ settings = Object.assign(Object.assign({}, keyframesMetadata), { easing: "linear" });
1211
+ }
1212
+ else {
1213
+ generator = getGenerator(0, 100);
1214
+ const keyframesMetadata = getKeyframes(generator);
1215
+ settings = {
1216
+ easing: "ease",
1217
+ duration: keyframesMetadata.overshootDuration,
1218
+ };
1219
+ }
1220
+ // TODO Add test for this
1221
+ if (generator && data && name) {
1222
+ data.generators[name] = generator;
1223
+ }
1224
+ return settings;
1225
+ },
1226
+ };
1227
+ };
1228
+ }
1229
+ const isNumberOrNull = (value) => typeof value !== "string";
1230
+
1231
+ const spring = createGeneratorEasing(createSpringGenerator);
1232
+
1233
+ const createGlideGenerator = ({ from = 0, velocity = 0.0, power = 0.8, decay = 0.325, bounceDamping, bounceStiffness, changeTarget, min, max, restDistance = 0.5, restSpeed, }) => {
1234
+ decay = ms(decay);
1235
+ const state = {
1236
+ value: from,
1237
+ target: from,
1238
+ velocity,
1239
+ hasReachedTarget: false,
1240
+ done: false,
1241
+ };
1242
+ const isOutOfBounds = (v) => (min !== undefined && v < min) || (max !== undefined && v > max);
1243
+ const nearestBoundary = (v) => {
1244
+ if (min === undefined)
1245
+ return max;
1246
+ if (max === undefined)
1247
+ return min;
1248
+ return Math.abs(min - v) < Math.abs(max - v) ? min : max;
1249
+ };
1250
+ let amplitude = power * velocity;
1251
+ const ideal = from + amplitude;
1252
+ const target = changeTarget === undefined ? ideal : changeTarget(ideal);
1253
+ state.target = target;
1254
+ /**
1255
+ * If the target has changed we need to re-calculate the amplitude, otherwise
1256
+ * the animation will start from the wrong position.
1257
+ */
1258
+ if (target !== ideal)
1259
+ amplitude = target - from;
1260
+ const calcDelta = (t) => -amplitude * Math.exp(-t / decay);
1261
+ const calcLatest = (t) => target + calcDelta(t);
1262
+ const applyFriction = (t) => {
1263
+ const delta = calcDelta(t);
1264
+ const latest = calcLatest(t);
1265
+ state.done = Math.abs(delta) <= restDistance;
1266
+ state.value = state.done ? target : latest;
1267
+ state.velocity =
1268
+ t === 0 ? velocity : calcVelocity(calcLatest, t, state.value);
1269
+ };
1270
+ /**
1271
+ * Ideally this would resolve for t in a stateless way, we could
1272
+ * do that by always precalculating the animation but as we know
1273
+ * this will be done anyway we can assume that spring will
1274
+ * be discovered during that.
1275
+ */
1276
+ let timeReachedBoundary;
1277
+ let spring;
1278
+ const checkCatchBoundary = (t) => {
1279
+ if (!isOutOfBounds(state.value))
1280
+ return;
1281
+ timeReachedBoundary = t;
1282
+ spring = createSpringGenerator({
1283
+ from: state.value,
1284
+ to: nearestBoundary(state.value),
1285
+ velocity: state.velocity,
1286
+ damping: bounceDamping,
1287
+ stiffness: bounceStiffness,
1288
+ restDistance,
1289
+ restSpeed,
1290
+ });
1291
+ };
1292
+ checkCatchBoundary(0);
1293
+ return {
1294
+ next: (t) => {
1295
+ /**
1296
+ * We need to resolve the friction to figure out if we need a
1297
+ * spring but we don't want to do this twice per frame. So here
1298
+ * we flag if we updated for this frame and later if we did
1299
+ * we can skip doing it again.
1300
+ */
1301
+ let hasUpdatedFrame = false;
1302
+ if (!spring && timeReachedBoundary === undefined) {
1303
+ hasUpdatedFrame = true;
1304
+ applyFriction(t);
1305
+ checkCatchBoundary(t);
1306
+ }
1307
+ /**
1308
+ * If we have a spring and the provided t is beyond the moment the friction
1309
+ * animation crossed the min/max boundary, use the spring.
1310
+ */
1311
+ if (timeReachedBoundary !== undefined && t > timeReachedBoundary) {
1312
+ state.hasReachedTarget = true;
1313
+ return spring.next(t - timeReachedBoundary);
1314
+ }
1315
+ else {
1316
+ state.hasReachedTarget = false;
1317
+ !hasUpdatedFrame && applyFriction(t);
1318
+ return state;
1319
+ }
1320
+ },
1321
+ };
1322
+ };
1323
+
1324
+ const glide = createGeneratorEasing(createGlideGenerator);
1325
+
1326
+ function hasChanged(a, b) {
1327
+ if (typeof a !== typeof b)
1328
+ return true;
1329
+ if (Array.isArray(a) && Array.isArray(b))
1330
+ return !shallowCompare(a, b);
1331
+ return a !== b;
1332
+ }
1333
+ function shallowCompare(next, prev) {
1334
+ const prevLength = prev.length;
1335
+ if (prevLength !== next.length)
1336
+ return false;
1337
+ for (let i = 0; i < prevLength; i++) {
1338
+ if (prev[i] !== next[i])
1339
+ return false;
1340
+ }
1341
+ return true;
1342
+ }
1343
+
1344
+ function isVariant(definition) {
1345
+ return typeof definition === "object";
1346
+ }
1347
+
1348
+ function resolveVariant(definition, variants) {
1349
+ if (isVariant(definition)) {
1350
+ return definition;
1351
+ }
1352
+ else if (definition && variants) {
1353
+ return variants[definition];
1354
+ }
1355
+ }
1356
+
1357
+ let scheduled = undefined;
1358
+ function processScheduledAnimations() {
1359
+ if (!scheduled)
1360
+ return;
1361
+ const generators = scheduled.sort(compareByDepth).map(fireAnimateUpdates);
1362
+ generators.forEach(fireNext);
1363
+ generators.forEach(fireNext);
1364
+ scheduled = undefined;
1365
+ }
1366
+ function scheduleAnimation(state) {
1367
+ if (!scheduled) {
1368
+ scheduled = [state];
1369
+ requestAnimationFrame(processScheduledAnimations);
1370
+ }
1371
+ else {
1372
+ addUniqueItem(scheduled, state);
1373
+ }
1374
+ }
1375
+ function unscheduleAnimation(state) {
1376
+ scheduled && removeItem(scheduled, state);
1377
+ }
1378
+ const compareByDepth = (a, b) => a.getDepth() - b.getDepth();
1379
+ const fireAnimateUpdates = (state) => state.animateUpdates();
1380
+ const fireNext = (iterator) => iterator.next();
1381
+
1382
+ const motionEvent = (name, target) => new CustomEvent(name, { detail: { target } });
1383
+ function dispatchPointerEvent(element, name, event) {
1384
+ element.dispatchEvent(new CustomEvent(name, { detail: { originalEvent: event } }));
1385
+ }
1386
+ function dispatchViewEvent(element, name, entry) {
1387
+ element.dispatchEvent(new CustomEvent(name, { detail: { originalEntry: entry } }));
1388
+ }
1389
+
1390
+ /**
1391
+ * TODO: Support viewport options
1392
+ */
1393
+ const inView = {
1394
+ isActive: (options) => Boolean(options.inView),
1395
+ subscribe: (element, { enable, disable }) => {
1396
+ let isVisible = false;
1397
+ if (typeof IntersectionObserver !== "undefined") {
1398
+ const observer = new IntersectionObserver(([entry]) => {
1399
+ if (!isVisible && entry.isIntersecting) {
1400
+ enable();
1401
+ dispatchViewEvent(element, "viewenter", entry);
1402
+ }
1403
+ else if (isVisible && !entry.isIntersecting) {
1404
+ disable();
1405
+ dispatchViewEvent(element, "viewleave", entry);
1406
+ }
1407
+ isVisible = entry.isIntersecting;
1408
+ });
1409
+ observer.observe(element);
1410
+ return () => {
1411
+ observer.unobserve(element);
1412
+ observer.disconnect();
1413
+ };
1414
+ }
1415
+ else {
1416
+ enable();
1417
+ return () => { };
1418
+ }
1419
+ },
1420
+ };
1421
+
1422
+ const mouseEvent = (element, name, action) => (event) => {
1423
+ if (event.pointerType && event.pointerType !== "mouse")
1424
+ return;
1425
+ action();
1426
+ dispatchPointerEvent(element, name, event);
1427
+ };
1428
+ const hover = {
1429
+ isActive: (options) => Boolean(options.hover),
1430
+ subscribe: (element, { enable, disable }) => {
1431
+ const onEnter = mouseEvent(element, "hoverstart", enable);
1432
+ const onLeave = mouseEvent(element, "hoverend", disable);
1433
+ element.addEventListener("pointerenter", onEnter);
1434
+ element.addEventListener("pointerleave", onLeave);
1435
+ return () => {
1436
+ element.removeEventListener("pointerenter", onEnter);
1437
+ element.removeEventListener("pointerleave", onLeave);
1438
+ };
1439
+ },
1440
+ };
1441
+
1442
+ const press = {
1443
+ isActive: (options) => Boolean(options.press),
1444
+ subscribe: (element, { enable, disable }) => {
1445
+ const onPointerUp = (event) => {
1446
+ disable();
1447
+ dispatchPointerEvent(element, "pressend", event);
1448
+ window.removeEventListener("pointerup", onPointerUp);
1449
+ };
1450
+ const onPointerDown = (event) => {
1451
+ enable();
1452
+ dispatchPointerEvent(element, "pressstart", event);
1453
+ window.addEventListener("pointerup", onPointerUp);
1454
+ };
1455
+ element.addEventListener("pointerdown", onPointerDown);
1456
+ return () => {
1457
+ element.removeEventListener("pointerdown", onPointerDown);
1458
+ window.removeEventListener("pointerup", onPointerUp);
1459
+ };
1460
+ },
1461
+ };
1462
+
1463
+ const gestures = { inView, hover, press };
1464
+ /**
1465
+ * A list of state types, in priority order. If a value is defined in
1466
+ * a righter-most type, it will override any definition in a lefter-most.
1467
+ */
1468
+ const stateTypes = ["initial", "animate", ...Object.keys(gestures), "exit"];
1469
+ /**
1470
+ * A global store of all generated motion states. This can be used to lookup
1471
+ * a motion state for a given Element.
1472
+ */
1473
+ const mountedStates = new WeakMap();
1474
+ function createMotionState(options = {}, parent) {
1475
+ /**
1476
+ * The element represented by the motion state. This is an empty reference
1477
+ * when we create the state to support SSR and allow for later mounting
1478
+ * in view libraries.
1479
+ *
1480
+ * @ts-ignore
1481
+ */
1482
+ let element;
1483
+ /**
1484
+ * Calculate a depth that we can use to order motion states by tree depth.
1485
+ */
1486
+ let depth = parent ? parent.getDepth() + 1 : 0;
1487
+ /**
1488
+ * Track which states are currently active.
1489
+ */
1490
+ const activeStates = { initial: true, animate: true };
1491
+ /**
1492
+ * A map of functions that, when called, will remove event listeners for
1493
+ * a given gesture.
1494
+ */
1495
+ const gestureSubscriptions = {};
1496
+ /**
1497
+ * Initialise a context to share through motion states. This
1498
+ * will be populated by variant names (if any).
1499
+ */
1500
+ const context = {};
1501
+ for (const name of stateTypes) {
1502
+ context[name] =
1503
+ typeof options[name] === "string"
1504
+ ? options[name]
1505
+ : parent === null || parent === void 0 ? void 0 : parent.getContext()[name];
1506
+ }
1507
+ /**
1508
+ * If initial is set to false we use the animate prop as the initial
1509
+ * animation state.
1510
+ */
1511
+ const initialVariantSource = options.initial === false ? "animate" : "initial";
1512
+ /**
1513
+ * Destructure an initial target out from the resolved initial variant.
1514
+ */
1515
+ let _a = resolveVariant(options[initialVariantSource] || context[initialVariantSource], options.variants) || {}, target = __rest(_a, ["transition"]);
1516
+ /**
1517
+ * The base target is a cached map of values that we'll use to animate
1518
+ * back to if a value is removed from all active state types. This
1519
+ * is usually the initial value as read from the DOM, for instance if
1520
+ * it hasn't been defined in initial.
1521
+ */
1522
+ const baseTarget = Object.assign({}, target);
1523
+ /**
1524
+ * A generator that will be processed by the global animation scheduler.
1525
+ * This yeilds when it switches from reading the DOM to writing to it
1526
+ * to prevent layout thrashing.
1527
+ */
1528
+ function* animateUpdates() {
1529
+ var _a, _b;
1530
+ const prevTarget = target;
1531
+ target = {};
1532
+ const resolvedVariants = {};
1533
+ const enteringInto = {};
1534
+ const animationOptions = {};
1535
+ for (const name of stateTypes) {
1536
+ if (!activeStates[name])
1537
+ continue;
1538
+ const variant = resolveVariant(options[name]);
1539
+ if (!variant)
1540
+ continue;
1541
+ resolvedVariants[name] = variant;
1542
+ for (const key in variant) {
1543
+ if (key === "transition")
1544
+ continue;
1545
+ target[key] = variant[key];
1546
+ animationOptions[key] = getOptions((_b = (_a = variant.transition) !== null && _a !== void 0 ? _a : options.transition) !== null && _b !== void 0 ? _b : {}, key);
1547
+ /**
1548
+ * Mark which state type this value is animating into.
1549
+ */
1550
+ enteringInto[key] = name;
1551
+ }
1552
+ }
1553
+ const allTargetKeys = new Set([
1554
+ ...Object.keys(target),
1555
+ ...Object.keys(prevTarget),
1556
+ ]);
1557
+ const animationFactories = [];
1558
+ allTargetKeys.forEach((key) => {
1559
+ var _a;
1560
+ if (target[key] === undefined) {
1561
+ target[key] = baseTarget[key];
1562
+ }
1563
+ if (hasChanged(prevTarget[key], target[key])) {
1564
+ (_a = baseTarget[key]) !== null && _a !== void 0 ? _a : (baseTarget[key] = style.get(element, key));
1565
+ animationFactories.push(animateStyle(element, key, target[key], animationOptions[key]));
1566
+ }
1567
+ });
1568
+ // Wait for all animation states to read from the DOM
1569
+ yield;
1570
+ const animations = animationFactories
1571
+ .map((factory) => factory())
1572
+ .filter(Boolean);
1573
+ if (!animations.length)
1574
+ return;
1575
+ const animationTarget = target;
1576
+ element.dispatchEvent(motionEvent("motionstart", animationTarget));
1577
+ Promise.all(animations.map((animation) => animation.finished))
1578
+ .then(() => {
1579
+ element.dispatchEvent(motionEvent("motioncomplete", animationTarget));
1580
+ })
1581
+ .catch(noop);
1582
+ }
1583
+ const setGesture = (name, isActive) => () => {
1584
+ activeStates[name] = isActive;
1585
+ scheduleAnimation(state);
1586
+ };
1587
+ const updateGestureSubscriptions = () => {
1588
+ for (const name in gestures) {
1589
+ const isGestureActive = gestures[name].isActive(options);
1590
+ const remove = gestureSubscriptions[name];
1591
+ if (isGestureActive && !remove) {
1592
+ gestureSubscriptions[name] = gestures[name].subscribe(element, {
1593
+ enable: setGesture(name, true),
1594
+ disable: setGesture(name, false),
1595
+ });
1596
+ }
1597
+ else if (!isGestureActive && remove) {
1598
+ remove();
1599
+ delete gestureSubscriptions[name];
1600
+ }
1601
+ }
1602
+ };
1603
+ const state = {
1604
+ update: (newOptions) => {
1605
+ if (!element)
1606
+ return;
1607
+ options = newOptions;
1608
+ updateGestureSubscriptions();
1609
+ scheduleAnimation(state);
1610
+ },
1611
+ setActive: (name, isActive) => {
1612
+ if (!element)
1613
+ return Promise.resolve();
1614
+ activeStates[name] = isActive;
1615
+ scheduleAnimation(state);
1616
+ return new Promise((resolve) => {
1617
+ setTimeout(() => resolve(), 100);
1618
+ });
1619
+ },
1620
+ animateUpdates,
1621
+ getDepth: () => depth,
1622
+ getTarget: () => target,
1623
+ getOptions: () => options,
1624
+ getContext: () => context,
1625
+ mount: (newElement) => {
1626
+ invariant(Boolean(newElement), "Animation state must be mounted with valid Element");
1627
+ element = newElement;
1628
+ mountedStates.set(element, state);
1629
+ updateGestureSubscriptions();
1630
+ return () => {
1631
+ mountedStates.delete(element);
1632
+ unscheduleAnimation(state);
1633
+ for (const key in gestureSubscriptions) {
1634
+ gestureSubscriptions[key]();
1635
+ }
1636
+ };
1637
+ },
1638
+ isMounted: () => Boolean(element),
1639
+ };
1640
+ return state;
1641
+ }
1642
+
1643
+ function createStyles(keyframes) {
1644
+ const initialKeyframes = {};
1645
+ const transformKeys = [];
1646
+ for (let key in keyframes) {
1647
+ const value = keyframes[key];
1648
+ if (isTransform(key)) {
1649
+ if (transformAlias[key])
1650
+ key = transformAlias[key];
1651
+ transformKeys.push(key);
1652
+ key = asTransformCssVar(key);
1653
+ }
1654
+ let initialKeyframe = Array.isArray(value) ? value[0] : value;
1655
+ /**
1656
+ * If this is a number and we have a default value type, convert the number
1657
+ * to this type.
1658
+ */
1659
+ const definition = transformDefinitions.get(key);
1660
+ if (definition) {
1661
+ initialKeyframe = isNumber(value)
1662
+ ? definition.toDefaultUnit(value)
1663
+ : value;
1664
+ }
1665
+ initialKeyframes[key] = initialKeyframe;
1666
+ }
1667
+ if (transformKeys.length) {
1668
+ initialKeyframes.transform = buildTransformTemplate(transformKeys);
1669
+ }
1670
+ return initialKeyframes;
1671
+ }
1672
+
1673
+ const camelLetterToPipeLetter = (letter) => `-${letter.toLowerCase()}`;
1674
+ const camelToPipeCase = (str) => str.replace(/[A-Z]/g, camelLetterToPipeLetter);
1675
+ function createStyleString(target = {}) {
1676
+ const styles = createStyles(target);
1677
+ let style = "";
1678
+ for (const key in styles) {
1679
+ style += key.startsWith("--") ? key : camelToPipeCase(key);
1680
+ style += `: ${styles[key]}; `;
1681
+ }
1682
+ return style;
37
1683
  }
38
1684
 
39
1685
  function test() {
@@ -41,7 +1687,19 @@
41
1687
  }
42
1688
 
43
1689
  exports.animate = animate;
1690
+ exports.animateStyle = animateStyle;
1691
+ exports.createMotionState = createMotionState;
1692
+ exports.createStyleString = createStyleString;
1693
+ exports.createStyles = createStyles;
1694
+ exports.getAnimationData = getAnimationData;
1695
+ exports.getStyleName = getStyleName;
1696
+ exports.glide = glide;
1697
+ exports.mountedStates = mountedStates;
1698
+ exports.spring = spring;
1699
+ exports.stagger = stagger;
1700
+ exports.style = style;
44
1701
  exports.test = test;
1702
+ exports.timeline = timeline;
45
1703
 
46
1704
  Object.defineProperty(exports, '__esModule', { value: true });
47
1705