forked from ionic-team/ionic-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanimation.ts
More file actions
829 lines (662 loc) · 21.2 KB
/
animation.ts
File metadata and controls
829 lines (662 loc) · 21.2 KB
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
import {CSS, rafFrames, transitionEnd} from '../util/dom';
import {assign, isDefined} from '../util/util';
/**
* @private
**/
export class Animation {
private _parent: Animation;
private _c: Animation[];
private _el: HTMLElement[];
private _opts: AnimationOptions;
private _fx: {[key: string]: EffectProperty};
private _dur: number;
private _easing: string;
private _bfSty: { [property: string]: any; };
private _bfAdd: string[];
private _bfRmv: string[];
private _afSty: { [property: string]: any; };
private _afAdd: string[];
private _afRmv: string[];
private _pFns: Function[];
private _fFns: Function[];
private _fOnceFns: Function[];
private _wChg: boolean = false;
private _rv: boolean = false;
private _unregTrans: Function;
private _tmr: number;
private _lastUpd: number = 0;
public isPlaying: boolean = false;
public hasTween: boolean = false;
public hasCompleted: boolean = false;
constructor(ele?: any, opts: AnimationOptions = {}) {
this._reset();
this.element(ele);
this._opts = assign({
renderDelay: 24
}, opts);
}
_reset() {
this._el = [];
this._c = [];
this._fx = {};
this._bfSty = {};
this._bfAdd = [];
this._bfRmv = [];
this._afSty = {};
this._afAdd = [];
this._afRmv = [];
this._pFns = [];
this._fFns = [];
this._fOnceFns = [];
this._easing = this._dur = null;
}
element(ele: any): Animation {
var i: number;
if (ele) {
if (Array.isArray(ele)) {
for (i = 0; i < ele.length; i++) {
this._addEle(ele[i]);
}
} else if (typeof ele === 'string') {
ele = document.querySelectorAll(ele);
for (i = 0; i < ele.length; i++) {
this._addEle(ele[i]);
}
} else {
this._addEle(ele);
}
}
return this;
}
private _addEle(ele: any) {
if (ele.nativeElement) {
ele = ele.nativeElement;
}
if (ele.nodeType === 1) {
this._el.push(ele);
// does this element suport will-change property?
this._wChg = (typeof ele.style.willChange !== 'undefined');
}
}
parent(parentAnimation: Animation): Animation {
this._parent = parentAnimation;
return this;
}
add(childAnimation: Animation): Animation {
childAnimation.parent(this);
this._c.push(childAnimation);
return this;
}
getDuration(): number {
return this._dur !== null ? this._dur : (this._parent && this._parent.getDuration()) || 0;
}
duration(milliseconds: number): Animation {
this._dur = milliseconds;
return this;
}
getEasing(): string {
return this._easing !== null ? this._easing : (this._parent && this._parent.getEasing()) || null;
}
easing(name: string): Animation {
this._easing = name;
return this;
}
from(prop: string, val: any): Animation {
this._addProp('from', prop, val);
return this;
}
to(prop: string, val: any, clearProperyAfterTransition?: boolean): Animation {
var fx: EffectProperty = this._addProp('to', prop, val);
if (clearProperyAfterTransition) {
// if this effect is a transform then clear the transform effect
// otherwise just clear the actual property
this.after.clearStyles([ fx.trans ? CSS.transform : prop]);
}
return this;
}
fromTo(prop: string, fromVal: any, toVal: any, clearProperyAfterTransition?: boolean): Animation {
return this.from(prop, fromVal).to(prop, toVal, clearProperyAfterTransition);
}
private _addProp(state: string, prop: string, val: any): EffectProperty {
var fxProp: EffectProperty = this._fx[prop];
if (!fxProp) {
// first time we've see this EffectProperty
fxProp = this._fx[prop] = {
trans: (typeof TRANSFORMS[prop] !== 'undefined'),
wc: ''
};
// add the will-change property fo transforms or opacity
if (fxProp.trans) {
fxProp.wc = CSS.transform;
} else if (prop === 'opacity') {
fxProp.wc = prop;
}
}
// add from/to EffectState to the EffectProperty
var fxState = fxProp[state] = {
val: val,
num: null,
unit: '',
};
if (typeof val === 'string' && val.indexOf(' ') < 0) {
let r = val.match(CSS_VALUE_REGEX);
let num = parseFloat(r[1]);
if (!isNaN(num)) {
fxState.num = num;
}
fxState.unit = (r[0] != r[2] ? r[2] : '');
} else if (typeof val === 'number') {
fxState.num = val;
}
return fxProp;
}
fadeIn(): Animation {
return this.fromTo('opacity', 0.001, 1, true);
}
fadeOut(): Animation {
return this.fromTo('opacity', 0.999, 0);
}
get before() {
return {
addClass: (className: string): Animation => {
this._bfAdd.push(className);
return this;
},
removeClass: (className: string): Animation => {
this._bfRmv.push(className);
return this;
},
setStyles: (styles: { [property: string]: any; }): Animation => {
this._bfSty = styles;
return this;
},
clearStyles: (propertyNames: string[]): Animation => {
for (var i = 0; i < propertyNames.length; i++) {
this._bfSty[propertyNames[i]] = '';
}
return this;
}
}
}
get after() {
return {
addClass: (className: string): Animation => {
this._afAdd.push(className);
return this;
},
removeClass: (className: string): Animation => {
this._afRmv.push(className);
return this;
},
setStyles: (styles: { [property: string]: any; }): Animation => {
this._afSty = styles;
return this;
},
clearStyles: (propertyNames: string[]): Animation => {
for (var i = 0; i < propertyNames.length; i++) {
this._afSty[propertyNames[i]] = '';
}
return this;
}
}
}
play(opts: PlayOptions = {}) {
var self = this;
var i: number;
var duration: number = isDefined(opts.duration) ? opts.duration : self._dur;
console.debug('Animation, play, duration', duration, 'easing', self._easing);
// always default that an animation does not tween
// a tween requires that an Animation class has an element
// and that it has at least one FROM/TO effect
// and that the FROM/TO effect can tween numeric values
self.hasTween = false;
self.hasCompleted = false;
// fire off all the onPlays
for (i = 0; i < self._pFns.length; i++) {
self._pFns[i]();
}
self.isPlaying = true;
// this is the top level animation and is in full control
// of when the async play() should actually kick off
// if there is no duration then it'll set the TO property immediately
// if there is a duration, then it'll stage all animations at the
// FROM property and transition duration, wait a few frames, then
// kick off the animation by setting the TO property for each animation
// stage all of the before css classes and inline styles
// will recursively stage all child elements
self._before();
// ensure all past transition end events have been cleared
self._clearAsync();
if (duration > 30) {
// this animation has a duration, so it should animate
// place all the elements with their FROM properties
// set the FROM properties
self._progress(0);
// add the will-change or translateZ properties when applicable
self._willChg(true);
// set the async TRANSITION END event
// and run onFinishes when the transition ends
self._asyncEnd(duration, true);
// begin each animation when everything is rendered in their place
// and the transition duration/easing is ready to go
rafFrames(self._opts.renderDelay / 16, function() {
// there's been a moment and the elements are in place
// now set the TRANSITION duration/easing
self._setTrans(duration, false);
// wait a few moments again to wait for the transition
// info to take hold in the DOM
rafFrames(2, function() {
// browser had some time to render everything in place
// and the transition duration/easing is set
// now set the TO properties
// which will trigger the transition to begin
self._progress(1);
});
});
} else {
// this animation does not have a duration, so it should not animate
// just go straight to the TO properties and call it done
self._progress(1);
// since there was no animation, immediately run the after
self._after();
// since there was no animation, it's done
// fire off all the onFinishes
self._didFinish(true);
}
}
stop(opts: PlayOptions = {}) {
var self = this;
var duration = isDefined(opts.duration) ? opts.duration : 0;
var stepValue = isDefined(opts.stepValue) ? opts.stepValue : 1;
// ensure all past transition end events have been cleared
this._clearAsync();
// set the TO properties
self._progress(stepValue);
if (duration > 30) {
// this animation has a duration, so it should animate
// place all the elements with their TO properties
// now set the TRANSITION duration
self._setTrans(duration, true);
// set the async TRANSITION END event
// and run onFinishes when the transition ends
self._asyncEnd(duration, false);
} else {
// this animation does not have a duration, so it should not animate
// just go straight to the TO properties and call it done
self._after();
// since there was no animation, it's done
// fire off all the onFinishes
self._didFinish(false);
}
}
_asyncEnd(duration: number, shouldComplete: boolean) {
var self = this;
function onTransitionEnd(ev) {
console.debug('Animation onTransitionEnd', ev.target.nodeName, ev.propertyName);
// ensure transition end events and timeouts have been cleared
self._clearAsync();
// set the after styles
self._after();
// remove will change properties
self._willChg(false);
// transition finished
self._didFinish(shouldComplete);
}
function onTransitionFallback() {
console.debug('Animation onTransitionFallback');
// oh noz! the transition end event didn't fire in time!
// instead the fallback timer when first
// clear the other async end events from firing
self._tmr = 0;
self._clearAsync();
// too late to have a smooth animation, just finish it
self._setTrans(0, true);
// ensure the ending progress step gets rendered
self._progress(1);
// set the after styles
self._after();
// remove will change properties
self._willChg(false);
// transition finished
self._didFinish(shouldComplete);
}
// set the TRANSITION END event on one of the transition elements
self._unregTrans = transitionEnd(self._transEl(), onTransitionEnd);
// set a fallback timeout if the transition end event never fires, or is too slow
// transition end fallback: (animation duration + XXms)
self._tmr = setTimeout(onTransitionFallback, duration + 400);
}
_clearAsync() {
this._unregTrans && this._unregTrans();
if (this._tmr) {
clearTimeout(this._tmr);
this._tmr = 0;
}
}
_progress(stepValue: number) {
// bread 'n butter
var i: number;
var prop: string;
var fx: EffectProperty;
var val: any;
var transforms: string[];
var tweenEffect: boolean;
for (i = 0; i < this._c.length; i++) {
this._c[i]._progress(stepValue);
}
if (this._el.length) {
// flip the number if we're going in reverse
if (this._rv) {
stepValue = ((stepValue * -1) + 1);
}
transforms = [];
for (prop in this._fx) {
fx = this._fx[prop];
if (fx.from && fx.to) {
tweenEffect = (fx.from.num !== fx.to.num);
if (tweenEffect) {
this.hasTween = true;
}
if (stepValue === 0) {
// FROM
val = fx.from.val;
} else if (stepValue === 1) {
// TO
val = fx.to.val;
} else if (tweenEffect) {
// EVERYTHING IN BETWEEN
val = (((fx.to.num - fx.from.num) * stepValue) + fx.from.num) + fx.to.unit;
} else {
val = null;
}
if (val !== null) {
if (fx.trans) {
transforms.push(prop + '(' + val + ')');
} else {
for (i = 0; i < this._el.length; i++) {
this._el[i].style[prop] = val;
}
}
}
}
}
// place all transforms on the same property
if (transforms.length) {
if (!this._wChg) {
// if the element doesn't support will-change
// then auto add translateZ for transform properties
transforms.push('translateZ(0px)');
}
for (i = 0; i < this._el.length; i++) {
this._el[i].style[CSS.transform] = transforms.join(' ');
}
}
}
}
_setTrans(duration: number, forcedLinearEasing: boolean) {
var i: number;
var easing: string;
// set the TRANSITION properties inline on the element
for (i = 0; i < this._c.length; i++) {
this._c[i]._setTrans(duration, forcedLinearEasing);
}
if (Object.keys(this._fx).length) {
for (i = 0; i < this._el.length; i++) {
// all parent/child animations should have the same duration
this._el[i].style[CSS.transitionDuration] = duration + 'ms';
// each animation can have a different easing
easing = (forcedLinearEasing ? 'linear' : this.getEasing());
if (easing) {
this._el[i].style[CSS.transitionTimingFn] = easing;
}
}
}
}
_willChg(addWillChange: boolean) {
var i: number;
var wc: string[];
var prop: string;
for (i = 0; i < this._c.length; i++) {
this._c[i]._willChg(addWillChange);
}
if (this._wChg) {
wc = [];
if (addWillChange) {
for (prop in this._fx) {
if (this._fx[prop].wc !== '') {
wc.push(this._fx[prop].wc);
}
}
}
for (i = 0; i < this._el.length; i++) {
this._el[i].style['willChange'] = wc.join(',');
}
}
}
_before() {
// before the RENDER_DELAY
// before the animations have started
var i: number;
var j: number;
var prop: string;
var ele: HTMLElement;
// stage all of the child animations
for (i = 0; i < this._c.length; i++) {
this._c[i]._before();
}
if (!this._rv) {
for (i = 0; i < this._el.length; i++) {
ele = this._el[i];
// css classes to add before the animation
for (j = 0; j < this._bfAdd.length; j++) {
ele.classList.add(this._bfAdd[j]);
}
// css classes to remove before the animation
for (j = 0; j < this._bfRmv.length; j++) {
ele.classList.remove(this._bfRmv[j]);
}
// inline styles to add before the animation
for (prop in this._bfSty) {
ele.style[prop] = this._bfSty[prop];
}
}
}
}
_after() {
// after the animations have finished
var i: number;
var j: number;
var prop: string;
var ele: HTMLElement;
for (i = 0; i < this._c.length; i++) {
this._c[i]._after();
}
for (i = 0; i < this._el.length; i++) {
ele = this._el[i];
// remove the transition duration/easing
ele.style[CSS.transitionDuration] = '';
ele.style[CSS.transitionTimingFn] = '';
if (this._rv) {
// finished in reverse direction
// css classes that were added before the animation should be removed
for (j = 0; j < this._bfAdd.length; j++) {
ele.classList.remove(this._bfAdd[j]);
}
// css classes that were removed before the animation should be added
for (j = 0; j < this._bfRmv.length; j++) {
ele.classList.add(this._bfRmv[j]);
}
// inline styles that were added before the animation should be removed
for (prop in this._bfSty) {
ele.style[prop] = '';
}
} else {
// finished in forward direction
// css classes to add after the animation
for (j = 0; j < this._afAdd.length; j++) {
ele.classList.add(this._afAdd[j]);
}
// css classes to remove after the animation
for (j = 0; j < this._afRmv.length; j++) {
ele.classList.remove(this._afRmv[j]);
}
// inline styles to add after the animation
for (prop in this._afSty) {
ele.style[prop] = this._afSty[prop];
}
}
}
}
progressStart() {
for (var i = 0; i < this._c.length; i++) {
this._c[i].progressStart();
}
this._before();
// force no duration, linear easing
this._setTrans(0, true);
}
progressStep(stepValue: number) {
let now = Date.now();
// only update if the last update was more than 16ms ago
if (now - 16 > this._lastUpd) {
this._lastUpd = now;
stepValue = Math.min(1, Math.max(0, stepValue));
for (var i = 0; i < this._c.length; i++) {
this._c[i].progressStep(stepValue);
}
if (this._rv) {
// if the animation is going in reverse then
// flip the step value: 0 becomes 1, 1 becomes 0
stepValue = ((stepValue * -1) + 1);
}
this._progress(stepValue);
}
}
progressEnd(shouldComplete: boolean, currentStepValue: number) {
console.debug('Animation, progressEnd, shouldComplete', shouldComplete, 'currentStepValue', currentStepValue);
for (var i = 0; i < this._c.length; i++) {
this._c[i].progressEnd(shouldComplete, currentStepValue);
}
// set all the animations to their final position
this._progress(shouldComplete ? 1 : 0);
// if it's already at the final position, or close, then it's done
// otherwise we need to add a transition end event listener
if (currentStepValue < 0.05 || currentStepValue > 0.95) {
// the progress was already left off at the point that is finished
// for example, the left menu was dragged all the way open already
this._after();
this._willChg(false);
this._didFinish(shouldComplete);
} else {
// the stepValue was left off at a point when it needs to finish transition still
// for example, the left menu was opened 75% and needs to finish opening
this._asyncEnd(64, shouldComplete);
// force quick duration, linear easing
this._setTrans(64, true);
}
}
onPlay(callback: Function): Animation {
this._pFns.push(callback);
return this;
}
onFinish(callback: Function, onceTimeCallback: boolean = false, clearOnFinishCallacks: boolean = false): Animation {
if (clearOnFinishCallacks) {
this._fFns = [];
this._fOnceFns = [];
}
if (onceTimeCallback) {
this._fOnceFns.push(callback);
} else {
this._fFns.push(callback);
}
return this;
}
_didFinish(hasCompleted: boolean) {
this.isPlaying = false;
this.hasCompleted = hasCompleted;
var i: number;
for (i = 0; i < this._fFns.length; i++) {
this._fFns[i](this);
}
for (i = 0; i < this._fOnceFns.length; i++) {
this._fOnceFns[i](this);
}
this._fOnceFns = [];
}
reverse(shouldReverse: boolean = true): Animation {
for (var i = 0; i < this._c.length; i++) {
this._c[i].reverse(shouldReverse);
}
this._rv = shouldReverse;
return this;
}
destroy(removeElement?: boolean) {
var i: number;
var ele: HTMLElement;
for (i = 0; i < this._c.length; i++) {
this._c[i].destroy(removeElement);
}
if (removeElement) {
for (i = 0; i < this._el.length; i++) {
ele = this._el[i];
ele.parentNode && ele.parentNode.removeChild(ele);
}
}
this._clearAsync();
this._reset();
}
_transEl(): HTMLElement {
// get the lowest level element that has an Animation
var i: number;
var targetEl: HTMLElement;
for (i = 0; i < this._c.length; i++) {
targetEl = this._c[i]._transEl();
if (targetEl) {
return targetEl;
}
}
return (this.hasTween && this._el.length ? this._el[0] : null);
}
/*
STATIC CLASSES
*/
static create(name: string, opts: AnimationOptions = {}): Animation {
let AnimationClass = AnimationRegistry[name];
if (!AnimationClass) {
// couldn't find an animation by the given name
// fallback to just the base Animation class
AnimationClass = Animation;
}
return new AnimationClass(null, opts);
}
static register(name: string, AnimationClass) {
AnimationRegistry[name] = AnimationClass;
}
}
export interface AnimationOptions {
animation?: string;
renderDelay?: number;
}
export interface PlayOptions {
duration?: number;
stepValue?: number;
}
interface EffectProperty {
trans: boolean;
wc: string;
to?: EffectState;
from?: EffectState;
}
interface EffectState {
val: any;
num: number;
unit: string;
}
const TRANSFORMS = {
'translateX':1, 'translateY':1, 'translateZ':1,
'scale':1, 'scaleX':1, 'scaleY':1, 'scaleZ':1,
'rotate':1, 'rotateX':1, 'rotateY':1, 'rotateZ':1,
'skewX':1, 'skewY':1, 'perspective':1
};
const CSS_VALUE_REGEX = /(^-?\d*\.?\d*)(.*)/;
let AnimationRegistry = {};