@angular/animations 16.0.0-next.3 → 16.0.0-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/browser/index.d.ts +1 -1
  2. package/browser/testing/index.d.ts +1 -1
  3. package/esm2022/browser/src/render/animation_driver.mjs +52 -0
  4. package/{esm2020 → esm2022}/browser/src/render/special_cased_styles.mjs +2 -2
  5. package/esm2022/browser/src/warning_helpers.mjs +33 -0
  6. package/esm2022/browser/testing/src/mock_animation_driver.mjs +123 -0
  7. package/{esm2020 → esm2022}/src/version.mjs +1 -1
  8. package/{fesm2015 → fesm2022}/animations.mjs +1 -1
  9. package/{fesm2020 → fesm2022}/browser/testing.mjs +2 -2
  10. package/{fesm2020 → fesm2022}/browser/testing.mjs.map +1 -1
  11. package/{fesm2020 → fesm2022}/browser.mjs +11 -11
  12. package/fesm2022/browser.mjs.map +1 -0
  13. package/index.d.ts +1 -1
  14. package/package.json +12 -22
  15. package/esm2020/browser/src/render/animation_driver.mjs +0 -52
  16. package/esm2020/browser/src/warning_helpers.mjs +0 -33
  17. package/esm2020/browser/testing/src/mock_animation_driver.mjs +0 -123
  18. package/fesm2015/animations.mjs.map +0 -1
  19. package/fesm2015/browser/testing.mjs +0 -941
  20. package/fesm2015/browser/testing.mjs.map +0 -1
  21. package/fesm2015/browser.mjs +0 -4626
  22. package/fesm2015/browser.mjs.map +0 -1
  23. package/fesm2020/animations.mjs +0 -1179
  24. package/fesm2020/browser.mjs.map +0 -1
  25. /package/{esm2020 → esm2022}/animations.mjs +0 -0
  26. /package/{esm2020 → esm2022}/browser/browser.mjs +0 -0
  27. /package/{esm2020 → esm2022}/browser/index.mjs +0 -0
  28. /package/{esm2020 → esm2022}/browser/public_api.mjs +0 -0
  29. /package/{esm2020 → esm2022}/browser/src/browser.mjs +0 -0
  30. /package/{esm2020 → esm2022}/browser/src/dsl/animation.mjs +0 -0
  31. /package/{esm2020 → esm2022}/browser/src/dsl/animation_ast.mjs +0 -0
  32. /package/{esm2020 → esm2022}/browser/src/dsl/animation_ast_builder.mjs +0 -0
  33. /package/{esm2020 → esm2022}/browser/src/dsl/animation_dsl_visitor.mjs +0 -0
  34. /package/{esm2020 → esm2022}/browser/src/dsl/animation_timeline_builder.mjs +0 -0
  35. /package/{esm2020 → esm2022}/browser/src/dsl/animation_timeline_instruction.mjs +0 -0
  36. /package/{esm2020 → esm2022}/browser/src/dsl/animation_transition_expr.mjs +0 -0
  37. /package/{esm2020 → esm2022}/browser/src/dsl/animation_transition_factory.mjs +0 -0
  38. /package/{esm2020 → esm2022}/browser/src/dsl/animation_transition_instruction.mjs +0 -0
  39. /package/{esm2020 → esm2022}/browser/src/dsl/animation_trigger.mjs +0 -0
  40. /package/{esm2020 → esm2022}/browser/src/dsl/element_instruction_map.mjs +0 -0
  41. /package/{esm2020 → esm2022}/browser/src/dsl/style_normalization/animation_style_normalizer.mjs +0 -0
  42. /package/{esm2020 → esm2022}/browser/src/dsl/style_normalization/web_animations_style_normalizer.mjs +0 -0
  43. /package/{esm2020 → esm2022}/browser/src/error_helpers.mjs +0 -0
  44. /package/{esm2020 → esm2022}/browser/src/errors.mjs +0 -0
  45. /package/{esm2020 → esm2022}/browser/src/private_export.mjs +0 -0
  46. /package/{esm2020 → esm2022}/browser/src/render/animation_engine_instruction.mjs +0 -0
  47. /package/{esm2020 → esm2022}/browser/src/render/animation_engine_next.mjs +0 -0
  48. /package/{esm2020 → esm2022}/browser/src/render/shared.mjs +0 -0
  49. /package/{esm2020 → esm2022}/browser/src/render/timeline_animation_engine.mjs +0 -0
  50. /package/{esm2020 → esm2022}/browser/src/render/transition_animation_engine.mjs +0 -0
  51. /package/{esm2020 → esm2022}/browser/src/render/web_animations/animatable_props_set.mjs +0 -0
  52. /package/{esm2020 → esm2022}/browser/src/render/web_animations/dom_animation.mjs +0 -0
  53. /package/{esm2020 → esm2022}/browser/src/render/web_animations/web_animations_driver.mjs +0 -0
  54. /package/{esm2020 → esm2022}/browser/src/render/web_animations/web_animations_player.mjs +0 -0
  55. /package/{esm2020 → esm2022}/browser/src/util.mjs +0 -0
  56. /package/{esm2020 → esm2022}/browser/testing/index.mjs +0 -0
  57. /package/{esm2020 → esm2022}/browser/testing/public_api.mjs +0 -0
  58. /package/{esm2020 → esm2022}/browser/testing/src/testing.mjs +0 -0
  59. /package/{esm2020 → esm2022}/browser/testing/testing.mjs +0 -0
  60. /package/{esm2020 → esm2022}/index.mjs +0 -0
  61. /package/{esm2020 → esm2022}/public_api.mjs +0 -0
  62. /package/{esm2020 → esm2022}/src/animation_builder.mjs +0 -0
  63. /package/{esm2020 → esm2022}/src/animation_event.mjs +0 -0
  64. /package/{esm2020 → esm2022}/src/animation_metadata.mjs +0 -0
  65. /package/{esm2020 → esm2022}/src/animations.mjs +0 -0
  66. /package/{esm2020 → esm2022}/src/players/animation_group_player.mjs +0 -0
  67. /package/{esm2020 → esm2022}/src/players/animation_player.mjs +0 -0
  68. /package/{esm2020 → esm2022}/src/private_export.mjs +0 -0
  69. /package/{esm2020 → esm2022}/src/util.mjs +0 -0
  70. /package/{fesm2020 → fesm2022}/animations.mjs.map +0 -0
