-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
binding_spec.ts
607 lines (552 loc) Β· 24.8 KB
/
binding_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
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
/**
* @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 * as e from '../../../src/expression_parser/ast';
import * as a from '../../../src/render3/r3_ast';
import {DirectiveMeta, InputOutputPropertySet} from '../../../src/render3/view/t2_api';
import {R3TargetBinder} from '../../../src/render3/view/t2_binder';
import {parseTemplate} from '../../../src/render3/view/template';
import {CssSelector, SelectorMatcher} from '../../../src/selector';
import {findExpression} from './util';
/**
* A `InputOutputPropertySet` which only uses an identity mapping for fields and properties.
*/
class IdentityInputMapping implements InputOutputPropertySet {
private names: Set<string>;
constructor(names: string[]) {
this.names = new Set(names);
}
hasBindingPropertyName(propertyName: string): boolean {
return this.names.has(propertyName);
}
}
function makeSelectorMatcher(): SelectorMatcher<DirectiveMeta[]> {
const matcher = new SelectorMatcher<DirectiveMeta[]>();
matcher.addSelectables(CssSelector.parse('[ngFor][ngForOf]'), [{
name: 'NgFor',
exportAs: null,
inputs: new IdentityInputMapping(['ngForOf']),
outputs: new IdentityInputMapping([]),
isComponent: false,
isStructural: true,
selector: '[ngFor][ngForOf]',
animationTriggerNames: null,
}]);
matcher.addSelectables(CssSelector.parse('[dir]'), [{
name: 'Dir',
exportAs: ['dir'],
inputs: new IdentityInputMapping([]),
outputs: new IdentityInputMapping([]),
isComponent: false,
isStructural: false,
selector: '[dir]',
animationTriggerNames: null,
}]);
matcher.addSelectables(CssSelector.parse('[hasOutput]'), [{
name: 'HasOutput',
exportAs: null,
inputs: new IdentityInputMapping([]),
outputs: new IdentityInputMapping(['outputBinding']),
isComponent: false,
isStructural: false,
selector: '[hasOutput]',
animationTriggerNames: null,
}]);
matcher.addSelectables(CssSelector.parse('[hasInput]'), [{
name: 'HasInput',
exportAs: null,
inputs: new IdentityInputMapping(['inputBinding']),
outputs: new IdentityInputMapping([]),
isComponent: false,
isStructural: false,
selector: '[hasInput]',
animationTriggerNames: null,
}]);
matcher.addSelectables(CssSelector.parse('[sameSelectorAsInput]'), [{
name: 'SameSelectorAsInput',
exportAs: null,
inputs: new IdentityInputMapping(['sameSelectorAsInput']),
outputs: new IdentityInputMapping([]),
isComponent: false,
isStructural: false,
selector: '[sameSelectorAsInput]',
animationTriggerNames: null,
}]);
matcher.addSelectables(CssSelector.parse('comp'), [{
name: 'Comp',
exportAs: null,
inputs: new IdentityInputMapping([]),
outputs: new IdentityInputMapping([]),
isComponent: true,
isStructural: false,
selector: 'comp',
animationTriggerNames: null,
}]);
const simpleDirectives = ['a', 'b', 'c', 'd', 'e', 'f'];
const deferBlockDirectives = ['loading', 'error', 'placeholder'];
for (const dir of [...simpleDirectives, ...deferBlockDirectives]) {
const name = dir[0].toUpperCase() + dir.slice(1).toLowerCase();
matcher.addSelectables(CssSelector.parse(`[${dir}]`), [{
name: `Dir${name}`,
exportAs: null,
inputs: new IdentityInputMapping([]),
outputs: new IdentityInputMapping([]),
isComponent: false,
isStructural: true,
selector: `[${dir}]`,
animationTriggerNames: null,
}]);
}
return matcher;
}
describe('t2 binding', () => {
it('should bind a simple template', () => {
const template = parseTemplate('<div *ngFor="let item of items">{{item.name}}</div>', '', {});
const binder = new R3TargetBinder(new SelectorMatcher<DirectiveMeta[]>());
const res = binder.bind({template: template.nodes});
const itemBinding =
(findExpression(template.nodes, '{{item.name}}')! as e.Interpolation).expressions[0] as
e.PropertyRead;
const item = itemBinding.receiver;
const itemTarget = res.getExpressionTarget(item);
if (!(itemTarget instanceof a.Variable)) {
return fail('Expected item to point to a Variable');
}
expect(itemTarget.value).toBe('$implicit');
const itemTemplate = res.getDefinitionNodeOfSymbol(itemTarget);
expect(itemTemplate).not.toBeNull();
expect(res.getNestingLevel(itemTemplate!)).toBe(1);
});
it('should match directives when binding a simple template', () => {
const template = parseTemplate('<div *ngFor="let item of items">{{item.name}}</div>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const tmpl = template.nodes[0] as a.Template;
const directives = res.getDirectivesOfNode(tmpl)!;
expect(directives).not.toBeNull();
expect(directives.length).toBe(1);
expect(directives[0].name).toBe('NgFor');
});
it('should match directives on namespaced elements', () => {
const template = parseTemplate('<svg><text dir>SVG</text></svg>', '', {});
const matcher = new SelectorMatcher<DirectiveMeta[]>();
matcher.addSelectables(CssSelector.parse('text[dir]'), [{
name: 'Dir',
exportAs: null,
inputs: new IdentityInputMapping([]),
outputs: new IdentityInputMapping([]),
isComponent: false,
isStructural: false,
selector: 'text[dir]',
animationTriggerNames: null,
}]);
const binder = new R3TargetBinder(matcher);
const res = binder.bind({template: template.nodes});
const svgNode = template.nodes[0] as a.Element;
const textNode = svgNode.children[0] as a.Element;
const directives = res.getDirectivesOfNode(textNode)!;
expect(directives).not.toBeNull();
expect(directives.length).toBe(1);
expect(directives[0].name).toBe('Dir');
});
it('should not match directives intended for an element on a microsyntax template', () => {
const template = parseTemplate('<div *ngFor="let item of items" dir></div>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const tmpl = template.nodes[0] as a.Template;
const tmplDirectives = res.getDirectivesOfNode(tmpl)!;
expect(tmplDirectives).not.toBeNull();
expect(tmplDirectives.length).toBe(1);
expect(tmplDirectives[0].name).toBe('NgFor');
const elDirectives = res.getDirectivesOfNode(tmpl.children[0] as a.Element)!;
expect(elDirectives).not.toBeNull();
expect(elDirectives.length).toBe(1);
expect(elDirectives[0].name).toBe('Dir');
});
describe('matching inputs to consuming directives', () => {
it('should work for bound attributes', () => {
const template = parseTemplate('<div hasInput [inputBinding]="myValue"></div>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const attr = el.inputs[0];
const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta;
expect(consumer.name).toBe('HasInput');
});
it('should work for text attributes on elements', () => {
const template = parseTemplate('<div hasInput inputBinding="text"></div>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const attr = el.attributes[1];
const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta;
expect(consumer.name).toBe('HasInput');
});
it('should work for text attributes on templates', () => {
const template =
parseTemplate('<ng-template hasInput inputBinding="text"></ng-template>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const attr = el.attributes[1];
const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta;
expect(consumer.name).toBe('HasInput');
});
it('should not match directives on attribute bindings with the same name as an input', () => {
const template =
parseTemplate('<ng-template [attr.sameSelectorAsInput]="123"></ng-template>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const input = el.inputs[0];
const consumer = res.getConsumerOfBinding(input);
expect(consumer).toEqual(el);
});
it('should bind to the encompassing node when no directive input is matched', () => {
const template = parseTemplate('<span dir></span>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const attr = el.attributes[0];
const consumer = res.getConsumerOfBinding(attr);
expect(consumer).toEqual(el);
});
});
describe('matching outputs to consuming directives', () => {
it('should work for bound events', () => {
const template =
parseTemplate('<div hasOutput (outputBinding)="myHandler($event)"></div>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const attr = el.outputs[0];
const consumer = res.getConsumerOfBinding(attr) as DirectiveMeta;
expect(consumer.name).toBe('HasOutput');
});
it('should bind to the encompassing node when no directive output is matched', () => {
const template = parseTemplate('<span dir (fakeOutput)="myHandler($event)"></span>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
const el = template.nodes[0] as a.Element;
const attr = el.outputs[0];
const consumer = res.getConsumerOfBinding(attr);
expect(consumer).toEqual(el);
});
});
describe('extracting defer blocks info', () => {
const templateOptions = {enabledBlockTypes: new Set(['defer'])};
it('should extract top-level defer blocks', () => {
const template = parseTemplate(
`
{#defer}<cmp-a />{/defer}
{#defer}<cmp-b />{/defer}
<cmp-c />
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const deferBlocks = bound.getDeferBlocks();
expect(deferBlocks.length).toBe(2);
});
it('should extract nested defer blocks and associated pipes', () => {
const template = parseTemplate(
`
{#defer}
{{ name | pipeA }}
{#defer}{{ name | pipeB }}{/defer}
{:loading}
{#defer}{{ name | pipeC }}{/defer}
{{ name | loading }}
{:placeholder}
{#defer}{{ name | pipeD }}{/defer}
{{ name | placeholder }}
{:error}
{#defer}{{ name | pipeE }}{/defer}
{{ name | error }}
{/defer}
{{ name | pipeF }}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const deferBlocks = bound.getDeferBlocks();
expect(deferBlocks.length).toBe(5);
// Record all pipes used within :placeholder, :loading and :error sub-blocks,
// also record pipes used outside of any {#defer} blocks.
expect(bound.getEagerlyUsedPipes()).toEqual(['placeholder', 'loading', 'error', 'pipeF']);
// Record *all* pipes from the template, including the ones from {#defer} blocks.
expect(bound.getUsedPipes()).toEqual([
'pipeA', 'pipeB', 'pipeD', 'placeholder', 'pipeC', 'loading', 'pipeE', 'error', 'pipeF'
]);
});
it('should identify pipes used after a nested defer block as being lazy', () => {
const template = parseTemplate(
`
{#defer}
{{ name | pipeA }}
{#defer}{{ name | pipeB }}{/defer}
{{ name | pipeC }}
{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
expect(bound.getUsedPipes()).toEqual(['pipeA', 'pipeB', 'pipeC']);
expect(bound.getEagerlyUsedPipes()).toEqual([]);
});
it('should extract nested defer blocks and associated directives', () => {
const template = parseTemplate(
`
{#defer}
<img *a />
{#defer}<img *b />{/defer}
{:loading}
{#defer}<img *c />{/defer}
<img *loading />
{:placeholder}
{#defer}<img *d />{/defer}
<img *placeholder />
{:error}
{#defer}<img *e />{/defer}
<img *error />
{/defer}
<img *f />
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const deferBlocks = bound.getDeferBlocks();
expect(deferBlocks.length).toBe(5);
// Record all directives used within :placeholder, :loading and :error sub-blocks,
// also record directives used outside of any {#defer} blocks.
const eagerDirs = bound.getEagerlyUsedDirectives();
expect(eagerDirs.length).toBe(4);
expect(eagerDirs.map(dir => dir.name)).toEqual([
'DirPlaceholder', 'DirLoading', 'DirError', 'DirF'
]);
// Record *all* directives from the template, including the ones from {#defer} blocks.
const allDirs = bound.getUsedDirectives();
expect(allDirs.length).toBe(9);
expect(allDirs.map(dir => dir.name)).toEqual([
'DirA', 'DirB', 'DirD', 'DirPlaceholder', 'DirC', 'DirLoading', 'DirE', 'DirError', 'DirF'
]);
});
it('should identify directives used after a nested defer block as being lazy', () => {
const template = parseTemplate(
`
{#defer}
<img *a />
{#defer}<img *b />{/defer}
<img *c />
{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const allDirs = bound.getUsedDirectives().map(dir => dir.name);
const eagerDirs = bound.getEagerlyUsedDirectives().map(dir => dir.name);
expect(allDirs).toEqual(['DirA', 'DirB', 'DirC']);
expect(eagerDirs).toEqual([]);
});
it('should identify a trigger element that is a parent of the deferred block', () => {
const template = parseTemplate(
`
<div #trigger>
{#defer on viewport(trigger)}{/defer}
</div>
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl?.name).toBe('div');
});
it('should identify a trigger element outside of the deferred block', () => {
const template = parseTemplate(
`
<div>
{#defer on viewport(trigger)}{/defer}
</div>
<div>
<div>
<button #trigger></button>
</div>
</div>
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl?.name).toBe('button');
});
it('should identify a trigger element in a parent embedded view', () => {
const template = parseTemplate(
`
<div *ngFor="let item of items">
<button #trigger></button>
<div *ngFor="let child of item.children">
<div *ngFor="let grandchild of child.children">
{#defer on viewport(trigger)}{/defer}
</div>
</div>
</div>
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl?.name).toBe('button');
});
it('should identify a trigger element inside the placeholder', () => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}
main
{:placeholder} <button #trigger></button>
{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl?.name).toBe('button');
});
it('should not identify a trigger inside the main content block', () => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}<button #trigger></button>{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl).toBeNull();
});
it('should identify a trigger element on a component', () => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}{/defer}
<comp #trigger/>
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl?.name).toBe('comp');
});
it('should identify a trigger element on a directive', () => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}{/defer}
<button dir #trigger="dir"></button>
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl?.name).toBe('button');
});
it('should not identify a trigger inside a sibling embedded view', () => {
const template = parseTemplate(
`
<div *ngIf="cond">
<button #trigger></button>
</div>
{#defer on viewport(trigger)}{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl).toBeNull();
});
it('should not identify a trigger element in an embedded view inside the placeholder', () => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}
main
{:placeholder}
<div *ngIf="cond"><button #trigger></button></div>
{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl).toBeNull();
});
it('should not identify a trigger element inside the a deferred block within the placeholder',
() => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}
main
{:placeholder}
{#defer}<button #trigger></button>{/defer}
{/defer}
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl).toBeNull();
});
it('should not identify a trigger element on a template', () => {
const template = parseTemplate(
`
{#defer on viewport(trigger)}{/defer}
<ng-template #trigger></ng-template>
`,
'', templateOptions);
const binder = new R3TargetBinder(makeSelectorMatcher());
const bound = binder.bind({template: template.nodes});
const block = Array.from(bound.getDeferBlocks())[0];
const triggerEl = bound.getDeferredTriggerTarget(block, block.triggers.viewport!);
expect(triggerEl).toBeNull();
});
});
describe('used pipes', () => {
it('should record pipes used in interpolations', () => {
const template = parseTemplate('{{value|date}}', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
expect(res.getUsedPipes()).toEqual(['date']);
});
it('should record pipes used in bound attributes', () => {
const template = parseTemplate('<person [age]="age|number"></person>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
expect(res.getUsedPipes()).toEqual(['number']);
});
it('should record pipes used in bound template attributes', () => {
const template = parseTemplate('<ng-template [ngIf]="obs|async"></ng-template>', '', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
expect(res.getUsedPipes()).toEqual(['async']);
});
it('should record pipes used in ICUs', () => {
const template = parseTemplate(
`<span i18n>{count|number, plural,
=1 { {{value|date}} }
}</span>`,
'', {});
const binder = new R3TargetBinder(makeSelectorMatcher());
const res = binder.bind({template: template.nodes});
expect(res.getUsedPipes()).toEqual(['number', 'date']);
});
});
});