-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathanimation.js
874 lines (774 loc) · 23.5 KB
/
animation.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
/**
* Copyright 2017 The AMP HTML Authors. 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.
*/
import {Deferred} from '#core/data-structures/promise';
import {
PRESET_OPTION_ATTRIBUTES,
presets,
setStyleForPreset,
} from './animation-presets';
import {Services} from '#service';
import {
StoryAnimationConfigDef,
StoryAnimationDimsDef,
StoryAnimationPresetDef,
WebAnimationDef,
WebAnimationPlayState,
WebAnimationSelectorDef,
WebAnimationTimingDef,
WebKeyframesCreateFnDef,
WebKeyframesDef,
} from './animation-types';
import {assertDoesNotContainDisplay} from '../../../src/assert-display';
import {dev, devAssert, user, userAssert} from '../../../src/log';
import {escapeCssSelectorIdent} from '#core/dom/css-selectors';
import {getChildJsonConfig} from '../../../src/json';
import {map, omit} from '#core/types/object';
import {prefersReducedMotion} from '#core/dom/media-query-props';
import {scopedQuerySelector, scopedQuerySelectorAll} from '#core/dom/query';
import {setStyles} from '#core/dom/style';
import {timeStrToMillis, unscaledClientRect} from './utils';
const TAG = 'AMP-STORY';
/** @const {string} */
export const ANIMATE_IN_ATTRIBUTE_NAME = 'animate-in';
/** @const {string} */
const ANIMATE_IN_DURATION_ATTRIBUTE_NAME = 'animate-in-duration';
/** @const {string} */
const ANIMATE_IN_DELAY_ATTRIBUTE_NAME = 'animate-in-delay';
/** @const {string} */
const ANIMATE_IN_AFTER_ATTRIBUTE_NAME = 'animate-in-after';
/** @const {string} */
const ANIMATE_IN_TIMING_FUNCTION_ATTRIBUTE_NAME = 'animate-in-timing-function';
/** @const {string} */
const ANIMATABLE_ELEMENTS_SELECTOR = `[${ANIMATE_IN_ATTRIBUTE_NAME}]`;
/** @const {string} */
const DEFAULT_EASING = 'cubic-bezier(0.4, 0.0, 0.2, 1)';
/**
* @param {!Element} element
* @return {boolean}
* TODO(alanorozco): maybe memoize?
*/
export function hasAnimations(element) {
const selector = `${ANIMATABLE_ELEMENTS_SELECTOR},>amp-story-animation`;
return !!scopedQuerySelector(element, selector);
}
/** @enum {number} */
const PlaybackActivity = {
START: 0,
FINISH: 1,
};
/**
* @param {!Element} root
* @param {!Element} element
* @return {?string}
*/
function getSequencingStartAfterId(root, element) {
if (!element.hasAttribute(ANIMATE_IN_AFTER_ATTRIBUTE_NAME)) {
return null;
}
const dependencyId = element.getAttribute(ANIMATE_IN_AFTER_ATTRIBUTE_NAME);
if (!root.querySelector(`#${escapeCssSelectorIdent(dependencyId)}`)) {
user().warn(
TAG,
`The attribute '${ANIMATE_IN_AFTER_ATTRIBUTE_NAME}' in tag ` +
`'${element.tagName}' is set to the invalid value ` +
`'${dependencyId}'. No children of parenting 'amp-story-page' ` +
`exist with id ${dependencyId}.`
);
return null;
}
return dependencyId;
}
/** Wraps WebAnimationRunner for story page elements. */
export class AnimationRunner {
/**
* @param {!Element} page
* @param {!StoryAnimationConfigDef} config
* @param {!Promise<!../../amp-animation/0.1/web-animations.Builder>} webAnimationBuilderPromise
* @param {!../../../src/service/vsync-impl.Vsync} vsync
* @param {!AnimationSequence} sequence
*/
constructor(page, config, webAnimationBuilderPromise, vsync, sequence) {
const {preset, source, spec, startAfterId} = config;
/** @private @const */
this.page_ = page;
/** @private @const */
this.source_ = source;
/** @private @const */
this.vsync_ = vsync;
/** @private @const {?Element} */
this.presetTarget_ = !!preset ? dev().assertElement(spec.target) : null;
/** @private @const */
this.sequence_ = sequence;
/** @private @const {?string} */
this.startAfterId_ = startAfterId;
/** @private @const {!Promise<!WebAnimationDef>} */
this.resolvedSpecPromise_ = this.resolveSpec_(config);
/**
* @private @const {!Promise<
* !../../amp-animation/0.1/runners/animation-runner.AnimationRunner>}
*/
this.runnerPromise_ = this.resolvedSpecPromise_.then((webAnimDef) =>
webAnimationBuilderPromise.then((builder) =>
builder.createRunner(webAnimDef)
)
);
/**
* Evaluated set of CSS properties for first animation frame.
* @private @const {!Promise<?Object<string, *>>}
*/
this.firstFrameProps_ = this.resolvedSpecPromise_.then((spec) => {
const {keyframes} = spec;
if (!this.presetTarget_) {
// It's only possible to backfill the first frame if we can define it
// as native CSS. <amp-animation> has CSS extensions and can have
// keyframes defined in a way that prevents us from doing this.
//
// To avoid visual jumps, this depends on the author properly
// defining their CSS so that the initial visual state matches the
// initial animation frame.
return null;
}
devAssert(
!keyframes[0].offset,
'First keyframe offset for animation preset should be 0 or undefined'
);
return omit(keyframes[0], ['offset']);
});
/** @private {?../../amp-animation/0.1/runners/animation-runner.AnimationRunner} */
this.runner_ = null;
/** @private {?PlaybackActivity} */
this.scheduledActivity_ = null;
/** @private {?Promise} */
this.scheduledWait_ = null;
if (this.presetTarget_) {
const {delay} = /** @type {!WebAnimationTimingDef} */ (spec);
userAssert(
dev().assertNumber(delay) >= 0,
'Negative delays are not allowed in amp-story "animate-in" animations.'
);
}
this.runnerPromise_.then((runner) => this.onRunnerReady_(runner));
}
/**
* @param {!Element} page
* @param {!StoryAnimationConfigDef} config
* @param {!Promise<!../../amp-animation/0.1/web-animations.Builder>} webAnimationBuilderPromise
* @param {!../../../src/service/vsync-impl.Vsync} vsync
* @param {!AnimationSequence} sequence
* @return {!AnimationRunner}
*/
static create(page, config, webAnimationBuilderPromise, vsync, sequence) {
return new AnimationRunner(
page,
config,
webAnimationBuilderPromise,
vsync,
sequence
);
}
/**
* @return {!Promise<!StoryAnimationDimsDef>}
* @visibleForTesting
*/
getDims() {
return this.vsync_.measurePromise(() => {
const target = dev().assertElement(this.presetTarget_);
const targetRect = unscaledClientRect(target);
const pageRect = unscaledClientRect(this.page_);
// TODO(alanorozco, https://go.amp.dev/issue/27758):
// Expose equivalents to <amp-animation>
// - targetWidth/targetHeight are already available as width()/height()
// - pageWidth/pageHeight should be exposed as vw/vh
// - targetX/targetY should be exposed somehow (?)
//
// TODO(alanorozco, https://go.amp.dev/issue/27758):
// After exposing these to <amp-animation> syntax, we
// can get rid of this entire method (and this async chain!) if we ensure
// that presets avoid visual jumps either via:
// a) default styles and/or
// b) by not using special <amp-animation> syntax in initial keyframe.
return /** @type {!StoryAnimationDimsDef} */ ({
pageWidth: pageRect.width,
pageHeight: pageRect.height,
targetWidth: targetRect.width,
targetHeight: targetRect.height,
targetX: targetRect.left - pageRect.left,
targetY: targetRect.top - pageRect.top,
});
});
}
/**
* Evaluates a preset's keyframes function using dimensions.
* @param {!WebKeyframesDef|!WebKeyframesCreateFnDef} keyframesOrCreateFn
* @param {!Object<string, *>=} keyframeOptions
* @return {!Promise<!WebKeyframesDef>}
* @private
*/
resolvePresetKeyframes_(keyframesOrCreateFn, keyframeOptions) {
if (typeof keyframesOrCreateFn === 'function') {
return this.getDims().then((dimensions) => {
const fn = /** @type {!WebKeyframesCreateFnDef} */ (
keyframesOrCreateFn
);
return fn(dimensions, keyframeOptions || {});
});
}
return Promise.resolve(keyframesOrCreateFn);
}
/**
* Resolves an animation spec that may be incomplete, like from an
* [animate-in] preset.
* @param {!StoryAnimationConfigDef} config
* @return {!Promise<!WebAnimationDef>}
*/
resolveSpec_(config) {
const {keyframeOptions, preset, spec} = config;
if (!preset) {
// This is an amp-animation config, so it's already formed how the
// WebAnimations Builder wants it.
return Promise.resolve(/** @type {!WebAnimationDef} */ (spec));
}
// The need for this cast is an unfortunate result of using @mixes in
// WebAnimationDef. Otherwise Closure will not understand the timing props
// mixed in from another type.
const {delay, duration, easing} = /** @type {!WebAnimationTimingDef} */ (
spec
);
const {target} = /** @type {!WebAnimationSelectorDef} */ (spec);
return this.resolvePresetKeyframes_(preset.keyframes, keyframeOptions).then(
(keyframes) => ({
keyframes,
target,
delay,
duration,
easing,
fill: 'forwards',
})
);
}
/**
* Applies the first animation frame as CSS props. This is similar to filling
* the animation backwards, except:
* - it evaluates before amp-animation is ready to prevent a race and cause
* a visual jump before being able to fill the first frame
* - it allows for sequencing before an animation has started, like with
* `animate-in-after`.
* @return {!Promise<void>}
*/
applyFirstFrame() {
if (this.hasStarted()) {
return Promise.resolve();
}
if (this.runner_) {
this.runner_.cancel();
}
return this.firstFrameProps_.then((firstFrameProps) => {
if (!firstFrameProps) {
// These are only available when they can be evaluated:
// - delay is not negative
// - first frame is defined in plain CSS, so it does not use special
// <amp-animation> CSS syntax/extensions.
//
// We can't guarantee any of these properties when using
// <amp-story-animation> effects, but we can do it for our own presets.
return;
}
return this.vsync_.mutatePromise(() => {
setStyles(
dev().assertElement(this.presetTarget_),
assertDoesNotContainDisplay(devAssert(firstFrameProps))
);
});
});
}
/**
* Applies the last animation frame.
* @return {!Promise<void>}
*/
applyLastFrame() {
if (this.presetTarget_) {
return Promise.resolve();
}
this.runnerPromise_.then((runner) => {
runner.init();
runner.finish(/* pauseOnError */ true);
});
}
/** Starts or resumes the animation. */
start() {
if (this.hasStarted()) {
return;
}
this.playback_(PlaybackActivity.START, this.getStartWaitPromise_());
}
/**
* @return {!Promise}
* @private
*/
getStartWaitPromise_() {
if (this.startAfterId_) {
return this.sequence_.waitFor(this.startAfterId_);
}
return Promise.resolve();
}
/**
* @param {!../../amp-animation/0.1/runners/animation-runner.AnimationRunner} runner
* @private
*/
startWhenReady_(runner) {
runner.start();
}
/** @return {boolean} */
hasStarted() {
return (
this.isActivityScheduled_(PlaybackActivity.START) ||
(!!this.runner_ &&
devAssert(this.runner_).getPlayState() == WebAnimationPlayState.RUNNING)
);
}
/** Force-finishes all animations. */
finish() {
if (!this.runner_) {
this.notifyFinish_();
}
this.playback_(PlaybackActivity.FINISH);
}
/** Pauses the animation. */
pause() {
// Animation hasn't started yet since it's waiting for a sequenced
// animation.
if (this.scheduledWait_ !== null) {
return;
}
if (this.runner_) {
this.runner_.pause();
}
}
/** Resumes the animation. */
resume() {
// Animation hasn't started yet since it's waiting for a sequenced
// animation.
if (this.scheduledWait_ !== null) {
return;
}
if (this.runner_) {
this.runner_.resume();
}
}
/**
* @param {!../../amp-animation/0.1/runners/animation-runner.AnimationRunner} runner
* @private
*/
finishWhenReady_(runner) {
if (this.runner_) {
// Init or no-op if the runner was already running.
runner.start();
runner.finish();
}
}
/** Cancels animation. */
cancel() {
this.scheduledActivity_ = null;
this.scheduledWait_ = null;
if (this.runner_) {
devAssert(this.runner_).cancel();
}
}
/**
* @param {!PlaybackActivity} activity
* @param {!Promise=} opt_wait
* @private
*/
playback_(activity, opt_wait) {
const wait = opt_wait || null;
this.scheduledActivity_ = activity;
this.scheduledWait_ = wait;
if (this.runner_) {
this.playbackWhenReady_(activity, wait);
}
}
/**
* Executes playback activity if runner is ready.
* @param {!PlaybackActivity} activity
* @param {?Promise} wait
* @private
*/
playbackWhenReady_(activity, wait) {
const runner =
/**
* @type {!../../amp-animation/0.1/runners/animation-runner.AnimationRunner}
*/
(
devAssert(
this.runner_,
'Tried to execute playbackWhenReady_ before runner was resolved.'
)
);
(wait || Promise.resolve()).then(() => {
if (!this.isActivityScheduled_(activity)) {
return;
}
this.scheduledActivity_ = null;
this.scheduledWait_ = null;
switch (activity) {
case PlaybackActivity.START:
return this.startWhenReady_(runner);
case PlaybackActivity.FINISH:
return this.finishWhenReady_(runner);
}
});
}
/**
* Marks runner as ready and executes playback activity if needed.
* @param {!../../amp-animation/0.1/runners/animation-runner.AnimationRunner} runner
* @private
*/
onRunnerReady_(runner) {
this.runner_ = runner;
runner.onPlayStateChanged((state) => {
if (state == WebAnimationPlayState.FINISHED) {
this.notifyFinish_();
}
});
if (!this.isActivityScheduled_()) {
return;
}
this.playbackWhenReady_(
/** @type {!PlaybackActivity} */ (this.scheduledActivity_),
this.scheduledWait_
);
}
/**
* @param {!PlaybackActivity=} opt_activity
* @return {boolean}
* @private
*/
isActivityScheduled_(opt_activity) {
if (!opt_activity) {
return this.scheduledActivity_ !== null;
}
return this.scheduledActivity_ === opt_activity;
}
/** @private */
notifyFinish_() {
if (this.source_.id) {
this.sequence_.notifyFinish(this.source_.id);
}
}
}
// TODO(alanorozco): Looping animations
/** Manager for animations in story pages. */
export class AnimationManager {
/**
* @param {!Element} page
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(page, ampdoc) {
/** @private @const */
this.page_ = page;
/** @private @const */
this.ampdoc_ = ampdoc;
/** @private @const */
this.vsync_ = Services.vsyncFor(this.ampdoc_.win);
/** @private @const */
this.builderPromise_ = this.createAnimationBuilderPromise_();
/** @private @const {bool} */
this.prefersReducedMotion_ = prefersReducedMotion(ampdoc.win);
/** @private {?Array<!AnimationRunner>} */
this.runners_ = null;
/** @private */
this.sequence_ = AnimationSequence.create();
}
/**
* Decouples constructor so it can be stubbed in tests.
* @param {!Element} page
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {string} unusedBaseUrl
* @return {!AnimationManager}
*/
static create(page, ampdoc, unusedBaseUrl) {
return new AnimationManager(page, ampdoc);
}
/**
* Applies first frame to target element before starting animation.
* @return {!Promise}
*/
applyFirstFrameOrFinish() {
return Promise.all(
this.getOrCreateRunners_().map((runner) =>
this.prefersReducedMotion_
? runner.applyLastFrame()
: runner.applyFirstFrame()
)
);
}
/**
* Applies last frame to target element before starting animation.
* @return {!Promise}
*/
applyLastFrame() {
return Promise.all(
this.getOrCreateRunners_().map((runner) => runner.applyLastFrame())
);
}
/** Starts all entrance animations for the page. */
animateIn() {
if (this.prefersReducedMotion_) {
return;
}
this.getRunners_().forEach((runner) => runner.start());
}
/** Skips all entrance animations for the page. */
finishAll() {
this.getRunners_().forEach((runner) => runner.finish());
}
/** Cancels all entrance animations for the page. */
cancelAll() {
if (!this.runners_) {
// nothing to cancel when the first frame has not been applied yet.
return;
}
this.getRunners_().forEach((runner) => runner.cancel());
}
/** Pauses all animations in the page. */
pauseAll() {
if (!this.runners_ || this.prefersReducedMotion_) {
return;
}
this.getRunners_().forEach((runner) => runner.pause());
}
/** Resumes all animations in the page. */
resumeAll() {
if (!this.runners_ || this.prefersReducedMotion_) {
return;
}
this.getRunners_().forEach((runner) => runner.resume());
}
/**
* Determines if there is an animation running.
* @return {boolean}
*/
hasAnimationStarted() {
return this.getRunners_().some((runner) => runner.hasStarted());
}
/**
* @return {!Array<!AnimationRunner>}
* @private
*/
getRunners_() {
return devAssert(this.runners_, 'Executed before applyFirstFrameOrFinish');
}
/**
* Gets or creates AnimationRunners.
* These are either from an <amp-story-animation> spec or resolved from
* presets via animate-in attributes.
* If a page element contains both kinds of definitions, they'll run
* concurrently.
* @return {!Array<!AnimationRunner>}
* @private
*/
getOrCreateRunners_() {
if (!this.runners_) {
this.runners_ = Array.prototype.map
.call(
scopedQuerySelectorAll(this.page_, ANIMATABLE_ELEMENTS_SELECTOR),
(el) => {
const preset = this.getPreset_(el);
if (!preset) {
return null;
}
return this.createRunner_({
preset,
source: el,
startAfterId: getSequencingStartAfterId(this.page_, el),
keyframeOptions: this.getKeyframeOptions_(el),
spec: this.partialAnimationSpecFromPreset_(el, preset),
});
}
)
.concat(
Array.prototype.map.call(
this.page_.querySelectorAll(
'amp-story-animation[trigger=visibility]'
),
(el) =>
this.createRunner_({
source: el,
startAfterId: getSequencingStartAfterId(this.page_, el),
// Casting since we're getting a JsonObject. This will be
// validated during preparation phase.
spec: /** @type {!WebAnimationDef} */ (getChildJsonConfig(el)),
})
)
)
.filter(Boolean);
}
return devAssert(this.runners_);
}
/**
* @param {!StoryAnimationConfigDef} config
* @return {!AnimationRunner}
*/
createRunner_(config) {
return AnimationRunner.create(
this.page_,
config,
devAssert(this.builderPromise_),
this.vsync_,
this.sequence_
);
}
/**
* @param {!Element} el
* @param {!StoryAnimationPresetDef} preset
* @return {!WebAnimationDef}
* @private
*/
partialAnimationSpecFromPreset_(el, preset) {
const animationDef = {
target: el,
delay: preset.delay || 0,
duration: preset.duration || 0,
easing: preset.easing || DEFAULT_EASING,
// This field is so that we type this as a WebAnimationDef, but it's
// replaced when passed to an AnimationRunner.
keyframes: [],
};
if (el.hasAttribute(ANIMATE_IN_DURATION_ATTRIBUTE_NAME)) {
animationDef.duration = timeStrToMillis(
el.getAttribute(ANIMATE_IN_DURATION_ATTRIBUTE_NAME),
animationDef.duration
);
}
if (el.hasAttribute(ANIMATE_IN_DELAY_ATTRIBUTE_NAME)) {
animationDef.delay = timeStrToMillis(
el.getAttribute(ANIMATE_IN_DELAY_ATTRIBUTE_NAME),
animationDef.delay
);
}
if (el.hasAttribute(ANIMATE_IN_TIMING_FUNCTION_ATTRIBUTE_NAME)) {
animationDef.easing = el.getAttribute(
ANIMATE_IN_TIMING_FUNCTION_ATTRIBUTE_NAME
);
}
return animationDef;
}
/**
* @return {!Promise<!../../amp-animation/0.1/web-animations.Builder>}
* @private
*/
createAnimationBuilderPromise_() {
return Services.extensionsFor(this.ampdoc_.win)
.installExtensionForDoc(this.ampdoc_, 'amp-animation')
.then(() => Services.webAnimationServiceFor(this.page_))
.then((webAnimationService) =>
webAnimationService.createBuilder({
scope: this.page_,
scaleByScope: true,
})
);
}
/**
* @param {!Element} el
* @return {?StoryAnimationPresetDef}
*/
getPreset_(el) {
const name = el.getAttribute(ANIMATE_IN_ATTRIBUTE_NAME);
if (!presets[name]) {
user().warn(
TAG,
'Invalid',
ANIMATE_IN_ATTRIBUTE_NAME,
'preset',
name,
'for element',
el
);
return null;
}
// TODO(alanorozco): This should be part of a mutate cycle.
setStyleForPreset(el, name);
return presets[name];
}
/**
* @param {!Element} el
* @return {!Object<string, *>}
* @private
*/
getKeyframeOptions_(el) {
const options = {};
PRESET_OPTION_ATTRIBUTES.forEach((name) => {
if (!el.hasAttribute(name)) {
return;
}
const value = parseFloat(el.getAttribute(name));
if (isNaN(value) || value <= 0) {
user().warn(
TAG,
name,
'attribute must be a positive number. Found negative or zero in element',
el
);
return;
}
options[name] = value;
});
return options;
}
}
/** Bus for animation sequencing. */
export class AnimationSequence {
/**
* @public
*/
constructor() {
/** @private @const {!Object<string, !Promise>} */
this.subscriptionPromises_ = map();
/** @private @const {!Object<string, !Function>} */
this.subscriptionResolvers_ = map();
}
/**
* Decouples constructor for testing.
*
* @return {!AnimationSequence}
*/
static create() {
return new AnimationSequence();
}
/**
* Notifies dependent elements that animation has finished.
* @param {string} id
*/
notifyFinish(id) {
if (id in this.subscriptionPromises_) {
devAssert(this.subscriptionResolvers_[id])();
delete this.subscriptionPromises_[id];
}
}
/**
* Waits for another element to finish animating.
* @param {string} id
* @return {!Promise<void>}
*/
waitFor(id) {
if (!(id in this.subscriptionPromises_)) {
const deferred = new Deferred();
this.subscriptionPromises_[id] = deferred.promise;
this.subscriptionResolvers_[id] = deferred.resolve;
}
return this.subscriptionPromises_[id];
}
}