Skip to content

Commit 0b6f8bb

Browse files
fix(core): skip leave animations on view swaps
We accounted for skipping leave animations during moves, but not swaps. This accounts for the swap cases and updates how we deal with swaps and moves. Now we always queue animations and then essentially dequeue them if we attach them back in the same render pass. fixes: angular#64818 fixes: angular#64730
1 parent a0fe177 commit 0b6f8bb

File tree

7 files changed

+137
-62
lines changed

7 files changed

+137
-62
lines changed

packages/core/src/animation/interfaces.ts

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -52,23 +52,10 @@ const MAX_ANIMATION_TIMEOUT_DEFAULT = 4000;
5252
*/
5353
export type AnimationFunction = (event: AnimationCallbackEvent) => void;
5454

55-
export type AnimationEventFunction = (
56-
el: Element,
57-
value: AnimationFunction,
58-
) => AnimationRemoveFunction;
59-
export type AnimationClassFunction = (
60-
el: Element,
61-
value: Set<string> | null,
62-
resolvers: Function[] | undefined,
63-
) => AnimationRemoveFunction;
64-
export type AnimationRemoveFunction = (removeFn: VoidFunction) => void;
55+
export type RunEnterAnimationFn = VoidFunction;
56+
export type RunLeaveAnimationFn = () => {promise: Promise<void>; resolve: VoidFunction};
6557

66-
export interface AnimationDetails {
67-
classes: Set<string> | null;
68-
classFns?: Function[];
69-
animateFn: AnimationRemoveFunction;
70-
isEventBinding: boolean;
71-
}
58+
export type RunAnimationFn = RunEnterAnimationFn | RunLeaveAnimationFn;
7259

7360
export interface LongestAnimation {
7461
animationName: string | undefined;
@@ -77,7 +64,7 @@ export interface LongestAnimation {
7764
}
7865

7966
export interface NodeAnimations {
80-
animateFns: Function[];
67+
animateFns: RunAnimationFn[];
8168
resolvers?: VoidFunction[];
8269
}
8370

@@ -92,11 +79,9 @@ export interface AnimationLViewData {
9279
// We chose to use unknown instead of PromiseSettledResult<void> to avoid requiring the type
9380
running?: Promise<unknown>;
9481

95-
// Skip leave animations
96-
// This flag is solely used when move operations occur. DOM Node move
97-
// operations occur in lists, like `@for` loops, and use the same code
98-
// path during move that detaching or removing does. So to prevent
99-
// unexpected disappearing of moving nodes, we use this flag to skip
100-
// the animations in that case.
101-
skipLeaveAnimations?: boolean;
82+
// Animation functions that have been queued for this view when the view is detached.
83+
// This is used to later remove them from the global animation queue if the view
84+
// is attached before the animation queue runs. This is used in cases where views are
85+
// moved or swapped during list reconciliation.
86+
detachFnQueue?: VoidFunction[];
10287
}

packages/core/src/animation/queue.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88

99
import {afterNextRender} from '../render3/after_render/hooks';
1010
import {InjectionToken, Injector} from '../di';
11-
import {NodeAnimations} from './interfaces';
11+
import {AnimationLViewData, NodeAnimations} from './interfaces';
1212

1313
export interface AnimationQueue {
14-
queue: Set<Function>;
14+
queue: Set<VoidFunction>;
1515
isScheduled: boolean;
1616
scheduler: Function | null;
1717
}
@@ -33,18 +33,40 @@ export const ANIMATION_QUEUE = new InjectionToken<AnimationQueue>(
3333
},
3434
);
3535

