-
Notifications
You must be signed in to change notification settings - Fork 0
/
web-animations.js
2548 lines (2405 loc) · 79.3 KB
/
web-animations.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
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() {
function detectFeatures() {
var style = document.createElement('style');
style.textContent = '' +
'dummyRuleForTesting {' +
'width: calc(0px);' +
'width: -webkit-calc(0px); }';
document.head.appendChild(style);
var transformCandidates = [
'transform',
'webkitTransform',
'msTransform'
];
var transformProperty = transformCandidates.filter(function(property) {
return property in style.sheet.cssRules[0].style;
})[0];
var calcFunction = style.sheet.cssRules[0].style.width.split('(')[0];
document.head.removeChild(style);
return {
transformProperty: transformProperty,
calcFunction: calcFunction
};
}
var features = detectFeatures();
var createObject = function(proto, obj) {
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
var strip = function(str) {
return str.replace(/^\s+/, '').replace(/\s+$/, '');
};
var IndexSizeError = function(message) {
Error.call(this);
this.name = "IndexSizeError";
this.message = message;
};
IndexSizeError.prototype = Object.create(Error.prototype);
/** @constructor */
var Timing = function(timingDict) {
this.startDelay = timingDict.startDelay || 0.0;
this.duration = timingDict.duration;
if (this.duration < 0.0) {
throw new IndexSizeError('duration must be >= 0');
}
this.iterationCount = isDefined(timingDict.iterationCount) ?
timingDict.iterationCount : 1.0;
if (this.iterationCount < 0.0) {
throw new IndexSizeError('iterationCount must be >= 0');
}
this.iterationStart = timingDict.iterationStart || 0.0;
if (this.iterationStart < 0.0) {
throw new IndexSizeError('iterationStart must be >= 0');
}
this.playbackRate = isDefined(timingDict.playbackRate) ?
timingDict.playbackRate : 1.0;
//this.playbackRate = timingDict.playbackRate || 1.0;
this.direction = timingDict.direction || 'normal';
if (typeof timingDict.timingFunction === 'string') {
this.timingFunction =
TimingFunction.createFromString(timingDict.timingFunction);
} else {
this.timingFunction = timingDict.timingFunction;
}
this.fillMode = timingDict.fillMode || 'forwards';
};
Timing.prototype = {
// TODO: Is this supposed to be public?
clone: function() {
return new Timing({
startDelay: this.startDelay,
duration: this.duration,
iterationCount: this.iterationCount,
iterationStart: this.iterationStart,
playbackRate: this.playbackRate,
direction: this.direction,
timingFunction: this.timingFunction ? this.timingFunction.clone() : null,
fillMode: this.fillMode
});
}
};
/** @constructor */
var TimingProxy = function(timing, setter) {
this._timing = timing;
this._setter = setter;
};
TimingProxy.prototype = {
extractMutableTiming: function() {
return new Timing({
startDelay: this._timing.startDelay,
duration: this._timing.duration,
iterationCount: this._timing.iterationCount,
iterationStart: this._timing.iterationStart,
playbackRate: this._timing.playbackRate,
direction: this._timing.direction,
timingFunction: this._timing.timingFunction ?
this._timing.timingFunction.clone() : null,
fillMode: this._timing.fillMode
});
},
clone: function() {
return this._timing.clone();
}
};
// Configures an accessor descriptor for use with Object.defineProperty() to
// allow the property to be changed and enumerated, to match __defineGetter__()
// and __defineSetter__().
var configureDescriptor = function(descriptor) {
descriptor.configurable = true,
descriptor.enumerable = true;
return descriptor;
};
['startDelay', 'duration', 'iterationCount', 'iterationStart', 'playbackRate',
'direction', 'timingFunction', 'fillMode'].forEach(function(s) {
Object.defineProperty(TimingProxy.prototype, s, configureDescriptor({
get: function() {
return this._timing[s];
},
set: function(v) {
var old = this._timing[s];
this._timing[s] = v;
try {
this._setter(v);
} catch (e) {
this._timing[s] = old;
throw e;
}
},
}));
});
var isDefined = function(val) {
return typeof val !== 'undefined';
};
var isDefinedAndNotNull = function(val) {
return isDefined(val) && (val !== null);
};
/** @constructor */
var DocumentTimeline = function() {
};
DocumentTimeline.prototype = {
get currentTime() {
return documentTime();
},
play: function(source) {
return new Player(source, this);
},
// This is exposed for testing purposes.
// TODO: Consider adding this to the API.
_getPlayers: function() {
return PLAYERS;
},
};
// TODO: Remove dead Players from here?
var PLAYERS = [];
// Controls a tree of animations via its root TimedItem.
/** @constructor */
var Player = function(source, timeline) {
this.source = source;
this._timeline = timeline;
this._startTime =
this._timeline.currentTime === null ? 0 : this._timeline.currentTime;
this._timeDrift = 0.0;
this._pauseTime = undefined;
this.source.timeDrift = 0.0;
this._update();
PLAYERS.push(this);
maybeRestartAnimation();
};
Player.prototype = {
set source(source) {
if (isDefinedAndNotNull(this.source)) {
// To prevent infinite recursion.
var oldTimedItem = this.source;
this._source = null;
oldTimedItem._attach(null);
}
this._source = source;
if (isDefinedAndNotNull(this.source)) {
this.source._attach(this);
}
},
get source() {
return this._source;
},
set currentTime(currentTime) {
// This seeks by updating _drift. It does not affect the startTime.
if (!isDefined(this._pauseTime)) {
this._timeDrift =
this._timeline.currentTime - this.startTime - currentTime;
} else {
this._pauseTime = currentTime;
}
maybeRestartAnimation();
},
get currentTime() {
return !isDefined(this._pauseTime) ?
this._timeline.currentTime - this._timeDrift - this.startTime :
this._pauseTime;
},
set startTime(startTime) {
// This seeks by updating _startTime and hence the currentTime. It does not
// affect _drift.
this._startTime = startTime;
maybeRestartAnimation();
},
get startTime() {
return this._startTime;
},
set paused(isPaused) {
if (isPaused) {
this._pauseTime = this.currentTime;
} else if (isDefined(this._pauseTime)) {
this._timeDrift =
this._timeline.currentTime - this.startTime - this._pauseTime;
this._pauseTime = undefined;
maybeRestartAnimation();
}
},
get paused() {
return isDefined(this._pauseTime);
},
_update: function() {
if (this.source !== null) {
this.source._updateInheritedTime(this.currentTime);
}
},
_isPastEndOfActiveInterval: function() {
return this.source === null ||
this.source._isPastEndOfActiveInterval();
},
_getLeafItemsInEffect: function(items) {
if (this.source) {
this.source._getLeafItemsInEffect(items);
}
},
};
/** @constructor */
var TimedItem = function(timing, parentGroup) {
this.timing = new TimingProxy(interpretTimingParam(timing), function() {
this._updateInternalState();
}.bind(this));
this._inheritedTime = null;
this.currentIteration = null;
this.iterationTime = null;
this.animationTime = null;
this._startTime = 0.0;
// A TimedItem has either a _player, or a _parentGroup, or neither, but
// never both.
this._player = null;
// Note that we don't use the public setter, because we call _addInternal()
// below.
if (parentGroup === this) {
throw new Error('parentGroup can not be set to self!');
}
this._parentGroup = this._sanitizeParent(parentGroup);
this.timeDrift = 0;
if (this.parentGroup) {
// This will set our inheritedTime via _childrenStateModified().
this.parentGroup._addInternal(this);
}
this._updateInternalState();
};
TimedItem.prototype = {
// TODO: It would be good to avoid the need for this. We would need to modify
// call sites to instead rely on a call from the parent.
get _effectiveParentTime() {
return
this.parentGroup !== null && this.parentGroup.iterationTime !== null ?
this.parentGroup.iterationTime : 0;
},
get currentTime() {
return this._inheritedTime - this._startTime - this.timeDrift;
},
set currentTime(seekTime) {
this.timeDrift = this._inheritedTime - this._startTime - seekTime;
this._updateTimeMarkers();
},
get startTime() {
return this._startTime;
},
set duration(duration) {
this._duration = duration;
this._updateInternalState();
},
get duration() {
return isDefined(this._duration) ?
this._duration : (isDefined(this.timing.duration) ?
this.timing.duration : this._intrinsicDuration());
},
set animationDuration(animationDuration) {
this._animationDuration = animationDuration;
this._updateInternalState();
},
get animationDuration() {
if (isDefined(this._animationDuration)) {
return this._animationDuration;
}
var repeatedDuration = this.duration * this.timing.iterationCount;
return repeatedDuration / Math.abs(this.timing.playbackRate);
},
get endTime() {
return this._startTime + this.animationDuration + this.timing.startDelay +
this.timeDrift;
},
get parentGroup() {
return this._parentGroup;
},
_attach: function(player) {
// Remove ourselves from our parent, if we have one. This also removes any
// exsisting player.
this._reparent(null);
this._player = player;
},
_sanitizeParent: function(parentGroup) {
if (parentGroup === null || parentGroup instanceof AnimationGroup) {
return parentGroup;
} else if (!isDefined(parentGroup)) {
return null;
}
throw new TypeError('parentGroup is not an AnimationGroup');
},
// Takes care of updating the outgoing parent. This is called with a non-null
// parent only from AnimationGroup.splice(), which takes care of calling
// AnimationGroup._childrenStateModified() for the new parent.
_reparent: function(parentGroup) {
if (parentGroup === this) {
throw new Error('parentGroup can not be set to self!');
}
if (this._player !== null) {
this._player.source = null;
this._player = null;
}
if (this.parentGroup !== null) {
this.parentGroup.remove(this.parentGroup.indexOf(this), 1);
}
this._parentGroup = parentGroup;
this.timeDrift = 0;
// In the case of a SeqGroup parent, _startTime will be updated by
// AnimationGroup.splice().
if (this.parentGroup === null || this.parentGroup.type !== 'seq') {
this._startTime =
this._stashedStartTime === undefined ? 0.0 : this._stashedStartTime;
this._stashedStartTime = undefined;
}
// In the case of the parent being non-null, _childrenStateModified() will
// call this via _updateChildInheritedTimes().
// TODO: Consider optimising this case by skipping this call.
this._updateTimeMarkers();
},
_intrinsicDuration: function() {
return 0.0;
},
_updateInternalState: function() {
if (this.parentGroup) {
this.parentGroup._childrenStateModified();
}
this._updateTimeMarkers();
},
// We push time down to children. We could instead have children pull from
// above, but this is tricky because a TImedItem may use either a parent
// TimedItem or an Player. This requires either logic in
// TimedItem, or for TimedItem and Player to implement Timeline
// (or an equivalent), both of which are ugly.
_updateInheritedTime: function(inheritedTime) {
this._inheritedTime = inheritedTime;
this._updateTimeMarkers();
},
_updateItemTime: function() {
if (this._inheritedTime !== null) {
this.itemTime = this._inheritedTime - this._startTime - this.timeDrift;
} else {
this.itemTime = null;
}
},
_updateAnimationTime: function() {
if (this.itemTime < this.timing.startDelay) {
if (this.timing.fillMode === 'backwards' ||
this.timing.fillMode === 'both') {
this.animationTime = 0;
} else {
this.animationTime = null;
}
} else if (this.itemTime <=
this.timing.startDelay + this.animationDuration) {
this.animationTime = this.itemTime - this.timing.startDelay;
} else {
if (this.timing.fillMode === 'forwards' ||
this.timing.fillMode === 'both') {
this.animationTime = this.animationDuration;
} else {
this.animationTime = null;
}
}
},
_updateIterationParamsZeroDuration: function() {
this.iterationTime = 0;
var isAtEndOfIterations = this.timing.iterationCount != 0 &&
this.itemTime >= this.timing.startDelay;
this.currentIteration = isAtEndOfIterations ?
this._floorWithOpenClosedRange(this.timing.iterationStart +
this.timing.iterationCount, 1.0) :
this._floorWithClosedOpenRange(this.timing.iterationStart, 1.0);
// Equivalent to unscaledIterationTime below.
var unscaledFraction = isAtEndOfIterations ?
this._modulusWithOpenClosedRange(this.timing.iterationStart +
this.timing.iterationCount, 1.0) :
this._modulusWithClosedOpenRange(this.timing.iterationStart, 1.0);
this._timeFraction = this._isCurrentDirectionForwards(
this.timing.direction, this.currentIteration) ?
unscaledFraction :
1.0 - unscaledFraction;
if (this.timing.timingFunction) {
this._timeFraction = this.timing.timingFunction.scaleTime(
this._timeFraction);
}
},
_getAdjustedAnimationTime: function(animationTime) {
var startOffset =
multiplyZeroGivesZero(this.timing.iterationStart, this.duration);
return (this.timing.playbackRate < 0 ?
(animationTime - this.animationDuration) : animationTime) *
this.timing.playbackRate + startOffset;
},
_scaleIterationTime: function(unscaledIterationTime) {
return this._isCurrentDirectionForwards(
this.timing.direction, this.currentIteration) ?
unscaledIterationTime :
this.duration - unscaledIterationTime;
},
_updateIterationParams: function() {
var adjustedAnimationTime =
this._getAdjustedAnimationTime(this.animationTime);
var repeatedDuration = this.duration * this.timing.iterationCount;
var startOffset = this.timing.iterationStart * this.duration;
var isAtEndOfIterations = (this.timing.iterationCount != 0) &&
(adjustedAnimationTime - startOffset == repeatedDuration);
this.currentIteration = isAtEndOfIterations ?
this._floorWithOpenClosedRange(
adjustedAnimationTime, this.duration) :
this._floorWithClosedOpenRange(
adjustedAnimationTime, this.duration);
var unscaledIterationTime = isAtEndOfIterations ?
this._modulusWithOpenClosedRange(
adjustedAnimationTime, this.duration) :
this._modulusWithClosedOpenRange(
adjustedAnimationTime, this.duration);
this.iterationTime = this._scaleIterationTime(unscaledIterationTime);
this._timeFraction = this.iterationTime / this.duration;
if (this.timing.timingFunction) {
this._timeFraction = this.timing.timingFunction.scaleTime(
this._timeFraction);
this.iterationTime = this._timeFraction * this.duration;
}
},
_updateTimeMarkers: function() {
this._updateItemTime();
if (this.itemTime === null) {
this.animationTime = null;
this.iterationTime = null;
this.currentIteration = null;
this._timeFraction = null;
return false;
}
this._updateAnimationTime();
if (this.animationTime === null) {
this.iterationTime = null;
this.currentIteration = null;
this._timeFraction = null;
} else if (this.duration == 0) {
this._updateIterationParamsZeroDuration();
} else {
this._updateIterationParams();
}
maybeRestartAnimation();
},
changePlaybackRate: function(playbackRate) {
var previousRate = this.timing.playbackRate;
this.timing.playbackRate = playbackRate;
if (previousRate == 0 || playbackRate == 0) {
return;
}
// TODO: invert the fillMode?
var seekAdjustment = (this.itemTime - this.timing.startDelay) *
(1 - previousRate / playbackRate);
this.currentTime = this.itemTime - seekAdjustment;
},
_floorWithClosedOpenRange: function(x, range) {
return Math.floor(x / range);
},
_floorWithOpenClosedRange: function(x, range) {
return Math.ceil(x / range) - 1;
},
_modulusWithClosedOpenRange: function(x, range) {
return x % range;
},
_modulusWithOpenClosedRange: function(x, range) {
var ret = this._modulusWithClosedOpenRange(x, range);
return ret == 0 ? range : ret;
},
_isCurrentDirectionForwards: function(direction, currentIteration) {
if (direction == 'normal') {
return true;
}
if (direction == 'reverse') {
return false;
}
var d = currentIteration;
if (direction == 'alternate-reverse') {
d += 1;
}
// TODO: 6.13.3 step 3. wtf?
return d % 2 == 0;
},
clone: function() {
throw new Error(
"Derived classes must override TimedItem.clone()");
},
// Gets the leaf TimedItems currently in effect. Note that this is a superset
// of the leaf TimedItems in their active interval, as a TimedItem can have an
// effect outside its active interval due to fill.
_getLeafItemsInEffect: function(items) {
if (this._timeFraction !== null) {
this._getLeafItemsInEffectImpl(items);
}
},
_getLeafItemsInEffectImpl: function(items) {
throw new Error(
"Derived classes must override TimedItem._getLeafItemsInEffectImpl()");
},
_isPastEndOfActiveInterval: function() {
return this._player.currentTime > this.endTime;
},
getPlayer: function() {
return this.parentGroup === null ?
this._player : this.parentGroup.getPlayer();
}
};
var isCustomAnimationFunction = function(animationFunction) {
// TODO: How does WebIDL actually differentiate different callback interfaces?
return typeof animationFunction === "object" &&
animationFunction.hasOwnProperty("sample") &&
typeof animationFunction.sample === "function";
};
var interpretAnimationFunction = function(animationFunction) {
if (animationFunction instanceof AnimationFunction) {
return animationFunction;
} else if (typeof animationFunction === 'object') {
if (isCustomAnimationFunction(animationFunction)) {
return animationFunction;
} else {
return AnimationFunction.createFromProperties(animationFunction);
}
} else {
try {
throw new Error('TypeError');
} catch (e) { console.log(e.stack); throw e; }
}
};
var cloneAnimationFunction = function(animationFunction) {
if (animationFunction instanceof AnimationFunction) {
return animationFunction.clone();
} else if (isCustomAnimationFunction(animationFunction)) {
if (typeof animationFunction.clone === "function") {
return animationFunction.clone();
} else {
return animationFunction;
}
} else {
return null;
}
};
var interpretTimingParam = function(timing) {
if (!isDefinedAndNotNull(timing)) {
return new Timing({});
}
if (timing instanceof Timing || timing instanceof TimingProxy) {
return timing;
}
if (typeof(timing) === 'number') {
return new Timing({duration: timing});
}
if (typeof(timing) === 'object') {
return new Timing(timing);
}
throw new TypeError('timing parameters must be undefined, Timing objects, ' +
'numbers, or timing dictionaries; not \'' + timing + '\'');
};
/** @constructor */
var Animation = function(target, animationFunction, timing, parentGroup) {
this.animationFunction = interpretAnimationFunction(animationFunction);
this.timing = interpretTimingParam(timing);
TimedItem.call(this, timing, parentGroup);
this.targetElement = target;
this.name = this.animationFunction instanceof KeyframesAnimationFunction ?
this.animationFunction.property : '<anon>';
};
Animation.prototype = createObject(TimedItem.prototype, {
_sample: function() {
this.animationFunction.sample(this._timeFraction,
this.currentIteration, this.targetElement,
this.underlyingValue);
},
_getLeafItemsInEffectImpl: function(items) {
items.push(this);
},
clone: function() {
return new Animation(this.targetElement,
cloneAnimationFunction(this.animationFunction), this.timing.clone());
},
toString: function() {
var funcDescr = this.animationFunction instanceof AnimationFunction ?
this.animationFunction.toString() : 'Custom scripted function';
return 'Animation ' + this.startTime + '-' + this.endTime + ' (' +
this.timeDrift + ' @' + this.currentTime + ') ' + funcDescr;
}
});
/** @constructor */
var AnimationGroup = function(type, children, timing, parentGroup) {
// Take a copy of the children array, as it could be modified as a side-effect
// of creating this object. See
// https://github.com/web-animations/web-animations-js/issues/65 for details.
var childrenCopy = (children && Array.isArray(children)) ?
children.slice() : [];
// used by TimedItem via _intrinsicDuration(), so needs to be set before
// initializing super.
this.type = type || 'par';
this.children = [];
this.length = 0;
TimedItem.call(this, timing, parentGroup);
// We add children after setting the parent. This means that if an ancestor
// (including the parent) is specified as a child, it will be removed from our
// ancestors and used as a child,
for (var i = 0; i < childrenCopy.length; i++) {
this.add(childrenCopy[i]);
}
// TODO: Work out where to expose name in the API
// this.name = properties.name || '<anon>';
};
AnimationGroup.prototype = createObject(TimedItem.prototype, {
_childrenStateModified: function() {
// See _updateChildStartTimes().
this._isInOnChildrenStateModified = true;
// We need to walk up and down the tree to re-layout. endTime and the
// various durations (which are all calculated lazily) are the only
// properties of a TimedItem which can affect the layout of its ancestors.
// So it should be sufficient to simply update start times and time markers
// on the way down.
// This calls up to our parent, then calls _updateTimeMarkers().
this._updateInternalState();
this._updateChildInheritedTimes();
// Update child start times before walking down.
this._updateChildStartTimes();
this._isInOnChildrenStateModified = false;
},
_updateInheritedTime: function(inheritedTime) {
this._inheritedTime = inheritedTime;
this._updateTimeMarkers();
this._updateChildInheritedTimes();
},
_updateChildInheritedTimes: function() {
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
child._updateInheritedTime(this.iterationTime);
}
},
_updateChildStartTimes: function() {
if (this.type == 'seq') {
var cumulativeStartTime = 0;
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if (child._stashedStartTime === undefined) {
child._stashedStartTime = child._startTime;
}
child._startTime = cumulativeStartTime;
// Avoid updating the child's inherited time and time markers if this is
// about to be done in the down phase of _childrenStateModified().
if (!child._isInOnChildrenStateModified) {
// This calls _updateTimeMarkers() on the child.
child._updateInheritedTime(this.iterationTime);
}
cumulativeStartTime += Math.max(0, child.timing.startDelay +
child.animationDuration);
}
}
},
getAnimationsForElement: function(elem) {
var result = [];
for (var i = 0; i < this.children.length; i++) {
if (this.children[i].getAnimationsForElement) {
result = result.concat(this.children[i].getAnimationsForElement(elem));
} else if (this.children[i].targetElement == elem) {
result.push(this.children[i]);
}
}
return result;
},
_intrinsicDuration: function() {
if (this.type == 'par') {
var dur = Math.max.apply(undefined, this.children.map(function(a) {
return a.endTime;
}));
return Math.max(0, dur);
} else if (this.type == 'seq') {
var result = 0;
this.children.forEach(function(a) {
result += a.animationDuration + a.timing.startDelay;
});
return result;
} else {
throw 'Unsupported type ' + this.type;
}
},
_getLeafItemsInEffectImpl: function(items) {
for (var i = 0; i < this.children.length; i++) {
this.children[i]._getLeafItemsInEffect(items);
}
},
clone: function() {
var children = [];
this.children.forEach(function(child) {
children.push(child.clone());
});
return this.type === "par" ?
new ParGroup(children, this.timing.clone()) :
new SeqGroup(children, this.timing.clone());
},
_lengthChanged: function() {
while (this.length < this.children.length) {
var i = this.length++;
Object.defineProperty(this, i, configureDescriptor({
set: function(x) { this.children[i] = x; },
get: function() { return this.children[i]; },
}));
}
while (this.length > this.children.length) {
var i = --this.length;
delete this[i];
}
},
clear: function() {
this.splice(0, this.children.length);
},
add: function() {
var newItems = [];
for (var i = 0; i < arguments.length; i++) {
newItems.push(arguments[i]);
}
this.splice(this.length, 0, newItems);
return newItems;
},
_addInternal: function(child) {
this.children.push(child);
this._lengthChanged();
this._childrenStateModified();
},
indexOf: function(item) {
return this.children.indexOf(item);
},
splice: function(start, deleteCount, newItems) {
var args = arguments;
if (args.length == 3) {
args = [start, deleteCount].concat(newItems);
}
for (var i = 2; i < args.length; i++) {
var newChild = args[i];
// Check whether the new child is an ancestor. If so, we need to break the
// chain immediately below the new child.
for (var ancestor = this; ancestor.parentGroup != null;
ancestor = ancestor.parentGroup) {
if (ancestor.parentGroup === newChild) {
newChild.remove(ancestor);
break;
}
}
newChild._reparent(this);
}
var result = Array.prototype['splice'].apply(this.children, args);
for (var i = 0; i < result.length; i++) {
result[i]._parentGroup = null;
}
this._lengthChanged();
this._childrenStateModified();
return result;
},
remove: function(index, count) {
if (!isDefined(count)) {
count = 1;
}
return this.splice(index, count);
},
toString: function() {
return this.type + ' ' + this.startTime + '-' + this.endTime + ' (' +
this.timeDrift + ' @' + this.currentTime + ') ' + ' [' +
this.children.map(function(a) { return a.toString(); }) + ']'
},
});
/** @constructor */
var ParGroup = function(children, timing, parentGroup) {
AnimationGroup.call(this, 'par', children, timing, parentGroup);
};
ParGroup.prototype = Object.create(AnimationGroup.prototype);
/** @constructor */
var SeqGroup = function(children, timing, parentGroup) {
AnimationGroup.call(this, 'seq', children, timing, parentGroup);
};
SeqGroup.prototype = Object.create(AnimationGroup.prototype);
/** @constructor */
var AnimationFunction = function(operation, accumulateOperation) {
this.operation = operation === undefined ? 'replace' : operation;
this.accumulateOperation =
accumulateOperation == undefined ? 'replace' : operation;
};
AnimationFunction.prototype = {
sample: function(timeFraction, currentIteration, target) {
throw 'Unimplemented sample function';
},
getValue: function(target) {
return;
},
clone: function() {
throw 'Unimplemented clone method'
}
};
AnimationFunction.createFromProperties = function(properties) {
// Step 1 - determine set of animation properties
var animProps = [];
for (var candidate in properties) {
if (candidate == 'operation') {
continue;
}
animProps.push(candidate);
}
// Step 2 - Create AnimationFunction objects
if (animProps.length === 0) {
return null;
} else if (animProps.length === 1) {
return AnimationFunction._createKeyframeFunction(
animProps[0], properties[animProps[0]], properties.operation);
} else {
var result = new GroupedAnimationFunction();
for (var i = 0; i < animProps.length; i++) {
result.add(AnimationFunction._createKeyframeFunction(
animProps[i], properties[animProps[i]], properties.operation));
}
return result;
}
}
// Step 3 - Create a KeyframesAnimationFunction object
AnimationFunction._createKeyframeFunction =
function(property, value, operation) {
var func = new KeyframesAnimationFunction(property);
if (typeof value === 'string') {
func.frames.add(new Keyframe(value, 0));
func.frames.add(new Keyframe(value, 1));
func.operation = 'merge';
} else if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
if (typeof value[i] !== 'string') {
var val = isDefinedAndNotNull(value[i].value) ? value[i].value : "";
var offset = isDefinedAndNotNull(value[i].offset) ? value[i].offset : 1;
func.frames.add(new Keyframe(val, offset));
} else {
var offset = i / (value.length - 1);
func.frames.add(new Keyframe(value[i], offset));
}
}
} else {
try {
throw new Error('TypeError');
} catch (e) { console.log(e.stack); throw e; }
}
if (isDefinedAndNotNull(operation)) {
func.operation = operation;
}
return func;
}
/** @constructor */
var GroupedAnimationFunction = function() {
AnimationFunction.call(this);
this.children = [];
};
GroupedAnimationFunction.prototype = createObject(AnimationFunction.prototype, {
item: function(i) {
return this.children[i];
},
add: function(func) {
this.children.push(func);
},
remove: function(i) {
this.children.splice(i, 1);
},
sample: function(timeFraction, currentIteration, target) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].sample(timeFraction, currentIteration, target);
}
},
clone: function() {
var result = new GroupedAnimationFunction();
for (var i = 0; i < this.children.length; i++) {
result.add(this.children[i].clone());
}
},
get length() {
return this.children.length;
}
});
/** @constructor */
var PathAnimationFunction = function(path, operation, accumulateOperation) {
AnimationFunction.call(this, operation, accumulateOperation);
// TODO: path argument is not in the spec -- seems useful since
// SVGPathSegList doesn't have a constructor.
this._path = path;
};
PathAnimationFunction.prototype = createObject(AnimationFunction.prototype, {
sample: function(timeFraction, currentIteration, target) {
var length = this._path.getTotalLength();
var point = this._path.getPointAtLength(timeFraction * length);
var x = point.x - target.offsetWidth / 2;
var y = point.y - target.offsetHeight / 2;
// TODO: calc(point.x - 50%) doesn't work?
var value = [{t: 'translate', d: [{px: x}, {px: y}]}];