-
Notifications
You must be signed in to change notification settings - Fork 0
/
anime.js
1282 lines (1111 loc) · 39.7 KB
/
anime.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* anime.js v3.1.0
* (c) 2019 Julian Garnier
* Released under the MIT license
* animejs.com
*/
'use strict';
// Defaults
var defaultInstanceSettings = {
update: null,
begin: null,
loopBegin: null,
changeBegin: null,
change: null,
changeComplete: null,
loopComplete: null,
complete: null,
loop: 1,
direction: 'normal',
autoplay: true,
timelineOffset: 0
};
var defaultTweenSettings = {
duration: 1000,
delay: 0,
endDelay: 0,
easing: 'easeOutElastic(1, .5)',
round: 0
};
var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective'];
// Caching
var cache = {
CSS: {},
springs: {}
};
// Utils
function minMax(val, min, max) {
return Math.min(Math.max(val, min), max);
}
function stringContains(str, text) {
return str.indexOf(text) > -1;
}
function applyArguments(func, args) {
return func.apply(null, args);
}
var is = {
arr: function (a) { return Array.isArray(a); },
obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); },
pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); },
svg: function (a) { return a instanceof SVGElement; },
inp: function (a) { return a instanceof HTMLInputElement; },
dom: function (a) { return a.nodeType || is.svg(a); },
str: function (a) { return typeof a === 'string'; },
fnc: function (a) { return typeof a === 'function'; },
und: function (a) { return typeof a === 'undefined'; },
hex: function (a) { return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a); },
rgb: function (a) { return /^rgb/.test(a); },
hsl: function (a) { return /^hsl/.test(a); },
col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); },
key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; }
};
// Easings
function parseEasingParameters(string) {
var match = /\(([^)]+)\)/.exec(string);
return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : [];
}
// Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js
function spring(string, duration) {
var params = parseEasingParameters(string);
var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100);
var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100);
var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100);
var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100);
var w0 = Math.sqrt(stiffness / mass);
var zeta = damping / (2 * Math.sqrt(stiffness * mass));
var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
var a = 1;
var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
function solver(t) {
var progress = duration ? (duration * t) / 1000 : t;
if (zeta < 1) {
progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
} else {
progress = (a + b * progress) * Math.exp(-progress * w0);
}
if (t === 0 || t === 1) { return t; }
return 1 - progress;
}
function getDuration() {
var cached = cache.springs[string];
if (cached) { return cached; }
var frame = 1/6;
var elapsed = 0;
var rest = 0;
while(true) {
elapsed += frame;
if (solver(elapsed) === 1) {
rest++;
if (rest >= 16) { break; }
} else {
rest = 0;
}
}
var duration = elapsed * frame * 1000;
cache.springs[string] = duration;
return duration;
}
return duration ? solver : getDuration;
}
// Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
function steps(steps) {
if ( steps === void 0 ) steps = 10;
return function (t) { return Math.round(t * steps) * (1 / steps); };
}
// BezierEasing https://github.com/gre/bezier-easing
var bezier = (function () {
var kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 }
function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 }
function C(aA1) { return 3.0 * aA1 }
function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT }
function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) }
function binarySubdivide(aX, aA, aB, mX1, mX2) {
var currentX, currentT, i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) { aB = currentT; } else { aA = currentT; }
} while (Math.abs(currentX) > 0.0000001 && ++i < 10);
return currentT;
}
function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
for (var i = 0; i < 4; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) { return aGuessT; }
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function bezier(mX1, mY1, mX2, mY2) {
if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; }
var sampleValues = new Float32Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (var i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function getTForX(aX) {
var intervalStart = 0;
var currentSample = 1;
var lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= 0.001) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
return function (x) {
if (mX1 === mY1 && mX2 === mY2) { return x; }
if (x === 0 || x === 1) { return x; }
return calcBezier(getTForX(x), mY1, mY2);
}
}
return bezier;
})();
var penner = (function () {
// Based on jQuery UI's implemenation of easing equations from Robert Penner (http://www.robertpenner.com/easing)
var eases = { linear: function () { return function (t) { return t; }; } };
var functionEasings = {
Sine: function () { return function (t) { return 1 - Math.cos(t * Math.PI / 2); }; },
Circ: function () { return function (t) { return 1 - Math.sqrt(1 - t * t); }; },
Back: function () { return function (t) { return t * t * (3 * t - 2); }; },
Bounce: function () { return function (t) {
var pow2, b = 4;
while (t < (( pow2 = Math.pow(2, --b)) - 1) / 11) {}
return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow(( pow2 * 3 - 2 ) / 22 - t, 2)
}; },
Elastic: function (amplitude, period) {
if ( amplitude === void 0 ) amplitude = 1;
if ( period === void 0 ) period = .5;
var a = minMax(amplitude, 1, 10);
var p = minMax(period, .1, 2);
return function (t) {
return (t === 0 || t === 1) ? t :
-a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);
}
}
};
var baseEasings = ['Quad', 'Cubic', 'Quart', 'Quint', 'Expo'];
baseEasings.forEach(function (name, i) {
functionEasings[name] = function () { return function (t) { return Math.pow(t, i + 2); }; };
});
Object.keys(functionEasings).forEach(function (name) {
var easeIn = functionEasings[name];
eases['easeIn' + name] = easeIn;
eases['easeOut' + name] = function (a, b) { return function (t) { return 1 - easeIn(a, b)(1 - t); }; };
eases['easeInOut' + name] = function (a, b) { return function (t) { return t < 0.5 ? easeIn(a, b)(t * 2) / 2 :
1 - easeIn(a, b)(t * -2 + 2) / 2; }; };
});
return eases;
})();
function parseEasings(easing, duration) {
if (is.fnc(easing)) { return easing; }
var name = easing.split('(')[0];
var ease = penner[name];
var args = parseEasingParameters(easing);
switch (name) {
case 'spring' : return spring(easing, duration);
case 'cubicBezier' : return applyArguments(bezier, args);
case 'steps' : return applyArguments(steps, args);
default : return applyArguments(ease, args);
}
}
// Strings
function selectString(str) {
try {
var nodes = document.querySelectorAll(str);
return nodes;
} catch(e) {
return;
}
}
// Arrays
function filterArray(arr, callback) {
var len = arr.length;
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
var result = [];
for (var i = 0; i < len; i++) {
if (i in arr) {
var val = arr[i];
if (callback.call(thisArg, val, i, arr)) {
result.push(val);
}
}
}
return result;
}
function flattenArray(arr) {
return arr.reduce(function (a, b) { return a.concat(is.arr(b) ? flattenArray(b) : b); }, []);
}
function toArray(o) {
if (is.arr(o)) { return o; }
if (is.str(o)) { o = selectString(o) || o; }
if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); }
return [o];
}
function arrayContains(arr, val) {
return arr.some(function (a) { return a === val; });
}
// Objects
function cloneObject(o) {
var clone = {};
for (var p in o) { clone[p] = o[p]; }
return clone;
}
function replaceObjectProps(o1, o2) {
var o = cloneObject(o1);
for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; }
return o;
}
function mergeObjects(o1, o2) {
var o = cloneObject(o1);
for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; }
return o;
}
// Colors
function rgbToRgba(rgbValue) {
var rgb = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(rgbValue);
return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue;
}
function hexToRgba(hexValue) {
var rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
var hex = hexValue.replace(rgx, function (m, r, g, b) { return r + r + g + g + b + b; } );
var rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
var r = parseInt(rgb[1], 16);
var g = parseInt(rgb[2], 16);
var b = parseInt(rgb[3], 16);
return ("rgba(" + r + "," + g + "," + b + ",1)");
}
function hslToRgba(hslValue) {
var hsl = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(hslValue) || /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(hslValue);
var h = parseInt(hsl[1], 10) / 360;
var s = parseInt(hsl[2], 10) / 100;
var l = parseInt(hsl[3], 10) / 100;
var a = hsl[4] || 1;
function hue2rgb(p, q, t) {
if (t < 0) { t += 1; }
if (t > 1) { t -= 1; }
if (t < 1/6) { return p + (q - p) * 6 * t; }
if (t < 1/2) { return q; }
if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
return p;
}
var r, g, b;
if (s == 0) {
r = g = b = l;
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")");
}
function colorToRgb(val) {
if (is.rgb(val)) { return rgbToRgba(val); }
if (is.hex(val)) { return hexToRgba(val); }
if (is.hsl(val)) { return hslToRgba(val); }
}
// Units
function getUnit(val) {
var split = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(val);
if (split) { return split[1]; }
}
function getTransformUnit(propName) {
if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; }
if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; }
}
// Values
function getFunctionValue(val, animatable) {
if (!is.fnc(val)) { return val; }
return val(animatable.target, animatable.id, animatable.total);
}
function getAttribute(el, prop) {
return el.getAttribute(prop);
}
function convertPxToUnit(el, value, unit) {
var valueUnit = getUnit(value);
if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; }
var cached = cache.CSS[value + unit];
if (!is.und(cached)) { return cached; }
var baseline = 100;
var tempEl = document.createElement(el.tagName);
var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body;
parentEl.appendChild(tempEl);
tempEl.style.position = 'absolute';
tempEl.style.width = baseline + unit;
var factor = baseline / tempEl.offsetWidth;
parentEl.removeChild(tempEl);
var convertedUnit = factor * parseFloat(value);
cache.CSS[value + unit] = convertedUnit;
return convertedUnit;
}
function getCSSValue(el, prop, unit) {
if (prop in el.style) {
var uppercasePropName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
var value = el.style[prop] || getComputedStyle(el).getPropertyValue(uppercasePropName) || '0';
return unit ? convertPxToUnit(el, value, unit) : value;
}
}
function getAnimationType(el, prop) {
if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; }
if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; }
if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; }
if (el[prop] != null) { return 'object'; }
}
function getElementTransforms(el) {
if (!is.dom(el)) { return; }
var str = el.style.transform || '';
var reg = /(\w+)\(([^)]*)\)/g;
var transforms = new Map();
var m; while (m = reg.exec(str)) { transforms.set(m[1], m[2]); }
return transforms;
}
function getTransformValue(el, propName, animatable, unit) {
var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName);
var value = getElementTransforms(el).get(propName) || defaultVal;
if (animatable) {
animatable.transforms.list.set(propName, value);
animatable.transforms['last'] = propName;
}
return unit ? convertPxToUnit(el, value, unit) : value;
}
function getOriginalTargetValue(target, propName, unit, animatable) {
switch (getAnimationType(target, propName)) {
case 'transform': return getTransformValue(target, propName, animatable, unit);
case 'css': return getCSSValue(target, propName, unit);
case 'attribute': return getAttribute(target, propName);
default: return target[propName] || 0;
}
}
function getRelativeValue(to, from) {
var operator = /^(\*=|\+=|-=)/.exec(to);
if (!operator) { return to; }
var u = getUnit(to) || 0;
var x = parseFloat(from);
var y = parseFloat(to.replace(operator[0], ''));
switch (operator[0][0]) {
case '+': return x + y + u;
case '-': return x - y + u;
case '*': return x * y + u;
}
}
function validateValue(val, unit) {
if (is.col(val)) { return colorToRgb(val); }
if (/\s/g.test(val)) { return val; }
var originalUnit = getUnit(val);
var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val;
if (unit) { return unitLess + unit; }
return unitLess;
}
// getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes
// adapted from https://gist.github.com/SebLambla/3e0550c496c236709744
function getDistance(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
function getCircleLength(el) {
return Math.PI * 2 * getAttribute(el, 'r');
}
function getRectLength(el) {
return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2);
}
function getLineLength(el) {
return getDistance(
{x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')},
{x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')}
);
}
function getPolylineLength(el) {
var points = el.points;
var totalLength = 0;
var previousPos;
for (var i = 0 ; i < points.numberOfItems; i++) {
var currentPos = points.getItem(i);
if (i > 0) { totalLength += getDistance(previousPos, currentPos); }
previousPos = currentPos;
}
return totalLength;
}
function getPolygonLength(el) {
var points = el.points;
return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
}
// Path animation
function getTotalLength(el) {
if (el.getTotalLength) { return el.getTotalLength(); }
switch(el.tagName.toLowerCase()) {
case 'circle': return getCircleLength(el);
case 'rect': return getRectLength(el);
case 'line': return getLineLength(el);
case 'polyline': return getPolylineLength(el);
case 'polygon': return getPolygonLength(el);
}
}
function setDashoffset(el) {
var pathLength = getTotalLength(el);
el.setAttribute('stroke-dasharray', pathLength);
return pathLength;
}
// Motion path
function getParentSvgEl(el) {
var parentEl = el.parentNode;
while (is.svg(parentEl)) {
if (!is.svg(parentEl.parentNode)) { break; }
parentEl = parentEl.parentNode;
}
return parentEl;
}
function getParentSvg(pathEl, svgData) {
var svg = svgData || {};
var parentSvgEl = svg.el || getParentSvgEl(pathEl);
var rect = parentSvgEl.getBoundingClientRect();
var viewBoxAttr = getAttribute(parentSvgEl, 'viewBox');
var width = rect.width;
var height = rect.height;
var viewBox = svg.viewBox || (viewBoxAttr ? viewBoxAttr.split(' ') : [0, 0, width, height]);
return {
el: parentSvgEl,
viewBox: viewBox,
x: viewBox[0] / 1,
y: viewBox[1] / 1,
w: width / viewBox[2],
h: height / viewBox[3]
}
}
function getPath(path, percent) {
var pathEl = is.str(path) ? selectString(path)[0] : path;
var p = percent || 100;
return function(property) {
return {
property: property,
el: pathEl,
svg: getParentSvg(pathEl),
totalLength: getTotalLength(pathEl) * (p / 100)
}
}
}
function getPathProgress(path, progress) {
function point(offset) {
if ( offset === void 0 ) offset = 0;
var l = progress + offset >= 1 ? progress + offset : 0;
return path.el.getPointAtLength(l);
}
var svg = getParentSvg(path.el, path.svg);
var p = point();
var p0 = point(-1);
var p1 = point(+1);
switch (path.property) {
case 'x': return (p.x - svg.x) * svg.w;
case 'y': return (p.y - svg.y) * svg.h;
case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
}
}
// Decompose value
function decomposeValue(val, unit) {
// const rgx = /-?\d*\.?\d+/g; // handles basic numbers
// const rgx = /[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g; // handles exponents notation
var rgx = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g; // handles exponents notation
var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + '';
return {
original: value,
numbers: value.match(rgx) ? value.match(rgx).map(Number) : [0],
strings: (is.str(val) || unit) ? value.split(rgx) : []
}
}
// Animatables
function parseTargets(targets) {
var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : [];
return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; });
}
function getAnimatables(targets) {
var parsed = parseTargets(targets);
return parsed.map(function (t, i) {
return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } };
});
}
// Properties
function normalizePropertyTweens(prop, tweenSettings) {
var settings = cloneObject(tweenSettings);
// Override duration if easing is a spring
if (/^spring/.test(settings.easing)) { settings.duration = spring(settings.easing); }
if (is.arr(prop)) {
var l = prop.length;
var isFromTo = (l === 2 && !is.obj(prop[0]));
if (!isFromTo) {
// Duration divided by the number of tweens
if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; }
} else {
// Transform [from, to] values shorthand to a valid tween value
prop = {value: prop};
}
}
var propArray = is.arr(prop) ? prop : [prop];
return propArray.map(function (v, i) {
var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v};
// Default delay value should only be applied to the first tween
if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; }
// Default endDelay value should only be applied to the last tween
if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; }
return obj;
}).map(function (k) { return mergeObjects(k, settings); });
}
function flattenKeyframes(keyframes) {
var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); })
.reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []);
var properties = {};
var loop = function ( i ) {
var propName = propertyNames[i];
properties[propName] = keyframes.map(function (key) {
var newKey = {};
for (var p in key) {
if (is.key(p)) {
if (p == propName) { newKey.value = key[p]; }
} else {
newKey[p] = key[p];
}
}
return newKey;
});
};
for (var i = 0; i < propertyNames.length; i++) loop( i );
return properties;
}
function getProperties(tweenSettings, params) {
var properties = [];
var keyframes = params.keyframes;
if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); }
for (var p in params) {
if (is.key(p)) {
properties.push({
name: p,
tweens: normalizePropertyTweens(params[p], tweenSettings)
});
}
}
return properties;
}
// Tweens
function normalizeTweenValues(tween, animatable) {
var t = {};
for (var p in tween) {
var value = getFunctionValue(tween[p], animatable);
if (is.arr(value)) {
value = value.map(function (v) { return getFunctionValue(v, animatable); });
if (value.length === 1) { value = value[0]; }
}
t[p] = value;
}
t.duration = parseFloat(t.duration);
t.delay = parseFloat(t.delay);
return t;
}
function normalizeTweens(prop, animatable) {
var previousTween;
return prop.tweens.map(function (t) {
var tween = normalizeTweenValues(t, animatable);
var tweenValue = tween.value;
var to = is.arr(tweenValue) ? tweenValue[1] : tweenValue;
var toUnit = getUnit(to);
var originalValue = getOriginalTargetValue(animatable.target, prop.name, toUnit, animatable);
var previousValue = previousTween ? previousTween.to.original : originalValue;
var from = is.arr(tweenValue) ? tweenValue[0] : previousValue;
var fromUnit = getUnit(from) || getUnit(originalValue);
var unit = toUnit || fromUnit;
if (is.und(to)) { to = previousValue; }
tween.from = decomposeValue(from, unit);
tween.to = decomposeValue(getRelativeValue(to, from), unit);
tween.start = previousTween ? previousTween.end : 0;
tween.end = tween.start + tween.delay + tween.duration + tween.endDelay;
tween.easing = parseEasings(tween.easing, tween.duration);
tween.isPath = is.pth(tweenValue);
tween.isColor = is.col(tween.from.original);
if (tween.isColor) { tween.round = 1; }
previousTween = tween;
return tween;
});
}
// Tween progress
var setProgressValue = {
css: function (t, p, v) { return t.style[p] = v; },
attribute: function (t, p, v) { return t.setAttribute(p, v); },
object: function (t, p, v) { return t[p] = v; },
transform: function (t, p, v, transforms, manual) {
transforms.list.set(p, v);
if (p === transforms.last || manual) {
var str = '';
transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; });
t.style.transform = str;
}
}
};
// Set Value helper
function setTargetsValue(targets, properties) {
var animatables = getAnimatables(targets);
animatables.forEach(function (animatable) {
for (var property in properties) {
var value = getFunctionValue(properties[property], animatable);
var target = animatable.target;
var valueUnit = getUnit(value);
var originalValue = getOriginalTargetValue(target, property, valueUnit, animatable);
var unit = valueUnit || getUnit(originalValue);
var to = getRelativeValue(validateValue(value, unit), originalValue);
var animType = getAnimationType(target, property);
setProgressValue[animType](target, property, to, animatable.transforms, true);
}
});
}
// Animations
function createAnimation(animatable, prop) {
var animType = getAnimationType(animatable.target, prop.name);
if (animType) {
var tweens = normalizeTweens(prop, animatable);
var lastTween = tweens[tweens.length - 1];
return {
type: animType,
property: prop.name,
animatable: animatable,
tweens: tweens,
duration: lastTween.end,
delay: tweens[0].delay,
endDelay: lastTween.endDelay
}
}
}
function getAnimations(animatables, properties) {
return filterArray(flattenArray(animatables.map(function (animatable) {
return properties.map(function (prop) {
return createAnimation(animatable, prop);
});
})), function (a) { return !is.und(a); });
}
// Create Instance
function getInstanceTimings(animations, tweenSettings) {
var animLength = animations.length;
var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; };
var timings = {};
timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration;
timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay;
timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay;
return timings;
}
var instanceID = 0;
function createNewInstance(params) {
var instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
var tweenSettings = replaceObjectProps(defaultTweenSettings, params);
var properties = getProperties(tweenSettings, params);
var animatables = getAnimatables(params.targets);
var animations = getAnimations(animatables, properties);
var timings = getInstanceTimings(animations, tweenSettings);
var id = instanceID;
instanceID++;
return mergeObjects(instanceSettings, {
id: id,
children: [],
animatables: animatables,
animations: animations,
duration: timings.duration,
delay: timings.delay,
endDelay: timings.endDelay
});
}
// Core
var activeInstances = [];
var pausedInstances = [];
var raf;
var engine = (function () {
function play() {
raf = requestAnimationFrame(step);
}
function step(t) {
var activeInstancesLength = activeInstances.length;
if (activeInstancesLength) {
var i = 0;
while (i < activeInstancesLength) {
var activeInstance = activeInstances[i];
if (!activeInstance.paused) {
activeInstance.tick(t);
} else {
var instanceIndex = activeInstances.indexOf(activeInstance);
if (instanceIndex > -1) {
activeInstances.splice(instanceIndex, 1);
activeInstancesLength = activeInstances.length;
}
}
i++;
}
play();
} else {
raf = cancelAnimationFrame(raf);
}
}
return play;
})();
function handleVisibilityChange() {
if (document.hidden) {
activeInstances.forEach(function (ins) { return ins.pause(); });
pausedInstances = activeInstances.slice(0);
anime.running = activeInstances = [];
} else {
pausedInstances.forEach(function (ins) { return ins.play(); });
}
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', handleVisibilityChange);
}
// Public Instance
function anime(params) {
if ( params === void 0 ) params = {};
var startTime = 0, lastTime = 0, now = 0;
var children, childrenLength = 0;
var resolve = null;
function makePromise(instance) {
var promise = window.Promise && new Promise(function (_resolve) { return resolve = _resolve; });
instance.finished = promise;
return promise;
}
var instance = createNewInstance(params);
var promise = makePromise(instance);
function toggleInstanceDirection() {
var direction = instance.direction;
if (direction !== 'alternate') {
instance.direction = direction !== 'normal' ? 'normal' : 'reverse';
}
instance.reversed = !instance.reversed;
children.forEach(function (child) { return child.reversed = instance.reversed; });
}
function adjustTime(time) {
return instance.reversed ? instance.duration - time : time;
}
function resetTime() {
startTime = 0;
lastTime = adjustTime(instance.currentTime) * (1 / anime.speed);
}
function seekChild(time, child) {
if (child) { child.seek(time - child.timelineOffset); }
}
function syncInstanceChildren(time) {
if (!instance.reversePlayback) {
for (var i = 0; i < childrenLength; i++) { seekChild(time, children[i]); }
} else {
for (var i$1 = childrenLength; i$1--;) { seekChild(time, children[i$1]); }
}
}
function setAnimationsProgress(insTime) {
var i = 0;
var animations = instance.animations;
var animationsLength = animations.length;
while (i < animationsLength) {
var anim = animations[i];
var animatable = anim.animatable;
var tweens = anim.tweens;
var tweenLength = tweens.length - 1;
var tween = tweens[tweenLength];
// Only check for keyframes if there is more than one tween
if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; }
var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration;
var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed);
var strings = tween.to.strings;
var round = tween.round;
var numbers = [];
var toNumbersLength = tween.to.numbers.length;
var progress = (void 0);
for (var n = 0; n < toNumbersLength; n++) {
var value = (void 0);
var toNumber = tween.to.numbers[n];
var fromNumber = tween.from.numbers[n] || 0;
if (!tween.isPath) {
value = fromNumber + (eased * (toNumber - fromNumber));
} else {
value = getPathProgress(tween.value, eased * toNumber);
}
if (round) {
if (!(tween.isColor && n > 2)) {
value = Math.round(value * round) / round;
}
}
numbers.push(value);
}
// Manual Array.reduce for better performances
var stringsLength = strings.length;
if (!stringsLength) {
progress = numbers[0];
} else {
progress = strings[0];
for (var s = 0; s < stringsLength; s++) {
var a = strings[s];
var b = strings[s + 1];
var n$1 = numbers[s];
if (!isNaN(n$1)) {
if (!b) {
progress += n$1 + ' ';
} else {
progress += n$1 + b;
}