36-
export function addToAnimationQueue(injector: Injector, animationFns: Function | Function[]) {
36+
export function addToAnimationQueue(
37+
injector: Injector,
38+
animationFns: VoidFunction | VoidFunction[],
39+
animationData?: AnimationLViewData,
40+
) {
3741
const animationQueue = injector.get(ANIMATION_QUEUE);
3842
if (Array.isArray(animationFns)) {
3943
for (const animateFn of animationFns) {
4044
animationQueue.queue.add(animateFn);
45+
// If a node is detached, we need to keep track of the queued animation functions
46+
// so we can later remove them from the global animation queue if the view
47+
// is re-attached before the animation queue runs.
48+
animationData?.detachFnQueue?.push(animateFn);
4149
}
4250
} else {
4351
animationQueue.queue.add(animationFns);
52+
// If a node is detached, we need to keep track of the queued animation functions
53+
// so we can later remove them from the global animation queue if the view
54+
// is re-attached before the animation queue runs.
55+
animationData?.detachFnQueue?.push(animationFns);
4456
}
4557
animationQueue.scheduler && animationQueue.scheduler(injector);
4658
}
4759

60+
export function removeFromAnimationQueue(injector: Injector, animationData: AnimationLViewData) {
61+
const animationQueue = injector.get(ANIMATION_QUEUE);
62+
if (animationData.detachFnQueue) {
63+
for (const animationFn of animationData.detachFnQueue) {
64+
animationQueue.queue.delete(animationFn);
65+
}
66+
animationData.detachFnQueue = undefined;
67+
}
68+
}
69+
4870
export function scheduleAnimationQueue(injector: Injector) {
4971
const animationQueue = injector.get(ANIMATION_QUEUE);
5072
// We only want to schedule the animation queue if it hasn't already been scheduled.

packages/core/src/animation/utils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88

99
import {stringify} from '../util/stringify'; // Adjust imports as per actual location
10-
import {ANIMATIONS_DISABLED, LongestAnimation, NodeAnimations} from './interfaces';
10+
import {ANIMATIONS_DISABLED, LongestAnimation, NodeAnimations, RunAnimationFn} from './interfaces';
1111
import {INJECTOR, LView, DECLARATION_LCONTAINER, ANIMATIONS} from '../render3/interfaces/view';
1212
import {RuntimeError, RuntimeErrorCode} from '../errors';
1313
import {Renderer} from '../render3/interfaces/renderer';
@@ -255,7 +255,7 @@ export function isLongestAnimation(
255255
export function addAnimationToLView(
256256
animations: Map<number, NodeAnimations>,
257257
tNode: TNode,
258-
fn: Function,
258+
fn: RunAnimationFn,
259259
) {
260260
const nodeAnimations = animations.get(tNode.index) ?? {animateFns: []};
261261
nodeAnimations.animateFns.push(fn);

packages/core/src/render3/instructions/control_flow.ts

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
DECLARATION_COMPONENT_VIEW,
2929
HEADER_OFFSET,
3030
HYDRATION,
31+
INJECTOR,
3132
LView,
3233
TVIEW,
3334
TView,
@@ -48,6 +49,8 @@ import {
4849
removeLViewFromLContainer,
4950
} from '../view/container';
5051
import {declareNoDirectiveHostTemplate} from './template';
52+
import {removeFromAnimationQueue} from '../../animation/queue';
53+
import {allLeavingAnimations} from '../../animation/longest_animation';
5154

5255
/**
5356
* Creates an LContainer for an ng-template representing a root node
@@ -419,10 +422,11 @@ class LiveCollectionLContainerImpl extends LiveCollection<
419422
index,
420423
shouldAddViewToDom(this.templateTNode, dehydratedView),
421424
);
425+
clearDetachFlag(this.lContainer, index);
422426
}
423-
override detach(index: number, skipLeaveAnimations?: boolean): LView<RepeaterContext<unknown>> {
427+
override detach(index: number): LView<RepeaterContext<unknown>> {
424428
this.needsIndexUpdate ||= index !== this.length - 1;
425-
if (skipLeaveAnimations) setSkipLeaveAnimations(this.lContainer, index);
429+
setDetachFlag(this.lContainer, index);
426430
return detachExistingView<RepeaterContext<unknown>>(this.lContainer, index);
427431
}
428432
override create(index: number, value: unknown): LView<RepeaterContext<unknown>> {
@@ -570,13 +574,35 @@ function getLContainer(lView: LView, index: number): LContainer {
570574
return lContainer;
571575
}
572576

573-
function setSkipLeaveAnimations(lContainer: LContainer, index: number): void {
577+
function clearDetachFlag(lContainer: LContainer, index: number): void {
578+
if (lContainer.length <= CONTAINER_HEADER_OFFSET) return;
579+
580+
const indexInContainer = CONTAINER_HEADER_OFFSET + index;
581+
const viewToDetach = lContainer[indexInContainer];
582+
if (
583+
viewToDetach &&
584+
viewToDetach[ANIMATIONS] &&
585+
(viewToDetach[ANIMATIONS] as AnimationLViewData).detachFnQueue &&
586+
(viewToDetach[ANIMATIONS] as AnimationLViewData).detachFnQueue!.length > 0
587+
) {
588+
const animations = viewToDetach[ANIMATIONS] as AnimationLViewData;
589+
if (animations.detachFnQueue && animations.detachFnQueue.length > 0) {
590+
const injector = viewToDetach[INJECTOR];
591+
removeFromAnimationQueue(injector, animations);
592+
allLeavingAnimations.delete(viewToDetach);
593+
animations.detachFnQueue = undefined;
594+
}
595+
}
596+
}
597+
598+
function setDetachFlag(lContainer: LContainer, index: number): void {
574599
if (lContainer.length <= CONTAINER_HEADER_OFFSET) return;
575600

576601
const indexInContainer = CONTAINER_HEADER_OFFSET + index;
577602
const viewToDetach = lContainer[indexInContainer];
578603
if (viewToDetach && viewToDetach[ANIMATIONS]) {
579-
(viewToDetach[ANIMATIONS] as AnimationLViewData).skipLeaveAnimations = true;
604+
const animations = viewToDetach[ANIMATIONS] as AnimationLViewData;
605+
animations.detachFnQueue = [];
580606
}
581607
}
582608

packages/core/src/render3/list_reconciliation.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export abstract class LiveCollection<T, V> {
2121
abstract get length(): number;
2222
abstract at(index: number): V;
2323
abstract attach(index: number, item: T): void;
24-
abstract detach(index: number, skipLeaveAnimations?: boolean): T;
24+
abstract detach(index: number): T;
2525
abstract create(index: number, value: V): T;
2626
destroy(item: T): void {
2727
// noop by default
@@ -50,7 +50,7 @@ export abstract class LiveCollection<T, V> {
5050
// DOM nodes, which would trigger `animate.leave` bindings. We need to skip
5151
// those animations in the case of a move operation so the moving elements don't
5252
// unexpectedly disappear.
53-
this.attach(newIdx, this.detach(prevIndex, true /* skipLeaveAnimations */));
53+
this.attach(newIdx, this.detach(prevIndex));
5454
}
5555
}
5656