@@ -1,4626 +0,0 @@
1
- /**
2
- * @license Angular v16.0.0-next.3
3
- * (c) 2010-2022 Google LLC. https://angular.io/
4
- * License: MIT
5
- */
6
-
7
- import { ɵAnimationGroupPlayer, NoopAnimationPlayer, AUTO_STYLE, ɵPRE_STYLE, sequence, style } from '@angular/animations';
8
- import * as i0 from '@angular/core';
9
- import { ɵRuntimeError, Injectable } from '@angular/core';
10
-
11
- const LINE_START = '\n - ';
12
- function invalidTimingValue(exp) {
13
- return new ɵRuntimeError(3000 /* RuntimeErrorCode.INVALID_TIMING_VALUE */, ngDevMode && `The provided timing value "${exp}" is invalid.`);
14
- }
15
- function negativeStepValue() {
16
- return new ɵRuntimeError(3100 /* RuntimeErrorCode.NEGATIVE_STEP_VALUE */, ngDevMode && 'Duration values below 0 are not allowed for this animation step.');
17
- }
18
- function negativeDelayValue() {
19
- return new ɵRuntimeError(3101 /* RuntimeErrorCode.NEGATIVE_DELAY_VALUE */, ngDevMode && 'Delay values below 0 are not allowed for this animation step.');
20
- }
21
- function invalidStyleParams(varName) {
22
- return new ɵRuntimeError(3001 /* RuntimeErrorCode.INVALID_STYLE_PARAMS */, ngDevMode &&
23
- `Unable to resolve the local animation param ${varName} in the given list of values`);
24
- }
25
- function invalidParamValue(varName) {
26
- return new ɵRuntimeError(3003 /* RuntimeErrorCode.INVALID_PARAM_VALUE */, ngDevMode && `Please provide a value for the animation param ${varName}`);
27
- }
28
- function invalidNodeType(nodeType) {
29
- return new ɵRuntimeError(3004 /* RuntimeErrorCode.INVALID_NODE_TYPE */, ngDevMode && `Unable to resolve animation metadata node #${nodeType}`);
30
- }
31
- function invalidCssUnitValue(userProvidedProperty, value) {
32
- return new ɵRuntimeError(3005 /* RuntimeErrorCode.INVALID_CSS_UNIT_VALUE */, ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`);
33
- }
34
- function invalidTrigger() {
35
- return new ɵRuntimeError(3006 /* RuntimeErrorCode.INVALID_TRIGGER */, ngDevMode &&
36
- 'animation triggers cannot be prefixed with an `@` sign (e.g. trigger(\'@foo\', [...]))');
37
- }
38
- function invalidDefinition() {
39
- return new ɵRuntimeError(3007 /* RuntimeErrorCode.INVALID_DEFINITION */, ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()');
40
- }
41
- function invalidState(metadataName, missingSubs) {
42
- return new ɵRuntimeError(3008 /* RuntimeErrorCode.INVALID_STATE */, ngDevMode &&
43
- `state("${metadataName}", ...) must define default values for all the following style substitutions: ${missingSubs.join(', ')}`);
44
- }
45
- function invalidStyleValue(value) {
46
- return new ɵRuntimeError(3002 /* RuntimeErrorCode.INVALID_STYLE_VALUE */, ngDevMode && `The provided style string value ${value} is not allowed.`);
47
- }
48
- function invalidProperty(prop) {
49
- return new ɵRuntimeError(3009 /* RuntimeErrorCode.INVALID_PROPERTY */, ngDevMode &&
50
- `The provided animation property "${prop}" is not a supported CSS property for animations`);
51
- }
52
- function invalidParallelAnimation(prop, firstStart, firstEnd, secondStart, secondEnd) {
53
- return new ɵRuntimeError(3010 /* RuntimeErrorCode.INVALID_PARALLEL_ANIMATION */, ngDevMode &&
54
- `The CSS property "${prop}" that exists between the times of "${firstStart}ms" and "${firstEnd}ms" is also being animated in a parallel animation between the times of "${secondStart}ms" and "${secondEnd}ms"`);
55
- }
56
- function invalidKeyframes() {
57
- return new ɵRuntimeError(3011 /* RuntimeErrorCode.INVALID_KEYFRAMES */, ngDevMode && `keyframes() must be placed inside of a call to animate()`);
58
- }
59
- function invalidOffset() {
60
- return new ɵRuntimeError(3012 /* RuntimeErrorCode.INVALID_OFFSET */, ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`);
61
- }
62
- function keyframeOffsetsOutOfOrder() {
63
- return new ɵRuntimeError(3200 /* RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER */, ngDevMode && `Please ensure that all keyframe offsets are in order`);
64
- }
65
- function keyframesMissingOffsets() {
66
- return new ɵRuntimeError(3202 /* RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS */, ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`);
67
- }
68
- function invalidStagger() {
69
- return new ɵRuntimeError(3013 /* RuntimeErrorCode.INVALID_STAGGER */, ngDevMode && `stagger() can only be used inside of query()`);
70
- }
71
- function invalidQuery(selector) {
72
- return new ɵRuntimeError(3014 /* RuntimeErrorCode.INVALID_QUERY */, ngDevMode &&
73
- `\`query("${selector}")\` returned zero elements. (Use \`query("${selector}", { optional: true })\` if you wish to allow this.)`);
74
- }
75
- function invalidExpression(expr) {
76
- return new ɵRuntimeError(3015 /* RuntimeErrorCode.INVALID_EXPRESSION */, ngDevMode && `The provided transition expression "${expr}" is not supported`);
77
- }
78
- function invalidTransitionAlias(alias) {
79
- return new ɵRuntimeError(3016 /* RuntimeErrorCode.INVALID_TRANSITION_ALIAS */, ngDevMode && `The transition alias value "${alias}" is not supported`);
80
- }
81
- function validationFailed(errors) {
82
- return new ɵRuntimeError(3500 /* RuntimeErrorCode.VALIDATION_FAILED */, ngDevMode && `animation validation failed:\n${errors.map(err => err.message).join('\n')}`);
83
- }
84
- function buildingFailed(errors) {
85
- return new ɵRuntimeError(3501 /* RuntimeErrorCode.BUILDING_FAILED */, ngDevMode && `animation building failed:\n${errors.map(err => err.message).join('\n')}`);
86
- }
87
- function triggerBuildFailed(name, errors) {
88
- return new ɵRuntimeError(3404 /* RuntimeErrorCode.TRIGGER_BUILD_FAILED */, ngDevMode &&
89
- `The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors.map(err => err.message).join('\n - ')}`);
90
- }
91
- function animationFailed(errors) {
92
- return new ɵRuntimeError(3502 /* RuntimeErrorCode.ANIMATION_FAILED */, ngDevMode &&
93
- `Unable to animate due to the following errors:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);
94
- }
95
- function registerFailed(errors) {
96
- return new ɵRuntimeError(3503 /* RuntimeErrorCode.REGISTRATION_FAILED */, ngDevMode &&
97
- `Unable to build the animation due to the following errors: ${errors.map(err => err.message).join('\n')}`);
98
- }
99
- function missingOrDestroyedAnimation() {
100
- return new ɵRuntimeError(3300 /* RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION */, ngDevMode && 'The requested animation doesn\'t exist or has already been destroyed');
101
- }
102
- function createAnimationFailed(errors) {
103
- return new ɵRuntimeError(3504 /* RuntimeErrorCode.CREATE_ANIMATION_FAILED */, ngDevMode &&
104
- `Unable to create the animation due to the following errors:${errors.map(err => err.message).join('\n')}`);
105
- }
106
- function missingPlayer(id) {
107
- return new ɵRuntimeError(3301 /* RuntimeErrorCode.MISSING_PLAYER */, ngDevMode && `Unable to find the timeline player referenced by ${id}`);
108
- }
109
- function missingTrigger(phase, name) {
110
- return new ɵRuntimeError(3302 /* RuntimeErrorCode.MISSING_TRIGGER */, ngDevMode &&
111
- `Unable to listen on the animation trigger event "${phase}" because the animation trigger "${name}" doesn\'t exist!`);
112
- }
113
- function missingEvent(name) {
114
- return new ɵRuntimeError(3303 /* RuntimeErrorCode.MISSING_EVENT */, ngDevMode &&
115
- `Unable to listen on the animation trigger "${name}" because the provided event is undefined!`);
116
- }
117
- function unsupportedTriggerEvent(phase, name) {
118
- return new ɵRuntimeError(3400 /* RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT */, ngDevMode &&
119
- `The provided animation trigger event "${phase}" for the animation trigger "${name}" is not supported!`);
120
- }
121
- function unregisteredTrigger(name) {
122
- return new ɵRuntimeError(3401 /* RuntimeErrorCode.UNREGISTERED_TRIGGER */, ngDevMode && `The provided animation trigger "${name}" has not been registered!`);
123
- }
124
- function triggerTransitionsFailed(errors) {
125
- return new ɵRuntimeError(3402 /* RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED */, ngDevMode &&
126
- `Unable to process animations due to the following failed trigger transitions\n ${errors.map(err => err.message).join('\n')}`);
127
- }
128
- function triggerParsingFailed(name, errors) {
129
- return new ɵRuntimeError(3403 /* RuntimeErrorCode.TRIGGER_PARSING_FAILED */, ngDevMode &&
130
- `Animation parsing for the ${name} trigger have failed:${LINE_START}${errors.map(err => err.message).join(LINE_START)}`);
131
- }
132
- function transitionFailed(name, errors) {
133
- return new ɵRuntimeError(3505 /* RuntimeErrorCode.TRANSITION_FAILED */, ngDevMode && `@${name} has failed due to:\n ${errors.map(err => err.message).join('\n- ')}`);
134
- }
135
-
136
- /**
137
- * Set of all animatable CSS properties
138
- *
139
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
140
- */
141
- const ANIMATABLE_PROP_SET = new Set([
142
- '-moz-outline-radius',
143
- '-moz-outline-radius-bottomleft',
144
- '-moz-outline-radius-bottomright',
145
- '-moz-outline-radius-topleft',
146
- '-moz-outline-radius-topright',
147
- '-ms-grid-columns',
148
- '-ms-grid-rows',
149
- '-webkit-line-clamp',
150
- '-webkit-text-fill-color',
151
- '-webkit-text-stroke',
152
- '-webkit-text-stroke-color',
153
- 'accent-color',
154
- 'all',
155
- 'backdrop-filter',
156
- 'background',
157
- 'background-color',
158
- 'background-position',
159
- 'background-size',
160
- 'block-size',
161
- 'border',
162
- 'border-block-end',
163
- 'border-block-end-color',
164
- 'border-block-end-width',
165
- 'border-block-start',
166
- 'border-block-start-color',
167
- 'border-block-start-width',
168
- 'border-bottom',
169
- 'border-bottom-color',
170
- 'border-bottom-left-radius',
171
- 'border-bottom-right-radius',
172
- 'border-bottom-width',
173
- 'border-color',
174
- 'border-end-end-radius',
175
- 'border-end-start-radius',
176
- 'border-image-outset',
177
- 'border-image-slice',
178
- 'border-image-width',
179
- 'border-inline-end',
180
- 'border-inline-end-color',
181
- 'border-inline-end-width',
182
- 'border-inline-start',
183
- 'border-inline-start-color',
184
- 'border-inline-start-width',
185
- 'border-left',
186
- 'border-left-color',
187
- 'border-left-width',
188
- 'border-radius',
189
- 'border-right',
190
- 'border-right-color',
191
- 'border-right-width',
192
- 'border-start-end-radius',
193
- 'border-start-start-radius',
194
- 'border-top',
195
- 'border-top-color',
196
- 'border-top-left-radius',
197
- 'border-top-right-radius',
198
- 'border-top-width',
199
- 'border-width',
200
- 'bottom',
201
- 'box-shadow',
202
- 'caret-color',
203
- 'clip',
204
- 'clip-path',
205
- 'color',
206
- 'column-count',
207
- 'column-gap',
208
- 'column-rule',
209
- 'column-rule-color',
210
- 'column-rule-width',
211
- 'column-width',
212
- 'columns',
213
- 'filter',
214
- 'flex',
215
- 'flex-basis',
216
- 'flex-grow',
217
- 'flex-shrink',
218
- 'font',
219
- 'font-size',
220
- 'font-size-adjust',
221
- 'font-stretch',
222
- 'font-variation-settings',
223
- 'font-weight',
224
- 'gap',
225
- 'grid-column-gap',
226
- 'grid-gap',
227
- 'grid-row-gap',
228
- 'grid-template-columns',
229
- 'grid-template-rows',
230
- 'height',
231
- 'inline-size',
232
- 'input-security',
233
- 'inset',
234
- 'inset-block',
235
- 'inset-block-end',
236
- 'inset-block-start',
237
- 'inset-inline',
238
- 'inset-inline-end',
239
- 'inset-inline-start',
240
- 'left',
241
- 'letter-spacing',
242
- 'line-clamp',
243
- 'line-height',
244
- 'margin',
245
- 'margin-block-end',
246
- 'margin-block-start',
247
- 'margin-bottom',
248
- 'margin-inline-end',
249
- 'margin-inline-start',
250
- 'margin-left',
251
- 'margin-right',
252
- 'margin-top',
253
- 'mask',
254
- 'mask-border',
255
- 'mask-position',
256
- 'mask-size',
257
- 'max-block-size',
258
- 'max-height',
259
- 'max-inline-size',
260
- 'max-lines',
261
- 'max-width',
262
- 'min-block-size',
263
- 'min-height',
264
- 'min-inline-size',
265
- 'min-width',
266
- 'object-position',
267
- 'offset',
268
- 'offset-anchor',
269
- 'offset-distance',
270
- 'offset-path',
271
- 'offset-position',
272
- 'offset-rotate',
273
- 'opacity',
274
- 'order',
275
- 'outline',
276
- 'outline-color',
277
- 'outline-offset',
278
- 'outline-width',
279
- 'padding',
280
- 'padding-block-end',
281
- 'padding-block-start',
282
- 'padding-bottom',
283
- 'padding-inline-end',
284
- 'padding-inline-start',
285
- 'padding-left',
286
- 'padding-right',
287
- 'padding-top',
288
- 'perspective',
289
- 'perspective-origin',
290
- 'right',
291
- 'rotate',
292
- 'row-gap',
293
- 'scale',
294
- 'scroll-margin',
295
- 'scroll-margin-block',
296
- 'scroll-margin-block-end',
297
- 'scroll-margin-block-start',
298
- 'scroll-margin-bottom',
299
- 'scroll-margin-inline',
300
- 'scroll-margin-inline-end',
301
- 'scroll-margin-inline-start',
302
- 'scroll-margin-left',
303
- 'scroll-margin-right',
304
- 'scroll-margin-top',
305
- 'scroll-padding',
306
- 'scroll-padding-block',
307
- 'scroll-padding-block-end',
308
- 'scroll-padding-block-start',
309
- 'scroll-padding-bottom',
310
- 'scroll-padding-inline',
311
- 'scroll-padding-inline-end',
312
- 'scroll-padding-inline-start',
313
- 'scroll-padding-left',
314
- 'scroll-padding-right',
315
- 'scroll-padding-top',
316
- 'scroll-snap-coordinate',
317
- 'scroll-snap-destination',
318
- 'scrollbar-color',
319
- 'shape-image-threshold',
320
- 'shape-margin',
321
- 'shape-outside',
322
- 'tab-size',
323
- 'text-decoration',
324
- 'text-decoration-color',
325
- 'text-decoration-thickness',
326
- 'text-emphasis',
327
- 'text-emphasis-color',
328
- 'text-indent',
329
- 'text-shadow',
330
- 'text-underline-offset',
331
- 'top',
332
- 'transform',
333
- 'transform-origin',
334
- 'translate',
335
- 'vertical-align',
336
- 'visibility',
337
- 'width',
338
- 'word-spacing',
339
- 'z-index',
340
- 'zoom',
341
- ]);
342
-
343
- function isBrowser() {
344
- return (typeof window !== 'undefined' && typeof window.document !== 'undefined');
345
- }
346
- function isNode() {
347
- // Checking only for `process` isn't enough to identify whether or not we're in a Node
348
- // environment, because Webpack by default will polyfill the `process`. While we can discern
349
- // that Webpack polyfilled it by looking at `process.browser`, it's very Webpack-specific and
350
- // might not be future-proof. Instead we look at the stringified version of `process` which
351
- // is `[object process]` in Node and `[object Object]` when polyfilled.
352
- return typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
353
- }
354
- function optimizeGroupPlayer(players) {
355
- switch (players.length) {
356
- case 0:
357
- return new NoopAnimationPlayer();
358
- case 1:
359
- return players[0];
360
- default:
361
- return new ɵAnimationGroupPlayer(players);
362
- }
363
- }
364
- function normalizeKeyframes$1(driver, normalizer, element, keyframes, preStyles = new Map(), postStyles = new Map()) {
365
- const errors = [];
366
- const normalizedKeyframes = [];
367
- let previousOffset = -1;
368
- let previousKeyframe = null;
369
- keyframes.forEach(kf => {
370
- const offset = kf.get('offset');
371
- const isSameOffset = offset == previousOffset;
372
- const normalizedKeyframe = (isSameOffset && previousKeyframe) || new Map();
373
- kf.forEach((val, prop) => {
374
- let normalizedProp = prop;
375
- let normalizedValue = val;
376
- if (prop !== 'offset') {
377
- normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);
378
- switch (normalizedValue) {
379
- case ɵPRE_STYLE:
380
- normalizedValue = preStyles.get(prop);
381
- break;
382
- case AUTO_STYLE:
383
- normalizedValue = postStyles.get(prop);
384
- break;
385
- default:
386
- normalizedValue =
387
- normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);
388
- break;
389
- }
390
- }
391
- normalizedKeyframe.set(normalizedProp, normalizedValue);
392
- });
393
- if (!isSameOffset) {
394
- normalizedKeyframes.push(normalizedKeyframe);
395
- }
396
- previousKeyframe = normalizedKeyframe;
397
- previousOffset = offset;
398
- });
399
- if (errors.length) {
400
- throw animationFailed(errors);
401
- }
402
- return normalizedKeyframes;
403
- }
404
- function listenOnPlayer(player, eventName, event, callback) {
405
- switch (eventName) {
406
- case 'start':
407
- player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));
408
- break;
409
- case 'done':
410
- player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));
411
- break;
412
- case 'destroy':
413
- player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));
414
- break;
415
- }
416
- }
417
- function copyAnimationEvent(e, phaseName, player) {
418
- const totalTime = player.totalTime;
419
- const disabled = player.disabled ? true : false;
420
- const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);
421
- const data = e['_data'];
422
- if (data != null) {
423
- event['_data'] = data;
424
- }
425
- return event;
426
- }
427
- function makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {
428
- return { element, triggerName, fromState, toState, phaseName, totalTime, disabled: !!disabled };
429
- }
430
- function getOrSetDefaultValue(map, key, defaultValue) {
431
- let value = map.get(key);
432
- if (!value) {
433
- map.set(key, value = defaultValue);
434
- }
435
- return value;
436
- }
437
- function parseTimelineCommand(command) {
438
- const separatorPos = command.indexOf(':');
439
- const id = command.substring(1, separatorPos);
440
- const action = command.slice(separatorPos + 1);
441
- return [id, action];
442
- }
443
- let _contains = (elm1, elm2) => false;
444
- let _query = (element, selector, multi) => {
445
- return [];
446
- };
447
- let _documentElement = null;
448
- function getParentElement(element) {
449
- const parent = element.parentNode || element.host; // consider host to support shadow DOM
450
- if (parent === _documentElement) {
451
- return null;
452
- }
453
- return parent;
454
- }
455
- // Define utility methods for browsers and platform-server(domino) where Element
456
- // and utility methods exist.
457
- const _isNode = isNode();
458
- if (_isNode || typeof Element !== 'undefined') {
459
- if (!isBrowser()) {
460
- _contains = (elm1, elm2) => elm1.contains(elm2);
461
- }
462
- else {
463
- // Read the document element in an IIFE that's been marked pure to avoid a top-level property
464
- // read that may prevent tree-shaking.
465
- _documentElement = /* @__PURE__ */ (() => document.documentElement)();
466
- _contains = (elm1, elm2) => {
467
- while (elm2) {
468
- if (elm2 === elm1) {
469
- return true;
470
- }
471
- elm2 = getParentElement(elm2);
472
- }
473
- return false;
474
- };
475
- }
476
- _query = (element, selector, multi) => {
477
- if (multi) {
478
- return Array.from(element.querySelectorAll(selector));
479
- }
480
- const elem = element.querySelector(selector);
481
- return elem ? [elem] : [];
482
- };
483
- }
484
- function containsVendorPrefix(prop) {
485
- // Webkit is the only real popular vendor prefix nowadays
486
- // cc: http://shouldiprefix.com/
487
- return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit
488
- }
489
- let _CACHED_BODY = null;
490
- let _IS_WEBKIT = false;
491
- function validateStyleProperty(prop) {
492
- if (!_CACHED_BODY) {
493
- _CACHED_BODY = getBodyNode() || {};
494
- _IS_WEBKIT = _CACHED_BODY.style ? ('WebkitAppearance' in _CACHED_BODY.style) : false;
495
- }
496
- let result = true;
497
- if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {
498
- result = prop in _CACHED_BODY.style;
499
- if (!result && _IS_WEBKIT) {
500
- const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);
501
- result = camelProp in _CACHED_BODY.style;
502
- }
503
- }
504
- return result;
505
- }
506
- function validateWebAnimatableStyleProperty(prop) {
507
- return ANIMATABLE_PROP_SET.has(prop);
508
- }
509
- function getBodyNode() {
510
- if (typeof document != 'undefined') {
511
- return document.body;
512
- }
513
- return null;
514
- }
515
- const containsElement = _contains;
516
- const invokeQuery = _query;
517
- function hypenatePropsKeys(original) {
518
- const newMap = new Map();
519
- original.forEach((val, prop) => {
520
- const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');
521
- newMap.set(newProp, val);
522
- });
523
- return newMap;
524
- }
525
-
526
- /**
527
- * @publicApi
528
- */
529
- class NoopAnimationDriver {
530
- validateStyleProperty(prop) {
531
- return validateStyleProperty(prop);
532
- }
533
- matchesElement(_element, _selector) {
534
- // This method is deprecated and no longer in use so we return false.
535
- return false;
536
- }
537
- containsElement(elm1, elm2) {
538
- return containsElement(elm1, elm2);
539
- }
540
- getParentElement(element) {
541
- return getParentElement(element);
542
- }
543
- query(element, selector, multi) {
544
- return invokeQuery(element, selector, multi);
545
- }
546
- computeStyle(element, prop, defaultValue) {
547
- return defaultValue || '';
548
- }
549
- animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
550
- return new NoopAnimationPlayer(duration, delay);
551
- }
552
- }
553
- NoopAnimationDriver.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0-next.3", ngImport: i0, type: NoopAnimationDriver, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
554
- NoopAnimationDriver.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0-next.3", ngImport: i0, type: NoopAnimationDriver });
555
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0-next.3", ngImport: i0, type: NoopAnimationDriver, decorators: [{
556
- type: Injectable
557
- }] });
558
- /**
559
- * @publicApi
560
- */
561
- class AnimationDriver {
562
- }
563
- AnimationDriver.NOOP = ( /* @__PURE__ */new NoopAnimationDriver());
564
-
565
- const ONE_SECOND = 1000;
566
- const SUBSTITUTION_EXPR_START = '{{';
567
- const SUBSTITUTION_EXPR_END = '}}';
568
- const ENTER_CLASSNAME = 'ng-enter';
569
- const LEAVE_CLASSNAME = 'ng-leave';
570
- const NG_TRIGGER_CLASSNAME = 'ng-trigger';
571
- const NG_TRIGGER_SELECTOR = '.ng-trigger';
572
- const NG_ANIMATING_CLASSNAME = 'ng-animating';
573
- const NG_ANIMATING_SELECTOR = '.ng-animating';
574
- function resolveTimingValue(value) {
575
- if (typeof value == 'number')
576
- return value;
577
- const matches = value.match(/^(-?[\.\d]+)(m?s)/);
578
- if (!matches || matches.length < 2)
579
- return 0;
580
- return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
581
- }
582
- function _convertTimeValueToMS(value, unit) {
583
- switch (unit) {
584
- case 's':
585
- return value * ONE_SECOND;
586
- default: // ms or something else
587
- return value;
588
- }
589
- }
590
- function resolveTiming(timings, errors, allowNegativeValues) {
591
- return timings.hasOwnProperty('duration') ?
592
- timings :
593
- parseTimeExpression(timings, errors, allowNegativeValues);
594
- }
595
- function parseTimeExpression(exp, errors, allowNegativeValues) {
596
- const regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
597
- let duration;
598
- let delay = 0;
599
- let easing = '';
600
- if (typeof exp === 'string') {
601
- const matches = exp.match(regex);
602
- if (matches === null) {
603
- errors.push(invalidTimingValue(exp));
604
- return { duration: 0, delay: 0, easing: '' };
605
- }
606
- duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
607
- const delayMatch = matches[3];
608
- if (delayMatch != null) {
609
- delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);
610
- }
611
- const easingVal = matches[5];
612
- if (easingVal) {
613
- easing = easingVal;
614
- }
615
- }
616
- else {
617
- duration = exp;
618
- }
619
- if (!allowNegativeValues) {
620
- let containsErrors = false;
621
- let startIndex = errors.length;
622
- if (duration < 0) {
623
- errors.push(negativeStepValue());
624
- containsErrors = true;
625
- }
626
- if (delay < 0) {
627
- errors.push(negativeDelayValue());
628
- containsErrors = true;
629
- }
630
- if (containsErrors) {
631
- errors.splice(startIndex, 0, invalidTimingValue(exp));
632
- }
633
- }
634
- return { duration, delay, easing };
635
- }
636
- function copyObj(obj, destination = {}) {
637
- Object.keys(obj).forEach(prop => {
638
- destination[prop] = obj[prop];
639
- });
640
- return destination;
641
- }
642
- function convertToMap(obj) {
643
- const styleMap = new Map();
644
- Object.keys(obj).forEach(prop => {
645
- const val = obj[prop];
646
- styleMap.set(prop, val);
647
- });
648
- return styleMap;
649
- }
650
- function normalizeKeyframes(keyframes) {
651
- if (!keyframes.length) {
652
- return [];
653
- }
654
- if (keyframes[0] instanceof Map) {
655
- return keyframes;
656
- }
657
- return keyframes.map(kf => convertToMap(kf));
658
- }
659
- function normalizeStyles(styles) {
660
- const normalizedStyles = new Map();
661
- if (Array.isArray(styles)) {
662
- styles.forEach(data => copyStyles(data, normalizedStyles));
663
- }
664
- else {
665
- copyStyles(styles, normalizedStyles);
666
- }
667
- return normalizedStyles;
668
- }
669
- function copyStyles(styles, destination = new Map(), backfill) {
670
- if (backfill) {
671
- for (let [prop, val] of backfill) {
672
- destination.set(prop, val);
673
- }
674
- }
675
- for (let [prop, val] of styles) {
676
- destination.set(prop, val);
677
- }
678
- return destination;
679
- }
680
- function getStyleAttributeString(element, key, value) {
681
- // Return the key-value pair string to be added to the style attribute for the
682
- // given CSS style key.
683
- if (value) {
684
- return key + ':' + value + ';';
685
- }
686
- else {
687
- return '';
688
- }
689
- }
690
- function writeStyleAttribute(element) {
691
- // Read the style property of the element and manually reflect it to the
692
- // style attribute. This is needed because Domino on platform-server doesn't
693
- // understand the full set of allowed CSS properties and doesn't reflect some
694
- // of them automatically.
695
- let styleAttrValue = '';
696
- for (let i = 0; i < element.style.length; i++) {
697
- const key = element.style.item(i);
698
- styleAttrValue += getStyleAttributeString(element, key, element.style.getPropertyValue(key));
699
- }
700
- for (const key in element.style) {
701
- // Skip internal Domino properties that don't need to be reflected.
702
- if (!element.style.hasOwnProperty(key) || key.startsWith('_')) {
703
- continue;
704
- }
705
- const dashKey = camelCaseToDashCase(key);
706
- styleAttrValue += getStyleAttributeString(element, dashKey, element.style[key]);
707
- }
708
- element.setAttribute('style', styleAttrValue);
709
- }
710
- function setStyles(element, styles, formerStyles) {
711
- if (element['style']) {
712
- styles.forEach((val, prop) => {
713
- const camelProp = dashCaseToCamelCase(prop);
714
- if (formerStyles && !formerStyles.has(prop)) {
715
- formerStyles.set(prop, element.style[camelProp]);
716
- }
717
- element.style[camelProp] = val;
718
- });
719
- // On the server set the 'style' attribute since it's not automatically reflected.
720
- if (isNode()) {
721
- writeStyleAttribute(element);
722
- }
723
- }
724
- }
725
- function eraseStyles(element, styles) {
726
- if (element['style']) {
727
- styles.forEach((_, prop) => {
728
- const camelProp = dashCaseToCamelCase(prop);
729
- element.style[camelProp] = '';
730
- });
731
- // On the server set the 'style' attribute since it's not automatically reflected.
732
- if (isNode()) {
733
- writeStyleAttribute(element);
734
- }
735
- }
736
- }
737
- function normalizeAnimationEntry(steps) {
738
- if (Array.isArray(steps)) {
739
- if (steps.length == 1)
740
- return steps[0];
741
- return sequence(steps);
742
- }
743
- return steps;
744
- }
745
- function validateStyleParams(value, options, errors) {
746
- const params = options.params || {};
747
- const matches = extractStyleParams(value);
748
- if (matches.length) {
749
- matches.forEach(varName => {
750
- if (!params.hasOwnProperty(varName)) {
751
- errors.push(invalidStyleParams(varName));
752
- }
753
- });
754
- }
755
- }
756
- const PARAM_REGEX = new RegExp(`${SUBSTITUTION_EXPR_START}\\s*(.+?)\\s*${SUBSTITUTION_EXPR_END}`, 'g');
757
- function extractStyleParams(value) {
758
- let params = [];
759
- if (typeof value === 'string') {
760
- let match;
761
- while (match = PARAM_REGEX.exec(value)) {
762
- params.push(match[1]);
763
- }
764
- PARAM_REGEX.lastIndex = 0;
765
- }
766
- return params;
767
- }
768
- function interpolateParams(value, params, errors) {
769
- const original = value.toString();
770
- const str = original.replace(PARAM_REGEX, (_, varName) => {
771
- let localVal = params[varName];
772
- // this means that the value was never overridden by the data passed in by the user
773
- if (localVal == null) {
774
- errors.push(invalidParamValue(varName));
775
- localVal = '';
776
- }
777
- return localVal.toString();
778
- });
779
- // we do this to assert that numeric values stay as they are
780
- return str == original ? value : str;
781
- }
782
- function iteratorToArray(iterator) {
783
- const arr = [];
784
- let item = iterator.next();
785
- while (!item.done) {
786
- arr.push(item.value);
787
- item = iterator.next();
788
- }
789
- return arr;
790
- }
791
- const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
792
- function dashCaseToCamelCase(input) {
793
- return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
794
- }
795
- function camelCaseToDashCase(input) {
796
- return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
797
- }
798
- function allowPreviousPlayerStylesMerge(duration, delay) {
799
- return duration === 0 || delay === 0;
800
- }
801
- function balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {
802
- if (previousStyles.size && keyframes.length) {
803
- let startingKeyframe = keyframes[0];
804
- let missingStyleProps = [];
805
- previousStyles.forEach((val, prop) => {
806
- if (!startingKeyframe.has(prop)) {
807
- missingStyleProps.push(prop);
808
- }
809
- startingKeyframe.set(prop, val);
810
- });
811
- if (missingStyleProps.length) {
812
- for (let i = 1; i < keyframes.length; i++) {
813
- let kf = keyframes[i];
814
- missingStyleProps.forEach(prop => kf.set(prop, computeStyle(element, prop)));
815
- }
816
- }
817
- }
818
- return keyframes;
819
- }
820
- function visitDslNode(visitor, node, context) {
821
- switch (node.type) {
822
- case 7 /* AnimationMetadataType.Trigger */:
823
- return visitor.visitTrigger(node, context);
824
- case 0 /* AnimationMetadataType.State */:
825
- return visitor.visitState(node, context);
826
- case 1 /* AnimationMetadataType.Transition */:
827
- return visitor.visitTransition(node, context);
828
- case 2 /* AnimationMetadataType.Sequence */:
829
- return visitor.visitSequence(node, context);
830
- case 3 /* AnimationMetadataType.Group */:
831
- return visitor.visitGroup(node, context);
832
- case 4 /* AnimationMetadataType.Animate */:
833
- return visitor.visitAnimate(node, context);
834
- case 5 /* AnimationMetadataType.Keyframes */:
835
- return visitor.visitKeyframes(node, context);
836
- case 6 /* AnimationMetadataType.Style */:
837
- return visitor.visitStyle(node, context);
838
- case 8 /* AnimationMetadataType.Reference */:
839
- return visitor.visitReference(node, context);
840
- case 9 /* AnimationMetadataType.AnimateChild */:
841
- return visitor.visitAnimateChild(node, context);
842
- case 10 /* AnimationMetadataType.AnimateRef */:
843
- return visitor.visitAnimateRef(node, context);
844
- case 11 /* AnimationMetadataType.Query */:
845
- return visitor.visitQuery(node, context);
846
- case 12 /* AnimationMetadataType.Stagger */:
847
- return visitor.visitStagger(node, context);
848
- default:
849
- throw invalidNodeType(node.type);
850
- }
851
- }
852
- function computeStyle(element, prop) {
853
- return window.getComputedStyle(element)[prop];
854
- }
855
-
856
- const NG_DEV_MODE = typeof ngDevMode === 'undefined' || !!ngDevMode;
857
- function createListOfWarnings(warnings) {
858
- const LINE_START = '\n - ';
859
- return `${LINE_START}${warnings.filter(Boolean).map(warning => warning).join(LINE_START)}`;
860
- }
861
- function warnValidation(warnings) {
862
- NG_DEV_MODE && console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);
863
- }
864
- function warnTriggerBuild(name, warnings) {
865
- NG_DEV_MODE &&
866
- console.warn(`The animation trigger "${name}" has built with the following warnings:${createListOfWarnings(warnings)}`);
867
- }
868
- function warnRegister(warnings) {
869
- NG_DEV_MODE &&
870
- console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);
871
- }
872
- function triggerParsingWarnings(name, warnings) {
873
- NG_DEV_MODE &&
874
- console.warn(`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(warnings)}`);
875
- }
876
- function pushUnrecognizedPropertiesWarning(warnings, props) {
877
- if (props.length) {
878
- warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);
879
- }
880
- }
881
-
882
- const ANY_STATE = '*';
883
- function parseTransitionExpr(transitionValue, errors) {
884
- const expressions = [];
885
- if (typeof transitionValue == 'string') {
886
- transitionValue.split(/\s*,\s*/).forEach(str => parseInnerTransitionStr(str, expressions, errors));
887
- }
888
- else {
889
- expressions.push(transitionValue);
890
- }
891
- return expressions;
892
- }
893
- function parseInnerTransitionStr(eventStr, expressions, errors) {
894
- if (eventStr[0] == ':') {
895
- const result = parseAnimationAlias(eventStr, errors);
896
- if (typeof result == 'function') {
897
- expressions.push(result);
898
- return;
899
- }
900
- eventStr = result;
901
- }
902
- const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
903
- if (match == null || match.length < 4) {
904
- errors.push(invalidExpression(eventStr));
905
- return expressions;
906
- }
907
- const fromState = match[1];
908
- const separator = match[2];
909
- const toState = match[3];
910
- expressions.push(makeLambdaFromStates(fromState, toState));
911
- const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
912
- if (separator[0] == '<' && !isFullAnyStateExpr) {
913
- expressions.push(makeLambdaFromStates(toState, fromState));
914
- }
915
- }
916
- function parseAnimationAlias(alias, errors) {
917
- switch (alias) {
918
- case ':enter':
919
- return 'void => *';
920
- case ':leave':
921
- return '* => void';
922
- case ':increment':
923
- return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);
924
- case ':decrement':
925
- return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);
926
- default:
927
- errors.push(invalidTransitionAlias(alias));
928
- return '* => *';
929
- }
930
- }
931
- // DO NOT REFACTOR ... keep the follow set instantiations
932
- // with the values intact (closure compiler for some reason
933
- // removes follow-up lines that add the values outside of
934
- // the constructor...
935
- const TRUE_BOOLEAN_VALUES = new Set(['true', '1']);
936
- const FALSE_BOOLEAN_VALUES = new Set(['false', '0']);
937
- function makeLambdaFromStates(lhs, rhs) {
938
- const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
939
- const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);
940
- return (fromState, toState) => {
941
- let lhsMatch = lhs == ANY_STATE || lhs == fromState;
942
- let rhsMatch = rhs == ANY_STATE || rhs == toState;
943
- if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {
944
- lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);
945
- }
946
- if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {
947
- rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);
948
- }
949
- return lhsMatch && rhsMatch;
950
- };
951
- }
952
-
953
- const SELF_TOKEN = ':self';
954
- const SELF_TOKEN_REGEX = new RegExp(`\s*${SELF_TOKEN}\s*,?`, 'g');
955
- /*
956
- * [Validation]
957
- * The visitor code below will traverse the animation AST generated by the animation verb functions
958
- * (the output is a tree of objects) and attempt to perform a series of validations on the data. The
959
- * following corner-cases will be validated:
960
- *
961
- * 1. Overlap of animations
962
- * Given that a CSS property cannot be animated in more than one place at the same time, it's
963
- * important that this behavior is detected and validated. The way in which this occurs is that
964
- * each time a style property is examined, a string-map containing the property will be updated with
965
- * the start and end times for when the property is used within an animation step.
966
- *
967
- * If there are two or more parallel animations that are currently running (these are invoked by the
968
- * group()) on the same element then the validator will throw an error. Since the start/end timing
969
- * values are collected for each property then if the current animation step is animating the same
970
- * property and its timing values fall anywhere into the window of time that the property is
971
- * currently being animated within then this is what causes an error.
972
- *
973
- * 2. Timing values
974
- * The validator will validate to see if a timing value of `duration delay easing` or
975
- * `durationNumber` is valid or not.
976
- *
977
- * (note that upon validation the code below will replace the timing data with an object containing
978
- * {duration,delay,easing}.
979
- *
980
- * 3. Offset Validation
981
- * Each of the style() calls are allowed to have an offset value when placed inside of keyframes().
982
- * Offsets within keyframes() are considered valid when:
983
- *
984
- * - No offsets are used at all
985
- * - Each style() entry contains an offset value
986
- * - Each offset is between 0 and 1
987
- * - Each offset is greater to or equal than the previous one
988
- *
989
- * Otherwise an error will be thrown.
990
- */
991
- function buildAnimationAst(driver, metadata, errors, warnings) {
992
- return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);
993
- }
994
- const ROOT_SELECTOR = '';
995
- class AnimationAstBuilderVisitor {
996
- constructor(_driver) {
997
- this._driver = _driver;
998
- }
999
- build(metadata, errors, warnings) {
1000
- const context = new AnimationAstBuilderContext(errors);
1001
- this._resetContextStyleTimingState(context);
1002
- const ast = visitDslNode(this, normalizeAnimationEntry(metadata), context);
1003
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
1004
- if (context.unsupportedCSSPropertiesFound.size) {
1005
- pushUnrecognizedPropertiesWarning(warnings, [...context.unsupportedCSSPropertiesFound.keys()]);
1006
- }
1007
- }
1008
- return ast;
1009
- }
1010
- _resetContextStyleTimingState(context) {
1011
- context.currentQuerySelector = ROOT_SELECTOR;
1012
- context.collectedStyles = new Map();
1013
- context.collectedStyles.set(ROOT_SELECTOR, new Map());
1014
- context.currentTime = 0;
1015
- }
1016
- visitTrigger(metadata, context) {
1017
- let queryCount = context.queryCount = 0;
1018
- let depCount = context.depCount = 0;
1019
- const states = [];
1020
- const transitions = [];
1021
- if (metadata.name.charAt(0) == '@') {
1022
- context.errors.push(invalidTrigger());
1023
- }
1024
- metadata.definitions.forEach(def => {
1025
- this._resetContextStyleTimingState(context);
1026
- if (def.type == 0 /* AnimationMetadataType.State */) {
1027
- const stateDef = def;
1028
- const name = stateDef.name;
1029
- name.toString().split(/\s*,\s*/).forEach(n => {
1030
- stateDef.name = n;
1031
- states.push(this.visitState(stateDef, context));
1032
- });
1033
- stateDef.name = name;
1034
- }
1035
- else if (def.type == 1 /* AnimationMetadataType.Transition */) {
1036
- const transition = this.visitTransition(def, context);
1037
- queryCount += transition.queryCount;
1038
- depCount += transition.depCount;
1039
- transitions.push(transition);
1040
- }
1041
- else {
1042
- context.errors.push(invalidDefinition());
1043
- }
1044
- });
1045
- return {
1046
- type: 7 /* AnimationMetadataType.Trigger */,
1047
- name: metadata.name,
1048
- states,
1049
- transitions,
1050
- queryCount,
1051
- depCount,
1052
- options: null
1053
- };
1054
- }
1055
- visitState(metadata, context) {
1056
- const styleAst = this.visitStyle(metadata.styles, context);
1057
- const astParams = (metadata.options && metadata.options.params) || null;
1058
- if (styleAst.containsDynamicStyles) {
1059
- const missingSubs = new Set();
1060
- const params = astParams || {};
1061
- styleAst.styles.forEach(style => {
1062
- if (style instanceof Map) {
1063
- style.forEach(value => {
1064
- extractStyleParams(value).forEach(sub => {
1065
- if (!params.hasOwnProperty(sub)) {
1066
- missingSubs.add(sub);
1067
- }
1068
- });
1069
- });
1070
- }
1071
- });
1072
- if (missingSubs.size) {
1073
- const missingSubsArr = iteratorToArray(missingSubs.values());
1074
- context.errors.push(invalidState(metadata.name, missingSubsArr));
1075
- }
1076
- }
1077
- return {
1078
- type: 0 /* AnimationMetadataType.State */,
1079
- name: metadata.name,
1080
- style: styleAst,
1081
- options: astParams ? { params: astParams } : null
1082
- };
1083
- }
1084
- visitTransition(metadata, context) {
1085
- context.queryCount = 0;
1086
- context.depCount = 0;
1087
- const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
1088
- const matchers = parseTransitionExpr(metadata.expr, context.errors);
1089
- return {
1090
- type: 1 /* AnimationMetadataType.Transition */,
1091
- matchers,
1092
- animation,
1093
- queryCount: context.queryCount,
1094
- depCount: context.depCount,
1095
- options: normalizeAnimationOptions(metadata.options)
1096
- };
1097
- }
1098
- visitSequence(metadata, context) {
1099
- return {
1100
- type: 2 /* AnimationMetadataType.Sequence */,
1101
- steps: metadata.steps.map(s => visitDslNode(this, s, context)),
1102
- options: normalizeAnimationOptions(metadata.options)
1103
- };
1104
- }
1105
- visitGroup(metadata, context) {
1106
- const currentTime = context.currentTime;
1107
- let furthestTime = 0;
1108
- const steps = metadata.steps.map(step => {
1109
- context.currentTime = currentTime;
1110
- const innerAst = visitDslNode(this, step, context);
1111
- furthestTime = Math.max(furthestTime, context.currentTime);
1112
- return innerAst;
1113
- });
1114
- context.currentTime = furthestTime;
1115
- return {
1116
- type: 3 /* AnimationMetadataType.Group */,
1117
- steps,
1118
- options: normalizeAnimationOptions(metadata.options)
1119
- };
1120
- }
1121
- visitAnimate(metadata, context) {
1122
- const timingAst = constructTimingAst(metadata.timings, context.errors);
1123
- context.currentAnimateTimings = timingAst;
1124
- let styleAst;
1125
- let styleMetadata = metadata.styles ? metadata.styles : style({});
1126
- if (styleMetadata.type == 5 /* AnimationMetadataType.Keyframes */) {
1127
- styleAst = this.visitKeyframes(styleMetadata, context);
1128
- }
1129
- else {
1130
- let styleMetadata = metadata.styles;
1131
- let isEmpty = false;
1132
- if (!styleMetadata) {
1133
- isEmpty = true;
1134
- const newStyleData = {};
1135
- if (timingAst.easing) {
1136
- newStyleData['easing'] = timingAst.easing;
1137
- }
1138
- styleMetadata = style(newStyleData);
1139
- }
1140
- context.currentTime += timingAst.duration + timingAst.delay;
1141
- const _styleAst = this.visitStyle(styleMetadata, context);
1142
- _styleAst.isEmptyStep = isEmpty;
1143
- styleAst = _styleAst;
1144
- }
1145
- context.currentAnimateTimings = null;
1146
- return {
1147
- type: 4 /* AnimationMetadataType.Animate */,
1148
- timings: timingAst,
1149
- style: styleAst,
1150
- options: null
1151
- };
1152
- }
1153
- visitStyle(metadata, context) {
1154
- const ast = this._makeStyleAst(metadata, context);
1155
- this._validateStyleAst(ast, context);
1156
- return ast;
1157
- }
1158
- _makeStyleAst(metadata, context) {
1159
- const styles = [];
1160
- const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];
1161
- for (let styleTuple of metadataStyles) {
1162
- if (typeof styleTuple === 'string') {
1163
- if (styleTuple === AUTO_STYLE) {
1164
- styles.push(styleTuple);
1165
- }
1166
- else {
1167
- context.errors.push(invalidStyleValue(styleTuple));
1168
- }
1169
- }
1170
- else {
1171
- styles.push(convertToMap(styleTuple));
1172
- }
1173
- }
1174
- let containsDynamicStyles = false;
1175
- let collectedEasing = null;
1176
- styles.forEach(styleData => {
1177
- if (styleData instanceof Map) {
1178
- if (styleData.has('easing')) {
1179
- collectedEasing = styleData.get('easing');
1180
- styleData.delete('easing');
1181
- }
1182
- if (!containsDynamicStyles) {
1183
- for (let value of styleData.values()) {
1184
- if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {
1185
- containsDynamicStyles = true;
1186
- break;
1187
- }
1188
- }
1189
- }
1190
- }
1191
- });
1192
- return {
1193
- type: 6 /* AnimationMetadataType.Style */,
1194
- styles,
1195
- easing: collectedEasing,
1196
- offset: metadata.offset,
1197
- containsDynamicStyles,
1198
- options: null
1199
- };
1200
- }
1201
- _validateStyleAst(ast, context) {
1202
- const timings = context.currentAnimateTimings;
1203
- let endTime = context.currentTime;
1204
- let startTime = context.currentTime;
1205
- if (timings && startTime > 0) {
1206
- startTime -= timings.duration + timings.delay;
1207
- }
1208
- ast.styles.forEach(tuple => {
1209
- if (typeof tuple === 'string')
1210
- return;
1211
- tuple.forEach((value, prop) => {
1212
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
1213
- if (!this._driver.validateStyleProperty(prop)) {
1214
- tuple.delete(prop);
1215
- context.unsupportedCSSPropertiesFound.add(prop);
1216
- return;
1217
- }
1218
- }
1219
- // This is guaranteed to have a defined Map at this querySelector location making it
1220
- // safe to add the assertion here. It is set as a default empty map in prior methods.
1221
- const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);
1222
- const collectedEntry = collectedStyles.get(prop);
1223
- let updateCollectedStyle = true;
1224
- if (collectedEntry) {
1225
- if (startTime != endTime && startTime >= collectedEntry.startTime &&
1226
- endTime <= collectedEntry.endTime) {
1227
- context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));
1228
- updateCollectedStyle = false;
1229
- }
1230
- // we always choose the smaller start time value since we
1231
- // want to have a record of the entire animation window where
1232
- // the style property is being animated in between
1233
- startTime = collectedEntry.startTime;
1234
- }
1235
- if (updateCollectedStyle) {
1236
- collectedStyles.set(prop, { startTime, endTime });
1237
- }
1238
- if (context.options) {
1239
- validateStyleParams(value, context.options, context.errors);
1240
- }
1241
- });
1242
- });
1243
- }
1244
- visitKeyframes(metadata, context) {
1245
- const ast = { type: 5 /* AnimationMetadataType.Keyframes */, styles: [], options: null };
1246
- if (!context.currentAnimateTimings) {
1247
- context.errors.push(invalidKeyframes());
1248
- return ast;
1249
- }
1250
- const MAX_KEYFRAME_OFFSET = 1;
1251
- let totalKeyframesWithOffsets = 0;
1252
- const offsets = [];
1253
- let offsetsOutOfOrder = false;
1254
- let keyframesOutOfRange = false;
1255
- let previousOffset = 0;
1256
- const keyframes = metadata.steps.map(styles => {
1257
- const style = this._makeStyleAst(styles, context);
1258
- let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);
1259
- let offset = 0;
1260
- if (offsetVal != null) {
1261
- totalKeyframesWithOffsets++;
1262
- offset = style.offset = offsetVal;
1263
- }
1264
- keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;
1265
- offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;
1266
- previousOffset = offset;
1267
- offsets.push(offset);
1268
- return style;
1269
- });
1270
- if (keyframesOutOfRange) {
1271
- context.errors.push(invalidOffset());
1272
- }
1273
- if (offsetsOutOfOrder) {
1274
- context.errors.push(keyframeOffsetsOutOfOrder());
1275
- }
1276
- const length = metadata.steps.length;
1277
- let generatedOffset = 0;
1278
- if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {
1279
- context.errors.push(keyframesMissingOffsets());
1280
- }
1281
- else if (totalKeyframesWithOffsets == 0) {
1282
- generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);
1283
- }
1284
- const limit = length - 1;
1285
- const currentTime = context.currentTime;
1286
- const currentAnimateTimings = context.currentAnimateTimings;
1287
- const animateDuration = currentAnimateTimings.duration;
1288
- keyframes.forEach((kf, i) => {
1289
- const offset = generatedOffset > 0 ? (i == limit ? 1 : (generatedOffset * i)) : offsets[i];
1290
- const durationUpToThisFrame = offset * animateDuration;
1291
- context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;
1292
- currentAnimateTimings.duration = durationUpToThisFrame;
1293
- this._validateStyleAst(kf, context);
1294
- kf.offset = offset;
1295
- ast.styles.push(kf);
1296
- });
1297
- return ast;
1298
- }
1299
- visitReference(metadata, context) {
1300
- return {
1301
- type: 8 /* AnimationMetadataType.Reference */,
1302
- animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
1303
- options: normalizeAnimationOptions(metadata.options)
1304
- };
1305
- }
1306
- visitAnimateChild(metadata, context) {
1307
- context.depCount++;
1308
- return {
1309
- type: 9 /* AnimationMetadataType.AnimateChild */,
1310
- options: normalizeAnimationOptions(metadata.options)
1311
- };
1312
- }
1313
- visitAnimateRef(metadata, context) {
1314
- return {
1315
- type: 10 /* AnimationMetadataType.AnimateRef */,
1316
- animation: this.visitReference(metadata.animation, context),
1317
- options: normalizeAnimationOptions(metadata.options)
1318
- };
1319
- }
1320
- visitQuery(metadata, context) {
1321
- const parentSelector = context.currentQuerySelector;
1322
- const options = (metadata.options || {});
1323
- context.queryCount++;
1324
- context.currentQuery = metadata;
1325
- const [selector, includeSelf] = normalizeSelector(metadata.selector);
1326
- context.currentQuerySelector =
1327
- parentSelector.length ? (parentSelector + ' ' + selector) : selector;
1328
- getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());
1329
- const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
1330
- context.currentQuery = null;
1331
- context.currentQuerySelector = parentSelector;
1332
- return {
1333
- type: 11 /* AnimationMetadataType.Query */,
1334
- selector,
1335
- limit: options.limit || 0,
1336
- optional: !!options.optional,
1337
- includeSelf,
1338
- animation,
1339
- originalSelector: metadata.selector,
1340
- options: normalizeAnimationOptions(metadata.options)
1341
- };
1342
- }
1343
- visitStagger(metadata, context) {
1344
- if (!context.currentQuery) {
1345
- context.errors.push(invalidStagger());
1346
- }
1347
- const timings = metadata.timings === 'full' ?
1348
- { duration: 0, delay: 0, easing: 'full' } :
1349
- resolveTiming(metadata.timings, context.errors, true);
1350
- return {
1351
- type: 12 /* AnimationMetadataType.Stagger */,
1352
- animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
1353
- timings,
1354
- options: null
1355
- };
1356
- }
1357
- }
1358
- function normalizeSelector(selector) {
1359
- const hasAmpersand = selector.split(/\s*,\s*/).find(token => token == SELF_TOKEN) ? true : false;
1360
- if (hasAmpersand) {
1361
- selector = selector.replace(SELF_TOKEN_REGEX, '');
1362
- }
1363
- // Note: the :enter and :leave aren't normalized here since those
1364
- // selectors are filled in at runtime during timeline building
1365
- selector = selector.replace(/@\*/g, NG_TRIGGER_SELECTOR)
1366
- .replace(/@\w+/g, match => NG_TRIGGER_SELECTOR + '-' + match.slice(1))
1367
- .replace(/:animating/g, NG_ANIMATING_SELECTOR);
1368
- return [selector, hasAmpersand];
1369
- }
1370
- function normalizeParams(obj) {
1371
- return obj ? copyObj(obj) : null;
1372
- }
1373
- class AnimationAstBuilderContext {
1374
- constructor(errors) {
1375
- this.errors = errors;
1376
- this.queryCount = 0;
1377
- this.depCount = 0;
1378
- this.currentTransition = null;
1379
- this.currentQuery = null;
1380
- this.currentQuerySelector = null;
1381
- this.currentAnimateTimings = null;
1382
- this.currentTime = 0;
1383
- this.collectedStyles = new Map();
1384
- this.options = null;
1385
- this.unsupportedCSSPropertiesFound = new Set();
1386
- }
1387
- }
1388
- function consumeOffset(styles) {
1389
- if (typeof styles == 'string')
1390
- return null;
1391
- let offset = null;
1392
- if (Array.isArray(styles)) {
1393
- styles.forEach(styleTuple => {
1394
- if (styleTuple instanceof Map && styleTuple.has('offset')) {
1395
- const obj = styleTuple;
1396
- offset = parseFloat(obj.get('offset'));
1397
- obj.delete('offset');
1398
- }
1399
- });
1400
- }
1401
- else if (styles instanceof Map && styles.has('offset')) {
1402
- const obj = styles;
1403
- offset = parseFloat(obj.get('offset'));
1404
- obj.delete('offset');
1405
- }
1406
- return offset;
1407
- }
1408
- function constructTimingAst(value, errors) {
1409
- if (value.hasOwnProperty('duration')) {
1410
- return value;
1411
- }
1412
- if (typeof value == 'number') {
1413
- const duration = resolveTiming(value, errors).duration;
1414
- return makeTimingAst(duration, 0, '');
1415
- }
1416
- const strValue = value;
1417
- const isDynamic = strValue.split(/\s+/).some(v => v.charAt(0) == '{' && v.charAt(1) == '{');
1418
- if (isDynamic) {
1419
- const ast = makeTimingAst(0, 0, '');
1420
- ast.dynamic = true;
1421
- ast.strValue = strValue;
1422
- return ast;
1423
- }
1424
- const timings = resolveTiming(strValue, errors);
1425
- return makeTimingAst(timings.duration, timings.delay, timings.easing);
1426
- }
1427
- function normalizeAnimationOptions(options) {
1428
- if (options) {
1429
- options = copyObj(options);
1430
- if (options['params']) {
1431
- options['params'] = normalizeParams(options['params']);
1432
- }
1433
- }
1434
- else {
1435
- options = {};
1436
- }
1437
- return options;
1438
- }
1439
- function makeTimingAst(duration, delay, easing) {
1440
- return { duration, delay, easing };
1441
- }
1442
-
1443
- function createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {
1444
- return {
1445
- type: 1 /* AnimationTransitionInstructionType.TimelineAnimation */,
1446
- element,
1447
- keyframes,
1448
- preStyleProps,
1449
- postStyleProps,
1450
- duration,
1451
- delay,
1452
- totalTime: duration + delay,
1453
- easing,
1454
- subTimeline
1455
- };
1456
- }
1457
-
1458
- class ElementInstructionMap {
1459
- constructor() {
1460
- this._map = new Map();
1461
- }
1462
- get(element) {
1463
- return this._map.get(element) || [];
1464
- }
1465
- append(element, instructions) {
1466
- let existingInstructions = this._map.get(element);
1467
- if (!existingInstructions) {
1468
- this._map.set(element, existingInstructions = []);
1469
- }
1470
- existingInstructions.push(...instructions);
1471
- }
1472
- has(element) {
1473
- return this._map.has(element);
1474
- }
1475
- clear() {
1476
- this._map.clear();
1477
- }
1478
- }
1479
-
1480
- const ONE_FRAME_IN_MILLISECONDS = 1;
1481
- const ENTER_TOKEN = ':enter';
1482
- const ENTER_TOKEN_REGEX = new RegExp(ENTER_TOKEN, 'g');
1483
- const LEAVE_TOKEN = ':leave';
1484
- const LEAVE_TOKEN_REGEX = new RegExp(LEAVE_TOKEN, 'g');
1485
- /*
1486
- * The code within this file aims to generate web-animations-compatible keyframes from Angular's
1487
- * animation DSL code.
1488
- *
1489
- * The code below will be converted from:
1490
- *
1491
- * ```
1492
- * sequence([
1493
- * style({ opacity: 0 }),
1494
- * animate(1000, style({ opacity: 0 }))
1495
- * ])
1496
- * ```
1497
- *
1498
- * To:
1499
- * ```
1500
- * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]
1501
- * duration = 1000
1502
- * delay = 0
1503
- * easing = ''
1504
- * ```
1505
- *
1506
- * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a
1507
- * combination of AST traversal and merge-sort-like algorithms are used.
1508
- *
1509
- * [AST Traversal]
1510
- * Each of the animation verbs, when executed, will return an string-map object representing what
1511
- * type of action it is (style, animate, group, etc...) and the data associated with it. This means
1512
- * that when functional composition mix of these functions is evaluated (like in the example above)
1513
- * then it will end up producing a tree of objects representing the animation itself.
1514
- *
1515
- * When this animation object tree is processed by the visitor code below it will visit each of the
1516
- * verb statements within the visitor. And during each visit it will build the context of the
1517
- * animation keyframes by interacting with the `TimelineBuilder`.
1518
- *
1519
- * [TimelineBuilder]
1520
- * This class is responsible for tracking the styles and building a series of keyframe objects for a
1521
- * timeline between a start and end time. The builder starts off with an initial timeline and each
1522
- * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a
1523
- * `sequence()` then it will generate a sub timeline for each step as well as a new one after
1524
- * they are complete.
1525
- *
1526
- * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub
1527
- * timeline was created (based on one of the cases above) then the parent timeline will attempt to
1528
- * merge the styles used within the sub timelines into itself (only with group() this will happen).
1529
- * This happens with a merge operation (much like how the merge works in mergeSort) and it will only
1530
- * copy the most recently used styles from the sub timelines into the parent timeline. This ensures
1531
- * that if the styles are used later on in another phase of the animation then they will be the most
1532
- * up-to-date values.
1533
- *
1534
- * [How Missing Styles Are Updated]
1535
- * Each timeline has a `backFill` property which is responsible for filling in new styles into
1536
- * already processed keyframes if a new style shows up later within the animation sequence.
1537
- *
1538
- * ```
1539
- * sequence([
1540
- * style({ width: 0 }),
1541
- * animate(1000, style({ width: 100 })),
1542
- * animate(1000, style({ width: 200 })),
1543
- * animate(1000, style({ width: 300 }))
1544
- * animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere
1545
- * else
1546
- * ])
1547
- * ```
1548
- *
1549
- * What is happening here is that the `height` value is added later in the sequence, but is missing
1550
- * from all previous animation steps. Therefore when a keyframe is created it would also be missing
1551
- * from all previous keyframes up until where it is first used. For the timeline keyframe generation
1552
- * to properly fill in the style it will place the previous value (the value from the parent
1553
- * timeline) or a default value of `*` into the backFill map. The `copyStyles` method in util.ts
1554
- * handles propagating that backfill map to the styles object.
1555
- *
1556
- * When a sub-timeline is created it will have its own backFill property. This is done so that
1557
- * styles present within the sub-timeline do not accidentally seep into the previous/future timeline
1558
- * keyframes
1559
- *
1560
- * [Validation]
1561
- * The code in this file is not responsible for validation. That functionality happens with within
1562
- * the `AnimationValidatorVisitor` code.
1563
- */
1564
- function buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = new Map(), finalStyles = new Map(), options, subInstructions, errors = []) {
1565
- return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);
1566
- }
1567
- class AnimationTimelineBuilderVisitor {
1568
- buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {
1569
- subInstructions = subInstructions || new ElementInstructionMap();
1570
- const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);
1571
- context.options = options;
1572
- const delay = options.delay ? resolveTimingValue(options.delay) : 0;
1573
- context.currentTimeline.delayNextStep(delay);
1574
- context.currentTimeline.setStyles([startingStyles], null, context.errors, options);
1575
- visitDslNode(this, ast, context);
1576
- // this checks to see if an actual animation happened
1577
- const timelines = context.timelines.filter(timeline => timeline.containsAnimation());
1578
- // note: we just want to apply the final styles for the rootElement, so we do not
1579
- // just apply the styles to the last timeline but the last timeline which
1580
- // element is the root one (basically `*`-styles are replaced with the actual
1581
- // state style values only for the root element)
1582
- if (timelines.length && finalStyles.size) {
1583
- let lastRootTimeline;
1584
- for (let i = timelines.length - 1; i >= 0; i--) {
1585
- const timeline = timelines[i];
1586
- if (timeline.element === rootElement) {
1587
- lastRootTimeline = timeline;
1588
- break;
1589
- }
1590
- }
1591
- if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) {
1592
- lastRootTimeline.setStyles([finalStyles], null, context.errors, options);
1593
- }
1594
- }
1595
- return timelines.length ?
1596
- timelines.map(timeline => timeline.buildKeyframes()) :
1597
- [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)];
1598
- }
1599
- visitTrigger(ast, context) {
1600
- // these values are not visited in this AST
1601
- }
1602
- visitState(ast, context) {
1603
- // these values are not visited in this AST
1604
- }
1605
- visitTransition(ast, context) {
1606
- // these values are not visited in this AST
1607
- }
1608
- visitAnimateChild(ast, context) {
1609
- const elementInstructions = context.subInstructions.get(context.element);
1610
- if (elementInstructions) {
1611
- const innerContext = context.createSubContext(ast.options);
1612
- const startTime = context.currentTimeline.currentTime;
1613
- const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);
1614
- if (startTime != endTime) {
1615
- // we do this on the upper context because we created a sub context for
1616
- // the sub child animations
1617
- context.transformIntoNewTimeline(endTime);
1618
- }
1619
- }
1620
- context.previousNode = ast;
1621
- }
1622
- visitAnimateRef(ast, context) {
1623
- const innerContext = context.createSubContext(ast.options);
1624
- innerContext.transformIntoNewTimeline();
1625
- this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext);
1626
- this.visitReference(ast.animation, innerContext);
1627
- context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);
1628
- context.previousNode = ast;
1629
- }
1630
- _applyAnimationRefDelays(animationsRefsOptions, context, innerContext) {
1631
- var _a;
1632
- for (const animationRefOptions of animationsRefsOptions) {
1633
- const animationDelay = animationRefOptions === null || animationRefOptions === void 0 ? void 0 : animationRefOptions.delay;
1634
- if (animationDelay) {
1635
- const animationDelayValue = typeof animationDelay === 'number' ?
1636
- animationDelay :
1637
- resolveTimingValue(interpolateParams(animationDelay, (_a = animationRefOptions === null || animationRefOptions === void 0 ? void 0 : animationRefOptions.params) !== null && _a !== void 0 ? _a : {}, context.errors));
1638
- innerContext.delayNextStep(animationDelayValue);
1639
- }
1640
- }
1641
- }
1642
- _visitSubInstructions(instructions, context, options) {
1643
- const startTime = context.currentTimeline.currentTime;
1644
- let furthestTime = startTime;
1645
- // this is a special-case for when a user wants to skip a sub
1646
- // animation from being fired entirely.
1647
- const duration = options.duration != null ? resolveTimingValue(options.duration) : null;
1648
- const delay = options.delay != null ? resolveTimingValue(options.delay) : null;
1649
- if (duration !== 0) {
1650
- instructions.forEach(instruction => {
1651
- const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);
1652
- furthestTime =
1653
- Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);
1654
- });
1655
- }
1656
- return furthestTime;
1657
- }
1658
- visitReference(ast, context) {
1659
- context.updateOptions(ast.options, true);
1660
- visitDslNode(this, ast.animation, context);
1661
- context.previousNode = ast;
1662
- }
1663
- visitSequence(ast, context) {
1664
- const subContextCount = context.subContextCount;
1665
- let ctx = context;
1666
- const options = ast.options;
1667
- if (options && (options.params || options.delay)) {
1668
- ctx = context.createSubContext(options);
1669
- ctx.transformIntoNewTimeline();
1670
- if (options.delay != null) {
1671
- if (ctx.previousNode.type == 6 /* AnimationMetadataType.Style */) {
1672
- ctx.currentTimeline.snapshotCurrentStyles();
1673
- ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
1674
- }
1675
- const delay = resolveTimingValue(options.delay);
1676
- ctx.delayNextStep(delay);
1677
- }
1678
- }
1679
- if (ast.steps.length) {
1680
- ast.steps.forEach(s => visitDslNode(this, s, ctx));
1681
- // this is here just in case the inner steps only contain or end with a style() call
1682
- ctx.currentTimeline.applyStylesToKeyframe();
1683
- // this means that some animation function within the sequence
1684
- // ended up creating a sub timeline (which means the current
1685
- // timeline cannot overlap with the contents of the sequence)
1686
- if (ctx.subContextCount > subContextCount) {
1687
- ctx.transformIntoNewTimeline();
1688
- }
1689
- }
1690
- context.previousNode = ast;
1691
- }
1692
- visitGroup(ast, context) {
1693
- const innerTimelines = [];
1694
- let furthestTime = context.currentTimeline.currentTime;
1695
- const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;
1696
- ast.steps.forEach(s => {
1697
- const innerContext = context.createSubContext(ast.options);
1698
- if (delay) {
1699
- innerContext.delayNextStep(delay);
1700
- }
1701
- visitDslNode(this, s, innerContext);
1702
- furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);
1703
- innerTimelines.push(innerContext.currentTimeline);
1704
- });
1705
- // this operation is run after the AST loop because otherwise
1706
- // if the parent timeline's collected styles were updated then
1707
- // it would pass in invalid data into the new-to-be forked items
1708
- innerTimelines.forEach(timeline => context.currentTimeline.mergeTimelineCollectedStyles(timeline));
1709
- context.transformIntoNewTimeline(furthestTime);
1710
- context.previousNode = ast;
1711
- }
1712
- _visitTiming(ast, context) {
1713
- if (ast.dynamic) {
1714
- const strValue = ast.strValue;
1715
- const timingValue = context.params ? interpolateParams(strValue, context.params, context.errors) : strValue;
1716
- return resolveTiming(timingValue, context.errors);
1717
- }
1718
- else {
1719
- return { duration: ast.duration, delay: ast.delay, easing: ast.easing };
1720
- }
1721
- }
1722
- visitAnimate(ast, context) {
1723
- const timings = context.currentAnimateTimings = this._visitTiming(ast.timings, context);
1724
- const timeline = context.currentTimeline;
1725
- if (timings.delay) {
1726
- context.incrementTime(timings.delay);
1727
- timeline.snapshotCurrentStyles();
1728
- }
1729
- const style = ast.style;
1730
- if (style.type == 5 /* AnimationMetadataType.Keyframes */) {
1731
- this.visitKeyframes(style, context);
1732
- }
1733
- else {
1734
- context.incrementTime(timings.duration);
1735
- this.visitStyle(style, context);
1736
- timeline.applyStylesToKeyframe();
1737
- }
1738
- context.currentAnimateTimings = null;
1739
- context.previousNode = ast;
1740
- }
1741
- visitStyle(ast, context) {
1742
- const timeline = context.currentTimeline;
1743
- const timings = context.currentAnimateTimings;
1744
- // this is a special case for when a style() call
1745
- // directly follows an animate() call (but not inside of an animate() call)
1746
- if (!timings && timeline.hasCurrentStyleProperties()) {
1747
- timeline.forwardFrame();
1748
- }
1749
- const easing = (timings && timings.easing) || ast.easing;
1750
- if (ast.isEmptyStep) {
1751
- timeline.applyEmptyStep(easing);
1752
- }
1753
- else {
1754
- timeline.setStyles(ast.styles, easing, context.errors, context.options);
1755
- }
1756
- context.previousNode = ast;
1757
- }
1758
- visitKeyframes(ast, context) {
1759
- const currentAnimateTimings = context.currentAnimateTimings;
1760
- const startTime = (context.currentTimeline).duration;
1761
- const duration = currentAnimateTimings.duration;
1762
- const innerContext = context.createSubContext();
1763
- const innerTimeline = innerContext.currentTimeline;
1764
- innerTimeline.easing = currentAnimateTimings.easing;
1765
- ast.styles.forEach(step => {
1766
- const offset = step.offset || 0;
1767
- innerTimeline.forwardTime(offset * duration);
1768
- innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);
1769
- innerTimeline.applyStylesToKeyframe();
1770
- });
1771
- // this will ensure that the parent timeline gets all the styles from
1772
- // the child even if the new timeline below is not used
1773
- context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);
1774
- // we do this because the window between this timeline and the sub timeline
1775
- // should ensure that the styles within are exactly the same as they were before
1776
- context.transformIntoNewTimeline(startTime + duration);
1777
- context.previousNode = ast;
1778
- }
1779
- visitQuery(ast, context) {
1780
- // in the event that the first step before this is a style step we need
1781
- // to ensure the styles are applied before the children are animated
1782
- const startTime = context.currentTimeline.currentTime;
1783
- const options = (ast.options || {});
1784
- const delay = options.delay ? resolveTimingValue(options.delay) : 0;
1785
- if (delay &&
1786
- (context.previousNode.type === 6 /* AnimationMetadataType.Style */ ||
1787
- (startTime == 0 && context.currentTimeline.hasCurrentStyleProperties()))) {
1788
- context.currentTimeline.snapshotCurrentStyles();
1789
- context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
1790
- }
1791
- let furthestTime = startTime;
1792
- const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);
1793
- context.currentQueryTotal = elms.length;
1794
- let sameElementTimeline = null;
1795
- elms.forEach((element, i) => {
1796
- context.currentQueryIndex = i;
1797
- const innerContext = context.createSubContext(ast.options, element);
1798
- if (delay) {
1799
- innerContext.delayNextStep(delay);
1800
- }
1801
- if (element === context.element) {
1802
- sameElementTimeline = innerContext.currentTimeline;
1803
- }
1804
- visitDslNode(this, ast.animation, innerContext);
1805
- // this is here just incase the inner steps only contain or end
1806
- // with a style() call (which is here to signal that this is a preparatory
1807
- // call to style an element before it is animated again)
1808
- innerContext.currentTimeline.applyStylesToKeyframe();
1809
- const endTime = innerContext.currentTimeline.currentTime;
1810
- furthestTime = Math.max(furthestTime, endTime);
1811
- });
1812
- context.currentQueryIndex = 0;
1813
- context.currentQueryTotal = 0;
1814
- context.transformIntoNewTimeline(furthestTime);
1815
- if (sameElementTimeline) {
1816
- context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);
1817
- context.currentTimeline.snapshotCurrentStyles();
1818
- }
1819
- context.previousNode = ast;
1820
- }
1821
- visitStagger(ast, context) {
1822
- const parentContext = context.parentContext;
1823
- const tl = context.currentTimeline;
1824
- const timings = ast.timings;
1825
- const duration = Math.abs(timings.duration);
1826
- const maxTime = duration * (context.currentQueryTotal - 1);
1827
- let delay = duration * context.currentQueryIndex;
1828
- let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;
1829
- switch (staggerTransformer) {
1830
- case 'reverse':
1831
- delay = maxTime - delay;
1832
- break;
1833
- case 'full':
1834
- delay = parentContext.currentStaggerTime;
1835
- break;
1836
- }
1837
- const timeline = context.currentTimeline;
1838
- if (delay) {
1839
- timeline.delayNextStep(delay);
1840
- }
1841
- const startingTime = timeline.currentTime;
1842
- visitDslNode(this, ast.animation, context);
1843
- context.previousNode = ast;
1844
- // time = duration + delay
1845
- // the reason why this computation is so complex is because
1846
- // the inner timeline may either have a delay value or a stretched
1847
- // keyframe depending on if a subtimeline is not used or is used.
1848
- parentContext.currentStaggerTime =
1849
- (tl.currentTime - startingTime) + (tl.startTime - parentContext.currentTimeline.startTime);
1850
- }
1851
- }
1852
- const DEFAULT_NOOP_PREVIOUS_NODE = {};
1853
- class AnimationTimelineContext {
1854
- constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {
1855
- this._driver = _driver;
1856
- this.element = element;
1857
- this.subInstructions = subInstructions;
1858
- this._enterClassName = _enterClassName;
1859
- this._leaveClassName = _leaveClassName;
1860
- this.errors = errors;
1861
- this.timelines = timelines;
1862
- this.parentContext = null;
1863
- this.currentAnimateTimings = null;
1864
- this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
1865
- this.subContextCount = 0;
1866
- this.options = {};
1867
- this.currentQueryIndex = 0;
1868
- this.currentQueryTotal = 0;
1869
- this.currentStaggerTime = 0;
1870
- this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);
1871
- timelines.push(this.currentTimeline);
1872
- }
1873
- get params() {
1874
- return this.options.params;
1875
- }
1876
- updateOptions(options, skipIfExists) {
1877
- if (!options)
1878
- return;
1879
- const newOptions = options;
1880
- let optionsToUpdate = this.options;
1881
- // NOTE: this will get patched up when other animation methods support duration overrides
1882
- if (newOptions.duration != null) {
1883
- optionsToUpdate.duration = resolveTimingValue(newOptions.duration);
1884
- }
1885
- if (newOptions.delay != null) {
1886
- optionsToUpdate.delay = resolveTimingValue(newOptions.delay);
1887
- }
1888
- const newParams = newOptions.params;
1889
- if (newParams) {
1890
- let paramsToUpdate = optionsToUpdate.params;
1891
- if (!paramsToUpdate) {
1892
- paramsToUpdate = this.options.params = {};
1893
- }
1894
- Object.keys(newParams).forEach(name => {
1895
- if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {
1896
- paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);
1897
- }
1898
- });
1899
- }
1900
- }
1901
- _copyOptions() {
1902
- const options = {};
1903
- if (this.options) {
1904
- const oldParams = this.options.params;
1905
- if (oldParams) {
1906
- const params = options['params'] = {};
1907
- Object.keys(oldParams).forEach(name => {
1908
- params[name] = oldParams[name];
1909
- });
1910
- }
1911
- }
1912
- return options;
1913
- }
1914
- createSubContext(options = null, element, newTime) {
1915
- const target = element || this.element;
1916
- const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));
1917
- context.previousNode = this.previousNode;
1918
- context.currentAnimateTimings = this.currentAnimateTimings;
1919
- context.options = this._copyOptions();
1920
- context.updateOptions(options);
1921
- context.currentQueryIndex = this.currentQueryIndex;
1922
- context.currentQueryTotal = this.currentQueryTotal;
1923
- context.parentContext = this;
1924
- this.subContextCount++;
1925
- return context;
1926
- }
1927
- transformIntoNewTimeline(newTime) {
1928
- this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
1929
- this.currentTimeline = this.currentTimeline.fork(this.element, newTime);
1930
- this.timelines.push(this.currentTimeline);
1931
- return this.currentTimeline;
1932
- }
1933
- appendInstructionToTimeline(instruction, duration, delay) {
1934
- const updatedTimings = {
1935
- duration: duration != null ? duration : instruction.duration,
1936
- delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,
1937
- easing: ''
1938
- };
1939
- const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);
1940
- this.timelines.push(builder);
1941
- return updatedTimings;
1942
- }
1943
- incrementTime(time) {
1944
- this.currentTimeline.forwardTime(this.currentTimeline.duration + time);
1945
- }
1946
- delayNextStep(delay) {
1947
- // negative delays are not yet supported
1948
- if (delay > 0) {
1949
- this.currentTimeline.delayNextStep(delay);
1950
- }
1951
- }
1952
- invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {
1953
- let results = [];
1954
- if (includeSelf) {
1955
- results.push(this.element);
1956
- }
1957
- if (selector.length > 0) { // only if :self is used then the selector can be empty
1958
- selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);
1959
- selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);
1960
- const multi = limit != 1;
1961
- let elements = this._driver.query(this.element, selector, multi);
1962
- if (limit !== 0) {
1963
- elements = limit < 0 ? elements.slice(elements.length + limit, elements.length) :
1964
- elements.slice(0, limit);
1965
- }
1966
- results.push(...elements);
1967
- }
1968
- if (!optional && results.length == 0) {
1969
- errors.push(invalidQuery(originalSelector));
1970
- }
1971
- return results;
1972
- }
1973
- }
1974
- class TimelineBuilder {
1975
- constructor(_driver, element, startTime, _elementTimelineStylesLookup) {
1976
- this._driver = _driver;
1977
- this.element = element;
1978
- this.startTime = startTime;
1979
- this._elementTimelineStylesLookup = _elementTimelineStylesLookup;
1980
- this.duration = 0;
1981
- this.easing = null;
1982
- this._previousKeyframe = new Map();
1983
- this._currentKeyframe = new Map();
1984
- this._keyframes = new Map();
1985
- this._styleSummary = new Map();
1986
- this._localTimelineStyles = new Map();
1987
- this._pendingStyles = new Map();
1988
- this._backFill = new Map();
1989
- this._currentEmptyStepKeyframe = null;
1990
- if (!this._elementTimelineStylesLookup) {
1991
- this._elementTimelineStylesLookup = new Map();
1992
- }
1993
- this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);
1994
- if (!this._globalTimelineStyles) {
1995
- this._globalTimelineStyles = this._localTimelineStyles;
1996
- this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);
1997
- }
1998
- this._loadKeyframe();
1999
- }
2000
- containsAnimation() {
2001
- switch (this._keyframes.size) {
2002
- case 0:
2003
- return false;
2004
- case 1:
2005
- return this.hasCurrentStyleProperties();
2006
- default:
2007
- return true;
2008
- }
2009
- }
2010
- hasCurrentStyleProperties() {
2011
- return this._currentKeyframe.size > 0;
2012
- }
2013
- get currentTime() {
2014
- return this.startTime + this.duration;
2015
- }
2016
- delayNextStep(delay) {
2017
- // in the event that a style() step is placed right before a stagger()
2018
- // and that style() step is the very first style() value in the animation
2019
- // then we need to make a copy of the keyframe [0, copy, 1] so that the delay
2020
- // properly applies the style() values to work with the stagger...
2021
- const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size;
2022
- if (this.duration || hasPreStyleStep) {
2023
- this.forwardTime(this.currentTime + delay);
2024
- if (hasPreStyleStep) {
2025
- this.snapshotCurrentStyles();
2026
- }
2027
- }
2028
- else {
2029
- this.startTime += delay;
2030
- }
2031
- }
2032
- fork(element, currentTime) {
2033
- this.applyStylesToKeyframe();
2034
- return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);
2035
- }
2036
- _loadKeyframe() {
2037
- if (this._currentKeyframe) {
2038
- this._previousKeyframe = this._currentKeyframe;
2039
- }
2040
- this._currentKeyframe = this._keyframes.get(this.duration);
2041
- if (!this._currentKeyframe) {
2042
- this._currentKeyframe = new Map();
2043
- this._keyframes.set(this.duration, this._currentKeyframe);
2044
- }
2045
- }
2046
- forwardFrame() {
2047
- this.duration += ONE_FRAME_IN_MILLISECONDS;
2048
- this._loadKeyframe();
2049
- }
2050
- forwardTime(time) {
2051
- this.applyStylesToKeyframe();
2052
- this.duration = time;
2053
- this._loadKeyframe();
2054
- }
2055
- _updateStyle(prop, value) {
2056
- this._localTimelineStyles.set(prop, value);
2057
- this._globalTimelineStyles.set(prop, value);
2058
- this._styleSummary.set(prop, { time: this.currentTime, value });
2059
- }
2060
- allowOnlyTimelineStyles() {
2061
- return this._currentEmptyStepKeyframe !== this._currentKeyframe;
2062
- }
2063
- applyEmptyStep(easing) {
2064
- if (easing) {
2065
- this._previousKeyframe.set('easing', easing);
2066
- }
2067
- // special case for animate(duration):
2068
- // all missing styles are filled with a `*` value then
2069
- // if any destination styles are filled in later on the same
2070
- // keyframe then they will override the overridden styles
2071
- // We use `_globalTimelineStyles` here because there may be
2072
- // styles in previous keyframes that are not present in this timeline
2073
- for (let [prop, value] of this._globalTimelineStyles) {
2074
- this._backFill.set(prop, value || AUTO_STYLE);
2075
- this._currentKeyframe.set(prop, AUTO_STYLE);
2076
- }
2077
- this._currentEmptyStepKeyframe = this._currentKeyframe;
2078
- }
2079
- setStyles(input, easing, errors, options) {
2080
- var _a;
2081
- if (easing) {
2082
- this._previousKeyframe.set('easing', easing);
2083
- }
2084
- const params = (options && options.params) || {};
2085
- const styles = flattenStyles(input, this._globalTimelineStyles);
2086
- for (let [prop, value] of styles) {
2087
- const val = interpolateParams(value, params, errors);
2088
- this._pendingStyles.set(prop, val);
2089
- if (!this._localTimelineStyles.has(prop)) {
2090
- this._backFill.set(prop, (_a = this._globalTimelineStyles.get(prop)) !== null && _a !== void 0 ? _a : AUTO_STYLE);
2091
- }
2092
- this._updateStyle(prop, val);
2093
- }
2094
- }
2095
- applyStylesToKeyframe() {
2096
- if (this._pendingStyles.size == 0)
2097
- return;
2098
- this._pendingStyles.forEach((val, prop) => {
2099
- this._currentKeyframe.set(prop, val);
2100
- });
2101
- this._pendingStyles.clear();
2102
- this._localTimelineStyles.forEach((val, prop) => {
2103
- if (!this._currentKeyframe.has(prop)) {
2104
- this._currentKeyframe.set(prop, val);
2105
- }
2106
- });
2107
- }
2108
- snapshotCurrentStyles() {
2109
- for (let [prop, val] of this._localTimelineStyles) {
2110
- this._pendingStyles.set(prop, val);
2111
- this._updateStyle(prop, val);
2112
- }
2113
- }
2114
- getFinalKeyframe() {
2115
- return this._keyframes.get(this.duration);
2116
- }
2117
- get properties() {
2118
- const properties = [];
2119
- for (let prop in this._currentKeyframe) {
2120
- properties.push(prop);
2121
- }
2122
- return properties;
2123
- }
2124
- mergeTimelineCollectedStyles(timeline) {
2125
- timeline._styleSummary.forEach((details1, prop) => {
2126
- const details0 = this._styleSummary.get(prop);
2127
- if (!details0 || details1.time > details0.time) {
2128
- this._updateStyle(prop, details1.value);
2129
- }
2130
- });
2131
- }
2132
- buildKeyframes() {
2133
- this.applyStylesToKeyframe();
2134
- const preStyleProps = new Set();
2135
- const postStyleProps = new Set();
2136
- const isEmpty = this._keyframes.size === 1 && this.duration === 0;
2137
- let finalKeyframes = [];
2138
- this._keyframes.forEach((keyframe, time) => {
2139
- const finalKeyframe = copyStyles(keyframe, new Map(), this._backFill);
2140
- finalKeyframe.forEach((value, prop) => {
2141
- if (value === ɵPRE_STYLE) {
2142
- preStyleProps.add(prop);
2143
- }
2144
- else if (value === AUTO_STYLE) {
2145
- postStyleProps.add(prop);
2146
- }
2147
- });
2148
- if (!isEmpty) {
2149
- finalKeyframe.set('offset', time / this.duration);
2150
- }
2151
- finalKeyframes.push(finalKeyframe);
2152
- });
2153
- const preProps = preStyleProps.size ? iteratorToArray(preStyleProps.values()) : [];
2154
- const postProps = postStyleProps.size ? iteratorToArray(postStyleProps.values()) : [];
2155
- // special case for a 0-second animation (which is designed just to place styles onscreen)
2156
- if (isEmpty) {
2157
- const kf0 = finalKeyframes[0];
2158
- const kf1 = new Map(kf0);
2159
- kf0.set('offset', 0);
2160
- kf1.set('offset', 1);
2161
- finalKeyframes = [kf0, kf1];
2162
- }
2163
- return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);
2164
- }
2165
- }
2166
- class SubTimelineBuilder extends TimelineBuilder {
2167
- constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {
2168
- super(driver, element, timings.delay);
2169
- this.keyframes = keyframes;
2170
- this.preStyleProps = preStyleProps;
2171
- this.postStyleProps = postStyleProps;
2172
- this._stretchStartingKeyframe = _stretchStartingKeyframe;
2173
- this.timings = { duration: timings.duration, delay: timings.delay, easing: timings.easing };
2174
- }
2175
- containsAnimation() {
2176
- return this.keyframes.length > 1;
2177
- }
2178
- buildKeyframes() {
2179
- let keyframes = this.keyframes;
2180
- let { delay, duration, easing } = this.timings;
2181
- if (this._stretchStartingKeyframe && delay) {
2182
- const newKeyframes = [];
2183
- const totalTime = duration + delay;
2184
- const startingGap = delay / totalTime;
2185
- // the original starting keyframe now starts once the delay is done
2186
- const newFirstKeyframe = copyStyles(keyframes[0]);
2187
- newFirstKeyframe.set('offset', 0);
2188
- newKeyframes.push(newFirstKeyframe);
2189
- const oldFirstKeyframe = copyStyles(keyframes[0]);
2190
- oldFirstKeyframe.set('offset', roundOffset(startingGap));
2191
- newKeyframes.push(oldFirstKeyframe);
2192
- /*
2193
- When the keyframe is stretched then it means that the delay before the animation
2194
- starts is gone. Instead the first keyframe is placed at the start of the animation
2195
- and it is then copied to where it starts when the original delay is over. This basically
2196
- means nothing animates during that delay, but the styles are still rendered. For this
2197
- to work the original offset values that exist in the original keyframes must be "warped"
2198
- so that they can take the new keyframe + delay into account.
2199
-
2200
- delay=1000, duration=1000, keyframes = 0 .5 1
2201
-
2202
- turns into
2203
-
2204
- delay=0, duration=2000, keyframes = 0 .33 .66 1
2205
- */
2206
- // offsets between 1 ... n -1 are all warped by the keyframe stretch
2207
- const limit = keyframes.length - 1;
2208
- for (let i = 1; i <= limit; i++) {
2209
- let kf = copyStyles(keyframes[i]);
2210
- const oldOffset = kf.get('offset');
2211
- const timeAtKeyframe = delay + oldOffset * duration;
2212
- kf.set('offset', roundOffset(timeAtKeyframe / totalTime));
2213
- newKeyframes.push(kf);
2214
- }
2215
- // the new starting keyframe should be added at the start
2216
- duration = totalTime;
2217
- delay = 0;
2218
- easing = '';
2219
- keyframes = newKeyframes;
2220
- }
2221
- return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);
2222
- }
2223
- }
2224
- function roundOffset(offset, decimalPoints = 3) {
2225
- const mult = Math.pow(10, decimalPoints - 1);
2226
- return Math.round(offset * mult) / mult;
2227
- }
2228
- function flattenStyles(input, allStyles) {
2229
- const styles = new Map();
2230
- let allProperties;
2231
- input.forEach(token => {
2232
- if (token === '*') {
2233
- allProperties = allProperties || allStyles.keys();
2234
- for (let prop of allProperties) {
2235
- styles.set(prop, AUTO_STYLE);
2236
- }
2237
- }
2238
- else {
2239
- copyStyles(token, styles);
2240
- }
2241
- });
2242
- return styles;
2243
- }
2244
-
2245
- class Animation {
2246
- constructor(_driver, input) {
2247
- this._driver = _driver;
2248
- const errors = [];
2249
- const warnings = [];
2250
- const ast = buildAnimationAst(_driver, input, errors, warnings);
2251
- if (errors.length) {
2252
- throw validationFailed(errors);
2253
- }
2254
- if (warnings.length) {
2255
- warnValidation(warnings);
2256
- }
2257
- this._animationAst = ast;
2258
- }
2259
- buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {
2260
- const start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) :
2261
- startingStyles;
2262
- const dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) :
2263
- destinationStyles;
2264
- const errors = [];
2265
- subInstructions = subInstructions || new ElementInstructionMap();
2266
- const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);
2267
- if (errors.length) {
2268
- throw buildingFailed(errors);
2269
- }
2270
- return result;
2271
- }
2272
- }
2273
-
2274
- /**
2275
- * @publicApi
2276
- */
2277
- class AnimationStyleNormalizer {
2278
- }
2279
- /**
2280
- * @publicApi
2281
- */
2282
- class NoopAnimationStyleNormalizer {
2283
- normalizePropertyName(propertyName, errors) {
2284
- return propertyName;
2285
- }
2286
- normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
2287
- return value;
2288
- }
2289
- }
2290
-
2291
- const DIMENSIONAL_PROP_SET = new Set([
2292
- 'width',
2293
- 'height',
2294
- 'minWidth',
2295
- 'minHeight',
2296
- 'maxWidth',
2297
- 'maxHeight',
2298
- 'left',
2299
- 'top',
2300
- 'bottom',
2301
- 'right',
2302
- 'fontSize',
2303
- 'outlineWidth',
2304
- 'outlineOffset',
2305
- 'paddingTop',
2306
- 'paddingLeft',
2307
- 'paddingBottom',
2308
- 'paddingRight',
2309
- 'marginTop',
2310
- 'marginLeft',
2311
- 'marginBottom',
2312
- 'marginRight',
2313
- 'borderRadius',
2314
- 'borderWidth',
2315
- 'borderTopWidth',
2316
- 'borderLeftWidth',
2317
- 'borderRightWidth',
2318
- 'borderBottomWidth',
2319
- 'textIndent',
2320
- 'perspective'
2321
- ]);
2322
- class WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {
2323
- normalizePropertyName(propertyName, errors) {
2324
- return dashCaseToCamelCase(propertyName);
2325
- }
2326
- normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
2327
- let unit = '';
2328
- const strVal = value.toString().trim();
2329
- if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') {
2330
- if (typeof value === 'number') {
2331
- unit = 'px';
2332
- }
2333
- else {
2334
- const valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/);
2335
- if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
2336
- errors.push(invalidCssUnitValue(userProvidedProperty, value));
2337
- }
2338
- }
2339
- }
2340
- return strVal + unit;
2341
- }
2342
- }
2343
-
2344
- function createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {
2345
- return {
2346
- type: 0 /* AnimationTransitionInstructionType.TransitionAnimation */,
2347
- element,
2348
- triggerName,
2349
- isRemovalTransition,
2350
- fromState,
2351
- fromStyles,
2352
- toState,
2353
- toStyles,
2354
- timelines,
2355
- queriedElements,
2356
- preStyleProps,
2357
- postStyleProps,
2358
- totalTime,
2359
- errors
2360
- };
2361
- }
2362
-
2363
- const EMPTY_OBJECT = {};
2364
- class AnimationTransitionFactory {
2365
- constructor(_triggerName, ast, _stateStyles) {
2366
- this._triggerName = _triggerName;
2367
- this.ast = ast;
2368
- this._stateStyles = _stateStyles;
2369
- }
2370
- match(currentState, nextState, element, params) {
2371
- return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);
2372
- }
2373
- buildStyles(stateName, params, errors) {
2374
- let styler = this._stateStyles.get('*');
2375
- if (stateName !== undefined) {
2376
- styler = this._stateStyles.get(stateName === null || stateName === void 0 ? void 0 : stateName.toString()) || styler;
2377
- }
2378
- return styler ? styler.buildStyles(params, errors) : new Map();
2379
- }
2380
- build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {
2381
- var _a;
2382
- const errors = [];
2383
- const transitionAnimationParams = this.ast.options && this.ast.options.params || EMPTY_OBJECT;
2384
- const currentAnimationParams = currentOptions && currentOptions.params || EMPTY_OBJECT;
2385
- const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);
2386
- const nextAnimationParams = nextOptions && nextOptions.params || EMPTY_OBJECT;
2387
- const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);
2388
- const queriedElements = new Set();
2389
- const preStyleMap = new Map();
2390
- const postStyleMap = new Map();
2391
- const isRemoval = nextState === 'void';
2392
- const animationOptions = {
2393
- params: applyParamDefaults(nextAnimationParams, transitionAnimationParams),
2394
- delay: (_a = this.ast.options) === null || _a === void 0 ? void 0 : _a.delay,
2395
- };
2396
- const timelines = skipAstBuild ?
2397
- [] :
2398
- buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);
2399
- let totalTime = 0;
2400
- timelines.forEach(tl => {
2401
- totalTime = Math.max(tl.duration + tl.delay, totalTime);
2402
- });
2403
- if (errors.length) {
2404
- return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);
2405
- }
2406
- timelines.forEach(tl => {
2407
- const elm = tl.element;
2408
- const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set());
2409
- tl.preStyleProps.forEach(prop => preProps.add(prop));
2410
- const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set());
2411
- tl.postStyleProps.forEach(prop => postProps.add(prop));
2412
- if (elm !== element) {
2413
- queriedElements.add(elm);
2414
- }
2415
- });
2416
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
2417
- checkNonAnimatableInTimelines(timelines, this._triggerName, driver);
2418
- }
2419
- const queriedElementsList = iteratorToArray(queriedElements.values());
2420
- return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, queriedElementsList, preStyleMap, postStyleMap, totalTime);
2421
- }
2422
- }
2423
- /**
2424
- * Checks inside a set of timelines if they try to animate a css property which is not considered
2425
- * animatable, in that case it prints a warning on the console.
2426
- * Besides that the function doesn't have any other effect.
2427
- *
2428
- * Note: this check is done here after the timelines are built instead of doing on a lower level so
2429
- * that we can make sure that the warning appears only once per instruction (we can aggregate here
2430
- * all the issues instead of finding them separately).
2431
- *
2432
- * @param timelines The built timelines for the current instruction.
2433
- * @param triggerName The name of the trigger for the current instruction.
2434
- * @param driver Animation driver used to perform the check.
2435
- *
2436
- */
2437
- function checkNonAnimatableInTimelines(timelines, triggerName, driver) {
2438
- if (!driver.validateAnimatableStyleProperty) {
2439
- return;
2440
- }
2441
- const allowedNonAnimatableProps = new Set([
2442
- // 'easing' is a utility/synthetic prop we use to represent
2443
- // easing functions, it represents a property of the animation
2444
- // which is not animatable but different values can be used
2445
- // in different steps
2446
- 'easing'
2447
- ]);
2448
- const invalidNonAnimatableProps = new Set();
2449
- timelines.forEach(({ keyframes }) => {
2450
- const nonAnimatablePropsInitialValues = new Map();
2451
- keyframes.forEach(keyframe => {
2452
- const entriesToCheck = Array.from(keyframe.entries()).filter(([prop]) => !allowedNonAnimatableProps.has(prop));
2453
- for (const [prop, value] of entriesToCheck) {
2454
- if (!driver.validateAnimatableStyleProperty(prop)) {
2455
- if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) {
2456
- const propInitialValue = nonAnimatablePropsInitialValues.get(prop);
2457
- if (propInitialValue !== value) {
2458
- invalidNonAnimatableProps.add(prop);
2459
- }
2460
- }
2461
- else {
2462
- nonAnimatablePropsInitialValues.set(prop, value);
2463
- }
2464
- }
2465
- }
2466
- });
2467
- });
2468
- if (invalidNonAnimatableProps.size > 0) {
2469
- console.warn(`Warning: The animation trigger "${triggerName}" is attempting to animate the following` +
2470
- ' not animatable properties: ' + Array.from(invalidNonAnimatableProps).join(', ') + '\n' +
2471
- '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)');
2472
- }
2473
- }
2474
- function oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {
2475
- return matchFns.some(fn => fn(currentState, nextState, element, params));
2476
- }
2477
- function applyParamDefaults(userParams, defaults) {
2478
- const result = copyObj(defaults);
2479
- for (const key in userParams) {
2480
- if (userParams.hasOwnProperty(key) && userParams[key] != null) {
2481
- result[key] = userParams[key];
2482
- }
2483
- }
2484
- return result;
2485
- }
2486
- class AnimationStateStyles {
2487
- constructor(styles, defaultParams, normalizer) {
2488
- this.styles = styles;
2489
- this.defaultParams = defaultParams;
2490
- this.normalizer = normalizer;
2491
- }
2492
- buildStyles(params, errors) {
2493
- const finalStyles = new Map();
2494
- const combinedParams = copyObj(this.defaultParams);
2495
- Object.keys(params).forEach(key => {
2496
- const value = params[key];
2497
- if (value !== null) {
2498
- combinedParams[key] = value;
2499
- }
2500
- });
2501
- this.styles.styles.forEach(value => {
2502
- if (typeof value !== 'string') {
2503
- value.forEach((val, prop) => {
2504
- if (val) {
2505
- val = interpolateParams(val, combinedParams, errors);
2506
- }
2507
- const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);
2508
- val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);
2509
- finalStyles.set(prop, val);
2510
- });
2511
- }
2512
- });
2513
- return finalStyles;
2514
- }
2515
- }
2516
-
2517
- function buildTrigger(name, ast, normalizer) {
2518
- return new AnimationTrigger(name, ast, normalizer);
2519
- }
2520
- class AnimationTrigger {
2521
- constructor(name, ast, _normalizer) {
2522
- this.name = name;
2523
- this.ast = ast;
2524
- this._normalizer = _normalizer;
2525
- this.transitionFactories = [];
2526
- this.states = new Map();
2527
- ast.states.forEach(ast => {
2528
- const defaultParams = (ast.options && ast.options.params) || {};
2529
- this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer));
2530
- });
2531
- balanceProperties(this.states, 'true', '1');
2532
- balanceProperties(this.states, 'false', '0');
2533
- ast.transitions.forEach(ast => {
2534
- this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));
2535
- });
2536
- this.fallbackTransition = createFallbackTransition(name, this.states, this._normalizer);
2537
- }
2538
- get containsQueries() {
2539
- return this.ast.queryCount > 0;
2540
- }
2541
- matchTransition(currentState, nextState, element, params) {
2542
- const entry = this.transitionFactories.find(f => f.match(currentState, nextState, element, params));
2543
- return entry || null;
2544
- }
2545
- matchStyles(currentState, params, errors) {
2546
- return this.fallbackTransition.buildStyles(currentState, params, errors);
2547
- }
2548
- }
2549
- function createFallbackTransition(triggerName, states, normalizer) {
2550
- const matchers = [(fromState, toState) => true];
2551
- const animation = { type: 2 /* AnimationMetadataType.Sequence */, steps: [], options: null };
2552
- const transition = {
2553
- type: 1 /* AnimationMetadataType.Transition */,
2554
- animation,
2555
- matchers,
2556
- options: null,
2557
- queryCount: 0,
2558
- depCount: 0
2559
- };
2560
- return new AnimationTransitionFactory(triggerName, transition, states);
2561
- }
2562
- function balanceProperties(stateMap, key1, key2) {
2563
- if (stateMap.has(key1)) {
2564
- if (!stateMap.has(key2)) {
2565
- stateMap.set(key2, stateMap.get(key1));
2566
- }
2567
- }
2568
- else if (stateMap.has(key2)) {
2569
- stateMap.set(key1, stateMap.get(key2));
2570
- }
2571
- }
2572
-
2573
- const EMPTY_INSTRUCTION_MAP = new ElementInstructionMap();
2574
- class TimelineAnimationEngine {
2575
- constructor(bodyNode, _driver, _normalizer) {
2576
- this.bodyNode = bodyNode;
2577
- this._driver = _driver;
2578
- this._normalizer = _normalizer;
2579
- this._animations = new Map();
2580
- this._playersById = new Map();
2581
- this.players = [];
2582
- }
2583
- register(id, metadata) {
2584
- const errors = [];
2585
- const warnings = [];
2586
- const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
2587
- if (errors.length) {
2588
- throw registerFailed(errors);
2589
- }
2590
- else {
2591
- if (warnings.length) {
2592
- warnRegister(warnings);
2593
- }
2594
- this._animations.set(id, ast);
2595
- }
2596
- }
2597
- _buildPlayer(i, preStyles, postStyles) {
2598
- const element = i.element;
2599
- const keyframes = normalizeKeyframes$1(this._driver, this._normalizer, element, i.keyframes, preStyles, postStyles);
2600
- return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);
2601
- }
2602
- create(id, element, options = {}) {
2603
- const errors = [];
2604
- const ast = this._animations.get(id);
2605
- let instructions;
2606
- const autoStylesMap = new Map();
2607
- if (ast) {
2608
- instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, new Map(), new Map(), options, EMPTY_INSTRUCTION_MAP, errors);
2609
- instructions.forEach(inst => {
2610
- const styles = getOrSetDefaultValue(autoStylesMap, inst.element, new Map());
2611
- inst.postStyleProps.forEach(prop => styles.set(prop, null));
2612
- });
2613
- }
2614
- else {
2615
- errors.push(missingOrDestroyedAnimation());
2616
- instructions = [];
2617
- }
2618
- if (errors.length) {
2619
- throw createAnimationFailed(errors);
2620
- }
2621
- autoStylesMap.forEach((styles, element) => {
2622
- styles.forEach((_, prop) => {
2623
- styles.set(prop, this._driver.computeStyle(element, prop, AUTO_STYLE));
2624
- });
2625
- });
2626
- const players = instructions.map(i => {
2627
- const styles = autoStylesMap.get(i.element);
2628
- return this._buildPlayer(i, new Map(), styles);
2629
- });
2630
- const player = optimizeGroupPlayer(players);
2631
- this._playersById.set(id, player);
2632
- player.onDestroy(() => this.destroy(id));
2633
- this.players.push(player);
2634
- return player;
2635
- }
2636
- destroy(id) {
2637
- const player = this._getPlayer(id);
2638
- player.destroy();
2639
- this._playersById.delete(id);
2640
- const index = this.players.indexOf(player);
2641
- if (index >= 0) {
2642
- this.players.splice(index, 1);
2643
- }
2644
- }
2645
- _getPlayer(id) {
2646
- const player = this._playersById.get(id);
2647
- if (!player) {
2648
- throw missingPlayer(id);
2649
- }
2650
- return player;
2651
- }
2652
- listen(id, element, eventName, callback) {
2653
- // triggerName, fromState, toState are all ignored for timeline animations
2654
- const baseEvent = makeAnimationEvent(element, '', '', '');
2655
- listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);
2656
- return () => { };
2657
- }
2658
- command(id, element, command, args) {
2659
- if (command == 'register') {
2660
- this.register(id, args[0]);
2661
- return;
2662
- }
2663
- if (command == 'create') {
2664
- const options = (args[0] || {});
2665
- this.create(id, element, options);
2666
- return;
2667
- }
2668
- const player = this._getPlayer(id);
2669
- switch (command) {
2670
- case 'play':
2671
- player.play();
2672
- break;
2673
- case 'pause':
2674
- player.pause();
2675
- break;
2676
- case 'reset':
2677
- player.reset();
2678
- break;
2679
- case 'restart':
2680
- player.restart();
2681
- break;
2682
- case 'finish':
2683
- player.finish();
2684
- break;
2685
- case 'init':
2686
- player.init();
2687
- break;
2688
- case 'setPosition':
2689
- player.setPosition(parseFloat(args[0]));
2690
- break;
2691
- case 'destroy':
2692
- this.destroy(id);
2693
- break;
2694
- }
2695
- }
2696
- }
2697
-
2698
- const QUEUED_CLASSNAME = 'ng-animate-queued';
2699
- const QUEUED_SELECTOR = '.ng-animate-queued';
2700
- const DISABLED_CLASSNAME = 'ng-animate-disabled';
2701
- const DISABLED_SELECTOR = '.ng-animate-disabled';
2702
- const STAR_CLASSNAME = 'ng-star-inserted';
2703
- const STAR_SELECTOR = '.ng-star-inserted';
2704
- const EMPTY_PLAYER_ARRAY = [];
2705
- const NULL_REMOVAL_STATE = {
2706
- namespaceId: '',
2707
- setForRemoval: false,
2708
- setForMove: false,
2709
- hasAnimation: false,
2710
- removedBeforeQueried: false
2711
- };
2712
- const NULL_REMOVED_QUERIED_STATE = {
2713
- namespaceId: '',
2714
- setForMove: false,
2715
- setForRemoval: false,
2716
- hasAnimation: false,
2717
- removedBeforeQueried: true
2718
- };
2719
- const REMOVAL_FLAG = '__ng_removed';
2720
- class StateValue {
2721
- get params() {
2722
- return this.options.params;
2723
- }
2724
- constructor(input, namespaceId = '') {
2725
- this.namespaceId = namespaceId;
2726
- const isObj = input && input.hasOwnProperty('value');
2727
- const value = isObj ? input['value'] : input;
2728
- this.value = normalizeTriggerValue(value);
2729
- if (isObj) {
2730
- const options = copyObj(input);
2731
- delete options['value'];
2732
- this.options = options;
2733
- }
2734
- else {
2735
- this.options = {};
2736
- }
2737
- if (!this.options.params) {
2738
- this.options.params = {};
2739
- }
2740
- }
2741
- absorbOptions(options) {
2742
- const newParams = options.params;
2743
- if (newParams) {
2744
- const oldParams = this.options.params;
2745
- Object.keys(newParams).forEach(prop => {
2746
- if (oldParams[prop] == null) {
2747
- oldParams[prop] = newParams[prop];
2748
- }
2749
- });
2750
- }
2751
- }
2752
- }
2753
- const VOID_VALUE = 'void';
2754
- const DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE);
2755
- class AnimationTransitionNamespace {
2756
- constructor(id, hostElement, _engine) {
2757
- this.id = id;
2758
- this.hostElement = hostElement;
2759
- this._engine = _engine;
2760
- this.players = [];
2761
- this._triggers = new Map();
2762
- this._queue = [];
2763
- this._elementListeners = new Map();
2764
- this._hostClassName = 'ng-tns-' + id;
2765
- addClass(hostElement, this._hostClassName);
2766
- }
2767
- listen(element, name, phase, callback) {
2768
- if (!this._triggers.has(name)) {
2769
- throw missingTrigger(phase, name);
2770
- }
2771
- if (phase == null || phase.length == 0) {
2772
- throw missingEvent(name);
2773
- }
2774
- if (!isTriggerEventValid(phase)) {
2775
- throw unsupportedTriggerEvent(phase, name);
2776
- }
2777
- const listeners = getOrSetDefaultValue(this._elementListeners, element, []);
2778
- const data = { name, phase, callback };
2779
- listeners.push(data);
2780
- const triggersWithStates = getOrSetDefaultValue(this._engine.statesByElement, element, new Map());
2781
- if (!triggersWithStates.has(name)) {
2782
- addClass(element, NG_TRIGGER_CLASSNAME);
2783
- addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
2784
- triggersWithStates.set(name, DEFAULT_STATE_VALUE);
2785
- }
2786
- return () => {
2787
- // the event listener is removed AFTER the flush has occurred such
2788
- // that leave animations callbacks can fire (otherwise if the node
2789
- // is removed in between then the listeners would be deregistered)
2790
- this._engine.afterFlush(() => {
2791
- const index = listeners.indexOf(data);
2792
- if (index >= 0) {
2793
- listeners.splice(index, 1);
2794
- }
2795
- if (!this._triggers.has(name)) {
2796
- triggersWithStates.delete(name);
2797
- }
2798
- });
2799
- };
2800
- }
2801
- register(name, ast) {
2802
- if (this._triggers.has(name)) {
2803
- // throw
2804
- return false;
2805
- }
2806
- else {
2807
- this._triggers.set(name, ast);
2808
- return true;
2809
- }
2810
- }
2811
- _getTrigger(name) {
2812
- const trigger = this._triggers.get(name);
2813
- if (!trigger) {
2814
- throw unregisteredTrigger(name);
2815
- }
2816
- return trigger;
2817
- }
2818
- trigger(element, triggerName, value, defaultToFallback = true) {
2819
- const trigger = this._getTrigger(triggerName);
2820
- const player = new TransitionAnimationPlayer(this.id, triggerName, element);
2821
- let triggersWithStates = this._engine.statesByElement.get(element);
2822
- if (!triggersWithStates) {
2823
- addClass(element, NG_TRIGGER_CLASSNAME);
2824
- addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
2825
- this._engine.statesByElement.set(element, triggersWithStates = new Map());
2826
- }
2827
- let fromState = triggersWithStates.get(triggerName);
2828
- const toState = new StateValue(value, this.id);
2829
- const isObj = value && value.hasOwnProperty('value');
2830
- if (!isObj && fromState) {
2831
- toState.absorbOptions(fromState.options);
2832
- }
2833
- triggersWithStates.set(triggerName, toState);
2834
- if (!fromState) {
2835
- fromState = DEFAULT_STATE_VALUE;
2836
- }
2837
- const isRemoval = toState.value === VOID_VALUE;
2838
- // normally this isn't reached by here, however, if an object expression
2839
- // is passed in then it may be a new object each time. Comparing the value
2840
- // is important since that will stay the same despite there being a new object.
2841
- // The removal arc here is special cased because the same element is triggered
2842
- // twice in the event that it contains animations on the outer/inner portions
2843
- // of the host container
2844
- if (!isRemoval && fromState.value === toState.value) {
2845
- // this means that despite the value not changing, some inner params
2846
- // have changed which means that the animation final styles need to be applied
2847
- if (!objEquals(fromState.params, toState.params)) {
2848
- const errors = [];
2849
- const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);
2850
- const toStyles = trigger.matchStyles(toState.value, toState.params, errors);
2851
- if (errors.length) {
2852
- this._engine.reportError(errors);
2853
- }
2854
- else {
2855
- this._engine.afterFlush(() => {
2856
- eraseStyles(element, fromStyles);
2857
- setStyles(element, toStyles);
2858
- });
2859
- }
2860
- }
2861
- return;
2862
- }
2863
- const playersOnElement = getOrSetDefaultValue(this._engine.playersByElement, element, []);
2864
- playersOnElement.forEach(player => {
2865
- // only remove the player if it is queued on the EXACT same trigger/namespace
2866
- // we only also deal with queued players here because if the animation has
2867
- // started then we want to keep the player alive until the flush happens
2868
- // (which is where the previousPlayers are passed into the new player)
2869
- if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
2870
- player.destroy();
2871
- }
2872
- });
2873
- let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);
2874
- let isFallbackTransition = false;
2875
- if (!transition) {
2876
- if (!defaultToFallback)
2877
- return;
2878
- transition = trigger.fallbackTransition;
2879
- isFallbackTransition = true;
2880
- }
2881
- this._engine.totalQueuedPlayers++;
2882
- this._queue.push({ element, triggerName, transition, fromState, toState, player, isFallbackTransition });
2883
- if (!isFallbackTransition) {
2884
- addClass(element, QUEUED_CLASSNAME);
2885
- player.onStart(() => {
2886
- removeClass(element, QUEUED_CLASSNAME);
2887
- });
2888
- }
2889
- player.onDone(() => {
2890
- let index = this.players.indexOf(player);
2891
- if (index >= 0) {
2892
- this.players.splice(index, 1);
2893
- }
2894
- const players = this._engine.playersByElement.get(element);
2895
- if (players) {
2896
- let index = players.indexOf(player);
2897
- if (index >= 0) {
2898
- players.splice(index, 1);
2899
- }
2900
- }
2901
- });
2902
- this.players.push(player);
2903
- playersOnElement.push(player);
2904
- return player;
2905
- }
2906
- deregister(name) {
2907
- this._triggers.delete(name);
2908
- this._engine.statesByElement.forEach(stateMap => stateMap.delete(name));
2909
- this._elementListeners.forEach((listeners, element) => {
2910
- this._elementListeners.set(element, listeners.filter(entry => {
2911
- return entry.name != name;
2912
- }));
2913
- });
2914
- }
2915
- clearElementCache(element) {
2916
- this._engine.statesByElement.delete(element);
2917
- this._elementListeners.delete(element);
2918
- const elementPlayers = this._engine.playersByElement.get(element);
2919
- if (elementPlayers) {
2920
- elementPlayers.forEach(player => player.destroy());
2921
- this._engine.playersByElement.delete(element);
2922
- }
2923
- }
2924
- _signalRemovalForInnerTriggers(rootElement, context) {
2925
- const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);
2926
- // emulate a leave animation for all inner nodes within this node.
2927
- // If there are no animations found for any of the nodes then clear the cache
2928
- // for the element.
2929
- elements.forEach(elm => {
2930
- // this means that an inner remove() operation has already kicked off
2931
- // the animation on this element...
2932
- if (elm[REMOVAL_FLAG])
2933
- return;
2934
- const namespaces = this._engine.fetchNamespacesByElement(elm);
2935
- if (namespaces.size) {
2936
- namespaces.forEach(ns => ns.triggerLeaveAnimation(elm, context, false, true));
2937
- }
2938
- else {
2939
- this.clearElementCache(elm);
2940
- }
2941
- });
2942
- // If the child elements were removed along with the parent, their animations might not
2943
- // have completed. Clear all the elements from the cache so we don't end up with a memory leak.
2944
- this._engine.afterFlushAnimationsDone(() => elements.forEach(elm => this.clearElementCache(elm)));
2945
- }
2946
- triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {
2947
- const triggerStates = this._engine.statesByElement.get(element);
2948
- const previousTriggersValues = new Map();
2949
- if (triggerStates) {
2950
- const players = [];
2951
- triggerStates.forEach((state, triggerName) => {
2952
- previousTriggersValues.set(triggerName, state.value);
2953
- // this check is here in the event that an element is removed
2954
- // twice (both on the host level and the component level)
2955
- if (this._triggers.has(triggerName)) {
2956
- const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);
2957
- if (player) {
2958
- players.push(player);
2959
- }
2960
- }
2961
- });
2962
- if (players.length) {
2963
- this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);
2964
- if (destroyAfterComplete) {
2965
- optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));
2966
- }
2967
- return true;
2968
- }
2969
- }
2970
- return false;
2971
- }
2972
- prepareLeaveAnimationListeners(element) {
2973
- const listeners = this._elementListeners.get(element);
2974
- const elementStates = this._engine.statesByElement.get(element);
2975
- // if this statement fails then it means that the element was picked up
2976
- // by an earlier flush (or there are no listeners at all to track the leave).
2977
- if (listeners && elementStates) {
2978
- const visitedTriggers = new Set();
2979
- listeners.forEach(listener => {
2980
- const triggerName = listener.name;
2981
- if (visitedTriggers.has(triggerName))
2982
- return;
2983
- visitedTriggers.add(triggerName);
2984
- const trigger = this._triggers.get(triggerName);
2985
- const transition = trigger.fallbackTransition;
2986
- const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;
2987
- const toState = new StateValue(VOID_VALUE);
2988
- const player = new TransitionAnimationPlayer(this.id, triggerName, element);
2989
- this._engine.totalQueuedPlayers++;
2990
- this._queue.push({
2991
- element,
2992
- triggerName,
2993
- transition,
2994
- fromState,
2995
- toState,
2996
- player,
2997
- isFallbackTransition: true
2998
- });
2999
- });
3000
- }
3001
- }
3002
- removeNode(element, context) {
3003
- const engine = this._engine;
3004
- if (element.childElementCount) {
3005
- this._signalRemovalForInnerTriggers(element, context);
3006
- }
3007
- // this means that a * => VOID animation was detected and kicked off
3008
- if (this.triggerLeaveAnimation(element, context, true))
3009
- return;
3010
- // find the player that is animating and make sure that the
3011
- // removal is delayed until that player has completed
3012
- let containsPotentialParentTransition = false;
3013
- if (engine.totalAnimations) {
3014
- const currentPlayers = engine.players.length ? engine.playersByQueriedElement.get(element) : [];
3015
- // when this `if statement` does not continue forward it means that
3016
- // a previous animation query has selected the current element and
3017
- // is animating it. In this situation want to continue forwards and
3018
- // allow the element to be queued up for animation later.
3019
- if (currentPlayers && currentPlayers.length) {
3020
- containsPotentialParentTransition = true;
3021
- }
3022
- else {
3023
- let parent = element;
3024
- while (parent = parent.parentNode) {
3025
- const triggers = engine.statesByElement.get(parent);
3026
- if (triggers) {
3027
- containsPotentialParentTransition = true;
3028
- break;
3029
- }
3030
- }
3031
- }
3032
- }
3033
- // at this stage we know that the element will either get removed
3034
- // during flush or will be picked up by a parent query. Either way
3035
- // we need to fire the listeners for this element when it DOES get
3036
- // removed (once the query parent animation is done or after flush)
3037
- this.prepareLeaveAnimationListeners(element);
3038
- // whether or not a parent has an animation we need to delay the deferral of the leave
3039
- // operation until we have more information (which we do after flush() has been called)
3040
- if (containsPotentialParentTransition) {
3041
- engine.markElementAsRemoved(this.id, element, false, context);
3042
- }
3043
- else {
3044
- const removalFlag = element[REMOVAL_FLAG];
3045
- if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {
3046
- // we do this after the flush has occurred such
3047
- // that the callbacks can be fired
3048
- engine.afterFlush(() => this.clearElementCache(element));
3049
- engine.destroyInnerAnimations(element);
3050
- engine._onRemovalComplete(element, context);
3051
- }
3052
- }
3053
- }
3054
- insertNode(element, parent) {
3055
- addClass(element, this._hostClassName);
3056
- }
3057
- drainQueuedTransitions(microtaskId) {
3058
- const instructions = [];
3059
- this._queue.forEach(entry => {
3060
- const player = entry.player;
3061
- if (player.destroyed)
3062
- return;
3063
- const element = entry.element;
3064
- const listeners = this._elementListeners.get(element);
3065
- if (listeners) {
3066
- listeners.forEach((listener) => {
3067
- if (listener.name == entry.triggerName) {
3068
- const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);
3069
- baseEvent['_data'] = microtaskId;
3070
- listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
3071
- }
3072
- });
3073
- }
3074
- if (player.markedForDestroy) {
3075
- this._engine.afterFlush(() => {
3076
- // now we can destroy the element properly since the event listeners have
3077
- // been bound to the player
3078
- player.destroy();
3079
- });
3080
- }
3081
- else {
3082
- instructions.push(entry);
3083
- }
3084
- });
3085
- this._queue = [];
3086
- return instructions.sort((a, b) => {
3087
- // if depCount == 0 them move to front
3088
- // otherwise if a contains b then move back
3089
- const d0 = a.transition.ast.depCount;
3090
- const d1 = b.transition.ast.depCount;
3091
- if (d0 == 0 || d1 == 0) {
3092
- return d0 - d1;
3093
- }
3094
- return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
3095
- });
3096
- }
3097
- destroy(context) {
3098
- this.players.forEach(p => p.destroy());
3099
- this._signalRemovalForInnerTriggers(this.hostElement, context);
3100
- }
3101
- elementContainsData(element) {
3102
- let containsData = false;
3103
- if (this._elementListeners.has(element))
3104
- containsData = true;
3105
- containsData =
3106
- (this._queue.find(entry => entry.element === element) ? true : false) || containsData;
3107
- return containsData;
3108
- }
3109
- }
3110
- class TransitionAnimationEngine {
3111
- /** @internal */
3112
- _onRemovalComplete(element, context) {
3113
- this.onRemovalComplete(element, context);
3114
- }
3115
- constructor(bodyNode, driver, _normalizer) {
3116
- this.bodyNode = bodyNode;
3117
- this.driver = driver;
3118
- this._normalizer = _normalizer;
3119
- this.players = [];
3120
- this.newHostElements = new Map();
3121
- this.playersByElement = new Map();
3122
- this.playersByQueriedElement = new Map();
3123
- this.statesByElement = new Map();
3124
- this.disabledNodes = new Set();
3125
- this.totalAnimations = 0;
3126
- this.totalQueuedPlayers = 0;
3127
- this._namespaceLookup = {};
3128
- this._namespaceList = [];
3129
- this._flushFns = [];
3130
- this._whenQuietFns = [];
3131
- this.namespacesByHostElement = new Map();
3132
- this.collectedEnterElements = [];
3133
- this.collectedLeaveElements = [];
3134
- // this method is designed to be overridden by the code that uses this engine
3135
- this.onRemovalComplete = (element, context) => { };
3136
- }
3137
- get queuedPlayers() {
3138
- const players = [];
3139
- this._namespaceList.forEach(ns => {
3140
- ns.players.forEach(player => {
3141
- if (player.queued) {
3142
- players.push(player);
3143
- }
3144
- });
3145
- });
3146
- return players;
3147
- }
3148
- createNamespace(namespaceId, hostElement) {
3149
- const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
3150
- if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {
3151
- this._balanceNamespaceList(ns, hostElement);
3152
- }
3153
- else {
3154
- // defer this later until flush during when the host element has
3155
- // been inserted so that we know exactly where to place it in
3156
- // the namespace list
3157
- this.newHostElements.set(hostElement, ns);
3158
- // given that this host element is a part of the animation code, it
3159
- // may or may not be inserted by a parent node that is of an
3160
- // animation renderer type. If this happens then we can still have
3161
- // access to this item when we query for :enter nodes. If the parent
3162
- // is a renderer then the set data-structure will normalize the entry
3163
- this.collectEnterElement(hostElement);
3164
- }
3165
- return this._namespaceLookup[namespaceId] = ns;
3166
- }
3167
- _balanceNamespaceList(ns, hostElement) {
3168
- const namespaceList = this._namespaceList;
3169
- const namespacesByHostElement = this.namespacesByHostElement;
3170
- const limit = namespaceList.length - 1;
3171
- if (limit >= 0) {
3172
- let found = false;
3173
- // Find the closest ancestor with an existing namespace so we can then insert `ns` after it,
3174
- // establishing a top-down ordering of namespaces in `this._namespaceList`.
3175
- let ancestor = this.driver.getParentElement(hostElement);
3176
- while (ancestor) {
3177
- const ancestorNs = namespacesByHostElement.get(ancestor);
3178
- if (ancestorNs) {
3179
- // An animation namespace has been registered for this ancestor, so we insert `ns`
3180
- // right after it to establish top-down ordering of animation namespaces.
3181
- const index = namespaceList.indexOf(ancestorNs);
3182
- namespaceList.splice(index + 1, 0, ns);
3183
- found = true;
3184
- break;
3185
- }
3186
- ancestor = this.driver.getParentElement(ancestor);
3187
- }
3188
- if (!found) {
3189
- // No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to
3190
- // ensure that any existing descendants are ordered after `ns`, retaining the desired
3191
- // top-down ordering.
3192
- namespaceList.unshift(ns);
3193
- }
3194
- }
3195
- else {
3196
- namespaceList.push(ns);
3197
- }
3198
- namespacesByHostElement.set(hostElement, ns);
3199
- return ns;
3200
- }
3201
- register(namespaceId, hostElement) {
3202
- let ns = this._namespaceLookup[namespaceId];
3203
- if (!ns) {
3204
- ns = this.createNamespace(namespaceId, hostElement);
3205
- }
3206
- return ns;
3207
- }
3208
- registerTrigger(namespaceId, name, trigger) {
3209
- let ns = this._namespaceLookup[namespaceId];
3210
- if (ns && ns.register(name, trigger)) {
3211
- this.totalAnimations++;
3212
- }
3213
- }
3214
- destroy(namespaceId, context) {
3215
- if (!namespaceId)
3216
- return;
3217
- const ns = this._fetchNamespace(namespaceId);
3218
- this.afterFlush(() => {
3219
- this.namespacesByHostElement.delete(ns.hostElement);
3220
- delete this._namespaceLookup[namespaceId];
3221
- const index = this._namespaceList.indexOf(ns);
3222
- if (index >= 0) {
3223
- this._namespaceList.splice(index, 1);
3224
- }
3225
- });
3226
- this.afterFlushAnimationsDone(() => ns.destroy(context));
3227
- }
3228
- _fetchNamespace(id) {
3229
- return this._namespaceLookup[id];
3230
- }
3231
- fetchNamespacesByElement(element) {
3232
- // normally there should only be one namespace per element, however
3233
- // if @triggers are placed on both the component element and then
3234
- // its host element (within the component code) then there will be
3235
- // two namespaces returned. We use a set here to simply deduplicate
3236
- // the namespaces in case (for the reason described above) there are multiple triggers
3237
- const namespaces = new Set();
3238
- const elementStates = this.statesByElement.get(element);
3239
- if (elementStates) {
3240
- for (let stateValue of elementStates.values()) {
3241
- if (stateValue.namespaceId) {
3242
- const ns = this._fetchNamespace(stateValue.namespaceId);
3243
- if (ns) {
3244
- namespaces.add(ns);
3245
- }
3246
- }
3247
- }
3248
- }
3249
- return namespaces;
3250
- }
3251
- trigger(namespaceId, element, name, value) {
3252
- if (isElementNode(element)) {
3253
- const ns = this._fetchNamespace(namespaceId);
3254
- if (ns) {
3255
- ns.trigger(element, name, value);
3256
- return true;
3257
- }
3258
- }
3259
- return false;
3260
- }
3261
- insertNode(namespaceId, element, parent, insertBefore) {
3262
- if (!isElementNode(element))
3263
- return;
3264
- // special case for when an element is removed and reinserted (move operation)
3265
- // when this occurs we do not want to use the element for deletion later
3266
- const details = element[REMOVAL_FLAG];
3267
- if (details && details.setForRemoval) {
3268
- details.setForRemoval = false;
3269
- details.setForMove = true;
3270
- const index = this.collectedLeaveElements.indexOf(element);
3271
- if (index >= 0) {
3272
- this.collectedLeaveElements.splice(index, 1);
3273
- }
3274
- }
3275
- // in the event that the namespaceId is blank then the caller
3276
- // code does not contain any animation code in it, but it is
3277
- // just being called so that the node is marked as being inserted
3278
- if (namespaceId) {
3279
- const ns = this._fetchNamespace(namespaceId);
3280
- // This if-statement is a workaround for router issue #21947.
3281
- // The router sometimes hits a race condition where while a route
3282
- // is being instantiated a new navigation arrives, triggering leave
3283
- // animation of DOM that has not been fully initialized, until this
3284
- // is resolved, we need to handle the scenario when DOM is not in a
3285
- // consistent state during the animation.
3286
- if (ns) {
3287
- ns.insertNode(element, parent);
3288
- }
3289
- }
3290
- // only *directives and host elements are inserted before
3291
- if (insertBefore) {
3292
- this.collectEnterElement(element);
3293
- }
3294
- }
3295
- collectEnterElement(element) {
3296
- this.collectedEnterElements.push(element);
3297
- }
3298
- markElementAsDisabled(element, value) {
3299
- if (value) {
3300
- if (!this.disabledNodes.has(element)) {
3301
- this.disabledNodes.add(element);
3302
- addClass(element, DISABLED_CLASSNAME);
3303
- }
3304
- }
3305
- else if (this.disabledNodes.has(element)) {
3306
- this.disabledNodes.delete(element);
3307
- removeClass(element, DISABLED_CLASSNAME);
3308
- }
3309
- }
3310
- removeNode(namespaceId, element, isHostElement, context) {
3311
- if (isElementNode(element)) {
3312
- const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
3313
- if (ns) {
3314
- ns.removeNode(element, context);
3315
- }
3316
- else {
3317
- this.markElementAsRemoved(namespaceId, element, false, context);
3318
- }
3319
- if (isHostElement) {
3320
- const hostNS = this.namespacesByHostElement.get(element);
3321
- if (hostNS && hostNS.id !== namespaceId) {
3322
- hostNS.removeNode(element, context);
3323
- }
3324
- }
3325
- }
3326
- else {
3327
- this._onRemovalComplete(element, context);
3328
- }
3329
- }
3330
- markElementAsRemoved(namespaceId, element, hasAnimation, context, previousTriggersValues) {
3331
- this.collectedLeaveElements.push(element);
3332
- element[REMOVAL_FLAG] = {
3333
- namespaceId,
3334
- setForRemoval: context,
3335
- hasAnimation,
3336
- removedBeforeQueried: false,
3337
- previousTriggersValues
3338
- };
3339
- }
3340
- listen(namespaceId, element, name, phase, callback) {
3341
- if (isElementNode(element)) {
3342
- return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
3343
- }
3344
- return () => { };
3345
- }
3346
- _buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {
3347
- return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);
3348
- }
3349
- destroyInnerAnimations(containerElement) {
3350
- let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
3351
- elements.forEach(element => this.destroyActiveAnimationsForElement(element));
3352
- if (this.playersByQueriedElement.size == 0)
3353
- return;
3354
- elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
3355
- elements.forEach(element => this.finishActiveQueriedAnimationOnElement(element));
3356
- }
3357
- destroyActiveAnimationsForElement(element) {
3358
- const players = this.playersByElement.get(element);
3359
- if (players) {
3360
- players.forEach(player => {
3361
- // special case for when an element is set for destruction, but hasn't started.
3362
- // in this situation we want to delay the destruction until the flush occurs
3363
- // so that any event listeners attached to the player are triggered.
3364
- if (player.queued) {
3365
- player.markedForDestroy = true;
3366
- }
3367
- else {
3368
- player.destroy();
3369
- }
3370
- });
3371
- }
3372
- }
3373
- finishActiveQueriedAnimationOnElement(element) {
3374
- const players = this.playersByQueriedElement.get(element);
3375
- if (players) {
3376
- players.forEach(player => player.finish());
3377
- }
3378
- }
3379
- whenRenderingDone() {
3380
- return new Promise(resolve => {
3381
- if (this.players.length) {
3382
- return optimizeGroupPlayer(this.players).onDone(() => resolve());
3383
- }
3384
- else {
3385
- resolve();
3386
- }
3387
- });
3388
- }
3389
- processLeaveNode(element) {
3390
- var _a;
3391
- const details = element[REMOVAL_FLAG];
3392
- if (details && details.setForRemoval) {
3393
- // this will prevent it from removing it twice
3394
- element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
3395
- if (details.namespaceId) {
3396
- this.destroyInnerAnimations(element);
3397
- const ns = this._fetchNamespace(details.namespaceId);
3398
- if (ns) {
3399
- ns.clearElementCache(element);
3400
- }
3401
- }
3402
- this._onRemovalComplete(element, details.setForRemoval);
3403
- }
3404
- if ((_a = element.classList) === null || _a === void 0 ? void 0 : _a.contains(DISABLED_CLASSNAME)) {
3405
- this.markElementAsDisabled(element, false);
3406
- }
3407
- this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {
3408
- this.markElementAsDisabled(node, false);
3409
- });
3410
- }
3411
- flush(microtaskId = -1) {
3412
- let players = [];
3413
- if (this.newHostElements.size) {
3414
- this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
3415
- this.newHostElements.clear();
3416
- }
3417
- if (this.totalAnimations && this.collectedEnterElements.length) {
3418
- for (let i = 0; i < this.collectedEnterElements.length; i++) {
3419
- const elm = this.collectedEnterElements[i];
3420
- addClass(elm, STAR_CLASSNAME);
3421
- }
3422
- }
3423
- if (this._namespaceList.length &&
3424
- (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {
3425
- const cleanupFns = [];
3426
- try {
3427
- players = this._flushAnimations(cleanupFns, microtaskId);
3428
- }
3429
- finally {
3430
- for (let i = 0; i < cleanupFns.length; i++) {
3431
- cleanupFns[i]();
3432
- }
3433
- }
3434
- }
3435
- else {
3436
- for (let i = 0; i < this.collectedLeaveElements.length; i++) {
3437
- const element = this.collectedLeaveElements[i];
3438
- this.processLeaveNode(element);
3439
- }
3440
- }
3441
- this.totalQueuedPlayers = 0;
3442
- this.collectedEnterElements.length = 0;
3443
- this.collectedLeaveElements.length = 0;
3444
- this._flushFns.forEach(fn => fn());
3445
- this._flushFns = [];
3446
- if (this._whenQuietFns.length) {
3447
- // we move these over to a variable so that
3448
- // if any new callbacks are registered in another
3449
- // flush they do not populate the existing set
3450
- const quietFns = this._whenQuietFns;
3451
- this._whenQuietFns = [];
3452
- if (players.length) {
3453
- optimizeGroupPlayer(players).onDone(() => {
3454
- quietFns.forEach(fn => fn());
3455
- });
3456
- }
3457
- else {
3458
- quietFns.forEach(fn => fn());
3459
- }
3460
- }
3461
- }
3462
- reportError(errors) {
3463
- throw triggerTransitionsFailed(errors);
3464
- }
3465
- _flushAnimations(cleanupFns, microtaskId) {
3466
- const subTimelines = new ElementInstructionMap();
3467
- const skippedPlayers = [];
3468
- const skippedPlayersMap = new Map();
3469
- const queuedInstructions = [];
3470
- const queriedElements = new Map();
3471
- const allPreStyleElements = new Map();
3472
- const allPostStyleElements = new Map();
3473
- const disabledElementsSet = new Set();
3474
- this.disabledNodes.forEach(node => {
3475
- disabledElementsSet.add(node);
3476
- const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
3477
- for (let i = 0; i < nodesThatAreDisabled.length; i++) {
3478
- disabledElementsSet.add(nodesThatAreDisabled[i]);
3479
- }
3480
- });
3481
- const bodyNode = this.bodyNode;
3482
- const allTriggerElements = Array.from(this.statesByElement.keys());
3483
- const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);
3484
- // this must occur before the instructions are built below such that
3485
- // the :enter queries match the elements (since the timeline queries
3486
- // are fired during instruction building).
3487
- const enterNodeMapIds = new Map();
3488
- let i = 0;
3489
- enterNodeMap.forEach((nodes, root) => {
3490
- const className = ENTER_CLASSNAME + i++;
3491
- enterNodeMapIds.set(root, className);
3492
- nodes.forEach(node => addClass(node, className));
3493
- });
3494
- const allLeaveNodes = [];
3495
- const mergedLeaveNodes = new Set();
3496
- const leaveNodesWithoutAnimations = new Set();
3497
- for (let i = 0; i < this.collectedLeaveElements.length; i++) {
3498
- const element = this.collectedLeaveElements[i];
3499
- const details = element[REMOVAL_FLAG];
3500
- if (details && details.setForRemoval) {
3501
- allLeaveNodes.push(element);
3502
- mergedLeaveNodes.add(element);
3503
- if (details.hasAnimation) {
3504
- this.driver.query(element, STAR_SELECTOR, true).forEach(elm => mergedLeaveNodes.add(elm));
3505
- }
3506
- else {
3507
- leaveNodesWithoutAnimations.add(element);
3508
- }
3509
- }
3510
- }
3511
- const leaveNodeMapIds = new Map();
3512
- const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));
3513
- leaveNodeMap.forEach((nodes, root) => {
3514
- const className = LEAVE_CLASSNAME + i++;
3515
- leaveNodeMapIds.set(root, className);
3516
- nodes.forEach(node => addClass(node, className));
3517
- });
3518
- cleanupFns.push(() => {
3519
- enterNodeMap.forEach((nodes, root) => {
3520
- const className = enterNodeMapIds.get(root);
3521
- nodes.forEach(node => removeClass(node, className));
3522
- });
3523
- leaveNodeMap.forEach((nodes, root) => {
3524
- const className = leaveNodeMapIds.get(root);
3525
- nodes.forEach(node => removeClass(node, className));
3526
- });
3527
- allLeaveNodes.forEach(element => {
3528
- this.processLeaveNode(element);
3529
- });
3530
- });
3531
- const allPlayers = [];
3532
- const erroneousTransitions = [];
3533
- for (let i = this._namespaceList.length - 1; i >= 0; i--) {
3534
- const ns = this._namespaceList[i];
3535
- ns.drainQueuedTransitions(microtaskId).forEach(entry => {
3536
- const player = entry.player;
3537
- const element = entry.element;
3538
- allPlayers.push(player);
3539
- if (this.collectedEnterElements.length) {
3540
- const details = element[REMOVAL_FLAG];
3541
- // animations for move operations (elements being removed and reinserted,
3542
- // e.g. when the order of an *ngFor list changes) are currently not supported
3543
- if (details && details.setForMove) {
3544
- if (details.previousTriggersValues &&
3545
- details.previousTriggersValues.has(entry.triggerName)) {
3546
- const previousValue = details.previousTriggersValues.get(entry.triggerName);
3547
- // we need to restore the previous trigger value since the element has
3548
- // only been moved and hasn't actually left the DOM
3549
- const triggersWithStates = this.statesByElement.get(entry.element);
3550
- if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {
3551
- const state = triggersWithStates.get(entry.triggerName);
3552
- state.value = previousValue;
3553
- triggersWithStates.set(entry.triggerName, state);
3554
- }
3555
- }
3556
- player.destroy();
3557
- return;
3558
- }
3559
- }
3560
- const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);
3561
- const leaveClassName = leaveNodeMapIds.get(element);
3562
- const enterClassName = enterNodeMapIds.get(element);
3563
- const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);
3564
- if (instruction.errors && instruction.errors.length) {
3565
- erroneousTransitions.push(instruction);
3566
- return;
3567
- }
3568
- // even though the element may not be in the DOM, it may still
3569
- // be added at a later point (due to the mechanics of content
3570
- // projection and/or dynamic component insertion) therefore it's
3571
- // important to still style the element.
3572
- if (nodeIsOrphaned) {
3573
- player.onStart(() => eraseStyles(element, instruction.fromStyles));
3574
- player.onDestroy(() => setStyles(element, instruction.toStyles));
3575
- skippedPlayers.push(player);
3576
- return;
3577
- }
3578
- // if an unmatched transition is queued and ready to go
3579
- // then it SHOULD NOT render an animation and cancel the
3580
- // previously running animations.
3581
- if (entry.isFallbackTransition) {
3582
- player.onStart(() => eraseStyles(element, instruction.fromStyles));
3583
- player.onDestroy(() => setStyles(element, instruction.toStyles));
3584
- skippedPlayers.push(player);
3585
- return;
3586
- }
3587
- // this means that if a parent animation uses this animation as a sub-trigger
3588
- // then it will instruct the timeline builder not to add a player delay, but
3589
- // instead stretch the first keyframe gap until the animation starts. This is
3590
- // important in order to prevent extra initialization styles from being
3591
- // required by the user for the animation.
3592
- const timelines = [];
3593
- instruction.timelines.forEach(tl => {
3594
- tl.stretchStartingKeyframe = true;
3595
- if (!this.disabledNodes.has(tl.element)) {
3596
- timelines.push(tl);
3597
- }
3598
- });
3599
- instruction.timelines = timelines;
3600
- subTimelines.append(element, instruction.timelines);
3601
- const tuple = { instruction, player, element };
3602
- queuedInstructions.push(tuple);
3603
- instruction.queriedElements.forEach(element => getOrSetDefaultValue(queriedElements, element, []).push(player));
3604
- instruction.preStyleProps.forEach((stringMap, element) => {
3605
- if (stringMap.size) {
3606
- let setVal = allPreStyleElements.get(element);
3607
- if (!setVal) {
3608
- allPreStyleElements.set(element, setVal = new Set());
3609
- }
3610
- stringMap.forEach((_, prop) => setVal.add(prop));
3611
- }
3612
- });
3613
- instruction.postStyleProps.forEach((stringMap, element) => {
3614
- let setVal = allPostStyleElements.get(element);
3615
- if (!setVal) {
3616
- allPostStyleElements.set(element, setVal = new Set());
3617
- }
3618
- stringMap.forEach((_, prop) => setVal.add(prop));
3619
- });
3620
- });
3621
- }
3622
- if (erroneousTransitions.length) {
3623
- const errors = [];
3624
- erroneousTransitions.forEach(instruction => {
3625
- errors.push(transitionFailed(instruction.triggerName, instruction.errors));
3626
- });
3627
- allPlayers.forEach(player => player.destroy());
3628
- this.reportError(errors);
3629
- }
3630
- const allPreviousPlayersMap = new Map();
3631
- // this map tells us which element in the DOM tree is contained by
3632
- // which animation. Further down this map will get populated once
3633
- // the players are built and in doing so we can use it to efficiently
3634
- // figure out if a sub player is skipped due to a parent player having priority.
3635
- const animationElementMap = new Map();
3636
- queuedInstructions.forEach(entry => {
3637
- const element = entry.element;
3638
- if (subTimelines.has(element)) {
3639
- animationElementMap.set(element, element);
3640
- this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);
3641
- }
3642
- });
3643
- skippedPlayers.forEach(player => {
3644
- const element = player.element;
3645
- const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);
3646
- previousPlayers.forEach(prevPlayer => {
3647
- getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);
3648
- prevPlayer.destroy();
3649
- });
3650
- });
3651
- // this is a special case for nodes that will be removed either by
3652
- // having their own leave animations or by being queried in a container
3653
- // that will be removed once a parent animation is complete. The idea
3654
- // here is that * styles must be identical to ! styles because of
3655
- // backwards compatibility (* is also filled in by default in many places).
3656
- // Otherwise * styles will return an empty value or "auto" since the element
3657
- // passed to getComputedStyle will not be visible (since * === destination)
3658
- const replaceNodes = allLeaveNodes.filter(node => {
3659
- return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);
3660
- });
3661
- // POST STAGE: fill the * styles
3662
- const postStylesMap = new Map();
3663
- const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);
3664
- allLeaveQueriedNodes.forEach(node => {
3665
- if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {
3666
- replaceNodes.push(node);
3667
- }
3668
- });
3669
- // PRE STAGE: fill the ! styles
3670
- const preStylesMap = new Map();
3671
- enterNodeMap.forEach((nodes, root) => {
3672
- cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, ɵPRE_STYLE);
3673
- });
3674
- replaceNodes.forEach(node => {
3675
- var _a, _b;
3676
- const post = postStylesMap.get(node);
3677
- const pre = preStylesMap.get(node);
3678
- postStylesMap.set(node, new Map([...Array.from((_a = post === null || post === void 0 ? void 0 : post.entries()) !== null && _a !== void 0 ? _a : []), ...Array.from((_b = pre === null || pre === void 0 ? void 0 : pre.entries()) !== null && _b !== void 0 ? _b : [])]));
3679
- });
3680
- const rootPlayers = [];
3681
- const subPlayers = [];
3682
- const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};
3683
- queuedInstructions.forEach(entry => {
3684
- const { element, player, instruction } = entry;
3685
- // this means that it was never consumed by a parent animation which
3686
- // means that it is independent and therefore should be set for animation
3687
- if (subTimelines.has(element)) {
3688
- if (disabledElementsSet.has(element)) {
3689
- player.onDestroy(() => setStyles(element, instruction.toStyles));
3690
- player.disabled = true;
3691
- player.overrideTotalTime(instruction.totalTime);
3692
- skippedPlayers.push(player);
3693
- return;
3694
- }
3695
- // this will flow up the DOM and query the map to figure out
3696
- // if a parent animation has priority over it. In the situation
3697
- // that a parent is detected then it will cancel the loop. If
3698
- // nothing is detected, or it takes a few hops to find a parent,
3699
- // then it will fill in the missing nodes and signal them as having
3700
- // a detected parent (or a NO_PARENT value via a special constant).
3701
- let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;
3702
- if (animationElementMap.size > 1) {
3703
- let elm = element;
3704
- const parentsToAdd = [];
3705
- while (elm = elm.parentNode) {
3706
- const detectedParent = animationElementMap.get(elm);
3707
- if (detectedParent) {
3708
- parentWithAnimation = detectedParent;
3709
- break;
3710
- }
3711
- parentsToAdd.push(elm);
3712
- }
3713
- parentsToAdd.forEach(parent => animationElementMap.set(parent, parentWithAnimation));
3714
- }
3715
- const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);
3716
- player.setRealPlayer(innerPlayer);
3717
- if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {
3718
- rootPlayers.push(player);
3719
- }
3720
- else {
3721
- const parentPlayers = this.playersByElement.get(parentWithAnimation);
3722
- if (parentPlayers && parentPlayers.length) {
3723
- player.parentPlayer = optimizeGroupPlayer(parentPlayers);
3724
- }
3725
- skippedPlayers.push(player);
3726
- }
3727
- }
3728
- else {
3729
- eraseStyles(element, instruction.fromStyles);
3730
- player.onDestroy(() => setStyles(element, instruction.toStyles));
3731
- // there still might be a ancestor player animating this
3732
- // element therefore we will still add it as a sub player
3733
- // even if its animation may be disabled
3734
- subPlayers.push(player);
3735
- if (disabledElementsSet.has(element)) {
3736
- skippedPlayers.push(player);
3737
- }
3738
- }
3739
- });
3740
- // find all of the sub players' corresponding inner animation players
3741
- subPlayers.forEach(player => {
3742
- // even if no players are found for a sub animation it
3743
- // will still complete itself after the next tick since it's Noop
3744
- const playersForElement = skippedPlayersMap.get(player.element);
3745
- if (playersForElement && playersForElement.length) {
3746
- const innerPlayer = optimizeGroupPlayer(playersForElement);
3747
- player.setRealPlayer(innerPlayer);
3748
- }
3749
- });
3750
- // the reason why we don't actually play the animation is
3751
- // because all that a skipped player is designed to do is to
3752
- // fire the start/done transition callback events
3753
- skippedPlayers.forEach(player => {
3754
- if (player.parentPlayer) {
3755
- player.syncPlayerEvents(player.parentPlayer);
3756
- }
3757
- else {
3758
- player.destroy();
3759
- }
3760
- });
3761
- // run through all of the queued removals and see if they
3762
- // were picked up by a query. If not then perform the removal
3763
- // operation right away unless a parent animation is ongoing.
3764
- for (let i = 0; i < allLeaveNodes.length; i++) {
3765
- const element = allLeaveNodes[i];
3766
- const details = element[REMOVAL_FLAG];
3767
- removeClass(element, LEAVE_CLASSNAME);
3768
- // this means the element has a removal animation that is being
3769
- // taken care of and therefore the inner elements will hang around
3770
- // until that animation is over (or the parent queried animation)
3771
- if (details && details.hasAnimation)
3772
- continue;
3773
- let players = [];
3774
- // if this element is queried or if it contains queried children
3775
- // then we want for the element not to be removed from the page
3776
- // until the queried animations have finished
3777
- if (queriedElements.size) {
3778
- let queriedPlayerResults = queriedElements.get(element);
3779
- if (queriedPlayerResults && queriedPlayerResults.length) {
3780
- players.push(...queriedPlayerResults);
3781
- }
3782
- let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);
3783
- for (let j = 0; j < queriedInnerElements.length; j++) {
3784
- let queriedPlayers = queriedElements.get(queriedInnerElements[j]);
3785
- if (queriedPlayers && queriedPlayers.length) {
3786
- players.push(...queriedPlayers);
3787
- }
3788
- }
3789
- }
3790
- const activePlayers = players.filter(p => !p.destroyed);
3791
- if (activePlayers.length) {
3792
- removeNodesAfterAnimationDone(this, element, activePlayers);
3793
- }
3794
- else {
3795
- this.processLeaveNode(element);
3796
- }
3797
- }
3798
- // this is required so the cleanup method doesn't remove them
3799
- allLeaveNodes.length = 0;
3800
- rootPlayers.forEach(player => {
3801
- this.players.push(player);
3802
- player.onDone(() => {
3803
- player.destroy();
3804
- const index = this.players.indexOf(player);
3805
- this.players.splice(index, 1);
3806
- });
3807
- player.play();
3808
- });
3809
- return rootPlayers;
3810
- }
3811
- elementContainsData(namespaceId, element) {
3812
- let containsData = false;
3813
- const details = element[REMOVAL_FLAG];
3814
- if (details && details.setForRemoval)
3815
- containsData = true;
3816
- if (this.playersByElement.has(element))
3817
- containsData = true;
3818
- if (this.playersByQueriedElement.has(element))
3819
- containsData = true;
3820
- if (this.statesByElement.has(element))
3821
- containsData = true;
3822
- return this._fetchNamespace(namespaceId).elementContainsData(element) || containsData;
3823
- }
3824
- afterFlush(callback) {
3825
- this._flushFns.push(callback);
3826
- }
3827
- afterFlushAnimationsDone(callback) {
3828
- this._whenQuietFns.push(callback);
3829
- }
3830
- _getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {
3831
- let players = [];
3832
- if (isQueriedElement) {
3833
- const queriedElementPlayers = this.playersByQueriedElement.get(element);
3834
- if (queriedElementPlayers) {
3835
- players = queriedElementPlayers;
3836
- }
3837
- }
3838
- else {
3839
- const elementPlayers = this.playersByElement.get(element);
3840
- if (elementPlayers) {
3841
- const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;
3842
- elementPlayers.forEach(player => {
3843
- if (player.queued)
3844
- return;
3845
- if (!isRemovalAnimation && player.triggerName != triggerName)
3846
- return;
3847
- players.push(player);
3848
- });
3849
- }
3850
- }
3851
- if (namespaceId || triggerName) {
3852
- players = players.filter(player => {
3853
- if (namespaceId && namespaceId != player.namespaceId)
3854
- return false;
3855
- if (triggerName && triggerName != player.triggerName)
3856
- return false;
3857
- return true;
3858
- });
3859
- }
3860
- return players;
3861
- }
3862
- _beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {
3863
- const triggerName = instruction.triggerName;
3864
- const rootElement = instruction.element;
3865
- // when a removal animation occurs, ALL previous players are collected
3866
- // and destroyed (even if they are outside of the current namespace)
3867
- const targetNameSpaceId = instruction.isRemovalTransition ? undefined : namespaceId;
3868
- const targetTriggerName = instruction.isRemovalTransition ? undefined : triggerName;
3869
- for (const timelineInstruction of instruction.timelines) {
3870
- const element = timelineInstruction.element;
3871
- const isQueriedElement = element !== rootElement;
3872
- const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []);
3873
- const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);
3874
- previousPlayers.forEach(player => {
3875
- const realPlayer = player.getRealPlayer();
3876
- if (realPlayer.beforeDestroy) {
3877
- realPlayer.beforeDestroy();
3878
- }
3879
- player.destroy();
3880
- players.push(player);
3881
- });
3882
- }
3883
- // this needs to be done so that the PRE/POST styles can be
3884
- // computed properly without interfering with the previous animation
3885
- eraseStyles(rootElement, instruction.fromStyles);
3886
- }
3887
- _buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {
3888
- const triggerName = instruction.triggerName;
3889
- const rootElement = instruction.element;
3890
- // we first run this so that the previous animation player
3891
- // data can be passed into the successive animation players
3892
- const allQueriedPlayers = [];
3893
- const allConsumedElements = new Set();
3894
- const allSubElements = new Set();
3895
- const allNewPlayers = instruction.timelines.map(timelineInstruction => {
3896
- const element = timelineInstruction.element;
3897
- allConsumedElements.add(element);
3898
- // FIXME (matsko): make sure to-be-removed animations are removed properly
3899
- const details = element[REMOVAL_FLAG];
3900
- if (details && details.removedBeforeQueried)
3901
- return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);
3902
- const isQueriedElement = element !== rootElement;
3903
- const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY)
3904
- .map(p => p.getRealPlayer()))
3905
- .filter(p => {
3906
- // the `element` is not apart of the AnimationPlayer definition, but
3907
- // Mock/WebAnimations
3908
- // use the element within their implementation. This will be added in Angular5 to
3909
- // AnimationPlayer
3910
- const pp = p;
3911
- return pp.element ? pp.element === element : false;
3912
- });
3913
- const preStyles = preStylesMap.get(element);
3914
- const postStyles = postStylesMap.get(element);
3915
- const keyframes = normalizeKeyframes$1(this.driver, this._normalizer, element, timelineInstruction.keyframes, preStyles, postStyles);
3916
- const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);
3917
- // this means that this particular player belongs to a sub trigger. It is
3918
- // important that we match this player up with the corresponding (@trigger.listener)
3919
- if (timelineInstruction.subTimeline && skippedPlayersMap) {
3920
- allSubElements.add(element);
3921
- }
3922
- if (isQueriedElement) {
3923
- const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);
3924
- wrappedPlayer.setRealPlayer(player);
3925
- allQueriedPlayers.push(wrappedPlayer);
3926
- }
3927
- return player;
3928
- });
3929
- allQueriedPlayers.forEach(player => {
3930
- getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player);
3931
- player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));
3932
- });
3933
- allConsumedElements.forEach(element => addClass(element, NG_ANIMATING_CLASSNAME));
3934
- const player = optimizeGroupPlayer(allNewPlayers);
3935
- player.onDestroy(() => {
3936
- allConsumedElements.forEach(element => removeClass(element, NG_ANIMATING_CLASSNAME));
3937
- setStyles(rootElement, instruction.toStyles);
3938
- });
3939
- // this basically makes all of the callbacks for sub element animations
3940
- // be dependent on the upper players for when they finish
3941
- allSubElements.forEach(element => {
3942
- getOrSetDefaultValue(skippedPlayersMap, element, []).push(player);
3943
- });
3944
- return player;
3945
- }
3946
- _buildPlayer(instruction, keyframes, previousPlayers) {
3947
- if (keyframes.length > 0) {
3948
- return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);
3949
- }
3950
- // special case for when an empty transition|definition is provided
3951
- // ... there is no point in rendering an empty animation
3952
- return new NoopAnimationPlayer(instruction.duration, instruction.delay);
3953
- }
3954
- }
3955
- class TransitionAnimationPlayer {
3956
- constructor(namespaceId, triggerName, element) {
3957
- this.namespaceId = namespaceId;
3958
- this.triggerName = triggerName;
3959
- this.element = element;
3960
- this._player = new NoopAnimationPlayer();
3961
- this._containsRealPlayer = false;
3962
- this._queuedCallbacks = new Map();
3963
- this.destroyed = false;
3964
- this.parentPlayer = null;
3965
- this.markedForDestroy = false;
3966
- this.disabled = false;
3967
- this.queued = true;
3968
- this.totalTime = 0;
3969
- }
3970
- setRealPlayer(player) {
3971
- if (this._containsRealPlayer)
3972
- return;
3973
- this._player = player;
3974
- this._queuedCallbacks.forEach((callbacks, phase) => {
3975
- callbacks.forEach(callback => listenOnPlayer(player, phase, undefined, callback));
3976
- });
3977
- this._queuedCallbacks.clear();
3978
- this._containsRealPlayer = true;
3979
- this.overrideTotalTime(player.totalTime);
3980
- this.queued = false;
3981
- }
3982
- getRealPlayer() {
3983
- return this._player;
3984
- }
3985
- overrideTotalTime(totalTime) {
3986
- this.totalTime = totalTime;
3987
- }
3988
- syncPlayerEvents(player) {
3989
- const p = this._player;
3990
- if (p.triggerCallback) {
3991
- player.onStart(() => p.triggerCallback('start'));
3992
- }
3993
- player.onDone(() => this.finish());
3994
- player.onDestroy(() => this.destroy());
3995
- }
3996
- _queueEvent(name, callback) {
3997
- getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback);
3998
- }
3999
- onDone(fn) {
4000
- if (this.queued) {
4001
- this._queueEvent('done', fn);
4002
- }
4003
- this._player.onDone(fn);
4004
- }
4005
- onStart(fn) {
4006
- if (this.queued) {
4007
- this._queueEvent('start', fn);
4008
- }
4009
- this._player.onStart(fn);
4010
- }
4011
- onDestroy(fn) {
4012
- if (this.queued) {
4013
- this._queueEvent('destroy', fn);
4014
- }
4015
- this._player.onDestroy(fn);
4016
- }
4017
- init() {
4018
- this._player.init();
4019
- }
4020
- hasStarted() {
4021
- return this.queued ? false : this._player.hasStarted();
4022
- }
4023
- play() {
4024
- !this.queued && this._player.play();
4025
- }
4026
- pause() {
4027
- !this.queued && this._player.pause();
4028
- }
4029
- restart() {
4030
- !this.queued && this._player.restart();
4031
- }
4032
- finish() {
4033
- this._player.finish();
4034
- }
4035
- destroy() {
4036
- this.destroyed = true;
4037
- this._player.destroy();
4038
- }
4039
- reset() {
4040
- !this.queued && this._player.reset();
4041
- }
4042
- setPosition(p) {
4043
- if (!this.queued) {
4044
- this._player.setPosition(p);
4045
- }
4046
- }
4047
- getPosition() {
4048
- return this.queued ? 0 : this._player.getPosition();
4049
- }
4050
- /** @internal */
4051
- triggerCallback(phaseName) {
4052
- const p = this._player;
4053
- if (p.triggerCallback) {
4054
- p.triggerCallback(phaseName);
4055
- }
4056
- }
4057
- }
4058
- function deleteOrUnsetInMap(map, key, value) {
4059
- let currentValues = map.get(key);
4060
- if (currentValues) {
4061
- if (currentValues.length) {
4062
- const index = currentValues.indexOf(value);
4063
- currentValues.splice(index, 1);
4064
- }
4065
- if (currentValues.length == 0) {
4066
- map.delete(key);
4067
- }
4068
- }
4069
- return currentValues;
4070
- }
4071
- function normalizeTriggerValue(value) {
4072
- // we use `!= null` here because it's the most simple
4073
- // way to test against a "falsy" value without mixing
4074
- // in empty strings or a zero value. DO NOT OPTIMIZE.
4075
- return value != null ? value : null;
4076
- }
4077
- function isElementNode(node) {
4078
- return node && node['nodeType'] === 1;
4079
- }
4080
- function isTriggerEventValid(eventName) {
4081
- return eventName == 'start' || eventName == 'done';
4082
- }
4083
- function cloakElement(element, value) {
4084
- const oldValue = element.style.display;
4085
- element.style.display = value != null ? value : 'none';
4086
- return oldValue;
4087
- }
4088
- function cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {
4089
- const cloakVals = [];
4090
- elements.forEach(element => cloakVals.push(cloakElement(element)));
4091
- const failedElements = [];
4092
- elementPropsMap.forEach((props, element) => {
4093
- const styles = new Map();
4094
- props.forEach(prop => {
4095
- const value = driver.computeStyle(element, prop, defaultStyle);
4096
- styles.set(prop, value);
4097
- // there is no easy way to detect this because a sub element could be removed
4098
- // by a parent animation element being detached.
4099
- if (!value || value.length == 0) {
4100
- element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;
4101
- failedElements.push(element);
4102
- }
4103
- });
4104
- valuesMap.set(element, styles);
4105
- });
4106
- // we use a index variable here since Set.forEach(a, i) does not return
4107
- // an index value for the closure (but instead just the value)
4108
- let i = 0;
4109
- elements.forEach(element => cloakElement(element, cloakVals[i++]));
4110
- return failedElements;
4111
- }
4112
- /*
4113
- Since the Angular renderer code will return a collection of inserted
4114
- nodes in all areas of a DOM tree, it's up to this algorithm to figure
4115
- out which nodes are roots for each animation @trigger.
4116
-
4117
- By placing each inserted node into a Set and traversing upwards, it
4118
- is possible to find the @trigger elements and well any direct *star
4119
- insertion nodes, if a @trigger root is found then the enter element
4120
- is placed into the Map[@trigger] spot.
4121
- */
4122
- function buildRootMap(roots, nodes) {
4123
- const rootMap = new Map();
4124
- roots.forEach(root => rootMap.set(root, []));
4125
- if (nodes.length == 0)
4126
- return rootMap;
4127
- const NULL_NODE = 1;
4128
- const nodeSet = new Set(nodes);
4129
- const localRootMap = new Map();
4130
- function getRoot(node) {
4131
- if (!node)
4132
- return NULL_NODE;
4133
- let root = localRootMap.get(node);
4134
- if (root)
4135
- return root;
4136
- const parent = node.parentNode;
4137
- if (rootMap.has(parent)) { // ngIf inside @trigger
4138
- root = parent;
4139
- }
4140
- else if (nodeSet.has(parent)) { // ngIf inside ngIf
4141
- root = NULL_NODE;
4142
- }
4143
- else { // recurse upwards
4144
- root = getRoot(parent);
4145
- }
4146
- localRootMap.set(node, root);
4147
- return root;
4148
- }
4149
- nodes.forEach(node => {
4150
- const root = getRoot(node);
4151
- if (root !== NULL_NODE) {
4152
- rootMap.get(root).push(node);
4153
- }
4154
- });
4155
- return rootMap;
4156
- }
4157
- function addClass(element, className) {
4158
- var _a;
4159
- (_a = element.classList) === null || _a === void 0 ? void 0 : _a.add(className);
4160
- }
4161
- function removeClass(element, className) {
4162
- var _a;
4163
- (_a = element.classList) === null || _a === void 0 ? void 0 : _a.remove(className);
4164
- }
4165
- function removeNodesAfterAnimationDone(engine, element, players) {
4166
- optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));
4167
- }
4168
- function flattenGroupPlayers(players) {
4169
- const finalPlayers = [];
4170
- _flattenGroupPlayersRecur(players, finalPlayers);
4171
- return finalPlayers;
4172
- }
4173
- function _flattenGroupPlayersRecur(players, finalPlayers) {
4174
- for (let i = 0; i < players.length; i++) {
4175
- const player = players[i];
4176
- if (player instanceof ɵAnimationGroupPlayer) {
4177
- _flattenGroupPlayersRecur(player.players, finalPlayers);
4178
- }
4179
- else {
4180
- finalPlayers.push(player);
4181
- }
4182
- }
4183
- }
4184
- function objEquals(a, b) {
4185
- const k1 = Object.keys(a);
4186
- const k2 = Object.keys(b);
4187
- if (k1.length != k2.length)
4188
- return false;
4189
- for (let i = 0; i < k1.length; i++) {
4190
- const prop = k1[i];
4191
- if (!b.hasOwnProperty(prop) || a[prop] !== b[prop])
4192
- return false;
4193
- }
4194
- return true;
4195
- }
4196
- function replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {
4197
- const postEntry = allPostStyleElements.get(element);
4198
- if (!postEntry)
4199
- return false;
4200
- let preEntry = allPreStyleElements.get(element);
4201
- if (preEntry) {
4202
- postEntry.forEach(data => preEntry.add(data));
4203
- }
4204
- else {
4205
- allPreStyleElements.set(element, postEntry);
4206
- }
4207
- allPostStyleElements.delete(element);
4208
- return true;
4209
- }
4210
-
4211
- class AnimationEngine {
4212
- constructor(bodyNode, _driver, _normalizer) {
4213
- this.bodyNode = bodyNode;
4214
- this._driver = _driver;
4215
- this._normalizer = _normalizer;
4216
- this._triggerCache = {};
4217
- // this method is designed to be overridden by the code that uses this engine
4218
- this.onRemovalComplete = (element, context) => { };
4219
- this._transitionEngine = new TransitionAnimationEngine(bodyNode, _driver, _normalizer);
4220
- this._timelineEngine = new TimelineAnimationEngine(bodyNode, _driver, _normalizer);
4221
- this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);
4222
- }
4223
- registerTrigger(componentId, namespaceId, hostElement, name, metadata) {
4224
- const cacheKey = componentId + '-' + name;
4225
- let trigger = this._triggerCache[cacheKey];
4226
- if (!trigger) {
4227
- const errors = [];
4228
- const warnings = [];
4229
- const ast = buildAnimationAst(this._driver, metadata, errors, warnings);
4230
- if (errors.length) {
4231
- throw triggerBuildFailed(name, errors);
4232
- }
4233
- if (warnings.length) {
4234
- warnTriggerBuild(name, warnings);
4235
- }
4236
- trigger = buildTrigger(name, ast, this._normalizer);
4237
- this._triggerCache[cacheKey] = trigger;
4238
- }
4239
- this._transitionEngine.registerTrigger(namespaceId, name, trigger);
4240
- }
4241
- register(namespaceId, hostElement) {
4242
- this._transitionEngine.register(namespaceId, hostElement);
4243
- }
4244
- destroy(namespaceId, context) {
4245
- this._transitionEngine.destroy(namespaceId, context);
4246
- }
4247
- onInsert(namespaceId, element, parent, insertBefore) {
4248
- this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);
4249
- }
4250
- onRemove(namespaceId, element, context, isHostElement) {
4251
- this._transitionEngine.removeNode(namespaceId, element, isHostElement || false, context);
4252
- }
4253
- disableAnimations(element, disable) {
4254
- this._transitionEngine.markElementAsDisabled(element, disable);
4255
- }
4256
- process(namespaceId, element, property, value) {
4257
- if (property.charAt(0) == '@') {
4258
- const [id, action] = parseTimelineCommand(property);
4259
- const args = value;
4260
- this._timelineEngine.command(id, element, action, args);
4261
- }
4262
- else {
4263
- this._transitionEngine.trigger(namespaceId, element, property, value);
4264
- }
4265
- }
4266
- listen(namespaceId, element, eventName, eventPhase, callback) {
4267
- // @@listen
4268
- if (eventName.charAt(0) == '@') {
4269
- const [id, action] = parseTimelineCommand(eventName);
4270
- return this._timelineEngine.listen(id, element, action, callback);
4271
- }
4272
- return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);
4273
- }
4274
- flush(microtaskId = -1) {
4275
- this._transitionEngine.flush(microtaskId);
4276
- }
4277
- get players() {
4278
- return this._transitionEngine.players
4279
- .concat(this._timelineEngine.players);
4280
- }
4281
- whenRenderingDone() {
4282
- return this._transitionEngine.whenRenderingDone();
4283
- }
4284
- }
4285
-
4286
- /**
4287
- * Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are
4288
- * detected.
4289
- *
4290
- * In CSS there exist properties that cannot be animated within a keyframe animation
4291
- * (whether it be via CSS keyframes or web-animations) and the animation implementation
4292
- * will ignore them. This function is designed to detect those special cased styles and
4293
- * return a container that will be executed at the start and end of the animation.
4294
- *
4295
- * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`
4296
- */
4297
- function packageNonAnimatableStyles(element, styles) {
4298
- let startStyles = null;
4299
- let endStyles = null;
4300
- if (Array.isArray(styles) && styles.length) {
4301
- startStyles = filterNonAnimatableStyles(styles[0]);
4302
- if (styles.length > 1) {
4303
- endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);
4304
- }
4305
- }
4306
- else if (styles instanceof Map) {
4307
- startStyles = filterNonAnimatableStyles(styles);
4308
- }
4309
- return (startStyles || endStyles) ? new SpecialCasedStyles(element, startStyles, endStyles) :
4310
- null;
4311
- }
4312
- /**
4313
- * Designed to be executed during a keyframe-based animation to apply any special-cased styles.
4314
- *
4315
- * When started (when the `start()` method is run) then the provided `startStyles`
4316
- * will be applied. When finished (when the `finish()` method is called) the
4317
- * `endStyles` will be applied as well any any starting styles. Finally when
4318
- * `destroy()` is called then all styles will be removed.
4319
- */
4320
- class SpecialCasedStyles {
4321
- constructor(_element, _startStyles, _endStyles) {
4322
- this._element = _element;
4323
- this._startStyles = _startStyles;
4324
- this._endStyles = _endStyles;
4325
- this._state = 0 /* SpecialCasedStylesState.Pending */;
4326
- let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);
4327
- if (!initialStyles) {
4328
- SpecialCasedStyles.initialStylesByElement.set(_element, initialStyles = new Map());
4329
- }
4330
- this._initialStyles = initialStyles;
4331
- }
4332
- start() {
4333
- if (this._state < 1 /* SpecialCasedStylesState.Started */) {
4334
- if (this._startStyles) {
4335
- setStyles(this._element, this._startStyles, this._initialStyles);
4336
- }
4337
- this._state = 1 /* SpecialCasedStylesState.Started */;
4338
- }
4339
- }
4340
- finish() {
4341
- this.start();
4342
- if (this._state < 2 /* SpecialCasedStylesState.Finished */) {
4343
- setStyles(this._element, this._initialStyles);
4344
- if (this._endStyles) {
4345
- setStyles(this._element, this._endStyles);
4346
- this._endStyles = null;
4347
- }
4348
- this._state = 1 /* SpecialCasedStylesState.Started */;
4349
- }
4350
- }
4351
- destroy() {
4352
- this.finish();
4353
- if (this._state < 3 /* SpecialCasedStylesState.Destroyed */) {
4354
- SpecialCasedStyles.initialStylesByElement.delete(this._element);
4355
- if (this._startStyles) {
4356
- eraseStyles(this._element, this._startStyles);
4357
- this._endStyles = null;
4358
- }
4359
- if (this._endStyles) {
4360
- eraseStyles(this._element, this._endStyles);
4361
- this._endStyles = null;
4362
- }
4363
- setStyles(this._element, this._initialStyles);
4364
- this._state = 3 /* SpecialCasedStylesState.Destroyed */;
4365
- }
4366
- }
4367
- }
4368
- SpecialCasedStyles.initialStylesByElement = ( /* @__PURE__ */new WeakMap());
4369
- function filterNonAnimatableStyles(styles) {
4370
- let result = null;
4371
- styles.forEach((val, prop) => {
4372
- if (isNonAnimatableStyle(prop)) {
4373
- result = result || new Map();
4374
- result.set(prop, val);
4375
- }
4376
- });
4377
- return result;
4378
- }
4379
- function isNonAnimatableStyle(prop) {
4380
- return prop === 'display' || prop === 'position';
4381
- }
4382
-
4383
- class WebAnimationsPlayer {
4384
- constructor(element, keyframes, options, _specialStyles) {
4385
- this.element = element;
4386
- this.keyframes = keyframes;
4387
- this.options = options;
4388
- this._specialStyles = _specialStyles;
4389
- this._onDoneFns = [];
4390
- this._onStartFns = [];
4391
- this._onDestroyFns = [];
4392
- this._initialized = false;
4393
- this._finished = false;
4394
- this._started = false;
4395
- this._destroyed = false;
4396
- // the following original fns are persistent copies of the _onStartFns and _onDoneFns
4397
- // and are used to reset the fns to their original values upon reset()
4398
- // (since the _onStartFns and _onDoneFns get deleted after they are called)
4399
- this._originalOnDoneFns = [];
4400
- this._originalOnStartFns = [];
4401
- this.time = 0;
4402
- this.parentPlayer = null;
4403
- this.currentSnapshot = new Map();
4404
- this._duration = options['duration'];
4405
- this._delay = options['delay'] || 0;
4406
- this.time = this._duration + this._delay;
4407
- }
4408
- _onFinish() {
4409
- if (!this._finished) {
4410
- this._finished = true;
4411
- this._onDoneFns.forEach(fn => fn());
4412
- this._onDoneFns = [];
4413
- }
4414
- }
4415
- init() {
4416
- this._buildPlayer();
4417
- this._preparePlayerBeforeStart();
4418
- }
4419
- _buildPlayer() {
4420
- if (this._initialized)
4421
- return;
4422
- this._initialized = true;
4423
- const keyframes = this.keyframes;
4424
- // @ts-expect-error overwriting a readonly property
4425
- this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options);
4426
- this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map();
4427
- this.domPlayer.addEventListener('finish', () => this._onFinish());
4428
- }
4429
- _preparePlayerBeforeStart() {
4430
- // this is required so that the player doesn't start to animate right away
4431
- if (this._delay) {
4432
- this._resetDomPlayerState();
4433
- }
4434
- else {
4435
- this.domPlayer.pause();
4436
- }
4437
- }
4438
- _convertKeyframesToObject(keyframes) {
4439
- const kfs = [];
4440
- keyframes.forEach(frame => {
4441
- kfs.push(Object.fromEntries(frame));
4442
- });
4443
- return kfs;
4444
- }
4445
- /** @internal */
4446
- _triggerWebAnimation(element, keyframes, options) {
4447
- // jscompiler doesn't seem to know animate is a native property because it's not fully
4448
- // supported yet across common browsers (we polyfill it for Edge/Safari) [CL #143630929]
4449
- return element['animate'](this._convertKeyframesToObject(keyframes), options);
4450
- }
4451
- onStart(fn) {
4452
- this._originalOnStartFns.push(fn);
4453
- this._onStartFns.push(fn);
4454
- }
4455
- onDone(fn) {
4456
- this._originalOnDoneFns.push(fn);
4457
- this._onDoneFns.push(fn);
4458
- }
4459
- onDestroy(fn) {
4460
- this._onDestroyFns.push(fn);
4461
- }
4462
- play() {
4463
- this._buildPlayer();
4464
- if (!this.hasStarted()) {
4465
- this._onStartFns.forEach(fn => fn());
4466
- this._onStartFns = [];
4467
- this._started = true;
4468
- if (this._specialStyles) {
4469
- this._specialStyles.start();
4470
- }
4471
- }
4472
- this.domPlayer.play();
4473
- }
4474
- pause() {
4475
- this.init();
4476
- this.domPlayer.pause();
4477
- }
4478
- finish() {
4479
- this.init();
4480
- if (this._specialStyles) {
4481
- this._specialStyles.finish();
4482
- }
4483
- this._onFinish();
4484
- this.domPlayer.finish();
4485
- }
4486
- reset() {
4487
- this._resetDomPlayerState();
4488
- this._destroyed = false;
4489
- this._finished = false;
4490
- this._started = false;
4491
- this._onStartFns = this._originalOnStartFns;
4492
- this._onDoneFns = this._originalOnDoneFns;
4493
- }
4494
- _resetDomPlayerState() {
4495
- if (this.domPlayer) {
4496
- this.domPlayer.cancel();
4497
- }
4498
- }
4499
- restart() {
4500
- this.reset();
4501
- this.play();
4502
- }
4503
- hasStarted() {
4504
- return this._started;
4505
- }
4506
- destroy() {
4507
- if (!this._destroyed) {
4508
- this._destroyed = true;
4509
- this._resetDomPlayerState();
4510
- this._onFinish();
4511
- if (this._specialStyles) {
4512
- this._specialStyles.destroy();
4513
- }
4514
- this._onDestroyFns.forEach(fn => fn());
4515
- this._onDestroyFns = [];
4516
- }
4517
- }
4518
- setPosition(p) {
4519
- if (this.domPlayer === undefined) {
4520
- this.init();
4521
- }
4522
- this.domPlayer.currentTime = p * this.time;
4523
- }
4524
- getPosition() {
4525
- return this.domPlayer.currentTime / this.time;
4526
- }
4527
- get totalTime() {
4528
- return this._delay + this._duration;
4529
- }
4530
- beforeDestroy() {
4531
- const styles = new Map();
4532
- if (this.hasStarted()) {
4533
- // note: this code is invoked only when the `play` function was called prior to this
4534
- // (thus `hasStarted` returns true), this implies that the code that initializes
4535
- // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here
4536
- const finalKeyframe = this._finalKeyframe;
4537
- finalKeyframe.forEach((val, prop) => {
4538
- if (prop !== 'offset') {
4539
- styles.set(prop, this._finished ? val : computeStyle(this.element, prop));
4540
- }
4541
- });
4542
- }
4543
- this.currentSnapshot = styles;
4544
- }
4545
- /** @internal */
4546
- triggerCallback(phaseName) {
4547
- const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns;
4548
- methods.forEach(fn => fn());
4549
- methods.length = 0;
4550
- }
4551
- }
4552
-
4553
- class WebAnimationsDriver {
4554
- validateStyleProperty(prop) {
4555
- // Perform actual validation in dev mode only, in prod mode this check is a noop.
4556
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
4557
- return validateStyleProperty(prop);
4558
- }
4559
- return true;
4560
- }
4561
- validateAnimatableStyleProperty(prop) {
4562
- // Perform actual validation in dev mode only, in prod mode this check is a noop.
4563
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
4564
- const cssProp = camelCaseToDashCase(prop);
4565
- return validateWebAnimatableStyleProperty(cssProp);
4566
- }
4567
- return true;
4568
- }
4569
- matchesElement(_element, _selector) {
4570
- // This method is deprecated and no longer in use so we return false.
4571
- return false;
4572
- }
4573
- containsElement(elm1, elm2) {
4574
- return containsElement(elm1, elm2);
4575
- }
4576
- getParentElement(element) {
4577
- return getParentElement(element);
4578
- }
4579
- query(element, selector, multi) {
4580
- return invokeQuery(element, selector, multi);
4581
- }
4582
- computeStyle(element, prop, defaultValue) {
4583
- return window.getComputedStyle(element)[prop];
4584
- }
4585
- animate(element, keyframes, duration, delay, easing, previousPlayers = []) {
4586
- const fill = delay == 0 ? 'both' : 'forwards';
4587
- const playerOptions = { duration, delay, fill };
4588
- // we check for this to avoid having a null|undefined value be present
4589
- // for the easing (which results in an error for certain browsers #9752)
4590
- if (easing) {
4591
- playerOptions['easing'] = easing;
4592
- }
4593
- const previousStyles = new Map();
4594
- const previousWebAnimationPlayers = previousPlayers.filter(player => player instanceof WebAnimationsPlayer);
4595
- if (allowPreviousPlayerStylesMerge(duration, delay)) {
4596
- previousWebAnimationPlayers.forEach(player => {
4597
- player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val));
4598
- });
4599
- }
4600
- let _keyframes = normalizeKeyframes(keyframes).map(styles => copyStyles(styles));
4601
- _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles);
4602
- const specialStyles = packageNonAnimatableStyles(element, _keyframes);
4603
- return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles);
4604
- }
4605
- }
4606
-
4607
- /**
4608
- * @module
4609
- * @description
4610
- * Entry point for all animation APIs of the animation browser package.
4611
- */
4612
-
4613
- /**
4614
- * @module
4615
- * @description
4616
- * Entry point for all public APIs of this package.
4617
- */
4618
-
4619
- // This file is not used to build this module. It is only used during editing
4620
-
4621
- /**
4622
- * Generated bundle index. Do not edit.
4623
- */
4624
-
4625
- export { AnimationDriver, Animation as ɵAnimation, AnimationEngine as ɵAnimationEngine, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, NoopAnimationDriver as ɵNoopAnimationDriver, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, WebAnimationsDriver as ɵWebAnimationsDriver, WebAnimationsPlayer as ɵWebAnimationsPlayer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge, containsElement as ɵcontainsElement, getParentElement as ɵgetParentElement, invokeQuery as ɵinvokeQuery, normalizeKeyframes as ɵnormalizeKeyframes, validateStyleProperty as ɵvalidateStyleProperty };
4626
- //# sourceMappingURL=browser.mjs.map