/
transition_animation_engine.ts
1793 lines (1547 loc) Β· 63.3 KB
/
transition_animation_engine.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AnimationOptions, AnimationPlayer, AUTO_STYLE, NoopAnimationPlayer, Ι΅AnimationGroupPlayer as AnimationGroupPlayer, Ι΅PRE_STYLE as PRE_STYLE, Ι΅StyleDataMap} from '@angular/animations';
import {AnimationTimelineInstruction} from '../dsl/animation_timeline_instruction';
import {AnimationTransitionFactory} from '../dsl/animation_transition_factory';
import {AnimationTransitionInstruction} from '../dsl/animation_transition_instruction';
import {AnimationTrigger} from '../dsl/animation_trigger';
import {ElementInstructionMap} from '../dsl/element_instruction_map';
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';
import {missingEvent, missingTrigger, transitionFailed, triggerTransitionsFailed, unregisteredTrigger, unsupportedTriggerEvent} from '../error_helpers';
import {copyObj, ENTER_CLASSNAME, eraseStyles, LEAVE_CLASSNAME, NG_ANIMATING_CLASSNAME, NG_ANIMATING_SELECTOR, NG_TRIGGER_CLASSNAME, NG_TRIGGER_SELECTOR, setStyles} from '../util';
import {AnimationDriver} from './animation_driver';
import {getOrSetDefaultValue, listenOnPlayer, makeAnimationEvent, normalizeKeyframes, optimizeGroupPlayer} from './shared';
const QUEUED_CLASSNAME = 'ng-animate-queued';
const QUEUED_SELECTOR = '.ng-animate-queued';
const DISABLED_CLASSNAME = 'ng-animate-disabled';
const DISABLED_SELECTOR = '.ng-animate-disabled';
const STAR_CLASSNAME = 'ng-star-inserted';
const STAR_SELECTOR = '.ng-star-inserted';
const EMPTY_PLAYER_ARRAY: TransitionAnimationPlayer[] = [];
const NULL_REMOVAL_STATE: ElementAnimationState = {
namespaceId: '',
setForRemoval: false,
setForMove: false,
hasAnimation: false,
removedBeforeQueried: false
};
const NULL_REMOVED_QUERIED_STATE: ElementAnimationState = {
namespaceId: '',
setForMove: false,
setForRemoval: false,
hasAnimation: false,
removedBeforeQueried: true
};
interface TriggerListener {
name: string;
phase: string;
callback: (event: any) => any;
}
export interface QueueInstruction {
element: any;
triggerName: string;
fromState: StateValue;
toState: StateValue;
transition: AnimationTransitionFactory;
player: TransitionAnimationPlayer;
isFallbackTransition: boolean;
}
export const REMOVAL_FLAG = '__ng_removed';
export interface ElementAnimationState {
setForRemoval: boolean;
setForMove: boolean;
hasAnimation: boolean;
namespaceId: string;
removedBeforeQueried: boolean;
previousTriggersValues?: Map<string, string>;
}
export class StateValue {
public value: string;
public options: AnimationOptions;
get params(): {[key: string]: any} {
return this.options.params as {[key: string]: any};
}
constructor(input: any, public namespaceId: string = '') {
const isObj = input && input.hasOwnProperty('value');
const value = isObj ? input['value'] : input;
this.value = normalizeTriggerValue(value);
if (isObj) {
const options = copyObj(input as any);
delete options['value'];
this.options = options as AnimationOptions;
} else {
this.options = {};
}
if (!this.options.params) {
this.options.params = {};
}
}
absorbOptions(options: AnimationOptions) {
const newParams = options.params;
if (newParams) {
const oldParams = this.options.params!;
Object.keys(newParams).forEach(prop => {
if (oldParams[prop] == null) {
oldParams[prop] = newParams[prop];
}
});
}
}
}
export const VOID_VALUE = 'void';
export const DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE);
export class AnimationTransitionNamespace {
public players: TransitionAnimationPlayer[] = [];
private _triggers = new Map<string, AnimationTrigger>();
private _queue: QueueInstruction[] = [];
private _elementListeners = new Map<any, TriggerListener[]>();
private _hostClassName: string;
constructor(
public id: string, public hostElement: any, private _engine: TransitionAnimationEngine) {
this._hostClassName = 'ng-tns-' + id;
addClass(hostElement, this._hostClassName);
}
listen(element: any, name: string, phase: string, callback: (event: any) => boolean): () => any {
if (!this._triggers.has(name)) {
throw missingTrigger(phase, name);
}
if (phase == null || phase.length == 0) {
throw missingEvent(name);
}
if (!isTriggerEventValid(phase)) {
throw unsupportedTriggerEvent(phase, name);
}
const listeners = getOrSetDefaultValue(this._elementListeners, element, []);
const data = {name, phase, callback};
listeners.push(data);
const triggersWithStates =
getOrSetDefaultValue(this._engine.statesByElement, element, new Map<string, StateValue>());
if (!triggersWithStates.has(name)) {
addClass(element, NG_TRIGGER_CLASSNAME);
addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
triggersWithStates.set(name, DEFAULT_STATE_VALUE);
}
return () => {
// the event listener is removed AFTER the flush has occurred such
// that leave animations callbacks can fire (otherwise if the node
// is removed in between then the listeners would be deregistered)
this._engine.afterFlush(() => {
const index = listeners.indexOf(data);
if (index >= 0) {
listeners.splice(index, 1);
}
if (!this._triggers.has(name)) {
triggersWithStates.delete(name);
}
});
};
}
register(name: string, ast: AnimationTrigger): boolean {
if (this._triggers.has(name)) {
// throw
return false;
} else {
this._triggers.set(name, ast);
return true;
}
}
private _getTrigger(name: string) {
const trigger = this._triggers.get(name);
if (!trigger) {
throw unregisteredTrigger(name);
}
return trigger;
}
trigger(element: any, triggerName: string, value: any, defaultToFallback: boolean = true):
TransitionAnimationPlayer|undefined {
const trigger = this._getTrigger(triggerName);
const player = new TransitionAnimationPlayer(this.id, triggerName, element);
let triggersWithStates = this._engine.statesByElement.get(element);
if (!triggersWithStates) {
addClass(element, NG_TRIGGER_CLASSNAME);
addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
this._engine.statesByElement.set(element, triggersWithStates = new Map<string, StateValue>());
}
let fromState = triggersWithStates.get(triggerName);
const toState = new StateValue(value, this.id);
const isObj = value && value.hasOwnProperty('value');
if (!isObj && fromState) {
toState.absorbOptions(fromState.options);
}
triggersWithStates.set(triggerName, toState);
if (!fromState) {
fromState = DEFAULT_STATE_VALUE;
}
const isRemoval = toState.value === VOID_VALUE;
// normally this isn't reached by here, however, if an object expression
// is passed in then it may be a new object each time. Comparing the value
// is important since that will stay the same despite there being a new object.
// The removal arc here is special cased because the same element is triggered
// twice in the event that it contains animations on the outer/inner portions
// of the host container
if (!isRemoval && fromState.value === toState.value) {
// this means that despite the value not changing, some inner params
// have changed which means that the animation final styles need to be applied
if (!objEquals(fromState.params, toState.params)) {
const errors: Error[] = [];
const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);
const toStyles = trigger.matchStyles(toState.value, toState.params, errors);
if (errors.length) {
this._engine.reportError(errors);
} else {
this._engine.afterFlush(() => {
eraseStyles(element, fromStyles);
setStyles(element, toStyles);
});
}
}
return;
}
const playersOnElement: TransitionAnimationPlayer[] =
getOrSetDefaultValue(this._engine.playersByElement, element, []);
playersOnElement.forEach(player => {
// only remove the player if it is queued on the EXACT same trigger/namespace
// we only also deal with queued players here because if the animation has
// started then we want to keep the player alive until the flush happens
// (which is where the previousPlayers are passed into the new player)
if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
player.destroy();
}
});
let transition =
trigger.matchTransition(fromState.value, toState.value, element, toState.params);
let isFallbackTransition = false;
if (!transition) {
if (!defaultToFallback) return;
transition = trigger.fallbackTransition;
isFallbackTransition = true;
}
this._engine.totalQueuedPlayers++;
this._queue.push(
{element, triggerName, transition, fromState, toState, player, isFallbackTransition});
if (!isFallbackTransition) {
addClass(element, QUEUED_CLASSNAME);
player.onStart(() => {
removeClass(element, QUEUED_CLASSNAME);
});
}
player.onDone(() => {
let index = this.players.indexOf(player);
if (index >= 0) {
this.players.splice(index, 1);
}
const players = this._engine.playersByElement.get(element);
if (players) {
let index = players.indexOf(player);
if (index >= 0) {
players.splice(index, 1);
}
}
});
this.players.push(player);
playersOnElement.push(player);
return player;
}
deregister(name: string) {
this._triggers.delete(name);
this._engine.statesByElement.forEach(stateMap => stateMap.delete(name));
this._elementListeners.forEach((listeners, element) => {
this._elementListeners.set(element, listeners.filter(entry => {
return entry.name != name;
}));
});
}
clearElementCache(element: any) {
this._engine.statesByElement.delete(element);
this._elementListeners.delete(element);
const elementPlayers = this._engine.playersByElement.get(element);
if (elementPlayers) {
elementPlayers.forEach(player => player.destroy());
this._engine.playersByElement.delete(element);
}
}
private _signalRemovalForInnerTriggers(rootElement: any, context: any) {
const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);
// emulate a leave animation for all inner nodes within this node.
// If there are no animations found for any of the nodes then clear the cache
// for the element.
elements.forEach(elm => {
// this means that an inner remove() operation has already kicked off
// the animation on this element...
if (elm[REMOVAL_FLAG]) return;
const namespaces = this._engine.fetchNamespacesByElement(elm);
if (namespaces.size) {
namespaces.forEach(ns => ns.triggerLeaveAnimation(elm, context, false, true));
} else {
this.clearElementCache(elm);
}
});
// If the child elements were removed along with the parent, their animations might not
// have completed. Clear all the elements from the cache so we don't end up with a memory leak.
this._engine.afterFlushAnimationsDone(
() => elements.forEach(elm => this.clearElementCache(elm)));
}
triggerLeaveAnimation(
element: any, context: any, destroyAfterComplete?: boolean,
defaultToFallback?: boolean): boolean {
const triggerStates = this._engine.statesByElement.get(element);
const previousTriggersValues = new Map<string, string>();
if (triggerStates) {
const players: TransitionAnimationPlayer[] = [];
triggerStates.forEach((state, triggerName) => {
previousTriggersValues.set(triggerName, state.value);
// this check is here in the event that an element is removed
// twice (both on the host level and the component level)
if (this._triggers.has(triggerName)) {
const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);
if (player) {
players.push(player);
}
}
});
if (players.length) {
this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);
if (destroyAfterComplete) {
optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));
}
return true;
}
}
return false;
}
prepareLeaveAnimationListeners(element: any) {
const listeners = this._elementListeners.get(element);
const elementStates = this._engine.statesByElement.get(element);
// if this statement fails then it means that the element was picked up
// by an earlier flush (or there are no listeners at all to track the leave).
if (listeners && elementStates) {
const visitedTriggers = new Set<string>();
listeners.forEach(listener => {
const triggerName = listener.name;
if (visitedTriggers.has(triggerName)) return;
visitedTriggers.add(triggerName);
const trigger = this._triggers.get(triggerName)!;
const transition = trigger.fallbackTransition;
const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;
const toState = new StateValue(VOID_VALUE);
const player = new TransitionAnimationPlayer(this.id, triggerName, element);
this._engine.totalQueuedPlayers++;
this._queue.push({
element,
triggerName,
transition,
fromState,
toState,
player,
isFallbackTransition: true
});
});
}
}
removeNode(element: any, context: any): void {
const engine = this._engine;
if (element.childElementCount) {
this._signalRemovalForInnerTriggers(element, context);
}
// this means that a * => VOID animation was detected and kicked off
if (this.triggerLeaveAnimation(element, context, true)) return;
// find the player that is animating and make sure that the
// removal is delayed until that player has completed
let containsPotentialParentTransition = false;
if (engine.totalAnimations) {
const currentPlayers =
engine.players.length ? engine.playersByQueriedElement.get(element) : [];
// when this `if statement` does not continue forward it means that
// a previous animation query has selected the current element and
// is animating it. In this situation want to continue forwards and
// allow the element to be queued up for animation later.
if (currentPlayers && currentPlayers.length) {
containsPotentialParentTransition = true;
} else {
let parent = element;
while (parent = parent.parentNode) {
const triggers = engine.statesByElement.get(parent);
if (triggers) {
containsPotentialParentTransition = true;
break;
}
}
}
}
// at this stage we know that the element will either get removed
// during flush or will be picked up by a parent query. Either way
// we need to fire the listeners for this element when it DOES get
// removed (once the query parent animation is done or after flush)
this.prepareLeaveAnimationListeners(element);
// whether or not a parent has an animation we need to delay the deferral of the leave
// operation until we have more information (which we do after flush() has been called)
if (containsPotentialParentTransition) {
engine.markElementAsRemoved(this.id, element, false, context);
} else {
const removalFlag = element[REMOVAL_FLAG];
if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {
// we do this after the flush has occurred such
// that the callbacks can be fired
engine.afterFlush(() => this.clearElementCache(element));
engine.destroyInnerAnimations(element);
engine._onRemovalComplete(element, context);
}
}
}
insertNode(element: any, parent: any): void {
addClass(element, this._hostClassName);
}
drainQueuedTransitions(microtaskId: number): QueueInstruction[] {
const instructions: QueueInstruction[] = [];
this._queue.forEach(entry => {
const player = entry.player;
if (player.destroyed) return;
const element = entry.element;
const listeners = this._elementListeners.get(element);
if (listeners) {
listeners.forEach((listener: TriggerListener) => {
if (listener.name == entry.triggerName) {
const baseEvent = makeAnimationEvent(
element, entry.triggerName, entry.fromState.value, entry.toState.value);
(baseEvent as any)['_data'] = microtaskId;
listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
}
});
}
if (player.markedForDestroy) {
this._engine.afterFlush(() => {
// now we can destroy the element properly since the event listeners have
// been bound to the player
player.destroy();
});
} else {
instructions.push(entry);
}
});
this._queue = [];
return instructions.sort((a, b) => {
// if depCount == 0 them move to front
// otherwise if a contains b then move back
const d0 = a.transition.ast.depCount;
const d1 = b.transition.ast.depCount;
if (d0 == 0 || d1 == 0) {
return d0 - d1;
}
return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
});
}
destroy(context: any) {
this.players.forEach(p => p.destroy());
this._signalRemovalForInnerTriggers(this.hostElement, context);
}
elementContainsData(element: any): boolean {
let containsData = false;
if (this._elementListeners.has(element)) containsData = true;
containsData =
(this._queue.find(entry => entry.element === element) ? true : false) || containsData;
return containsData;
}
}
export interface QueuedTransition {
element: any;
instruction: AnimationTransitionInstruction;
player: TransitionAnimationPlayer;
}
export class TransitionAnimationEngine {
public players: TransitionAnimationPlayer[] = [];
public newHostElements = new Map<any, AnimationTransitionNamespace>();
public playersByElement = new Map<any, TransitionAnimationPlayer[]>();
public playersByQueriedElement = new Map<any, TransitionAnimationPlayer[]>();
public statesByElement = new Map<any, Map<string, StateValue>>();
public disabledNodes = new Set<any>();
public totalAnimations = 0;
public totalQueuedPlayers = 0;
private _namespaceLookup: {[id: string]: AnimationTransitionNamespace} = {};
private _namespaceList: AnimationTransitionNamespace[] = [];
private _flushFns: (() => any)[] = [];
private _whenQuietFns: (() => any)[] = [];
public namespacesByHostElement = new Map<any, AnimationTransitionNamespace>();
public collectedEnterElements: any[] = [];
public collectedLeaveElements: any[] = [];
// this method is designed to be overridden by the code that uses this engine
public onRemovalComplete = (element: any, context: any) => {};
/** @internal */
_onRemovalComplete(element: any, context: any) {
this.onRemovalComplete(element, context);
}
constructor(
public bodyNode: any, public driver: AnimationDriver,
private _normalizer: AnimationStyleNormalizer) {}
get queuedPlayers(): TransitionAnimationPlayer[] {
const players: TransitionAnimationPlayer[] = [];
this._namespaceList.forEach(ns => {
ns.players.forEach(player => {
if (player.queued) {
players.push(player);
}
});
});
return players;
}
createNamespace(namespaceId: string, hostElement: any) {
const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {
this._balanceNamespaceList(ns, hostElement);
} else {
// defer this later until flush during when the host element has
// been inserted so that we know exactly where to place it in
// the namespace list
this.newHostElements.set(hostElement, ns);
// given that this host element is a part of the animation code, it
// may or may not be inserted by a parent node that is of an
// animation renderer type. If this happens then we can still have
// access to this item when we query for :enter nodes. If the parent
// is a renderer then the set data-structure will normalize the entry
this.collectEnterElement(hostElement);
}
return this._namespaceLookup[namespaceId] = ns;
}
private _balanceNamespaceList(ns: AnimationTransitionNamespace, hostElement: any) {
const namespaceList = this._namespaceList;
const namespacesByHostElement = this.namespacesByHostElement;
const limit = namespaceList.length - 1;
if (limit >= 0) {
let found = false;
// Find the closest ancestor with an existing namespace so we can then insert `ns` after it,
// establishing a top-down ordering of namespaces in `this._namespaceList`.
let ancestor = this.driver.getParentElement(hostElement);
while (ancestor) {
const ancestorNs = namespacesByHostElement.get(ancestor);
if (ancestorNs) {
// An animation namespace has been registered for this ancestor, so we insert `ns`
// right after it to establish top-down ordering of animation namespaces.
const index = namespaceList.indexOf(ancestorNs);
namespaceList.splice(index + 1, 0, ns);
found = true;
break;
}
ancestor = this.driver.getParentElement(ancestor);
}
if (!found) {
// No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to
// ensure that any existing descendants are ordered after `ns`, retaining the desired
// top-down ordering.
namespaceList.unshift(ns);
}
} else {
namespaceList.push(ns);
}
namespacesByHostElement.set(hostElement, ns);
return ns;
}
register(namespaceId: string, hostElement: any) {
let ns = this._namespaceLookup[namespaceId];
if (!ns) {
ns = this.createNamespace(namespaceId, hostElement);
}
return ns;
}
registerTrigger(namespaceId: string, name: string, trigger: AnimationTrigger) {
let ns = this._namespaceLookup[namespaceId];
if (ns && ns.register(name, trigger)) {
this.totalAnimations++;
}
}
destroy(namespaceId: string, context: any) {
if (!namespaceId) return;
const ns = this._fetchNamespace(namespaceId);
this.afterFlush(() => {
this.namespacesByHostElement.delete(ns.hostElement);
delete this._namespaceLookup[namespaceId];
const index = this._namespaceList.indexOf(ns);
if (index >= 0) {
this._namespaceList.splice(index, 1);
}
});
this.afterFlushAnimationsDone(() => ns.destroy(context));
}
private _fetchNamespace(id: string) {
return this._namespaceLookup[id];
}
fetchNamespacesByElement(element: any): Set<AnimationTransitionNamespace> {
// normally there should only be one namespace per element, however
// if @triggers are placed on both the component element and then
// its host element (within the component code) then there will be
// two namespaces returned. We use a set here to simply deduplicate
// the namespaces in case (for the reason described above) there are multiple triggers
const namespaces = new Set<AnimationTransitionNamespace>();
const elementStates = this.statesByElement.get(element);
if (elementStates) {
for (let stateValue of elementStates.values()) {
if (stateValue.namespaceId) {
const ns = this._fetchNamespace(stateValue.namespaceId);
if (ns) {
namespaces.add(ns);
}
}
}
}
return namespaces;
}
trigger(namespaceId: string, element: any, name: string, value: any): boolean {
if (isElementNode(element)) {
const ns = this._fetchNamespace(namespaceId);
if (ns) {
ns.trigger(element, name, value);
return true;
}
}
return false;
}
insertNode(namespaceId: string, element: any, parent: any, insertBefore: boolean): void {
if (!isElementNode(element)) return;
// special case for when an element is removed and reinserted (move operation)
// when this occurs we do not want to use the element for deletion later
const details = element[REMOVAL_FLAG] as ElementAnimationState;
if (details && details.setForRemoval) {
details.setForRemoval = false;
details.setForMove = true;
const index = this.collectedLeaveElements.indexOf(element);
if (index >= 0) {
this.collectedLeaveElements.splice(index, 1);
}
}
// in the event that the namespaceId is blank then the caller
// code does not contain any animation code in it, but it is
// just being called so that the node is marked as being inserted
if (namespaceId) {
const ns = this._fetchNamespace(namespaceId);
// This if-statement is a workaround for router issue #21947.
// The router sometimes hits a race condition where while a route
// is being instantiated a new navigation arrives, triggering leave
// animation of DOM that has not been fully initialized, until this
// is resolved, we need to handle the scenario when DOM is not in a
// consistent state during the animation.
if (ns) {
ns.insertNode(element, parent);
}
}
// only *directives and host elements are inserted before
if (insertBefore) {
this.collectEnterElement(element);
}
}
collectEnterElement(element: any) {
this.collectedEnterElements.push(element);
}
markElementAsDisabled(element: any, value: boolean) {
if (value) {
if (!this.disabledNodes.has(element)) {
this.disabledNodes.add(element);
addClass(element, DISABLED_CLASSNAME);
}
} else if (this.disabledNodes.has(element)) {
this.disabledNodes.delete(element);
removeClass(element, DISABLED_CLASSNAME);
}
}
removeNode(namespaceId: string, element: any, isHostElement: boolean, context: any): void {
if (isElementNode(element)) {
const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
if (ns) {
ns.removeNode(element, context);
} else {
this.markElementAsRemoved(namespaceId, element, false, context);
}
if (isHostElement) {
const hostNS = this.namespacesByHostElement.get(element);
if (hostNS && hostNS.id !== namespaceId) {
hostNS.removeNode(element, context);
}
}
} else {
this._onRemovalComplete(element, context);
}
}
markElementAsRemoved(
namespaceId: string, element: any, hasAnimation?: boolean, context?: any,
previousTriggersValues?: Map<string, string>) {
this.collectedLeaveElements.push(element);
element[REMOVAL_FLAG] = {
namespaceId,
setForRemoval: context,
hasAnimation,
removedBeforeQueried: false,
previousTriggersValues
};
}
listen(
namespaceId: string, element: any, name: string, phase: string,
callback: (event: any) => boolean): () => any {
if (isElementNode(element)) {
return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
}
return () => {};
}
private _buildInstruction(
entry: QueueInstruction, subTimelines: ElementInstructionMap, enterClassName: string,
leaveClassName: string, skipBuildAst?: boolean) {
return entry.transition.build(
this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName,
leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);
}
destroyInnerAnimations(containerElement: any) {
let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
elements.forEach(element => this.destroyActiveAnimationsForElement(element));
if (this.playersByQueriedElement.size == 0) return;
elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
elements.forEach(element => this.finishActiveQueriedAnimationOnElement(element));
}
destroyActiveAnimationsForElement(element: any) {
const players = this.playersByElement.get(element);
if (players) {
players.forEach(player => {
// special case for when an element is set for destruction, but hasn't started.
// in this situation we want to delay the destruction until the flush occurs
// so that any event listeners attached to the player are triggered.
if (player.queued) {
player.markedForDestroy = true;
} else {
player.destroy();
}
});
}
}
finishActiveQueriedAnimationOnElement(element: any) {
const players = this.playersByQueriedElement.get(element);
if (players) {
players.forEach(player => player.finish());
}
}
whenRenderingDone(): Promise<any> {
return new Promise<void>(resolve => {
if (this.players.length) {
return optimizeGroupPlayer(this.players).onDone(() => resolve());
} else {
resolve();
}
});
}
processLeaveNode(element: any) {
const details = element[REMOVAL_FLAG] as ElementAnimationState;
if (details && details.setForRemoval) {
// this will prevent it from removing it twice
element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
if (details.namespaceId) {
this.destroyInnerAnimations(element);
const ns = this._fetchNamespace(details.namespaceId);
if (ns) {
ns.clearElementCache(element);
}
}
this._onRemovalComplete(element, details.setForRemoval);
}
if (element.classList?.contains(DISABLED_CLASSNAME)) {
this.markElementAsDisabled(element, false);
}
this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {
this.markElementAsDisabled(node, false);
});
}
flush(microtaskId: number = -1) {
let players: AnimationPlayer[] = [];
if (this.newHostElements.size) {
this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
this.newHostElements.clear();
}
if (this.totalAnimations && this.collectedEnterElements.length) {
for (let i = 0; i < this.collectedEnterElements.length; i++) {
const elm = this.collectedEnterElements[i];
addClass(elm, STAR_CLASSNAME);
}
}
if (this._namespaceList.length &&
(this.totalQueuedPlayers || this.collectedLeaveElements.length)) {
const cleanupFns: Function[] = [];
try {
players = this._flushAnimations(cleanupFns, microtaskId);
} finally {
for (let i = 0; i < cleanupFns.length; i++) {
cleanupFns[i]();
}
}
} else {
for (let i = 0; i < this.collectedLeaveElements.length; i++) {
const element = this.collectedLeaveElements[i];
this.processLeaveNode(element);
}
}
this.totalQueuedPlayers = 0;
this.collectedEnterElements.length = 0;
this.collectedLeaveElements.length = 0;
this._flushFns.forEach(fn => fn());
this._flushFns = [];
if (this._whenQuietFns.length) {
// we move these over to a variable so that
// if any new callbacks are registered in another
// flush they do not populate the existing set
const quietFns = this._whenQuietFns;
this._whenQuietFns = [];
if (players.length) {
optimizeGroupPlayer(players).onDone(() => {
quietFns.forEach(fn => fn());
});
} else {
quietFns.forEach(fn => fn());
}
}
}
reportError(errors: Error[]) {
throw triggerTransitionsFailed(errors);
}
private _flushAnimations(cleanupFns: Function[], microtaskId: number):
TransitionAnimationPlayer[] {
const subTimelines = new ElementInstructionMap();
const skippedPlayers: TransitionAnimationPlayer[] = [];
const skippedPlayersMap = new Map<any, AnimationPlayer[]>();
const queuedInstructions: QueuedTransition[] = [];
const queriedElements = new Map<any, TransitionAnimationPlayer[]>();
const allPreStyleElements = new Map<any, Set<string>>();
const allPostStyleElements = new Map<any, Set<string>>();
const disabledElementsSet = new Set<any>();
this.disabledNodes.forEach(node => {
disabledElementsSet.add(node);
const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
for (let i = 0; i < nodesThatAreDisabled.length; i++) {
disabledElementsSet.add(nodesThatAreDisabled[i]);
}
});
const bodyNode = this.bodyNode;
const allTriggerElements = Array.from(this.statesByElement.keys());
const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);
// this must occur before the instructions are built below such that
// the :enter queries match the elements (since the timeline queries
// are fired during instruction building).
const enterNodeMapIds = new Map<any, string>();
let i = 0;
enterNodeMap.forEach((nodes, root) => {
const className = ENTER_CLASSNAME + i++;
enterNodeMapIds.set(root, className);
nodes.forEach(node => addClass(node, className));
});
const allLeaveNodes: any[] = [];
const mergedLeaveNodes = new Set<any>();
const leaveNodesWithoutAnimations = new Set<any>();
for (let i = 0; i < this.collectedLeaveElements.length; i++) {
const element = this.collectedLeaveElements[i];
const details = element[REMOVAL_FLAG] as ElementAnimationState;
if (details && details.setForRemoval) {
allLeaveNodes.push(element);
mergedLeaveNodes.add(element);
if (details.hasAnimation) {
this.driver.query(element, STAR_SELECTOR, true).forEach(elm => mergedLeaveNodes.add(elm));
} else {
leaveNodesWithoutAnimations.add(element);
}
}
}
const leaveNodeMapIds = new Map<any, string>();
const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));
leaveNodeMap.forEach((nodes, root) => {
const className = LEAVE_CLASSNAME + i++;
leaveNodeMapIds.set(root, className);
nodes.forEach(node => addClass(node, className));
});
cleanupFns.push(() => {
enterNodeMap.forEach((nodes, root) => {
const className = enterNodeMapIds.get(root)!;
nodes.forEach(node => removeClass(node, className));
});
leaveNodeMap.forEach((nodes, root) => {
const className = leaveNodeMapIds.get(root)!;
nodes.forEach(node => removeClass(node, className));
});
allLeaveNodes.forEach(element => {
this.processLeaveNode(element);
});
});
const allPlayers: TransitionAnimationPlayer[] = [];
const erroneousTransitions: AnimationTransitionInstruction[] = [];
for (let i = this._namespaceList.length - 1; i >= 0; i--) {
const ns = this._namespaceList[i];