@@ -131,6 +131,7 @@ export function reconcile<T, V>(
131131
// compare from the beginning
132132
const liveStartValue = liveCollection.at(liveStartIdx);
133133
const newStartValue = newCollection[liveStartIdx];
134+
const newLastValue = newCollection[newEndIdx];
134135

135136
if (ngDevMode) {
136137
recordDuplicateKeys(duplicateKeys!, trackByFn(liveStartIdx, newStartValue), liveStartIdx);
@@ -180,6 +181,7 @@ export function reconcile<T, V>(
180181
const liveStartKey = trackByFn(liveStartIdx, liveStartValue);
181182
const liveEndKey = trackByFn(liveEndIdx, liveEndValue);
182183
const newStartKey = trackByFn(liveStartIdx, newStartValue);
184+
183185
if (Object.is(newStartKey, liveEndKey)) {
184186
const newEndKey = trackByFn(newEndIdx, newEndValue);
185187
// detect swap on both ends;

packages/core/src/render3/node_manipulation.ts

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import {getLViewParent, getNativeByTNode, unwrapRNode} from './util/view_utils';
8484
import {allLeavingAnimations} from '../animation/longest_animation';
8585
import {Injector} from '../di';
8686
import {addToAnimationQueue, queueEnterAnimations} from '../animation/queue';
87+
import {RunLeaveAnimationFn} from '../animation/interfaces';
8788

8889
const enum WalkTNodeTreeAction {
8990
/** node create in the native environment. Run on initial creation. */
@@ -386,37 +387,35 @@ function runLeaveAnimationsWithCallback(
386387
if (animations == null || animations.leave == undefined || !animations.leave.has(tNode.index))
387388
return callback(false);
388389

389-
// this is solely for move operations to prevent leave animations from running
390-
// on the moved nodes, which would have deleted the node.
391-
if (animations.skipLeaveAnimations) {
392-
animations.skipLeaveAnimations = false;
393-
return callback(false);
394-
}
395-
396390
if (lView) allLeavingAnimations.add(lView);
397391

398-
addToAnimationQueue(injector, () => {
399-
// it's possible that in the time between when the leave animation was
400-
// and the time it was executed, the data structure changed. So we need
401-
// to be safe here.
402-
if (animations.leave && animations.leave.has(tNode.index)) {
403-
const leaveAnimationMap = animations.leave;
404-
const leaveAnimations = leaveAnimationMap.get(tNode.index);
405-
const runningAnimations = [];
406-
if (leaveAnimations) {
407-
for (let index = 0; index < leaveAnimations.animateFns.length; index++) {
408-
const animationFn = leaveAnimations.animateFns[index];
409-
const {promise} = animationFn();
410-
runningAnimations.push(promise);
392+
addToAnimationQueue(
393+
injector,
394+
() => {
395+
// it's possible that in the time between when the leave animation was
396+
// and the time it was executed, the data structure changed. So we need
397+
// to be safe here.
398+
if (animations.leave && animations.leave.has(tNode.index)) {
399+
const leaveAnimationMap = animations.leave;
400+
const leaveAnimations = leaveAnimationMap.get(tNode.index);
401+
const runningAnimations = [];
402+
if (leaveAnimations) {
403+
for (let index = 0; index < leaveAnimations.animateFns.length; index++) {
404+
const animationFn = leaveAnimations.animateFns[index];
405+
const {promise} = animationFn() as ReturnType<RunLeaveAnimationFn>;
406+
runningAnimations.push(promise);
407+
}
408+
animations.detachFnQueue = undefined;
411409
}
410+
animations.running = Promise.allSettled(runningAnimations);
411+
runAfterLeaveAnimations(lView!, callback);
412+
} else {
413+
if (lView) allLeavingAnimations.delete(lView);
414+
callback(false);
412415
}
413-
animations.running = Promise.allSettled(runningAnimations);
414-
runAfterLeaveAnimations(lView!, callback);
415-
} else {
416-
if (lView) allLeavingAnimations.delete(lView);
417-
callback(false);
418-
}
419-
});
416+
},
417+
animations,
418+
);
420419
}
421420

422421
function runAfterLeaveAnimations(lView: LView, callback: Function) {

packages/core/test/acceptance/animation_spec.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,6 +2057,47 @@ describe('Animation', () => {
20572057
expect(fixture.debugElement.queryAll(By.css('p')).length).toBe(3);
20582058
}));
20592059

2060+
it('should not remove elements when swapping or moving nodes', fakeAsync(() => {
2061+
const animateSpy = jasmine.createSpy('animateSpy');
2062+
@Component({
2063+
selector: 'test-cmp',
2064+
template: `
2065+
<div>
2066+
@for (item of items; track item.id) {
2067+
<p (animate.leave)="animate($event)" #el>{{ item.id }}</p>
2068+
}
2069+
</div>
2070+
`,
2071+
encapsulation: ViewEncapsulation.None,
2072+
})
2073+
class TestComponent {
2074+
items = [{id: 1}, {id: 2}, {id: 3}];
2075+
private cd = inject(ChangeDetectorRef);
2076+
2077+
animate(event: AnimationCallbackEvent) {
2078+
animateSpy();
2079+
event.animationComplete();
2080+
}
2081+
2082+
shuffle() {
2083+
this.items = this.shuffleArray(this.items);
2084+
this.cd.markForCheck();
2085+
}
2086+
2087+
shuffleArray<T>(array: readonly T[]): T[] {
2088+
return [array[1], array[2], array[0]];
2089+
}
2090+
}
2091+
TestBed.configureTestingModule({animationsEnabled: true});
2092+
2093+
const fixture = TestBed.createComponent(TestComponent);
2094+
const cmp = fixture.componentInstance;
2095+
cmp.shuffle();
2096+
fixture.detectChanges();
2097+
expect(animateSpy).not.toHaveBeenCalled();
2098+
expect(fixture.debugElement.queryAll(By.css('p')).length).toBe(3);
2099+
}));
2100+
20602101
it('should not remove elements when child element animations finish', fakeAsync(() => {
20612102
const animateStyles = `
20622103
.fade {

0 commit comments

Comments
 (0)