-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathintegration_test.rs
More file actions
3903 lines (3455 loc) · 135 KB
/
integration_test.rs
File metadata and controls
3903 lines (3455 loc) · 135 KB
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
//! Integration tests for the Angular template compiler.
//!
//! These tests verify the complete compilation pipeline from
//! HTML template string to JavaScript output.
use oxc_allocator::Allocator;
use oxc_angular_compiler::{
AngularVersion, ResolvedResources, TransformOptions as ComponentTransformOptions,
output::ast::FunctionExpr,
output::emitter::JsEmitter,
parser::html::HtmlParser,
pipeline::{emit::compile_template, ingest::ingest_component},
transform::html_to_r3::{HtmlToR3Transform, TransformOptions},
transform_angular_file,
};
use oxc_span::Atom;
/// Compiles an Angular template to JavaScript.
fn compile_template_to_js(template: &str, component_name: &str) -> String {
let allocator = Allocator::default();
// Stage 1: Parse HTML (with expansion forms enabled for ICU/plural support)
let parser = HtmlParser::with_expansion_forms(&allocator, template, "test.html");
let html_result = parser.parse();
// Check for parse errors
if !html_result.errors.is_empty() {
let errors: Vec<_> = html_result.errors.iter().map(|e| e.msg.clone()).collect();
panic!("HTML parse errors: {errors:?}");
}
// Stage 2: Transform HTML AST to R3 AST
let transformer = HtmlToR3Transform::new(&allocator, template, TransformOptions::default());
let r3_result = transformer.transform(&html_result.nodes);
// Check for transform errors
if !r3_result.errors.is_empty() {
let errors: Vec<_> = r3_result.errors.iter().map(|e| e.msg.clone()).collect();
panic!("Transform errors: {errors:?}");
}
// Stage 3: Ingest R3 AST into IR
let mut job = ingest_component(&allocator, Atom::from(component_name), r3_result.nodes);
// Stage 4-5: Transform and emit
let result = compile_template(&mut job);
// Stage 6: Generate JavaScript
let emitter = JsEmitter::new();
// Emit declarations first (embedded view functions, constants)
let mut output = String::new();
for decl in &result.declarations {
output.push_str(&emitter.emit_statement(decl));
output.push('\n');
}
// Emit the main template function
output.push_str(&emit_function(&emitter, &result.template_fn));
output
}
/// Emit a FunctionExpr to JavaScript.
///
/// We emit statements individually since the emitter can work with references.
fn emit_function(emitter: &JsEmitter, func: &FunctionExpr<'_>) -> String {
// Build the function header
let mut result = String::new();
result.push_str("function ");
if let Some(ref name) = func.name {
result.push_str(name.as_str());
}
result.push('(');
for (i, param) in func.params.iter().enumerate() {
if i > 0 {
result.push(',');
}
result.push_str(param.name.as_str());
}
result.push_str(") {\n");
// Emit each statement
for stmt in &func.statements {
let stmt_str = emitter.emit_statement(stmt);
for line in stmt_str.lines() {
result.push_str(" ");
result.push_str(line);
result.push('\n');
}
}
result.push('}');
result
}
// ============================================================================
// Basic Element Tests
// ============================================================================
#[test]
fn test_empty_template() {
let js = compile_template_to_js("", "TestComponent");
insta::assert_snapshot!("empty_template", js);
}
#[test]
fn test_simple_element() {
let js = compile_template_to_js("<div></div>", "TestComponent");
insta::assert_snapshot!("simple_element", js);
}
#[test]
fn test_element_with_text() {
let js = compile_template_to_js("<div>Hello World</div>", "TestComponent");
insta::assert_snapshot!("element_with_text", js);
}
#[test]
fn test_nested_elements() {
let js = compile_template_to_js("<div><span>Inner</span></div>", "TestComponent");
insta::assert_snapshot!("nested_elements", js);
}
#[test]
fn test_void_element() {
let js = compile_template_to_js("<input>", "TestComponent");
insta::assert_snapshot!("void_element", js);
}
// ============================================================================
// Text Interpolation Tests
// ============================================================================
#[test]
fn test_text_interpolation() {
let js = compile_template_to_js("<div>{{name}}</div>", "TestComponent");
insta::assert_snapshot!("text_interpolation", js);
}
#[test]
fn test_multiple_interpolations() {
let js = compile_template_to_js("<div>{{first}} and {{second}}</div>", "TestComponent");
insta::assert_snapshot!("multiple_interpolations", js);
}
#[test]
fn test_html_entity_between_interpolations() {
// HTML entity × between two interpolations should produce literal UTF-8 in the output
let js = compile_template_to_js("<div>{{ a }}×{{ b }}</div>", "TestComponent");
// Should produce: textInterpolate2("", ctx.a, "\u{00D7}", ctx.b)
// Note: × (multiplication sign) = U+00D7, emitted as literal UTF-8
assert!(
js.contains("textInterpolate2(\"\",ctx.a,\"\u{00D7}\",ctx.b)"),
"Expected textInterpolate2 with literal times character. Got:\n{js}"
);
}
#[test]
fn test_html_entity_at_start_of_interpolation() {
// Entity at start: ×{{ a }}
let js = compile_template_to_js("<div>×{{ a }}</div>", "TestComponent");
// Should produce: textInterpolate1("\u{00D7}", ctx.a)
// Note: × (multiplication sign) = U+00D7, emitted as literal UTF-8
assert!(
js.contains("textInterpolate1(\"\u{00D7}\",ctx.a)")
|| js.contains("textInterpolate(\"\u{00D7}\",ctx.a)"),
"Expected textInterpolate with literal times character at start. Got:\n{js}"
);
}
#[test]
fn test_multiple_html_entities_between_interpolations() {
// Multiple entities: {{ a }} × {{ b }}
let js =
compile_template_to_js("<div>{{ a }} × {{ b }}</div>", "TestComponent");
// Should produce: textInterpolate2("", ctx.a, "\u{00A0}\u{00D7}\u{00A0}", ctx.b)
// Note: = U+00A0, × = U+00D7, both emitted as literal UTF-8
assert!(
js.contains("textInterpolate2(\"\",ctx.a,\"\u{00A0}\u{00D7}\u{00A0}\",ctx.b)"),
"Expected textInterpolate2 with literal Unicode entities. Got:\n{js}"
);
}
#[test]
fn test_interpolation_with_expression() {
let js = compile_template_to_js("<div>{{user.name}}</div>", "TestComponent");
insta::assert_snapshot!("interpolation_with_expression", js);
}
// ============================================================================
// Property Binding Tests
// ============================================================================
#[test]
fn test_property_binding() {
let js = compile_template_to_js(r#"<div [title]="myTitle"></div>"#, "TestComponent");
insta::assert_snapshot!("property_binding", js);
}
#[test]
fn test_attribute_binding() {
let js = compile_template_to_js(r#"<div [attr.aria-label]="label"></div>"#, "TestComponent");
insta::assert_snapshot!("attribute_binding", js);
}
#[test]
fn test_attribute_binding_with_interpolation() {
// Test attr.* with interpolation (e.g., attr.viewBox="0 0 {{ size }} {{ size }}")
// This should use ɵɵattribute with the prefix stripped
let js = compile_template_to_js(
r#"<svg attr.viewBox="0 0 {{ svgSize }} {{ svgSize }}"></svg>"#,
"TestComponent",
);
insta::assert_snapshot!("attribute_binding_with_interpolation", js);
}
#[test]
fn test_class_binding() {
let js = compile_template_to_js(r#"<div [class.active]="isActive"></div>"#, "TestComponent");
insta::assert_snapshot!("class_binding", js);
}
#[test]
fn test_style_binding() {
let js = compile_template_to_js(r#"<div [style.color]="textColor"></div>"#, "TestComponent");
insta::assert_snapshot!("style_binding", js);
}
#[test]
fn test_style_binding_camel_case() {
// Test that camelCase style properties are converted to kebab-case
let js = compile_template_to_js(
r#"<div [style.backgroundColor]="bgColor" [style.fontSize]="size"></div>"#,
"TestComponent",
);
insta::assert_snapshot!("style_binding_camel_case", js);
}
// ============================================================================
// Event Binding Tests
// ============================================================================
#[test]
fn test_event_binding() {
let js =
compile_template_to_js(r#"<button (click)="handleClick()"></button>"#, "TestComponent");
insta::assert_snapshot!("event_binding", js);
}
#[test]
fn test_event_with_event_object() {
let js = compile_template_to_js(r#"<input (input)="handleInput($event)">"#, "TestComponent");
insta::assert_snapshot!("event_with_event_object", js);
}
#[test]
fn test_sequence_expression_in_event_handler() {
// Test that sequence expressions (multiple statements separated by `;`)
// in event handlers are properly preserved.
// For example: `(blur)="isInputFocused.set(false); onTouch()"`
// Should produce:
// ctx.isInputFocused.set(false); // First statement
// return ctx.onTouch(); // Last statement wrapped in return
let js = compile_template_to_js(
r#"<input (blur)="isInputFocused.set(false); onTouch()">"#,
"TestComponent",
);
insta::assert_snapshot!("sequence_expression_in_event_handler", js);
}
#[test]
fn test_sequence_expression_with_template_ref() {
// Test that sequence expressions in event handlers work correctly
// when there's a template reference on the element.
// This reproduces an issue where the first statement would use `_unnamed_X`
// instead of `ctx`.
let js = compile_template_to_js(
r#"<form>
<input #input (blur)="isInputFocused.set(false); onTouch()"/>
<button *ngIf="showBtn">test</button>
</form>"#,
"TestComponent",
);
insta::assert_snapshot!("sequence_expression_with_template_ref", js);
}
// ============================================================================
// Two-way Binding Tests
// ============================================================================
#[test]
fn test_two_way_binding() {
let js = compile_template_to_js(r#"<input [(ngModel)]="name">"#, "TestComponent");
insta::assert_snapshot!("two_way_binding", js);
}
// ============================================================================
// Template Reference Tests
// ============================================================================
#[test]
fn test_template_reference() {
let js = compile_template_to_js(
r#"<input #myInput><button (click)="myInput.focus()"></button>"#,
"TestComponent",
);
insta::assert_snapshot!("template_reference", js);
}
#[test]
fn test_unused_template_reference() {
// The #unusedRef reference is declared but not used in the click handler
// The optimizer should remove the reference variable from the listener
let js = compile_template_to_js(
r#"<input #unusedRef><button (click)="doSomething()"></button>"#,
"TestComponent",
);
insta::assert_snapshot!("unused_template_reference", js);
}
#[test]
fn test_multiple_refs_partial_use() {
// Multiple references declared, but only one is used in the click handler
// The optimizer should keep only the used reference (usedRef) and remove the unused ones
let js = compile_template_to_js(
r#"<input #usedRef><input #unusedRef1><input #unusedRef2><button (click)="usedRef.focus()"></button>"#,
"TestComponent",
);
insta::assert_snapshot!("multiple_refs_partial_use", js);
}
// ============================================================================
// Control Flow Tests
// ============================================================================
#[test]
fn test_if_block() {
let js = compile_template_to_js(r"@if (condition) { <div>Visible</div> }", "TestComponent");
insta::assert_snapshot!("if_block", js);
}
#[test]
fn test_if_else_block() {
let js = compile_template_to_js(
r"@if (condition) { <div>True</div> } @else { <div>False</div> }",
"TestComponent",
);
insta::assert_snapshot!("if_else_block", js);
}
#[test]
fn test_if_else_block_with_different_classes() {
let js = compile_template_to_js(
r#"@if (condition) { <div class="class-a">True</div> } @else { <div class="class-b">False</div> }"#,
"TestComponent",
);
insta::assert_snapshot!("if_else_block_with_different_classes", js);
}
#[test]
fn test_conditional_alias_with_listener() {
// Test @if with alias (as) where the alias is used in a listener handler
// This tests that:
// 1. restoreView() result is assigned directly to the alias variable
// 2. No intermediate ctx_r5 variable followed by const parent_r7 = ctx_r5
// 3. In update blocks, the alias should have const parent_r6 = ctx
let js = compile_template_to_js(
r#"@if (getParent(renderedOptions); as parent) {
<button (click)="viewOption(parent, $event)">Click me</button>
}"#,
"TestComponent",
);
insta::assert_snapshot!("conditional_alias_with_listener", js);
}
#[test]
fn test_conditional_alias_with_binding_and_listener() {
// Test @if with alias where the alias is used both in bindings and listener
// This tests that:
// 1. restoreView() result is assigned directly to the alias variable in listener
// 2. In update blocks, the alias should have const parent = ctx
let js = compile_template_to_js(
r#"@if (getParent(renderedOptions); as parent) {
<button [class.active]="parent.active" (click)="viewOption(parent, $event)">{{parent.label}}</button>
}"#,
"TestComponent",
);
insta::assert_snapshot!("conditional_alias_with_binding_and_listener", js);
}
#[test]
fn test_bitwarden_if_else_template() {
// Simplified bitwarden template that should produce different const indices
let js = compile_template_to_js(
r#"@if (showWarning | async) {
<div class="tw-h-screen tw-flex tw-justify-center tw-items-center tw-p-4">
Warning content
</div>
} @else {
<div class="tw-h-screen tw-w-screen">
Main content
</div>
}"#,
"AppComponent",
);
insta::assert_snapshot!("bitwarden_if_else_template", js);
}
#[test]
fn test_for_block() {
let js = compile_template_to_js(
r"@for (item of items; track item.id) { <div>{{item.name}}</div> }",
"TestComponent",
);
insta::assert_snapshot!("for_block", js);
}
#[test]
fn test_for_with_empty() {
let js = compile_template_to_js(
r"@for (item of items; track item.id) { <div>{{item.name}}</div> } @empty { <div>No items</div> }",
"TestComponent",
);
insta::assert_snapshot!("for_with_empty", js);
}
#[test]
fn test_switch_block() {
let js = compile_template_to_js(
r"@switch (value) { @case (1) { <div>One</div> } @case (2) { <div>Two</div> } @default { <div>Other</div> } }",
"TestComponent",
);
insta::assert_snapshot!("switch_block", js);
}
#[test]
fn test_switch_block_default_first() {
// Test @switch with @default appearing first - Angular should reorder to put @default last
let js = compile_template_to_js(
r"@switch (value) { @default { <div>Other</div> } @case (1) { <div>One</div> } @case (2) { <div>Two</div> } }",
"TestComponent",
);
insta::assert_snapshot!("switch_block_default_first", js);
}
#[test]
fn test_if_alias_with_switch() {
// Test @if with alias (as data) followed by @switch (data.xxx)
// This is the pattern from Fido2Component that was generating unnecessary
// const data_r13 = ctx; instead of using ctx.xxx directly
let js = compile_template_to_js(
r#"@if (data$ | async; as data) {
@switch (data.message.type) {
@case ("ConfirmNewCredential") { <div>Confirm</div> }
@case ("PickCredential") { <div>Pick</div> }
@default { <div>Other</div> }
}
}"#,
"TestComponent",
);
insta::assert_snapshot!("if_alias_with_switch", js);
}
// ============================================================================
// Defer Block Tests
// ============================================================================
#[test]
fn test_defer_block() {
let js = compile_template_to_js(r"@defer { <heavy-component /> }", "TestComponent");
insta::assert_snapshot!("defer_block", js);
}
#[test]
fn test_defer_with_loading() {
let js = compile_template_to_js(
r"@defer { <heavy-component /> } @loading { <div>Loading...</div> }",
"TestComponent",
);
insta::assert_snapshot!("defer_with_loading", js);
}
#[test]
fn test_defer_on_viewport() {
let js =
compile_template_to_js(r"@defer (on viewport) { <heavy-component /> }", "TestComponent");
insta::assert_snapshot!("defer_on_viewport", js);
}
#[test]
#[should_panic(
expected = "Cannot specify additional `hydrate` triggers if `hydrate never` is present"
)]
fn test_hydrate_never_mutual_exclusivity() {
// This should fail because "hydrate never" cannot be combined with other hydrate triggers
compile_template_to_js(
r"@defer (hydrate never; hydrate on idle) { <heavy-component /> }",
"TestComponent",
);
}
// ============================================================================
// Let Declaration Tests
// ============================================================================
#[test]
fn test_let_declaration() {
let js = compile_template_to_js(
r"@let greeting = 'Hello'; <div>{{greeting}}</div>",
"TestComponent",
);
insta::assert_snapshot!("let_declaration", js);
}
#[test]
fn test_let_in_child_view() {
// @let used inside @if (child view) should have declareLet and storeLet
let js = compile_template_to_js(r"@let value = 123; @if (true) { {{value}} }", "TestComponent");
insta::assert_snapshot!("let_in_child_view", js);
}
#[test]
fn test_let_in_property_binding_same_view() {
// @let used only in property bindings in same view - should NOT have declareLet
// This mimics the bitwarden layout.component.html case
let js = compile_template_to_js(
r#"@let id = "test-id"; <div [id]="id" [attr.data-id]="id"></div>"#,
"TestComponent",
);
insta::assert_snapshot!("let_in_property_binding_same_view", js);
}
#[test]
fn test_let_used_in_ngif_child_view() {
// @let used inside *ngIf (which creates a child view) SHOULD have declareLet and storeLet
// This mimics the bitwarden anon-layout.component.html case:
// @let iconInput = icon(); <div *ngIf="iconInput !== null"><bit-icon [icon]="iconInput"></bit-icon></div>
let js = compile_template_to_js(
r#"@let val = getData(); <div *ngIf="val !== null"><span [title]="val">{{val}}</span></div>"#,
"TestComponent",
);
insta::assert_snapshot!("let_used_in_ngif_child_view", js);
}
#[test]
fn test_let_inside_for_if_with_component_method_call() {
// Reproduces the _unnamed_N bug from ClickUp's stylesheet-viewer.component.html.
//
// Pattern: @for → @if → TWO @let declarations calling component methods
//
// When there are two @let expressions that both need the component context,
// the context variable can't be inlined (used twice) and must be extracted
// as a named variable like `const ctx_rN = i0.ɵɵnextContext()`.
//
// Expected (Angular):
// const item_rN = i0.ɵɵnextContext().$implicit;
// const ctx_rN = i0.ɵɵnextContext();
// i0.ɵɵstoreLet(ctx_rN.computeA(item_rN.id));
// ...
// const b_rN = i0.ɵɵstoreLet(ctx_rN.computeB(item_rN.text));
//
// Actual (Oxc bug):
// const item_rN = i0.ɵɵnextContext().$implicit;
// i0.ɵɵstoreLet(_unnamed_N.computeA(item_rN.id));
// ...
// const b_rN = i0.ɵɵstoreLet(i0.ɵɵnextContext().computeB(item_rN.text));
let js = compile_template_to_js(
r"@for (item of items; track item) { @if (showDetail()) { @let a = computeA(item.id); @let b = computeB(item.text); @if (a > 0) { <div>{{b}}</div> } } }",
"TestComponent",
);
// The output must NOT contain _unnamed_ - all variables should be properly named
assert!(
!js.contains("_unnamed_"),
"Generated JS contains _unnamed_ references, indicating a naming bug.\nGenerated JS:\n{js}"
);
insta::assert_snapshot!("let_inside_for_if_with_component_method_call", js);
}
// ============================================================================
// @let with pipe in child view Tests
// ============================================================================
#[test]
fn test_let_with_pipe_used_in_child_view() {
// @let with pipe used in a child view (@if block) should keep BOTH declareLet and storeLet.
//
// When a @let wraps a pipe and is referenced from a child view:
// - declareLet is needed because pipes use DI which requires the TNode
// - storeLet is needed because the @let is accessed from another view via readContextLet
//
// Without storeLet, the pipe's varOffset would be wrong because storeLet contributes
// 1 var to the var counting, and removing it shifts all subsequent varOffsets.
//
// Expected Angular output:
// i0.ɵɵstoreLet(i0.ɵɵpipeBind1(1, varOffset, ctx.name));
//
// Bug output (missing storeLet):
// i0.ɵɵpipeBind1(1, varOffset, ctx.name);
let js = compile_template_to_js(
r"@let value = name | uppercase; @if (true) { {{value}} }",
"TestComponent",
);
// storeLet must wrap pipeBind because @let is used externally (in child @if view)
assert!(
js.contains("ɵɵstoreLet(i0.ɵɵpipeBind1("),
"storeLet should wrap pipeBind1 when @let with pipe is used in child view. Output:\n{js}"
);
// declareLet must be present (pipes need TNode for DI)
assert!(
js.contains("ɵɵdeclareLet("),
"declareLet should be present when @let contains a pipe. Output:\n{js}"
);
// readContextLet must be present in the child view
assert!(
js.contains("ɵɵreadContextLet("),
"readContextLet should be present in child view. Output:\n{js}"
);
insta::assert_snapshot!("let_with_pipe_used_in_child_view", js);
}
#[test]
fn test_let_with_pipe_used_in_listener() {
// @let with pipe used in an event listener in the same view should keep storeLet.
//
// Event listeners are callbacks (isCallback=true), so @let declarations
// in the same view generate ContextLetReferenceExpr in the listener's handler ops.
// This means the @let is "used externally" and storeLet must be preserved.
let js = compile_template_to_js(
r#"@let value = name | uppercase; <button (click)="onClick(value)">Click</button>"#,
"TestComponent",
);
// storeLet must wrap pipeBind because @let is used externally (in listener callback)
assert!(
js.contains("ɵɵstoreLet(i0.ɵɵpipeBind1("),
"storeLet should wrap pipeBind1 when @let with pipe is used in listener. Output:\n{js}"
);
insta::assert_snapshot!("let_with_pipe_used_in_listener", js);
}
#[test]
fn test_let_with_pipe_multiple_in_child_view_varoffset() {
// Multiple @let declarations with pipes used in a child view.
// Each storeLet contributes 1 var, so removing them would cause cumulative varOffset drift.
//
// This reproduces the ClickUp AdvancedTabComponent pattern where multiple @let
// declarations with pipes have their storeLet wrappers incorrectly removed,
// causing the second pipe's varOffset to drift by +1 for each missing storeLet.
let js = compile_template_to_js(
r"@let a = x | uppercase; @let b = y | lowercase; @if (true) { {{a}} {{b}} }",
"TestComponent",
);
// Both @let values should have storeLet wrappers
let store_let_count = js.matches("ɵɵstoreLet(").count();
assert!(
store_let_count >= 2,
"Expected at least 2 storeLet calls for 2 @let declarations with pipes used in child view, got {store_let_count}. Output:\n{js}"
);
insta::assert_snapshot!("let_with_pipe_multiple_in_child_view_varoffset", js);
}
// ============================================================================
// ng-content Tests
// ============================================================================
#[test]
fn test_ng_content() {
let js = compile_template_to_js(r"<ng-content></ng-content>", "TestComponent");
insta::assert_snapshot!("ng_content", js);
}
#[test]
fn test_ng_content_select() {
let js =
compile_template_to_js(r#"<ng-content select=".header"></ng-content>"#, "TestComponent");
insta::assert_snapshot!("ng_content_select", js);
}
#[test]
fn test_ng_content_with_ng_project_as() {
// Tests that ngProjectAs attribute generates the correct ProjectAs marker (5)
// and parsed CSS selector in the attributes array.
// Expected: ["ngProjectAs", "bit-label", 5, ["bit-label"]]
let js = compile_template_to_js(
r#"<ng-content ngProjectAs="bit-label"></ng-content>"#,
"TestComponent",
);
insta::assert_snapshot!("ng_content_with_ng_project_as", js);
}
#[test]
fn test_ng_content_with_ng_project_as_attribute_selector() {
// Tests ngProjectAs with an attribute selector
// Expected: ["ngProjectAs", "[card-content]", 5, ["", "card-content", ""]]
let js = compile_template_to_js(
r#"<ng-content ngProjectAs="[card-content]"></ng-content>"#,
"TestComponent",
);
insta::assert_snapshot!("ng_content_with_ng_project_as_attr_selector", js);
}
// ============================================================================
// ng-template Tests
// ============================================================================
#[test]
fn test_ng_template() {
let js = compile_template_to_js(
r"<ng-template #myTemplate><div>Template content</div></ng-template>",
"TestComponent",
);
insta::assert_snapshot!("ng_template", js);
}
#[test]
fn test_ng_template_reference_in_binding() {
// Tests that template references used in directive bindings (like ngIfElse)
// generate proper ɵɵreference calls instead of ctx.propertyName
let js = compile_template_to_js(
r#"<ng-template #loadingState><div>Loading...</div></ng-template>
<div *ngIf="!loading; else loadingState">Content</div>"#,
"TestComponent",
);
insta::assert_snapshot!("ng_template_reference_in_binding", js);
}
// ============================================================================
// Structural Directive Tests
// ============================================================================
#[test]
fn test_structural_directive_with_listener() {
// Tests that listeners on elements with structural directives (like *ngIf)
// are placed inside the embedded template, not at the parent level.
// The click listener should be on the button inside Template_0, not on the
// template instruction itself.
let js = compile_template_to_js(
r#"<button *ngIf="isVisible" (click)="handleClick()">Click me</button>"#,
"TestComponent",
);
insta::assert_snapshot!("structural_directive_with_listener", js);
}
#[test]
fn test_ngfor_attribute_ordering() {
// Tests that *ngFor produces template attributes in the correct order:
// ["ngFor", "ngForOf"] not ["ngForOf", "ngFor"]
//
// This is important for directive matching - the ordering must match Angular's
// behavior where text attributes appear before bound attributes in the
// template_attrs order.
//
// The fix ensures that text structural template attributes (like "ngFor")
// go through the same code path as bound structural template attributes
// (like "ngForOf"), preserving their original order from template_attrs.
let allocator = Allocator::default();
let source = r#"
import { Component } from '@angular/core';
@Component({
selector: 'test-comp',
template: '<li *ngFor="let item of items">{{item}}</li>',
standalone: true,
})
export class TestComponent {
items = ['a', 'b', 'c'];
}
"#;
let result = transform_angular_file(
&allocator,
"test.component.ts",
source,
&ComponentTransformOptions::default(),
None,
);
// The consts array should contain ["ngFor", "ngForOf"] in that order
// This is emitted under the Template marker (4) in the attribute array
// Template marker = 4, followed by attribute names
//
// Expected format: [4, "ngFor", "ngForOf", ...]
// Wrong format: [4, "ngForOf", "ngFor", ...]
//
// The regex looks for the consts array containing the Template marker (4)
// followed by "ngFor" then "ngForOf"
let has_correct_order = result.code.contains(r#"4,"ngFor","ngForOf""#);
assert!(
has_correct_order,
"ngFor should appear before ngForOf in the consts array. Got:\n{}",
result.code
);
// Also verify that the wrong order is NOT present
let has_wrong_order = result.code.contains(r#"4,"ngForOf","ngFor""#);
assert!(
!has_wrong_order,
"ngForOf should NOT appear before ngFor in the consts array. Got:\n{}",
result.code
);
insta::assert_snapshot!("ngfor_attribute_ordering", result.code);
}
#[test]
fn test_event_before_property_in_bindings() {
// Tests that in the bindings section of consts (marker 3), event bindings
// come before property bindings. This is important because Angular expects:
// [3, "click", "disabled"] (events first, then properties)
// Not:
// [3, "disabled", "click"] (properties before events - WRONG)
//
// This order is determined by the iteration order in attribute_extraction.ts,
// which processes create ops (listeners) before update ops (properties).
let allocator = Allocator::default();
let source = r#"
import { Component } from '@angular/core';
@Component({
selector: 'test-comp',
template: '<button (click)="onClick()" [disabled]="isDisabled">Click</button>',
standalone: true,
})
export class TestComponent {
isDisabled = false;
onClick() {}
}
"#;
let result = transform_angular_file(
&allocator,
"test.component.ts",
source,
&ComponentTransformOptions::default(),
None,
);
assert_eq!(result.component_count, 1);
assert!(!result.has_errors(), "Should not have errors: {:?}", result.diagnostics);
// The consts array should contain the bindings marker (3) followed by
// the event name first, then the property name.
// Expected: [3, "click", "disabled"]
// Wrong: [3, "disabled", "click"]
let has_correct_order = result.code.contains(r#"3,"click","disabled""#);
assert!(
has_correct_order,
"Event binding 'click' should appear before property binding 'disabled' in the consts array. Got:\n{}",
result.code
);
// Also verify that the wrong order is NOT present
let has_wrong_order = result.code.contains(r#"3,"disabled","click""#);
assert!(
!has_wrong_order,
"Property binding 'disabled' should NOT appear before event binding 'click' in the consts array. Got:\n{}",
result.code
);
insta::assert_snapshot!("event_before_property_in_bindings", result.code);
}
// ============================================================================
// Nested Control Flow Tests
// ============================================================================
#[test]
fn test_nested_for_loops() {
let js = compile_template_to_js(
r"@for (group of groups; track group.id) { <div>@for (item of group.items; track item.id) { <span>{{item.name}}</span> }</div> }",
"TestComponent",
);
insta::assert_snapshot!("nested_for_loops", js);
}
#[test]
fn test_if_inside_for() {
let js = compile_template_to_js(
r"@for (item of items; track item.id) { @if (item.visible) { <div>{{item.name}}</div> } }",
"TestComponent",
);
insta::assert_snapshot!("if_inside_for", js);
}
#[test]
fn test_for_inside_if() {
let js = compile_template_to_js(
r"@if (showItems) { @for (item of items; track item.id) { <div>{{item.name}}</div> } }",
"TestComponent",
);
insta::assert_snapshot!("for_inside_if", js);
}
#[test]
fn test_switch_inside_for() {
let js = compile_template_to_js(
r"@for (item of items; track item.id) { @switch (item.type) { @case ('a') { <div>Type A</div> } @case ('b') { <div>Type B</div> } @default { <div>Unknown</div> } } }",
"TestComponent",
);
insta::assert_snapshot!("switch_inside_for", js);
}
#[test]
fn test_for_with_context_variables() {
let js = compile_template_to_js(
r#"@for (item of items; track item.id; let idx = $index, first = $first, last = $last) { <div [class.first]="first" [class.last]="last">{{idx}}: {{item.name}}</div> }"#,
"TestComponent",
);
insta::assert_snapshot!("for_with_context_variables", js);
}
/// Tests that $index is correctly resolved in listener handlers in @for loops.
/// This is a regression test for an issue where context variables like $index
/// would use a fallback name like `_unnamed_1757` instead of being properly
/// captured from the restored view context as `ɵ$index_xxx_rN.$index`.
#[test]
fn test_for_listener_with_index() {
let js = compile_template_to_js(
r#"@for (item of items; track item.id; let idx = $index) { <button (click)="remove(idx)">Remove #{{ idx }}</button> }"#,
"TestComponent",
);
// The listener should have:
// 1. A variable that reads $index from the restored view context
// 2. Use that variable (like idx_r1) in the event handler expression
// 3. NOT use _unnamed_XXX fallback names
assert!(
!js.contains("_unnamed_"),
"Found _unnamed_ fallback variable - $index resolution failed"
);
insta::assert_snapshot!("for_listener_with_index", js);
}
/// Tests that $index is correctly resolved in two-way binding handlers in @for loops.
/// This is another regression test for the $index issue - the two-way binding
/// handler (e.g., [(ngModel)]="items[$index].value") needs proper $index resolution.
#[test]
fn test_for_two_way_binding_with_index() {
let js = compile_template_to_js(
r#"@for (item of items; track $index) { <input [(ngModel)]="items[$index].value"> }"#,
"TestComponent",
);
// The two-way listener should have:
// 1. A variable that reads $index from the restored view context
// 2. Use that variable in the binding set expression: items[idx_rN].value = $event
// 3. NOT use _unnamed_XXX fallback names
assert!(
!js.contains("_unnamed_"),
"Found _unnamed_ fallback variable - $index resolution in two-way binding failed"
);
insta::assert_snapshot!("for_two_way_binding_with_index", js);
}
// ============================================================================
// Pipe Tests
// ============================================================================
#[test]
fn test_interpolation_with_pipe() {
let js = compile_template_to_js(r"<div>{{name | uppercase}}</div>", "TestComponent");
insta::assert_snapshot!("interpolation_with_pipe", js);
}
#[test]
fn test_pipe_with_arguments() {
let js = compile_template_to_js(r"<div>{{date | date:'yyyy-MM-dd'}}</div>", "TestComponent");
insta::assert_snapshot!("pipe_with_arguments", js);
}
#[test]
fn test_chained_pipes() {
let js =
compile_template_to_js(r"<div>{{name | lowercase | slice:0:10}}</div>", "TestComponent");
insta::assert_snapshot!("chained_pipes", js);
}
#[test]
fn test_pipe_in_property_binding() {
let js = compile_template_to_js(r#"<div [title]="name | uppercase"></div>"#, "TestComponent");
insta::assert_snapshot!("pipe_in_property_binding", js);
}
#[test]
fn test_pipe_in_if_object_literal() {
// Test pipes inside @if with object literal condition (alias pattern)
// This should generate proper pipe declarations and pipeBind calls
let js = compile_template_to_js(
r"@if ({open: value | async, isOverlay: overlay | async}; as data) {
<div>{{data.open}}</div>
}",
"TestComponent",
);
insta::assert_snapshot!("pipe_in_if_object_literal", js);
}
#[test]
fn test_conditional_with_property_bindings_and_pipe() {
// Test @if block with multiple property bindings including a pipe inside
// This tests the var count calculation for embedded views
// Expected: embedded view should have correct var count for: