-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
animation_renderer_spec.ts
461 lines (386 loc) Β· 15.3 KB
/
animation_renderer_spec.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
/**
* @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 {
animate,
AnimationPlayer,
AnimationTriggerMetadata,
style,
transition,
trigger,
} from '@angular/animations';
import {
Ι΅AnimationEngine as AnimationEngine,
Ι΅AnimationRenderer as AnimationRenderer,
Ι΅AnimationRendererFactory as AnimationRendererFactory,
Ι΅BaseAnimationRenderer as BaseAnimationRenderer,
} from '@angular/animations/browser';
import {DOCUMENT} from '@angular/common';
import {
ANIMATION_MODULE_TYPE,
Component,
Injectable,
NgZone,
RendererFactory2,
RendererType2,
ViewChild,
Ι΅ChangeDetectionScheduler as ChangeDetectionScheduler,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Ι΅DomRendererFactory2 as DomRendererFactory2} from '@angular/platform-browser';
import {InjectableAnimationEngine} from '@angular/platform-browser/animations/src/providers';
import {el} from '@angular/platform-browser/testing/src/browser_util';
import {
AsyncAnimationRendererFactory,
DynamicDelegationRenderer,
} from '../src/async_animation_renderer';
type AnimationBrowserModule = typeof import('@angular/animations/browser');
(function () {
if (isNode) {
it('empty test so jasmine doesnt complain', () => {});
return;
}
describe('AnimationRenderer', () => {
let element: any;
beforeEach(() => {
element = el('<div></div>');
TestBed.configureTestingModule({
providers: [
{
provide: RendererFactory2,
useFactory: (
doc: Document,
renderer: DomRendererFactory2,
zone: NgZone,
engine: MockAnimationEngine,
) => {
const animationModule = {
Ι΅createEngine: (_: 'animations' | 'noop', _2: Document): AnimationEngine => engine,
Ι΅AnimationEngine: MockAnimationEngine as any,
Ι΅AnimationRenderer: AnimationRenderer,
Ι΅BaseAnimationRenderer: BaseAnimationRenderer,
Ι΅AnimationRendererFactory: AnimationRendererFactory,
} satisfies Partial<AnimationBrowserModule> as AnimationBrowserModule;
return new AsyncAnimationRendererFactory(
doc,
renderer,
zone,
'animations',
Promise.resolve(animationModule),
);
},
deps: [DOCUMENT, DomRendererFactory2, NgZone, AnimationEngine],
},
{provide: ANIMATION_MODULE_TYPE, useValue: 'BrowserAnimations'},
{provide: AnimationEngine, useClass: MockAnimationEngine},
],
});
});
function makeRenderer(animationTriggers: any[] = []): Promise<DynamicDelegationRenderer> {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': animationTriggers},
};
const factory = TestBed.inject(RendererFactory2) as AsyncAnimationRendererFactory;
const renderer = factory.createRenderer(element, type);
return (factory as any)._rendererFactoryPromise.then(() => renderer);
}
it("should hook into the engine's insert operations when appending children", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const container = el('<div></div>');
renderer.appendChild(container, element);
expect(engine.captures['onInsert'].pop()).toEqual([element]);
});
it("should hook into the engine's insert operations when inserting a child before another", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const container = el('<div></div>');
const element2 = el('<div></div>');
container.appendChild(element2);
renderer.insertBefore(container, element, element2);
expect(engine.captures['onInsert'].pop()).toEqual([element]);
});
it("should hook into the engine's insert operations when removing children", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const container = el('<div></div>');
renderer.removeChild(container, element, false);
expect(engine.captures['onRemove'].pop()).toEqual([element]);
});
it("should hook into the engine's setProperty call if the property begins with `@`", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
renderer.setProperty(element, 'prop', 'value');
expect(engine.captures['setProperty']).toBeFalsy();
renderer.setProperty(element, '@prop', 'value');
expect(engine.captures['setProperty'].pop()).toEqual([element, 'prop', 'value']);
});
// https://github.com/angular/angular/issues/32794
it('should support nested animation triggers', async () => {
const renderer = await makeRenderer([[trigger('myAnimation', [])]]);
const {triggers} = (renderer as any).delegate.engine as MockAnimationEngine;
expect(triggers.length).toEqual(1);
expect(triggers[0].name).toEqual('myAnimation');
});
describe('listen', () => {
it("should hook into the engine's listen call if the property begins with `@`", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const cb = (event: any): boolean => {
return true;
};
renderer.listen(element, 'event', cb);
expect(engine.captures['listen']).toBeFalsy();
renderer.listen(element, '@event.phase', cb);
expect(engine.captures['listen'].pop()).toEqual([element, 'event', 'phase']);
});
it('should resolve the body|document|window nodes given their values as strings as input', async () => {
const renderer = await makeRenderer();
const engine = (renderer['delegate'] as AnimationRenderer).engine as MockAnimationEngine;
const cb = (event: any): boolean => {
return true;
};
renderer.listen('body', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(document.body);
renderer.listen('document', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(document);
renderer.listen('window', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(window);
});
it('should store animations events passed to the default renderer and register them against the animation renderer', async () => {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': []},
};
const factory = TestBed.inject(RendererFactory2) as AsyncAnimationRendererFactory;
const renderer = factory.createRenderer(element, type) as DynamicDelegationRenderer;
const cb = (event: any): boolean => true;
renderer.listen('body', '@event', cb);
renderer.listen('document', '@event', cb);
renderer.listen('window', '@event', cb);
// The animation renderer is not loaded yet
expect((renderer['delegate'] as AnimationRenderer).engine).toBeUndefined();
// This will change the delegate renderer from the default one to the AnimationRenderer
await factory['_rendererFactoryPromise']!.then(() => renderer);
const engine = (renderer['delegate'] as AnimationRenderer).engine as MockAnimationEngine;
expect(engine.captures['listen'][0][0]).toBe(document.body);
expect(engine.captures['listen'][1][0]).toBe(document);
expect(engine.captures['listen'][2][0]).toBe(window);
});
});
it('should store animations properties set on the default renderer and set them also on the animation renderer', async () => {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': []},
};
const factory = TestBed.inject(RendererFactory2) as AsyncAnimationRendererFactory;
const renderer = factory.createRenderer(element, type) as DynamicDelegationRenderer;
renderer.setProperty(element, '@openClose', 'closed');
renderer.setProperty(element, '@openClose', 'open');
// The animation renderer is not loaded yet
expect((renderer['delegate'] as AnimationRenderer).engine).toBeUndefined();
// This will change the delegate renderer from the default one to the AnimationRenderer
await factory['_rendererFactoryPromise']!.then(() => renderer);
const engine = (renderer['delegate'] as AnimationRenderer).engine as MockAnimationEngine;
expect(engine.captures['setProperty'][0][2]).toBe('closed');
expect(engine.captures['setProperty'][1][2]).toBe('open');
});
describe('registering animations', () => {
it('should only create a trigger definition once even if the registered multiple times');
});
describe('flushing animations', () => {
beforeEach(() => {
TestBed.resetTestingModule();
});
// these tests are only meant to be run within the DOM
if (isNode) return;
it('should flush and fire callbacks when the zone becomes stable', (async) => {
@Component({
selector: 'my-cmp',
template: '<div [@myAnimation]="exp" (@myAnimation.start)="onStart($event)"></div>',
animations: [
trigger('myAnimation', [
transition('* => state', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
})
class Cmp {
exp: any;
event: any;
onStart(event: any) {
this.event = event;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(AnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'state';
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(cmp.event.triggerName).toEqual('myAnimation');
expect(cmp.event.phaseName).toEqual('start');
cmp.event = null;
engine.flush();
expect(cmp.event).toBeFalsy();
async();
});
});
it('should properly insert/remove nodes through the animation renderer that do not contain animations', (async) => {
@Component({
selector: 'my-cmp',
template: '<div #elm *ngIf="exp"></div>',
animations: [
trigger('someAnimation', [
transition('* => *', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
})
class Cmp {
exp: any;
@ViewChild('elm') public element: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
cmp.exp = false;
const element = cmp.element;
expect(element.nativeElement.parentNode).toBeTruthy();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.nativeElement.parentNode).toBeFalsy();
async();
});
});
});
it('should only queue up dom removals if the element itself contains a valid leave animation', () => {
@Component({
selector: 'my-cmp',
template: `
<div #elm1 *ngIf="exp1"></div>
<div #elm2 @animation1 *ngIf="exp2"></div>
<div #elm3 @animation2 *ngIf="exp3"></div>
`,
animations: [
trigger('animation1', [transition('a => b', [])]),
trigger('animation2', [transition(':leave', [])]),
],
})
class Cmp {
exp1: any = true;
exp2: any = true;
exp3: any = true;
@ViewChild('elm1') public elm1: any;
@ViewChild('elm2') public elm2: any;
@ViewChild('elm3') public elm3: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(AnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const elm1 = cmp.elm1;
const elm2 = cmp.elm2;
const elm3 = cmp.elm3;
assertHasParent(elm1);
assertHasParent(elm2);
assertHasParent(elm3);
engine.flush();
finishPlayers(engine.players);
cmp.exp1 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(0);
cmp.exp2 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2, false);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(0);
cmp.exp3 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2, false);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(1);
});
});
});
})();
@Injectable()
class MockAnimationEngine extends InjectableAnimationEngine {
captures: {[method: string]: any[]} = {};
triggers: AnimationTriggerMetadata[] = [];
private _capture(name: string, args: any[]) {
const data = (this.captures[name] = this.captures[name] || []);
data.push(args);
}
override registerTrigger(
componentId: string,
namespaceId: string,
hostElement: any,
name: string,
metadata: AnimationTriggerMetadata,
): void {
this.triggers.push(metadata);
}
override onInsert(namespaceId: string, element: any): void {
this._capture('onInsert', [element]);
}
override onRemove(namespaceId: string, element: any, domFn: () => any): void {
this._capture('onRemove', [element]);
}
override process(namespaceId: string, element: any, property: string, value: any): boolean {
this._capture('setProperty', [element, property, value]);
return true;
}
override listen(
namespaceId: string,
element: any,
eventName: string,
eventPhase: string,
callback: (event: any) => any,
): () => void {
// we don't capture the callback here since the renderer wraps it in a zone
this._capture('listen', [element, eventName, eventPhase]);
return () => {};
}
override flush() {}
override destroy(namespaceId: string) {}
}
function assertHasParent(element: any, yes: boolean = true) {
const parent = element.nativeElement.parentNode;
if (yes) {
expect(parent).toBeTruthy();
} else {
expect(parent).toBeFalsy();
}
}
function finishPlayers(players: AnimationPlayer[]) {
players.forEach((player) => player.finish());
}