forked from angular/angular
/
template_parser_spec.ts
2297 lines (2035 loc) · 95.1 KB
/
template_parser_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
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 {preserveWhitespacesDefault} from '@angular/compiler';
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeMetadata, CompilePipeSummary, CompileProviderMetadata, CompileTemplateMetadata, CompileTokenMetadata, tokenReference} from '@angular/compiler/src/compile_metadata';
import {DomElementSchemaRegistry} from '@angular/compiler/src/schema/dom_element_schema_registry';
import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, PropertyBindingType, ProviderAstType, ReferenceAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, VariableAst} from '@angular/compiler/src/template_parser/template_ast';
import {splitClasses, TemplateParser} from '@angular/compiler/src/template_parser/template_parser';
import {SchemaMetadata, SecurityContext} from '@angular/core';
import {Console} from '@angular/core/src/console';
import {inject, TestBed} from '@angular/core/testing';
import {JitReflector} from '@angular/platform-browser-dynamic/src/compiler_reflector';
import {createTokenForExternalReference, createTokenForReference, Identifiers} from '../../src/identifiers';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../src/ml_parser/interpolation_config';
import {newArray} from '../../src/util';
import {MockSchemaRegistry} from '../../testing';
import {unparse} from '../expression_parser/utils/unparser';
import {TEST_COMPILER_PROVIDERS} from '../test_bindings';
import {compileDirectiveMetadataCreate, compileTemplateMetadata, createTypeMeta} from './util/metadata';
const someModuleUrl = 'package:someModule';
const MOCK_SCHEMA_REGISTRY = [{
provide: ElementSchemaRegistry,
useValue: new MockSchemaRegistry(
{'invalidProp': false}, {'mappedAttr': 'mappedProp'}, {'unknown': false, 'un-known': false},
['onEvent'], ['onEvent']),
}];
function humanizeTplAst(
templateAsts: TemplateAst[], interpolationConfig?: InterpolationConfig): any[] {
const humanizer = new TemplateHumanizer(false, interpolationConfig);
templateVisitAll(humanizer, templateAsts);
return humanizer.result;
}
function humanizeTplAstSourceSpans(
templateAsts: TemplateAst[], interpolationConfig?: InterpolationConfig): any[] {
const humanizer = new TemplateHumanizer(true, interpolationConfig);
templateVisitAll(humanizer, templateAsts);
return humanizer.result;
}
class TemplateHumanizer implements TemplateAstVisitor {
result: any[] = [];
constructor(
private includeSourceSpan: boolean,
private interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {}
visitNgContent(ast: NgContentAst, context: any): any {
const res = [NgContentAst];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
const res = [EmbeddedTemplateAst];
this.result.push(this._appendSourceSpan(ast, res));
templateVisitAll(this, ast.attrs);
templateVisitAll(this, ast.outputs);
templateVisitAll(this, ast.references);
templateVisitAll(this, ast.variables);
templateVisitAll(this, ast.directives);
templateVisitAll(this, ast.children);
return null;
}
visitElement(ast: ElementAst, context: any): any {
const res = [ElementAst, ast.name];
this.result.push(this._appendSourceSpan(ast, res));
templateVisitAll(this, ast.attrs);
templateVisitAll(this, ast.inputs);
templateVisitAll(this, ast.outputs);
templateVisitAll(this, ast.references);
templateVisitAll(this, ast.directives);
templateVisitAll(this, ast.children);
return null;
}
visitReference(ast: ReferenceAst, context: any): any {
const res = [ReferenceAst, ast.name, ast.value];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitVariable(ast: VariableAst, context: any): any {
const res = [VariableAst, ast.name, ast.value];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitEvent(ast: BoundEventAst, context: any): any {
const res =
[BoundEventAst, ast.name, ast.target, unparse(ast.handler, this.interpolationConfig)];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
const res = [
BoundElementPropertyAst, ast.type, ast.name, unparse(ast.value, this.interpolationConfig),
ast.unit
];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitAttr(ast: AttrAst, context: any): any {
const res = [AttrAst, ast.name, ast.value];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitBoundText(ast: BoundTextAst, context: any): any {
const res = [BoundTextAst, unparse(ast.value, this.interpolationConfig)];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitText(ast: TextAst, context: any): any {
const res = [TextAst, ast.value];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
visitDirective(ast: DirectiveAst, context: any): any {
const res = [DirectiveAst, ast.directive];
this.result.push(this._appendSourceSpan(ast, res));
templateVisitAll(this, ast.inputs);
templateVisitAll(this, ast.hostProperties);
templateVisitAll(this, ast.hostEvents);
return null;
}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
const res = [
BoundDirectivePropertyAst, ast.directiveName, unparse(ast.value, this.interpolationConfig)
];
this.result.push(this._appendSourceSpan(ast, res));
return null;
}
private _appendSourceSpan(ast: TemplateAst, input: any[]): any[] {
if (!this.includeSourceSpan) return input;
input.push(ast.sourceSpan.toString());
return input;
}
}
function humanizeContentProjection(templateAsts: TemplateAst[]): any[] {
const humanizer = new TemplateContentProjectionHumanizer();
templateVisitAll(humanizer, templateAsts);
return humanizer.result;
}
class TemplateContentProjectionHumanizer implements TemplateAstVisitor {
result: any[] = [];
visitNgContent(ast: NgContentAst, context: any): any {
this.result.push(['ng-content', ast.ngContentIndex]);
return null;
}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
this.result.push(['template', ast.ngContentIndex]);
templateVisitAll(this, ast.children);
return null;
}
visitElement(ast: ElementAst, context: any): any {
this.result.push([ast.name, ast.ngContentIndex]);
templateVisitAll(this, ast.children);
return null;
}
visitReference(ast: ReferenceAst, context: any): any {
return null;
}
visitVariable(ast: VariableAst, context: any): any {
return null;
}
visitEvent(ast: BoundEventAst, context: any): any {
return null;
}
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
return null;
}
visitAttr(ast: AttrAst, context: any): any {
return null;
}
visitBoundText(ast: BoundTextAst, context: any): any {
this.result.push([`#text(${unparse(ast.value)})`, ast.ngContentIndex]);
return null;
}
visitText(ast: TextAst, context: any): any {
this.result.push([`#text(${ast.value})`, ast.ngContentIndex]);
return null;
}
visitDirective(ast: DirectiveAst, context: any): any {
return null;
}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
return null;
}
}
class ThrowingVisitor implements TemplateAstVisitor {
visitNgContent(ast: NgContentAst, context: any): any {
throw 'not implemented';
}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
throw 'not implemented';
}
visitElement(ast: ElementAst, context: any): any {
throw 'not implemented';
}
visitReference(ast: ReferenceAst, context: any): any {
throw 'not implemented';
}
visitVariable(ast: VariableAst, context: any): any {
throw 'not implemented';
}
visitEvent(ast: BoundEventAst, context: any): any {
throw 'not implemented';
}
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
throw 'not implemented';
}
visitAttr(ast: AttrAst, context: any): any {
throw 'not implemented';
}
visitBoundText(ast: BoundTextAst, context: any): any {
throw 'not implemented';
}
visitText(ast: TextAst, context: any): any {
throw 'not implemented';
}
visitDirective(ast: DirectiveAst, context: any): any {
throw 'not implemented';
}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
throw 'not implemented';
}
}
class FooAstTransformer extends ThrowingVisitor {
visitElement(ast: ElementAst, context: any): any {
if (ast.name != 'div') return ast;
return new ElementAst(
'foo', [], [], [], [], [], [], false, [], [], ast.ngContentIndex, ast.sourceSpan,
ast.endSourceSpan);
}
}
class BarAstTransformer extends FooAstTransformer {
visitElement(ast: ElementAst, context: any): any {
if (ast.name != 'foo') return ast;
return new ElementAst(
'bar', [], [], [], [], [], [], false, [], [], ast.ngContentIndex, ast.sourceSpan,
ast.endSourceSpan);
}
}
class NullVisitor implements TemplateAstVisitor {
visitNgContent(ast: NgContentAst, context: any): any {}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {}
visitElement(ast: ElementAst, context: any): any {}
visitReference(ast: ReferenceAst, context: any): any {}
visitVariable(ast: VariableAst, context: any): any {}
visitEvent(ast: BoundEventAst, context: any): any {}
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {}
visitAttr(ast: AttrAst, context: any): any {}
visitBoundText(ast: BoundTextAst, context: any): any {}
visitText(ast: TextAst, context: any): any {}
visitDirective(ast: DirectiveAst, context: any): any {}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {}
}
class ArrayConsole implements Console {
logs: string[] = [];
warnings: string[] = [];
log(msg: string) {
this.logs.push(msg);
}
warn(msg: string) {
this.warnings.push(msg);
}
}
(function() {
let ngIf: CompileDirectiveSummary;
let parse: (
template: string, directives: CompileDirectiveSummary[], pipes?: CompilePipeSummary[],
schemas?: SchemaMetadata[], preserveWhitespaces?: boolean) => TemplateAst[];
let console: ArrayConsole;
function configureCompiler() {
console = new ArrayConsole();
beforeEach(() => {
TestBed.configureCompiler({
providers: [
{provide: Console, useValue: console},
],
});
});
}
function commonBeforeEach() {
beforeEach(inject([TemplateParser], (parser: TemplateParser) => {
const someAnimation = ['someAnimation'];
const someTemplate = compileTemplateMetadata({animations: [someAnimation]});
const component = compileDirectiveMetadataCreate({
isHost: false,
selector: 'root',
template: someTemplate,
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'Root'}}),
isComponent: true
});
ngIf = compileDirectiveMetadataCreate({
selector: '[ngIf]',
template: someTemplate,
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'NgIf'}}),
inputs: ['ngIf']
}).toSummary();
parse =
(template: string, directives: CompileDirectiveSummary[],
pipes: CompilePipeSummary[]|null = null, schemas: SchemaMetadata[] = [],
preserveWhitespaces = true): TemplateAst[] => {
if (pipes === null) {
pipes = [];
}
return parser
.parse(
component, template, directives, pipes, schemas, 'TestComp', preserveWhitespaces)
.template;
};
}));
}
describe('TemplateAstVisitor', () => {
function expectVisitedNode(visitor: TemplateAstVisitor, node: TemplateAst) {
expect(node.visit(visitor, null)).toEqual(node);
}
it('should visit NgContentAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitNgContent(ast: NgContentAst, context: any): any {
return ast;
}
}, new NgContentAst(0, 0, null!));
});
it('should visit EmbeddedTemplateAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any) {
return ast;
}
}, new EmbeddedTemplateAst([], [], [], [], [], [], false, [], [], 0, null!));
});
it('should visit ElementAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitElement(ast: ElementAst, context: any) {
return ast;
}
}, new ElementAst('foo', [], [], [], [], [], [], false, [], [], 0, null!, null!));
});
it('should visit RefererenceAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitReference(ast: ReferenceAst, context: any): any {
return ast;
}
}, new ReferenceAst('foo', null!, null!, null!));
});
it('should visit VariableAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitVariable(ast: VariableAst, context: any): any {
return ast;
}
}, new VariableAst('foo', 'bar', null!));
});
it('should visit BoundEventAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitEvent(ast: BoundEventAst, context: any): any {
return ast;
}
}, new BoundEventAst('foo', 'bar', 'goo', null!, null!, null!));
});
it('should visit BoundElementPropertyAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {
return ast;
}
}, new BoundElementPropertyAst('foo', null!, null!, null!, 'bar', null!));
});
it('should visit AttrAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitAttr(ast: AttrAst, context: any): any {
return ast;
}
}, new AttrAst('foo', 'bar', null!));
});
it('should visit BoundTextAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitBoundText(ast: BoundTextAst, context: any): any {
return ast;
}
}, new BoundTextAst(null!, 0, null!));
});
it('should visit TextAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitText(ast: TextAst, context: any): any {
return ast;
}
}, new TextAst('foo', 0, null!));
});
it('should visit DirectiveAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitDirective(ast: DirectiveAst, context: any): any {
return ast;
}
}, new DirectiveAst(null!, [], [], [], 0, null!));
});
it('should visit DirectiveAst', () => {
expectVisitedNode(new class extends NullVisitor {
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {
return ast;
}
}, new BoundDirectivePropertyAst('foo', 'bar', null!, null!));
});
it('should skip the typed call of a visitor if visit() returns a truthy value', () => {
const visitor = new class extends ThrowingVisitor {
visit(ast: TemplateAst, context: any): any {
return true;
}
};
const nodes: TemplateAst[] = [
new NgContentAst(0, 0, null!),
new EmbeddedTemplateAst([], [], [], [], [], [], false, [], [], 0, null!),
new ElementAst('foo', [], [], [], [], [], [], false, [], [], 0, null!, null!),
new ReferenceAst('foo', null!, 'bar', null!), new VariableAst('foo', 'bar', null!),
new BoundEventAst('foo', 'bar', 'goo', null!, null!, null!),
new BoundElementPropertyAst('foo', null!, null!, null!, 'bar', null!),
new AttrAst('foo', 'bar', null!), new BoundTextAst(null!, 0, null!),
new TextAst('foo', 0, null!), new DirectiveAst(null!, [], [], [], 0, null!),
new BoundDirectivePropertyAst('foo', 'bar', null!, null!)
];
const result = templateVisitAll(visitor, nodes, null);
expect(result).toEqual(newArray(nodes.length).fill(true));
});
});
describe('TemplateParser Security', () => {
// Semi-integration test to make sure TemplateParser properly sets the security context.
// Uses the actual DomElementSchemaRegistry.
beforeEach(() => {
TestBed.configureCompiler({
providers: [
TEST_COMPILER_PROVIDERS,
{provide: ElementSchemaRegistry, useClass: DomElementSchemaRegistry, deps: []}
]
});
});
configureCompiler();
commonBeforeEach();
describe('security context', () => {
function secContext(tpl: string): SecurityContext {
const ast = parse(tpl, []);
const propBinding = (<ElementAst>ast[0]).inputs[0];
return propBinding.securityContext;
}
it('should set for properties', () => {
expect(secContext('<div [title]="v">')).toBe(SecurityContext.NONE);
expect(secContext('<div [innerHTML]="v">')).toBe(SecurityContext.HTML);
});
it('should set for property value bindings', () => {
expect(secContext('<div innerHTML="{{v}}">')).toBe(SecurityContext.HTML);
});
it('should set for attributes', () => {
expect(secContext('<a [attr.href]="v">')).toBe(SecurityContext.URL);
// NB: attributes below need to change case.
expect(secContext('<a [attr.innerHtml]="v">')).toBe(SecurityContext.HTML);
expect(secContext('<a [attr.formaction]="v">')).toBe(SecurityContext.URL);
});
it('should set for style', () => {
expect(secContext('<a [style.backgroundColor]="v">')).toBe(SecurityContext.STYLE);
});
});
});
describe('TemplateParser', () => {
beforeEach(() => {
TestBed.configureCompiler({providers: [TEST_COMPILER_PROVIDERS, MOCK_SCHEMA_REGISTRY]});
});
configureCompiler();
commonBeforeEach();
describe('parse', () => {
describe('nodes without bindings', () => {
it('should parse text nodes', () => {
expect(humanizeTplAst(parse('a', []))).toEqual([[TextAst, 'a']]);
});
it('should parse elements with attributes', () => {
expect(humanizeTplAst(parse('<div a=b>', []))).toEqual([
[ElementAst, 'div'], [AttrAst, 'a', 'b']
]);
});
});
it('should parse ngContent', () => {
const parsed = parse('<ng-content select="a"></ng-content>', []);
expect(humanizeTplAst(parsed)).toEqual([[NgContentAst]]);
});
it('should parse ngContent when it contains WS only', () => {
const parsed = parse('<ng-content select="a"> \n </ng-content>', []);
expect(humanizeTplAst(parsed)).toEqual([[NgContentAst]]);
});
it('should parse ngContent regardless the namespace', () => {
const parsed = parse('<svg><ng-content></ng-content></svg>', []);
expect(humanizeTplAst(parsed)).toEqual([
[ElementAst, ':svg:svg'],
[NgContentAst],
]);
});
it('should parse bound text nodes', () => {
expect(humanizeTplAst(parse('{{a}}', []))).toEqual([[BoundTextAst, '{{ a }}']]);
});
it('should parse bound text nodes inside quotes', () => {
expect(humanizeTplAst(parse('"{{a}}"', []))).toEqual([[BoundTextAst, '"{{ a }}"']]);
});
it('should parse bound text nodes with interpolations inside quotes', () => {
expect(humanizeTplAst(parse('{{ "{{a}}" }}', []))).toEqual([[BoundTextAst, '{{ "{{a}}" }}']]);
});
it('should not parse bound text nodes with mismatching quotes', () => {
expect(humanizeTplAst(parse(`{{ "{{a}}' }}`, []))).toEqual([[TextAst, `{{ "{{a}}' }}`]]);
});
it('should parse with custom interpolation config',
inject([TemplateParser], (parser: TemplateParser) => {
const component = CompileDirectiveMetadata.create({
selector: 'test',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'Test'}}),
isComponent: true,
template: new CompileTemplateMetadata({
interpolation: ['{%', '%}'],
isInline: false,
animations: [],
template: null,
templateUrl: null,
htmlAst: null,
ngContentSelectors: [],
externalStylesheets: [],
styleUrls: [],
styles: [],
encapsulation: null,
preserveWhitespaces: preserveWhitespacesDefault(null),
}),
isHost: false,
exportAs: null,
changeDetection: null,
inputs: [],
outputs: [],
host: {},
providers: [],
viewProviders: [],
queries: [],
guards: {},
viewQueries: [],
entryComponents: [],
componentViewType: null,
rendererType: null,
componentFactory: null
});
expect(humanizeTplAst(
parser.parse(component, '{%a%}', [], [], [], 'TestComp', true).template,
{start: '{%', end: '%}'}))
.toEqual([[BoundTextAst, '{% a %}']]);
}));
describe('bound properties', () => {
it('should parse mixed case bound properties', () => {
expect(humanizeTplAst(parse('<div [someProp]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null]
]);
});
it('should parse dash case bound properties', () => {
expect(humanizeTplAst(parse('<div [some-prop]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'some-prop', 'v', null]
]);
});
it('should parse dotted name bound properties', () => {
expect(humanizeTplAst(parse('<div [dot.name]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'dot.name', 'v', null]
]);
});
it('should normalize property names via the element schema', () => {
expect(humanizeTplAst(parse('<div [mappedAttr]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'mappedProp', 'v', null]
]);
});
it('should parse mixed case bound attributes', () => {
expect(humanizeTplAst(parse('<div [attr.someAttr]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr', 'v', null]
]);
});
it('should parse mixed case bound attributes with dot in the attribute name', () => {
expect(humanizeTplAst(parse('<div [attr.someAttr.someAttrSuffix]="v">', []))).toEqual([
[ElementAst, 'div'],
[
BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr.someAttrSuffix', 'v',
null
]
]);
});
it('should parse and dash case bound classes', () => {
expect(humanizeTplAst(parse('<div [class.some-class]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Class, 'some-class', 'v', null]
]);
});
it('should parse mixed case bound classes', () => {
expect(humanizeTplAst(parse('<div [class.someClass]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Class, 'someClass', 'v', null]
]);
});
it('should parse mixed case bound styles', () => {
expect(humanizeTplAst(parse('<div [style.someStyle]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Style, 'someStyle', 'v', null]
]);
});
describe('errors', () => {
it('should throw error when binding to an unknown property', () => {
expect(() => parse('<my-component [invalidProp]="bar"></my-component>', []))
.toThrowError(`Template parse errors:
Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.
1. If 'my-component' is an Angular component and it has 'invalidProp' input, then verify that it is part of this module.
2. If 'my-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("<my-component [ERROR ->][invalidProp]="bar"></my-component>"): TestComp@0:14`);
});
it('should throw error when binding to an unknown property of ng-container', () => {
expect(() => parse('<ng-container [invalidProp]="bar"></ng-container>', []))
.toThrowError(
`Template parse errors:
Can't bind to 'invalidProp' since it isn't a known property of 'ng-container'.
1. If 'invalidProp' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.` +
` ("<ng-container [ERROR ->][invalidProp]="bar"></ng-container>"): TestComp@0:14`);
});
it('should throw error when binding to an unknown element w/o bindings', () => {
expect(() => parse('<unknown></unknown>', [])).toThrowError(`Template parse errors:
'unknown' is not a known element:
1. If 'unknown' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("[ERROR ->]<unknown></unknown>"): TestComp@0:0`);
});
it('should throw error when binding to an unknown custom element w/o bindings', () => {
expect(() => parse('<un-known></un-known>', [])).toThrowError(`Template parse errors:
'un-known' is not a known element:
1. If 'un-known' is an Angular component, then verify that it is part of this module.
2. If 'un-known' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<un-known></un-known>"): TestComp@0:0`);
});
it('should throw error when binding to an invalid property', () => {
expect(() => parse('<my-component [onEvent]="bar"></my-component>', []))
.toThrowError(`Template parse errors:
Binding to property 'onEvent' is disallowed for security reasons ("<my-component [ERROR ->][onEvent]="bar"></my-component>"): TestComp@0:14`);
});
it('should throw error when binding to an invalid attribute', () => {
expect(() => parse('<my-component [attr.onEvent]="bar"></my-component>', []))
.toThrowError(`Template parse errors:
Binding to attribute 'onEvent' is disallowed for security reasons ("<my-component [ERROR ->][attr.onEvent]="bar"></my-component>"): TestComp@0:14`);
});
});
it('should parse bound properties via [...] and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div [prop]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null]
]);
});
it('should parse bound properties via bind- and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div bind-prop="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null]
]);
});
it('should report missing property names in bind- syntax', () => {
expect(() => parse('<div bind-></div>', [])).toThrowError(`Template parse errors:
Property name is missing in binding ("<div [ERROR ->]bind-></div>"): TestComp@0:5`);
});
it('should parse bound properties via {{...}} and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div prop="{{v}}">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null]
]);
});
it('should parse bound properties via bind-animate- and not report them as attributes',
() => {
expect(humanizeTplAst(parse('<div bind-animate-someAnimation="value2">', [], [], [])))
.toEqual([
[ElementAst, 'div'],
[
BoundElementPropertyAst, PropertyBindingType.Animation, 'someAnimation',
'value2', null
]
]);
});
it('should throw an error when parsing detects non-bound properties via @ that contain a value',
() => {
expect(() => {
parse('<div @someAnimation="value2">', [], [], []);
})
.toThrowError(
/Assigning animation triggers via @prop="exp" attributes with an expression is invalid. Use property bindings \(e.g. \[@prop\]="exp"\) or use an attribute without a value \(e.g. @prop\) instead. \("<div \[ERROR ->\]@someAnimation="value2">"\): TestComp@0:5/);
});
it('should report missing animation trigger in @ syntax', () => {
expect(() => parse('<div @></div>', [])).toThrowError(`Template parse errors:
Animation trigger is missing ("<div [ERROR ->]@></div>"): TestComp@0:5`);
});
it('should not issue a warning when host attributes contain a valid property-bound animation trigger',
() => {
const animationEntries = ['prop'];
const dirA = compileDirectiveMetadataCreate({
selector: 'div',
template: compileTemplateMetadata({animations: animationEntries}),
type: createTypeMeta({
reference: {filePath: someModuleUrl, name: 'DirA'},
}),
host: {'[@prop]': 'expr'}
}).toSummary();
humanizeTplAst(parse('<div></div>', [dirA]));
expect(console.warnings.length).toEqual(0);
});
it('should throw descriptive error when a host binding is not a string expression', () => {
const dirA = compileDirectiveMetadataCreate({
selector: 'broken',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}}),
host: {'[class.foo]': null!}
}).toSummary();
expect(() => {
parse('<broken></broken>', [dirA]);
})
.toThrowError(
`Template parse errors:\nValue of the host property binding "class.foo" needs to be a string representing an expression but got "null" (object) ("[ERROR ->]<broken></broken>"): TestComp@0:0, Directive DirA`);
});
it('should throw descriptive error when a host event is not a string expression', () => {
const dirA = compileDirectiveMetadataCreate({
selector: 'broken',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}}),
host: {'(click)': null!}
}).toSummary();
expect(() => {
parse('<broken></broken>', [dirA]);
})
.toThrowError(
`Template parse errors:\nValue of the host listener "click" needs to be a string representing an expression but got "null" (object) ("[ERROR ->]<broken></broken>"): TestComp@0:0, Directive DirA`);
});
it('should not issue a warning when an animation property is bound without an expression',
() => {
humanizeTplAst(parse('<div @someAnimation>', [], [], []));
expect(console.warnings.length).toEqual(0);
});
it('should parse bound properties via [@] and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div [@someAnimation]="value2">', [], [], []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Animation, 'someAnimation', 'value2', null]
]);
});
it('should support * directives', () => {
expect(humanizeTplAst(parse('<div *ngIf>', [ngIf]))).toEqual([
[EmbeddedTemplateAst],
[DirectiveAst, ngIf],
[BoundDirectivePropertyAst, 'ngIf', 'null'],
[ElementAst, 'div'],
]);
});
it('should support <ng-template>', () => {
expect(humanizeTplAst(parse('<ng-template>', []))).toEqual([
[EmbeddedTemplateAst],
]);
});
it('should treat <template> as a regular tag', () => {
expect(humanizeTplAst(parse('<template>', []))).toEqual([
[ElementAst, 'template'],
]);
});
it('should not special case the template attribute', () => {
expect(humanizeTplAst(parse('<p template="ngFor">', []))).toEqual([
[ElementAst, 'p'],
[AttrAst, 'template', 'ngFor'],
]);
});
});
describe('events', () => {
it('should parse bound events with a target', () => {
expect(humanizeTplAst(parse('<div (window:event)="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundEventAst, 'event', 'window', 'v'],
]);
});
it('should report an error on empty expression', () => {
expect(() => parse('<div (event)="">', []))
.toThrowError(/Empty expressions are not allowed/);
expect(() => parse('<div (event)=" ">', []))
.toThrowError(/Empty expressions are not allowed/);
});
it('should parse bound events via (...) and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div (event)="v">', []))).toEqual([
[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']
]);
});
it('should parse event names case sensitive', () => {
expect(humanizeTplAst(parse('<div (some-event)="v">', []))).toEqual([
[ElementAst, 'div'], [BoundEventAst, 'some-event', null, 'v']
]);
expect(humanizeTplAst(parse('<div (someEvent)="v">', []))).toEqual([
[ElementAst, 'div'], [BoundEventAst, 'someEvent', null, 'v']
]);
});
it('should parse bound events via on- and not report them as attributes', () => {
expect(humanizeTplAst(parse('<div on-event="v">', []))).toEqual([
[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']
]);
});
it('should report missing event names in on- syntax', () => {
expect(() => parse('<div on-></div>', [])).toThrowError(/Event name is missing in binding/);
});
it('should allow events on explicit embedded templates that are emitted by a directive',
() => {
const dirA = compileDirectiveMetadataCreate({
selector: 'ng-template',
outputs: ['e'],
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
}).toSummary();
expect(humanizeTplAst(parse('<ng-template (e)="f"></ng-template>', [dirA]))).toEqual([
[EmbeddedTemplateAst],
[BoundEventAst, 'e', null, 'f'],
[DirectiveAst, dirA],
]);
});
});
describe('bindon', () => {
it('should parse bound events and properties via [(...)] and not report them as attributes',
() => {
expect(humanizeTplAst(parse('<div [(prop)]="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null],
[BoundEventAst, 'propChange', null, 'v = $event']
]);
});
it('should parse bound events and properties via bindon- and not report them as attributes',
() => {
expect(humanizeTplAst(parse('<div bindon-prop="v">', []))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null],
[BoundEventAst, 'propChange', null, 'v = $event']
]);
});
it('should report missing property names in bindon- syntax', () => {
expect(() => parse('<div bindon-></div>', []))
.toThrowError(/Property name is missing in binding/);
});
});
describe('directives', () => {
it('should order directives by the directives array in the View and match them only once',
() => {
const dirA = compileDirectiveMetadataCreate({
selector: '[a]',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
}).toSummary();
const dirB = compileDirectiveMetadataCreate({
selector: '[b]',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirB'}})
}).toSummary();
const dirC = compileDirectiveMetadataCreate({
selector: '[c]',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirC'}})
}).toSummary();
expect(humanizeTplAst(parse('<div a c b a b>', [dirA, dirB, dirC]))).toEqual([
[ElementAst, 'div'], [AttrAst, 'a', ''], [AttrAst, 'c', ''], [AttrAst, 'b', ''],
[AttrAst, 'a', ''], [AttrAst, 'b', ''], [DirectiveAst, dirA], [DirectiveAst, dirB],
[DirectiveAst, dirC]
]);
});
it('should parse directive dotted properties', () => {
const dirA = compileDirectiveMetadataCreate({
selector: '[dot.name]',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}}),
inputs: ['localName: dot.name'],
}).toSummary();
expect(humanizeTplAst(parse('<div [dot.name]="expr"></div>', [dirA]))).toEqual([
[ElementAst, 'div'],
[DirectiveAst, dirA],
[BoundDirectivePropertyAst, 'localName', 'expr'],
]);
});
it('should locate directives in property bindings', () => {
const dirA = compileDirectiveMetadataCreate({
selector: '[a=b]',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirA'}})
}).toSummary();
const dirB = compileDirectiveMetadataCreate({
selector: '[b]',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'DirB'}})
}).toSummary();
expect(humanizeTplAst(parse('<div [a]="b">', [dirA, dirB]))).toEqual([
[ElementAst, 'div'],
[BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'b', null],
[DirectiveAst, dirA]
]);
});
it('should locate directives in inline templates', () => {
const dirTemplate =
compileDirectiveMetadataCreate({
selector: 'ng-template',
type: createTypeMeta({reference: {filePath: someModuleUrl, name: 'onTemplate'}})
}).toSummary();
expect(humanizeTplAst(parse('<div *ngIf="cond">', [ngIf, dirTemplate]))).toEqual([
[EmbeddedTemplateAst],
[DirectiveAst, ngIf],
[BoundDirectivePropertyAst, 'ngIf', 'cond'],
[DirectiveAst, dirTemplate],
[ElementAst, 'div'],
]);
});
it('should locate directives in event bindings', () => {
const dirA = compileDirectiveMetadataCreate({