-
Notifications
You must be signed in to change notification settings - Fork 20
/
smil-in-javascript.js
1445 lines (1291 loc) · 44.1 KB
/
smil-in-javascript.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 2014 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() {
'use strict';
var observedTags = {
animate: true,
animateMotion: true,
animateTransform: true,
mpath: true,
set: true
};
var observedAttributes = {
accumulate: true,
additive: true,
attributeName: true,
attributeType: true, // For animate and set elements: CSS | XML | auto
begin: true,
by: true,
calcMode: true,
dur: true,
end: true,
fill: true,
from: true,
keyPoints: true,
keySplines: true,
keyTimes: true,
max: true,
min: true,
onbegin: true,
onend: true,
onrepeat: true,
path: true,
repeatCount: true,
repeatDur: true,
restart: true,
rotate: true,
to: true,
type: true, // animatetransform: translate | scale | rotate | skewX | skewY
values: true,
'xlink:href': true
};
// These events are specified in
// http://www.w3.org/TR/SVG/interact.html#SVGEvents
var elementEvents = {
focusin: true,
focusout: true,
activate: true,
click: true,
mousedown: true,
mouseup: true,
mouseover: true,
mousemove: true,
mouseout: true,
DOMSubtreeModified: true,
DOMNodeInserted: true,
DOMNodeRemoved: true,
DOMNodeRemovedFromDocument: true,
DOMNodeInsertedIntoDocument: true,
DOMAttrModified: true,
DOMCharacterDataModified: true,
SVGLoad: true,
SVGUnload: true,
SVGAbort: true,
SVGError: true,
SVGResize: true,
SVGScroll: true,
SVGZoom: true,
beginEvent: true,
endEvent: true,
repeatEvent: true
};
// Control debug logging.
var verbose = false;
// indexed by animationRecordId and by element id
var animationRecords = {};
// Animations waiting for their target element to be created
var waitingAnimationRecords = {};
// Dependent time values waiting for their timebase element or its
// AnimationRecord to be created
var waitingDependentTimeValues = {};
// map from accessKey to TimeValueSpecification list
// null if there are not yet any elements waiting for an accessKey
var accessKeyTimeValueSpecs = null;
/** @constructor */
var PriorityQueue = function() {
// Each entry in the priority queue has a 'scheduleTime' property.
// We implement the priority queue using a heap.
// heap[0] is unused
// heap[1] has the earliest scheduleTime
// The children of heap[i] are heap[2 * i] and heap[2 * i + 1]
// The parent of heap[i] is heap[(i - i % 2) / 2]
this.heap = [null];
// We store in each entry a 'heapIndex' property, so we can efficiently
// remove any entry from the queue.
};
PriorityQueue.prototype = {
insert: function(newEntry) {
if (!isFinite(newEntry.scheduleTime)) {
throw new Error('newEntry.scheduleTime is not finite');
}
var index = this.heap.length;
this.heap.push(null);
this.shiftUp(index, newEntry);
},
remove: function(existingEntry) {
var index = existingEntry.heapIndex;
existingEntry.heapIndex = null;
var lastEntry = this.heap.pop();
if (lastEntry === existingEntry)
return;
if (index === 1) {
this.shiftDown(index, lastEntry);
return;
}
var parentIndex = (index - index % 2) / 2;
if (this.heap[parentIndex].scheduleTime <
lastEntry.scheduleTime) {
this.shiftDown(index, lastEntry);
} else {
this.shiftUp(index, lastEntry);
}
},
shiftUp: function(index, entry) {
while (index != 1) {
var parentIndex = (index - index % 2) / 2;
if (this.heap[parentIndex].scheduleTime <=
entry.scheduleTime) {
break;
}
this.heap[index] = this.heap[parentIndex];
this.heap[index].heapIndex = index;
index = parentIndex;
}
this.heap[index] = entry;
this.heap[index].heapIndex = index;
},
shiftDown: function(index, entry) {
while (2 * index < this.heap.length) {
var childIndex = 2 * index;
if (childIndex + 1 < this.heap.length &&
(this.heap[childIndex + 1].scheduleTime <
this.heap[childIndex].scheduleTime)) {
++childIndex;
}
if (entry.scheduleTime <=
this.heap[childIndex].scheduleTime) {
break;
}
this.heap[index] = this.heap[childIndex];
this.heap[index].heapIndex = index;
index = childIndex;
}
this.heap[index] = entry;
this.heap[index].heapIndex = index;
},
earliestScheduleTime: function() {
if (this.heap.length === 1) {
return Infinity;
}
return this.heap[1].scheduleTime;
},
// returns null if no entry has scheduleTime <= currentTime
extractFirst: function(currentTime) {
if (this.heap.length === 1 ||
currentTime < this.heap[1].scheduleTime) {
return null;
}
var first = this.heap[1];
this.remove(first);
return first;
}
};
var masterScheduler = {
scheduledAnimationRecords: new PriorityQueue(),
insertAnimationRecord: function(animationRecord) {
this.scheduledAnimationRecords.insert(animationRecord);
},
removeAnimationRecord: function(animationRecord) {
this.scheduledAnimationRecords.remove(animationRecord);
},
processingPendingRecords: function() {
var currentTime = document.timeline.currentTime;
var animationRecord;
while ((animationRecord =
this.scheduledAnimationRecords.extractFirst(currentTime))) {
animationRecord.processNow();
}
}
};
// FIXME: use a custom effect callback instead of polling
window.requestAnimationFrame(function pollSchedule() {
masterScheduler.processingPendingRecords();
window.requestAnimationFrame(pollSchedule);
});
/** @constructor */
var InstanceTimeList = function() {
// Each entry in the list has a 'scheduleTime' property.
// We implement the instance time list using an array, sorted by scheduleTime.
// entry[0] has the earliest scheduleTime
this.entries = [];
};
InstanceTimeList.prototype = {
insert: function(newEntry) {
var index = this.binarySearch(newEntry.scheduleTime);
this.entries.splice(index, 0, newEntry);
},
remove: function(existingEntry) {
var index = this.binarySearch(existingEntry.scheduleTime);
while (this.entries[index] !== existingEntry) {
++index;
}
this.entries.splice(index, 1);
},
binarySearch: function(scheduleTime) {
var first = 0;
var last = this.entries.length;
// We search [first,last)
while (first !== last) {
var middle = (first + last) >> 1;
if (this.entries[middle].scheduleTime < scheduleTime) {
first = middle + 1;
} else {
last = middle;
}
}
if (first < this.entries.length &&
this.entries[first].scheduleTime < scheduleTime) {
first = first + 1;
}
return first;
},
earliestScheduleTime: function() {
if (this.entries.length === 0) {
return Infinity;
}
return this.entries[0].scheduleTime;
},
// returns null if no entry has scheduleTime <= currentTime
extractFirst: function(currentTime) {
if (this.entries.length === 0 ||
currentTime < this.entries[0].scheduleTime) {
return null;
}
return this.entries.shift();
}
};
// Implements http://www.w3.org/TR/SVG/animate.html#ClockValueSyntax
// Converts value to milliseconds.
function parseClockValue(value) {
var result;
if (value === 'indefinite') {
result = Infinity;
} else if (value.indexOf(':') === -1) {
// We have a Timecount value
result = parseFloat(value);
if (value.indexOf('h') !== -1) {
result *= 3600000;
} else if (value.indexOf('min') !== -1) {
result *= 60000;
} else if (value.indexOf('ms') === -1) { // The default unit is seconds
result *= 1000;
} // else milliseconds
} else {
var components = value.split(':');
result = parseInt(components[0]) * 60;
if (components.length === 2) {
// Partial clock value with minutes : seconds [.fraction]
result += parseFloat(components[1]);
} else {
// Full clock value with hours : minutes : seconds [.fraction]
result += parseInt(components[1]);
result *= 60;
result += parseFloat(components[2]);
}
result *= 1000;
}
return result;
}
// Implements http://www.w3.org/TR/SMIL3/smil-timing.html#q23
// Converts value to milliseconds.
function parseOffsetValue(value) {
value = value.trim();
if (value[0] === '+') {
return parseClockValue(value.substring(1).trim());
} else if (value[0] === '-') {
return -parseClockValue(value.substring(1).trim());
} else {
return parseClockValue(value);
}
var result;
}
function nonEscapedIndexOf(str, searchValue) {
var start = 0;
var index = str.indexOf(searchValue, start);
while (index > 0 && str[index - 1] === '\\') {
index = str.indexOf(searchValue, index + 1);
}
return index;
}
// Used by parseBeginEnd to implement
// http://www.w3.org/TR/SMIL3/smil-timing.html#Timing-BeginValueListSyntax
// Returns a TimeValueSpecification, or undefined
function parseBeginEndValue(value) {
var result;
value = value.trim();
if (value === '') {
return undefined;
}
var initial = value[0];
if ((initial >= '0' && initial <= '9') || initial == '+' || initial == '-') {
return parseOffsetValue(value);
} else if (value.substring(0, 9) === 'wallclock') {
// FIXME: support wallclock sync values.
return undefined;
} else if (value === 'indefinite') {
return Infinity;
} else {
var plusIndex = value.indexOf('+');
// \- is ignored when delimiting,
// and treated as - in id or symbol
// http://www.w3.org/TR/SMIL3/smil-timing.html#q21
var minusIndex = nonEscapedIndexOf(value, '-');
var offsetIndex;
if (plusIndex === -1) {
offsetIndex = minusIndex;
} else if (minusIndex === -1) {
offsetIndex = plusIndex;
} else {
offsetIndex = Math.min(plusIndex, minusIndex);
}
var token;
var offset;
if (offsetIndex === -1) {
token = value;
offset = 0;
} else {
token = value.substring(0, offsetIndex).trim();
offset = parseOffsetValue(value.substring(offsetIndex));
}
// \. is ignored when delimiting,
// and treated as . in id or symbol
// http://www.w3.org/TR/SMIL3/smil-timing.html#q21
var separatorIndex = nonEscapedIndexOf(token, '.');
if (separatorIndex === -1) {
if (token.indexOf('accessKey(') === 0 &&
token[token.length - 1] === ')') {
return {
accessKey: token['accessKey('.length].charCodeAt(),
offset: offset
};
} else if (token in elementEvents) {
return {
eventKind: token,
offset: offset
};
} else {
return undefined;
}
}
// http://www.w3.org/TR/SMIL2/smil-timing.html#Timing-SyncbaseValueSyntax
// http://www.w3.org/TR/SMIL2/smil-timing.html#Timing-EventValueSyntax
// No white space allowed between a syncbase element and a time-symbol.
// No white space allowed between an eventbase element and an event-symbol.
var id = value.substring(0, separatorIndex).replace(/\\/g, '');
var suffix = token.substring(separatorIndex + 1);
if (suffix !== 'begin' && suffix !== 'end' &&
!(suffix in elementEvents)) {
return undefined;
}
result = {};
result.id = id;
if (suffix === 'begin' || suffix === 'end') {
result.timeSymbol = suffix;
} else {
result.eventKind = suffix;
}
result.offset = offset;
return result;
}
}
// Implements
// http://www.w3.org/TR/SMIL3/smil-timing.html#Timing-BeginValueListSyntax
function parseBeginEnd(isBegin, value) {
var result = [];
var entry;
if (value) {
var components = value.split(';');
for (var index = 0; index < components.length; ++index) {
entry = parseBeginEndValue(components[index]);
if (entry !== undefined) {
result.push(entry);
}
}
}
if (!result.length) {
var fallbackOffset = isBegin ? 0 : Infinity;
result.push(fallbackOffset);
}
return result;
}
var animationRecordCounter = 0;
/** @constructor */
var AnimationRecord = function(element) {
this.element = element;
this.nodeName = element.nodeName;
this.parentNode = element.parentNode;
this.startTime = Infinity; // not playing
this.animationRecordId = animationRecordCounter.toString();
++animationRecordCounter;
this.scheduleTime = Infinity;
this.beginInstanceTimes = new InstanceTimeList();
this.endInstanceTimes = new InstanceTimeList();
this.dependents = [];
this.activeState = 'preActive'; // 'active' on begin, 'postActive' on end
var attributes = element.attributes;
for (var index = 0; index < attributes.length; ++index) {
var attributeName = attributes[index].name;
if (attributeName in observedAttributes) {
this[attributeName] = attributes[index].value;
}
}
var targetRef = this['xlink:href'];
if (targetRef && targetRef[0] === '#') {
targetRef = targetRef.substring(1);
this.target =
document.getElementById(targetRef);
if (!(this.target instanceof SVGElement)) {
// Only animate SVG elements
this.target = null;
}
if (!this.target) {
var waiting = waitingAnimationRecords[targetRef];
if (!waiting) {
waiting = [];
waitingAnimationRecords[targetRef] = waiting;
}
waiting.push(this);
}
} else {
this.target = element.parentNode;
}
this.createEventListeners();
this.createTimingInput();
this.createEffectOptions();
if (this.nodeName === 'mpath') {
var parentRecord = animationRecords[element.parentNode.animationRecordId];
if (parentRecord) {
parentRecord.mpathRecord = this;
}
} else {
this.processBeginEndSpec(true, this['begin']);
this.processBeginEndSpec(false, this['end']);
if (this.nodeName !== 'animateMotion') {
this.createKeyframeAnimation();
}
// else we have animateMotion, and wait in case we have an mpath child
}
};
function createEventListener(element, eventType, script) {
if (!script) {
return;
}
try {
var action = new Function(script);
element.addEventListener(eventType, action);
} catch (ex) {
if (verbose) {
console.log('on' + eventType + ': ' + ex);
}
}
}
AnimationRecord.prototype = {
createEventListeners: function() {
// The onbegin, onend and onrepeat attributes are specified at
// http://www.w3.org/TR/SVG/script.html#AnimationEvents
createEventListener(this.element, 'begin', this.onbegin);
createEventListener(this.element, 'end', this.onend);
createEventListener(this.element, 'repeat', this.onrepeat);
},
addDependent: function(dependentTimeValue) {
this.dependents.push(dependentTimeValue);
dependentTimeValue.timebase = this;
},
createTimingInput: function() {
var timingInput = {};
if (this.dur) {
timingInput.duration = parseClockValue(this.dur);
} else {
// Absent duration means infinite duration.
timingInput.duration = Infinity;
}
if (this.repeatCount) {
if (this.repeatCount === 'indefinite') {
timingInput.iterations = Infinity;
} else {
timingInput.iterations = parseFloat(this.repeatCount);
}
if (timingInput.duration === 0 || timingInput.iterations === 0) {
// http://www.w3.org/TR/SMIL3/smil-timing.html#q79
// zero value * value = zero value
// zero value * indefinite = zero value
// e.g. 0 instead of NaN when {duration, iterations} = {0, Infinity}
this.repeatDuration = 0;
timingInput.duration = 0;
} else {
this.repeatDuration = timingInput.duration * timingInput.iterations;
}
} else {
this.repeatDuration = timingInput.duration;
}
if (this.repeatDur) {
if (this.repeatCount) {
this.repeatDuration = Math.min(
this.repeatDuration,
parseClockValue(this.repeatDur));
} else {
this.repeatDuration = parseClockValue(this.repeatDur);
}
if (timingInput.duration === 0) {
timingInput.iterations = 0;
} else {
timingInput.iterations = this.repeatDuration / timingInput.duration;
}
}
// http://www.w3.org/TR/smil/smil-timing.html#adef-restart
// http://www.w3.org/TR/smil/smil-timing.html#adef-restartDefault
if (!this.restart || this.restart === 'default') {
var ancestor = this.element;
var restartDefault = ancestor.getAttribute('restartdefault');
// Fall back to the inherited restartDefault if necessary
while ((!restartDefault || restartDefault === 'inherit') &&
ancestor.parentNode &&
ancestor.parentNode.getAttribute) {
ancestor = ancestor.parentNode;
restartDefault = ancestor.getAttribute('restartdefault');
}
this.restart = restartDefault;
}
// http://www.w3.org/TR/smil/smil-timing.html#adef-fill
// http://www.w3.org/TR/smil/smil-timing.html#adef-fillDefault
if (!this.fill || this.fill === 'default') {
var ancestor = this.element;
var fillDefault = ancestor.getAttribute('filldefault');
// Fall back to the inherited fillDefault if necessary
while ((!fillDefault || fillDefault === 'inherit') &&
ancestor.parentNode &&
ancestor.parentNode.getAttribute) {
ancestor = ancestor.parentNode;
fillDefault = ancestor.getAttribute('filldefault');
}
this.fill = fillDefault;
}
if (this.fill === 'freeze' ||
this.fill === 'hold' ||
this.fill === 'transition' ||
(this.fill !== 'remove' &&
!this.dur &&
!this.end &&
!this.repeatCount &&
!this.repeatDir)) {
timingInput.fill = 'forwards';
}
if (this.calcMode === 'paced') {
timingInput.easing = 'paced';
}
this.timingInput = timingInput;
if (this.min) {
this.minActiveDuration = parseClockValue(this.min);
} else {
this.minActiveDuration = 0;
}
if (this.max) {
this.maxActiveDuration = parseClockValue(this.max);
} else {
this.maxActiveDuration = Infinity;
}
if (this.maxActiveDuration < this.minActiveDuration) {
// http://www.w3.org/TR/SMIL3/smil-timing.html#Timing-MinMax
// If !(max >= min) then both attributes are ignored.
this.minActiveDuration = 0;
this.maxActiveDuration = Infinity;
} else {
if (this.repeatDuration < this.minActiveDuration) {
this.repeatDuration = this.minActiveDuration;
} else if (this.repeatDuration > this.maxActiveDuration) {
this.repeatDuration = this.maxActiveDuration;
}
}
},
createEffectOptions: function() {
var options = {};
// 'sum' adds to the underlying value of the attribute and other lower
// priority animations.
// http://www.w3.org/TR/smil/smil-animation.html#adef-additive
if (this.additive && this.additive === 'sum') {
// FIXME: use 'accumulate' when support is implemented in the
// Web Animations Polyfill.
options.composite = 'add';
} else {
// default behavior is options.composite = 'replace';
}
// http://www.w3.org/TR/smil/smil-animation.html#adef-accumulate
if (this.accumulate &&
this.accumulate === 'sum') {
options.iterationComposite = 'accumulate';
} else {
// default behavior is options.iterationComposite = 'replace';
}
// http://www.w3.org/TR/SVG/animate.html#AnimateMotionElement
if (this.rotate) {
if (this.rotate === 'auto') {
options.autoRotate = 'auto-rotate';
} else if (this.rotate === 'auto-reverse') {
options.autoRotate = 'auto-rotate';
options.angle = 180;
} else {
options.angle = parseFloat(this.rotate);
}
} else {
// default behavior is options.autoRotate = 'none';
}
this.options = options;
},
createAnimation: function() {
if (this.target) {
var animation = new Animation(this.target,
this.effect,
this.timingInput);
this.animation = animation;
if (isFinite(this.startTime)) {
// The animation started before the target existed
this.player =
document.timeline.play(this.animation);
this.player.startTime = this.startTime;
}
}
},
createKeyframeAnimation: function() {
var attributeName = this.attributeName;
if (!attributeName) {
return;
}
if (attributeName === 'offset') {
// Web Animations uses keyframe offset for timing.
// When the SVG attribute 'offset' is animated, we use
// 'svgOffset' when communicating with Web Animations.
attributeName = 'svgOffset';
}
var keyframes = null;
if ((this.nodeName === 'animate' ||
this.nodeName === 'animateTransform')) {
// FIXME: Support more ways of specifying keyframes, e.g. by, or only to.
// FIXME: Support ways of specifying timing function.
var processValue;
if (this.nodeName === 'animate') {
processValue = function(value) { return value; };
} else {
// this.nodeName === 'animateTransform'
var transformType;
if (this.type === 'scale' ||
this.type === 'rotate' ||
this.type === 'skewX' ||
this.type === 'skewY') {
transformType = this.type;
} else {
transformType = 'translate'; // default if type is not specified
}
processValue = function(value) {
// Web Animations requires rotate, scale and transform values to be
// comma separated.
value = value.trim().split(/\s*,\s*|\s+/).join(', ');
return transformType + '(' + value + ')';
};
}
var keyTimeList = undefined;
// http://www.w3.org/TR/SVG/animate.html#KeyTimesAttribute
// If the interpolation mode is 'paced', the ‘keyTimes’ attribute is
// ignored. If the simple duration is indefinite, any ‘keyTimes’
// specification will be ignored.
if (this.keyTimes && this.calcMode !== 'paced' &&
this.timingInput.duration !== Infinity) {
keyTimeList = this.keyTimes.split(';');
var previousKeyTime = 0;
var validKeyTime = true;
for (var keyTimeIndex = 0;
validKeyTime && keyTimeIndex < keyTimeList.length;
++keyTimeIndex) {
var currentKeyTime = parseFloat(keyTimeList[keyTimeIndex]);
keyTimeList[keyTimeIndex] = currentKeyTime;
validKeyTime =
currentKeyTime >= previousKeyTime &&
(keyTimeIndex !== 0 || currentKeyTime === 0) &&
currentKeyTime <= 1;
previousKeyTime = currentKeyTime;
}
if (!validKeyTime) {
keyTimeList = undefined;
}
}
if (this.values) {
var valueList = this.values.split(';');
if (valueList[valueList.length - 1].trim() === '') {
// The value list used by the LA Times spinner has a trailing ;
// FIXME: ignore any trailing ';' in other lists too
// Ignore the trailing ';'
valueList.pop();
}
if (valueList.length === 1) {
// We hold the value constant.
valueList.push(valueList[0]);
}
// http://www.w3.org/TR/SVG/animate.html#KeyTimesAttribute
// For animations specified with a ‘values’ list, the ‘keyTimes’
// attribute if specified must have exactly as many values as there
// are in the ‘values’ attribute.
if (keyTimeList && keyTimeList.length !== valueList.length) {
keyTimeList = undefined;
}
keyframes = [];
for (var valueIndex = 0; valueIndex < valueList.length; ++valueIndex) {
var keyframe = {};
keyframe[attributeName] = processValue(valueList[valueIndex].trim());
if (keyTimeList) {
keyframe.offset = keyTimeList[valueIndex];
}
keyframes.push(keyframe);
}
} else {
// http://www.w3.org/TR/SVG/animate.html#KeyTimesAttribute
// For from/to/by animations, the ‘keyTimes’ attribute if specified
// must have two values.
if (keyTimeList && keyTimeList.length === 2) {
keyframes = [
{offset: keyTimeList[0]},
{offset: keyTimeList[1]}
];
} else {
keyframes = [
{offset: 0},
{offset: 1}
];
}
if (this.from && this.to) {
keyframes[0][attributeName] = processValue(this.from);
keyframes[1][attributeName] = processValue(this.to);
} else if (this.to && !this.by) {
keyframes[1][attributeName] = processValue(this.to);
} else {
// FIXME: Support from-by animation and by animation
// http://www.w3.org/TR/2001/REC-smil-animation-20010904/#ByAttribute
keyframes = null;
}
}
} else if (this.nodeName === 'set' && this.to) {
keyframes = [
{offset: 0},
{offset: 1}
];
keyframes[0][attributeName] = this.to;
keyframes[1][attributeName] = this.to;
}
// http://www.w3.org/TR/SVG/animate.html#KeySplinesAttribute
// This attribute is ignored unless the ‘calcMode’ is set to 'spline'.
if (this.keySplines && this.calcMode === 'spline' && keyframes) {
var keySplineList = this.keySplines.split(';');
if (keySplineList.length + 1 === keyframes.length) {
for (var splineIndex = 0;
splineIndex < keySplineList.length;
++splineIndex) {
// SVG delimits values by whitespace and optionally a comma.
// Web Animations requires the comma.
// FIXME: check that the values are all in the range 0 to 1.
// The Web Animations spec requires x values must be in the range
// [0, 1], but (unlike SMIL) it does not mention an allowed range
// for y values.
var spline = keySplineList[splineIndex];
keyframes[splineIndex].easing = 'cubic-bezier(' +
spline.replace(/,/g, ' ').trim().replace(/\s+/g, ',') +
')';
}
}
}
if (verbose) {
console.log('keyframes = ' + JSON.stringify(keyframes));
console.log('options = ' + JSON.stringify(this.options));
console.log('timingInput = ' + JSON.stringify(
this.timingInput));
}
if (keyframes) {
this.keyframes = keyframes;
this.effect =
new KeyframeEffect(keyframes, this.options);
this.createAnimation();
}
},
createMotionPathAnimation: function() {
var resolvedPath;
if (this.mpathRecord) {
var pathRef = this.mpathRecord['xlink:href'];
if (pathRef && pathRef.indexOf('#') === 0) {
this.pathNode =
document.getElementById(pathRef.substring(1));
if (this.pathNode) {
resolvedPath = this.pathNode.getAttribute('d');
}
}
} else {
resolvedPath = this.path;
}
// http://www.w3.org/TR/SVG/animate.html#AnimateMotionElement
// Regarding the definition of the motion path, the ‘mpath’ element
// overrides the ‘path’ attribute, which overrides ‘values’, which
// overrides ‘from’, ‘by’ and ‘to’.
if (!resolvedPath) {
// FIXME: When an mpath child is added, we should update the resolvedPath
if (this.values) {
var valueList = this.values.split(';');
resolvedPath = 'M ' + valueList.join(' L ');
} else {
// FIXME: support 'by' and optional 'from', 'to'
if (this.from && this.to) {
resolvedPath = 'M ' + this.from + ' L ' + this.to;
}
}
}
this.timingInput.easing = 'paced';
if (this.calcMode === 'linear') {
this.options.spacing = 'distribute';
}
// http://www.w3.org/TR/SVG/animate.html#KeyPointsAttribute
var keyPointList = undefined;
if (this.keyPoints) {
keyPointList = this.keyPoints.split(';').map(parseFloat);
var validKeyPoint = true;
for (var keyPointIndex = 0;
validKeyPoint && keyPointIndex < keyPointList.length;
++keyPointIndex) {
var currentKeyPoint = keyPointList[keyPointIndex];
validKeyPoint =
currentKeyPoint >= 0 &&
currentKeyPoint <= 1;
}
if (!validKeyPoint) {
keyPointList = undefined;
}
}
// http://www.w3.org/TR/SVG/animate.html#KeyTimesAttribute
// If the interpolation mode is 'paced', the ‘keyTimes’ attribute is
// ignored. If the simple duration is indefinite, any ‘keyTimes’
// specification will be ignored.
var keyTimeList = undefined;
if (this.keyTimes && this.calcMode !== 'paced' &&
this.timingInput.duration !== Infinity) {
keyTimeList = this.keyTimes.split(';').map(parseFloat);
var previousKeyTime = 0;
var validKeyTime =
keyTimeList.length >= 2 &&
keyTimeList[0] === 0 &&
keyTimeList[keyTimeList.length - 1] === 1 &&
(!keyPointList || keyPointList.length === keyTimeList.length);
for (var keyTimeIndex = 0;
validKeyTime && keyTimeIndex < keyTimeList.length;
++keyTimeIndex) {
var currentKeyTime = keyTimeList[keyTimeIndex];
validKeyTime =
currentKeyTime >= previousKeyTime &&
currentKeyTime <= 1;
previousKeyTime = currentKeyTime;
}
if (!validKeyTime) {
keyTimeList = undefined;
} else {
this.options.spacing = 'distribute';
this.options.keyTimes = keyTimeList;
if (keyPointList) {
this.options.keyPoints = keyPointList;
}
}
}
if (verbose) {
console.log('resolvedPath = ' + resolvedPath);
console.log('options = ' + JSON.stringify(this.options));
console.log('timingInput = ' + JSON.stringify(
this.timingInput));
}
if (resolvedPath) {
this.resolvedPath = resolvedPath;
this.effect =
new MotionPathEffect(resolvedPath, this.options);
this.createAnimation();
}