-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathintegration_test.rs
More file actions
6358 lines (5622 loc) · 225 KB
/
integration_test.rs
File metadata and controls
6358 lines (5622 loc) · 225 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, R3Node, 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 raw × in the output
let js = compile_template_to_js("<div>{{ a }}×{{ b }}</div>", "TestComponent");
// Should produce: textInterpolate2("", ctx.a, "×", ctx.b)
// Note: × (multiplication sign) = U+00D7, emitted as raw UTF-8
assert!(
js.contains("textInterpolate2(\"\",ctx.a,\"\u{00D7}\",ctx.b)"),
"Expected textInterpolate2 with raw 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("×", ctx.a)
// Note: × (multiplication sign) = U+00D7, emitted as raw UTF-8
assert!(
js.contains("textInterpolate1(\"\u{00D7}\",ctx.a)")
|| js.contains("textInterpolate(\"\u{00D7}\",ctx.a)"),
"Expected textInterpolate with raw 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{00A0}", ctx.b)
// Note: = U+00A0, × = U+00D7, both emitted as raw UTF-8
assert!(
js.contains("textInterpolate2(\"\",ctx.a,\"\u{00A0}\u{00D7}\u{00A0}\",ctx.b)"),
"Expected textInterpolate2 with raw 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 reorders @default last
// Angular's ingestSwitchBlock iterates in source order, but generateConditionalExpressions
// splices @default out as the ternary fallback. We reorder at ingest to match the final output.
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);
}
/// Tests that @defer blocks inside i18n contexts get wrapped with i18nStart/i18nEnd.
/// Angular propagates i18n context into defer view templates so that the deferred
/// content is part of the i18n message. Each defer sub-block (main, loading,
/// placeholder, error) gets its own sub-template index.
///
/// Ported from Angular compliance test:
/// `r3_view_compiler_i18n/blocks/defer.ts`
#[test]
fn test_defer_inside_i18n() {
let js = compile_template_to_js(
r#"<div i18n>
Content:
@defer (when isLoaded) {
before<span>middle</span>after
} @placeholder {
before<div>placeholder</div>after
} @loading {
before<button>loading</button>after
} @error {
before<h1>error</h1>after
}
</div>"#,
"MyApp",
);
// Each deferred template function should be wrapped with i18nStart/i18nEnd
// with increasing sub-template indices (1, 2, 3, 4)
assert!(
js.contains("i18nStart(0,0,1)"),
"Main defer template should have i18nStart with sub-template index 1. Output:\n{js}"
);
assert!(
js.contains("i18nStart(0,0,2)"),
"Loading defer template should have i18nStart with sub-template index 2. Output:\n{js}"
);
assert!(
js.contains("i18nStart(0,0,3)"),
"Placeholder defer template should have i18nStart with sub-template index 3. Output:\n{js}"
);
assert!(
js.contains("i18nStart(0,0,4)"),
"Error defer template should have i18nStart with sub-template index 4. Output:\n{js}"
);
// The deferred templates should have 2 decls (i18nStart + element), not 1
// domTemplate(N, fn, 2, 0) - 2 declarations for each deferred view
assert!(
js.contains("MyApp_Defer_2_Template,2,0)"),
"Main defer domTemplate should have 2 decls. Output:\n{js}"
);
insta::assert_snapshot!("defer_inside_i18n", js);
}
/// When @defer is nested inside a structural directive (*ngIf template) that's inside
/// an i18n context, the i18n wrapping must propagate through the template boundary
/// to the defer view. This matches the unlock-view-confirm ClickUp pattern.
#[test]
fn test_defer_inside_structural_directive_in_i18n() {
let js = compile_template_to_js(
r#"<div i18n>
text
<span *ngIf="show">
@defer (on idle) {
<span>deferred</span>
}
</span>
</div>"#,
"MyApp",
);
// The defer template should have i18nStart wrapping since it's
// transitively inside an i18n context (through the *ngIf template)
assert!(
js.contains("i18nStart(0,"),
"Defer template inside structural directive in i18n should have i18nStart. Output:\n{js}"
);
insta::assert_snapshot!("defer_inside_structural_directive_in_i18n", 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);
}
// ============================================================================
// @let self-reference / forward-reference Tests
// ============================================================================
#[test]
fn test_let_self_reference_replaced_with_undefined() {
// A @let that references itself (self-reference) should have that reference
// replaced with `undefined`, matching Angular's behavior.
// Angular walks backward from the declaration op and replaces LexicalRead
// in the declaration op itself.
let js = compile_template_to_js(r"@let x = x + 1; <div>{{x}}</div>", "TestComponent");
insta::assert_snapshot!("let_self_reference", 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_i18n_attr_not_in_projection() {
// Verify i18n/i18n-* attrs are NOT included in ng-content projection attributes.
// Angular's I18nMetaVisitor strips these before r3_template_transform runs.
let js = compile_template_to_js(
r#"<ng-content i18n select=".header"></ng-content>"#,
"TestComponent",
);
assert!(
!js.contains(r#""i18n""#),
"i18n attribute should not appear in projection output. Got:\n{js}"
);
}
#[test]
fn test_ng_content_with_bound_select() {
// Tests that [select] binding on ng-content passes the binding name and value
// as attributes to the projection instruction.
// Angular treats ALL raw attrs on ng-content as TextAttributes, including bindings.
// [select] with brackets is NOT the same as the static `select` attribute for the
// CSS selector — the selector stays as "*" (wildcard).
// Expected: ɵɵprojectionDef() with no args (single wildcard),
// ɵɵprojection(0, 0, ["[select]", "'[slot=expanded-content]'"])
let js = compile_template_to_js(
r#"<ng-content [select]="'[slot=expanded-content]'" />"#,
"TestComponent",
);
insta::assert_snapshot!("ng_content_with_bound_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);
}
// ============================================================================
// Compilation Mode Tests (Full vs DomOnly)
// ============================================================================
#[test]
fn test_standalone_component_uses_full_mode() {
// OXC operates as a single-file compiler, equivalent to Angular's local compilation mode.
// In local compilation mode, Angular ALWAYS sets hasDirectiveDependencies=true,
// which means DomOnly mode is never used for component templates.
// See: angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts:1257