-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathhtml_to_r3.rs
More file actions
4587 lines (4151 loc) · 191 KB
/
html_to_r3.rs
File metadata and controls
4587 lines (4151 loc) · 191 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
//! HTML AST to R3 AST transformation.
//!
//! This module transforms parsed HTML template AST nodes into R3 AST nodes,
//! which are the intermediate representation used by the IR pipeline.
//!
//! Ported from Angular's `render3/r3_template_transform.ts`.
use oxc_allocator::{Allocator, Box, FromIn, HashMap, Vec};
use oxc_span::{Atom, Span};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::ast::expression::{
ASTWithSource, AbsoluteSourceSpan, AngularExpression, BindingType, ParseSpan, ParsedEventType,
};
use crate::ast::html::{
BlockType, HtmlAttribute, HtmlBlock, HtmlComponent, HtmlDirective, HtmlElement, HtmlExpansion,
HtmlNode, HtmlText, InterpolatedTokenType,
};
use crate::ast::r3::{
I18nBlockPlaceholder, I18nContainer, I18nIcu, I18nIcuPlaceholder, I18nMessage, I18nMeta,
I18nNode, I18nPlaceholder, I18nTagPlaceholder, I18nText, R3BoundAttribute, R3BoundEvent,
R3BoundText, R3Comment, R3Component, R3Content, R3DeferredBlock, R3Directive, R3Element,
R3ForLoopBlock, R3Icu, R3IcuPlaceholder, R3IfBlock, R3IfBlockBranch, R3LetDeclaration, R3Node,
R3ParseResult, R3Reference, R3SwitchBlock, R3Template, R3TemplateAttr, R3Text, R3TextAttribute,
R3Variable, SecurityContext, serialize_i18n_nodes,
};
use crate::i18n::parser::I18nMessageFactory;
use crate::i18n::placeholder::PlaceholderRegistry;
use crate::parser::expression::{BindingParser, find_comment_start};
use crate::parser::html::decode_entities_in_string;
use crate::schema::get_security_context;
use crate::transform::control_flow::{parse_conditional_params, parse_defer_triggers};
use crate::util::{ParseError, parse_loading_parameters, parse_placeholder_parameters};
/// Regex pattern for binding prefixes.
/// Matches: bind-, let-, ref-/#, on-, bindon-, @
const BIND_NAME_PREFIXES: &[(&str, BindingPrefix)] = &[
("bind-", BindingPrefix::Bind),
("let-", BindingPrefix::Let),
("ref-", BindingPrefix::Ref),
("#", BindingPrefix::Ref),
("on-", BindingPrefix::On),
("bindon-", BindingPrefix::BindOn),
("@", BindingPrefix::At),
];
/// Binding delimiters for Angular syntax.
const BANANA_BOX_START: &str = "[(";
const BANANA_BOX_END: &str = ")]";
const PROPERTY_START: char = '[';
const PROPERTY_END: char = ']';
const EVENT_START: char = '(';
const EVENT_END: char = ')';
/// Template attribute prefix for structural directives.
const TEMPLATE_ATTR_PREFIX: char = '*';
/// Tags that cannot be used as selectorless component tags.
/// These are special HTML or Angular elements that have reserved semantics.
const UNSUPPORTED_SELECTORLESS_TAGS: &[&str] =
&["link", "style", "script", "ng-template", "ng-container", "ng-content"];
/// Binding prefix types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BindingPrefix {
/// Property binding (bind-)
Bind,
/// Let variable (let-)
Let,
/// Template reference (ref- or #)
Ref,
/// Event binding (on-)
On,
/// Two-way binding (bindon-)
BindOn,
/// Animation (@)
At,
}
/// Info extracted from a template attribute (structural directive).
#[derive(Debug, Clone)]
struct TemplateAttrInfo<'a> {
/// The attribute name (e.g., `*ngFor`).
name: Atom<'a>,
/// The attribute value (e.g., `let item of items`).
value: Atom<'a>,
/// The full span of the attribute.
span: Span,
/// The span of the attribute name.
name_span: Span,
/// The span of the attribute value (if present).
value_span: Option<Span>,
}
/// Options for the HTML to R3 transformation.
#[derive(Debug, Clone, Default)]
pub struct TransformOptions {
/// Whether to collect comment nodes.
pub collect_comment_nodes: bool,
}
/// Inserts or updates a var entry in an ordered Vec, preserving first-insertion order.
/// This matches JS object semantics where reassigning an existing key keeps its position.
fn ordered_insert_var<'a>(
vec: &mut Vec<'a, (Atom<'a>, R3BoundText<'a>)>,
key: Atom<'a>,
value: R3BoundText<'a>,
) {
if let Some(existing) = vec.iter_mut().find(|(k, _)| *k == key) {
existing.1 = value;
} else {
vec.push((key, value));
}
}
/// Inserts or updates a placeholder entry in an ordered Vec, preserving first-insertion order.
/// This matches JS object semantics where reassigning an existing key keeps its position.
fn ordered_insert_placeholder<'a>(
vec: &mut Vec<'a, (Atom<'a>, R3IcuPlaceholder<'a>)>,
key: Atom<'a>,
value: R3IcuPlaceholder<'a>,
) {
if let Some(existing) = vec.iter_mut().find(|(k, _)| *k == key) {
existing.1 = value;
} else {
vec.push((key, value));
}
}
/// Transforms HTML AST to R3 AST.
pub struct HtmlToR3Transform<'a> {
allocator: &'a Allocator,
/// The source text of the template (for extracting attribute values).
source_text: &'a str,
/// Binding parser for parsing expressions.
binding_parser: BindingParser<'a>,
/// Parse errors.
/// Uses std::vec::Vec since ParseError contains Drop types (Arc, String).
errors: std::vec::Vec<ParseError>,
styles: Vec<'a, Atom<'a>>,
style_urls: Vec<'a, Atom<'a>>,
ng_content_selectors: Vec<'a, Atom<'a>>,
comment_nodes: Option<Vec<'a, R3Comment<'a>>>,
processed_nodes: FxHashSet<usize>,
namespace_stack: std::vec::Vec<ElementNamespace>,
/// Depth counter for ngNonBindable. When > 0, bindings are suppressed.
non_bindable_depth: u32,
/// Depth counter for i18n context. When > 0, ICU expansions are emitted.
i18n_depth: u32,
/// Counter for generating unique block placeholder names (for i18n).
block_placeholder_counter: u32,
/// Counters for generating unique ICU placeholder names (e.g., VAR_PLURAL, VAR_PLURAL_1, etc.).
/// Maps base name (e.g., "VAR_PLURAL") to count.
icu_placeholder_counts: FxHashMap<String, u32>,
/// Placeholder registry for generating unique tag placeholder names within i18n blocks.
/// Reset when entering a new i18n block.
i18n_placeholder_registry: PlaceholderRegistry,
/// Counter for generating unique i18n message instance IDs.
///
/// Each i18n message gets a unique instance ID that's used to track message identity
/// across moves/copies. This ensures that when the same attribute is processed twice
/// (e.g., by `ingestControlFlowInsertionPoint` and `ingestStaticAttributes`), both
/// can share the same i18n context.
i18n_message_instance_counter: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ElementNamespace {
Html,
Svg,
Math,
}
impl<'a> HtmlToR3Transform<'a> {
/// Creates a new HTML to R3 transformer.
pub fn new(allocator: &'a Allocator, source_text: &'a str, options: TransformOptions) -> Self {
let comment_nodes =
if options.collect_comment_nodes { Some(Vec::new_in(allocator)) } else { None };
Self {
allocator,
source_text,
binding_parser: BindingParser::new(allocator),
errors: std::vec::Vec::new(),
styles: Vec::new_in(allocator),
style_urls: Vec::new_in(allocator),
ng_content_selectors: Vec::new_in(allocator),
comment_nodes,
processed_nodes: FxHashSet::default(),
namespace_stack: std::vec::Vec::new(),
non_bindable_depth: 0,
i18n_depth: 0,
block_placeholder_counter: 0,
icu_placeholder_counts: FxHashMap::default(),
i18n_placeholder_registry: PlaceholderRegistry::new(),
i18n_message_instance_counter: 0,
}
}
/// Allocates a new unique instance ID for an i18n message.
fn allocate_i18n_message_instance_id(&mut self) -> u32 {
let id = self.i18n_message_instance_counter;
self.i18n_message_instance_counter += 1;
id
}
/// Transforms HTML nodes to R3 nodes.
pub fn transform(mut self, html_nodes: &[HtmlNode<'a>]) -> R3ParseResult<'a> {
let nodes = self.visit_siblings(html_nodes);
R3ParseResult {
nodes,
errors: self.errors,
styles: self.styles,
style_urls: self.style_urls,
ng_content_selectors: self.ng_content_selectors,
comment_nodes: self.comment_nodes,
}
}
/// Visits a list of sibling nodes, handling connected blocks.
fn visit_siblings(&mut self, siblings: &[HtmlNode<'a>]) -> Vec<'a, R3Node<'a>> {
let mut result = Vec::new_in(self.allocator);
for (index, node) in siblings.iter().enumerate() {
// Skip nodes that were already processed as connected blocks
let node_id = node as *const _ as usize;
if self.processed_nodes.contains(&node_id) {
continue;
}
// In ngNonBindable context, blocks should be flattened into text nodes + children
// (not wrapped in a Template). TypeScript returns [startText, ...children, endText].flat()
if self.non_bindable_depth > 0 {
if let HtmlNode::Block(block) = node {
let block_nodes = self.visit_block_as_text_flat(block);
for child in block_nodes {
result.push(child);
}
continue;
}
}
if let Some(r3_node) = self.visit_node_with_siblings(node, index, siblings) {
result.push(r3_node);
}
}
result
}
/// Visits a node with sibling context for connected block handling.
fn visit_node_with_siblings(
&mut self,
node: &HtmlNode<'a>,
index: usize,
siblings: &[HtmlNode<'a>],
) -> Option<R3Node<'a>> {
match node {
HtmlNode::Block(block) => self.visit_block_with_siblings(block, index, siblings),
_ => self.visit_node(node),
}
}
/// Visits an HTML node and returns the corresponding R3 node.
fn visit_node(&mut self, node: &HtmlNode<'a>) -> Option<R3Node<'a>> {
match node {
HtmlNode::Element(element) => self.visit_element(element),
HtmlNode::Component(component) => self.visit_html_component(component),
HtmlNode::Text(text) => self.visit_text(text),
HtmlNode::Comment(comment) => self.visit_comment(comment),
HtmlNode::Block(block) => self.visit_block(block),
HtmlNode::LetDeclaration(decl) => {
// Inside ngNonBindable, @let becomes plain text
// Angular reconstructs: `@let ${name} = ${value};`
if self.non_bindable_depth > 0 {
// Get the raw value text from source
let value_text = if decl.value_span.start < decl.value_span.end
&& (decl.value_span.end as usize) <= self.source_text.len()
{
&self.source_text
[decl.value_span.start as usize..decl.value_span.end as usize]
} else {
""
};
// Reconstruct the @let text with semicolon
let reconstructed = format!("@let {} = {};", decl.name.as_str(), value_text);
let text_value = Atom::from_in(reconstructed.as_str(), self.allocator);
let r3_text = R3Text { value: text_value, source_span: decl.span };
return Some(R3Node::Text(Box::new_in(r3_text, self.allocator)));
}
self.visit_let_declaration(decl)
}
HtmlNode::Expansion(expansion) => self.visit_expansion(expansion),
HtmlNode::ExpansionCase(_) => {
// Expansion cases are handled within visit_expansion
None
}
HtmlNode::Attribute(_) | HtmlNode::BlockParameter(_) => {
// These are not standalone nodes in R3 AST
None
}
}
}
/// Visits an HTML element.
fn visit_element(&mut self, element: &HtmlElement<'a>) -> Option<R3Node<'a>> {
let raw_name = element.name.as_str();
// Check for special elements
if raw_name == "script" {
return None;
}
if raw_name == "style" {
// Extract style content
if let Some(content) = self.get_text_content(element) {
self.styles.push(content);
}
return None;
}
if raw_name == "link" {
// Collect stylesheet URLs
if let Some(href) = self.get_stylesheet_href(element) {
self.style_urls.push(href);
}
// Filter out <link rel="stylesheet"> inside ngNonBindable elements
if self.non_bindable_depth > 0 && self.is_stylesheet_link(element) {
return None;
}
}
// Parse attributes
let (attributes, inputs, outputs, references, variables, template_attr) =
self.parse_attributes(&element.attrs, raw_name, raw_name == "ng-template");
// Resolve namespace for this element and its children.
// Note: foreignObject is an SVG element but its children use HTML namespace.
// We need to distinguish between the element's own namespace (for naming) and
// the namespace for its children (pushed to stack).
let parent_namespace = self.current_namespace();
let child_namespace = self.resolve_namespace(raw_name, parent_namespace);
// For foreignObject in SVG context: the element itself is SVG, only children are HTML.
// For all other elements: element namespace equals child namespace.
let element_namespace = if parent_namespace == ElementNamespace::Svg
&& raw_name.eq_ignore_ascii_case("foreignObject")
{
ElementNamespace::Svg
} else {
child_namespace
};
self.namespace_stack.push(child_namespace);
// Check if element has ngNonBindable attribute
let has_non_bindable =
element.attrs.iter().any(|attr| attr.name.as_str() == "ngNonBindable");
// Check if element has i18n attribute (marks ICU expansions for translation)
// and extract its metadata for the i18n block generation
let i18n_attr = element.attrs.iter().find(|attr| attr.name.as_str() == "i18n");
let has_i18n = i18n_attr.is_some();
// Generate i18n message string from HTML children BEFORE transforming to R3.
// This is needed because the message text comes from the original HTML content.
// Ported from Angular's I18nMetaVisitor._generateI18nMessage in i18n/meta.ts.
let i18n_message_string = if let Some(attr) = i18n_attr {
if !element.children.is_empty() {
// Use I18nMessageFactory to convert children to i18n AST and serialize
let factory = I18nMessageFactory::new(false, true);
let source_file = std::sync::Arc::new(crate::util::ParseSourceFile::new(
self.source_text,
"<template>",
));
let meaning = if attr.value.contains('|') {
Some(attr.value.split('|').next().unwrap_or("").trim())
} else {
None
};
let description = if attr.value.contains('|') {
attr.value.split('|').nth(1).map(|s| {
if let Some(pos) = s.find("@@") { s[..pos].trim() } else { s.trim() }
})
} else if let Some(pos) = attr.value.find("@@") {
Some(attr.value[..pos].trim())
} else if !attr.value.is_empty() {
Some(attr.value.as_str())
} else {
None
};
let custom_id = attr.value.find("@@").map(|pos| &attr.value.as_str()[pos + 2..]);
let message = factory.create_message(
&element.children,
meaning,
description,
custom_id,
None,
source_file,
);
message.serialize()
} else {
String::new()
}
} else {
String::new()
};
// Now create the i18n metadata with the generated message string
let i18n_meta = if let Some(attr) = i18n_attr {
// Element has its own i18n attribute - parse it as a Message with message string
let instance_id = self.allocate_i18n_message_instance_id();
Some(parse_i18n_meta_with_message(
self.allocator,
attr.value.as_str(),
instance_id,
&i18n_message_string,
))
} else if self.i18n_depth > 0 {
// Element is inside an i18n block - create a TagPlaceholder for it.
// This matches TypeScript's behavior where child elements inside i18n blocks
// get TagPlaceholder metadata assigned during i18n message parsing.
// Reference: i18n_parser.ts line 266-277
Some(self.create_i18n_tag_placeholder_for_element(element))
} else {
None
};
// Increment non_bindable depth if this element has ngNonBindable
if has_non_bindable {
self.non_bindable_depth += 1;
}
// Increment i18n depth if this element has i18n attribute.
// Also reset the placeholder registry when entering a new i18n root block.
if has_i18n {
if self.i18n_depth == 0 {
// Starting a new i18n root - reset the placeholder registry
self.i18n_placeholder_registry = PlaceholderRegistry::new();
}
self.i18n_depth += 1;
}
// Visit children
let children = self.visit_children(&element.children);
// Decrement non_bindable depth if we incremented it
if has_non_bindable {
self.non_bindable_depth -= 1;
}
// Decrement i18n depth if we incremented it
if has_i18n {
self.i18n_depth -= 1;
}
self.namespace_stack.pop();
// Transform selectorless directives from HTML AST
let directives = self.transform_directives(&element.directives, raw_name);
// Determine if element is self-closing (explicitly closed with />)
let is_self_closing = element.is_self_closing;
// Check for ng-content
// Reference: r3_template_transform.ts lines 191-204
// Children are passed directly without extra whitespace filtering
if raw_name == "ng-content" {
let selector = self.get_ng_content_selector(element);
self.ng_content_selectors.push(selector.clone());
// For ng-content, Angular converts ALL raw HTML attributes to TextAttributes.
// Reference: r3_template_transform.ts line 193:
// const attrs: t.TextAttribute[] = element.attrs.map((attr) => this.visitAttribute(attr));
// This includes bound attributes like [select]="..." which get serialized with
// their raw names (e.g., "[select]") and values into the projection instruction.
//
// However, i18n/i18n-* attributes are excluded because Angular's I18nMetaVisitor
// strips them from element.attrs before r3_template_transform runs.
let mut content_attributes: Vec<'a, R3TextAttribute<'a>> =
Vec::with_capacity_in(element.attrs.len(), self.allocator);
for attr in &element.attrs {
let name = attr.name.as_str();
if name == "i18n" || name.starts_with("i18n-") {
continue;
}
content_attributes.push(R3TextAttribute {
name: attr.name.clone(),
value: attr.value.clone(),
source_span: attr.span,
key_span: Some(attr.name_span),
value_span: attr.value_span,
i18n: None,
});
}
let content = R3Content {
selector,
attributes: content_attributes,
children, // Pass children directly like TypeScript does
is_self_closing,
source_span: element.span,
start_source_span: element.start_span,
end_source_span: element.end_span,
i18n: None,
};
let mut result = R3Node::Content(Box::new_in(content, self.allocator));
// Wrap in template if has structural directive (*ngIf, etc.)
// Reference: r3_template_transform.ts lines 266-277
if let Some(template_attr_info) = template_attr {
result = self.wrap_in_template(result, element, template_attr_info);
}
return Some(result);
}
// Check for ng-template
if raw_name == "ng-template" {
let name = self.qualify_element_name(element.name.clone(), element_namespace);
let template = R3Template {
tag_name: Some(name),
attributes,
inputs,
outputs,
directives,
template_attrs: Vec::new_in(self.allocator),
children,
references,
variables,
is_self_closing,
source_span: element.span,
start_source_span: element.start_span,
end_source_span: element.end_span,
i18n: i18n_meta,
};
let mut result = R3Node::Template(Box::new_in(template, self.allocator));
// Wrap in another template if has structural directive (*ngIf, etc.)
if let Some(template_attr_info) = template_attr {
result = self.wrap_in_template(result, element, template_attr_info);
}
return Some(result);
}
// Validate ng-container attribute bindings
// Reference: r3_template_transform.ts lines 238-247
if raw_name == "ng-container" {
use crate::ast::expression::BindingType;
for input in inputs.iter() {
if input.binding_type == BindingType::Attribute {
self.report_error(
"Attribute bindings are not supported on ng-container. Use property bindings instead.",
input.source_span,
);
}
}
}
let name = self.qualify_element_name(element.name.clone(), element_namespace);
// Check if this is a component (uppercase first letter or underscore)
let first_char = raw_name.chars().next().unwrap_or('a');
let is_component = first_char.is_ascii_uppercase() || first_char == '_';
let mut result = if is_component {
// Validate selectorless component - check for unsupported tags
let tag_name_lower = raw_name.to_ascii_lowercase();
if UNSUPPORTED_SELECTORLESS_TAGS.contains(&tag_name_lower.as_str()) {
self.report_error(
&format!("Tag name \"{}\" cannot be used as a component tag", raw_name),
element.start_span,
);
return None;
}
// Validate selectorless references
self.validate_selectorless_references(&references);
// Compute tag_name from component_prefix and component_tag_name
// Format: ":prefix:tag_name" (e.g., ":svg:rect") or just "tag_name"
let tag_name = match (&element.component_prefix, &element.component_tag_name) {
(None, None) => None,
(None, Some(tag)) => Some(tag.clone()),
(Some(prefix), None) => {
// Has prefix but no tag name - use "ng-component" as default
Some(Atom::from_in(&format!(":{}:ng-component", prefix), self.allocator))
}
(Some(prefix), Some(tag)) => {
// Both prefix and tag name: ":prefix:tag_name"
Some(Atom::from_in(&format!(":{}:{}", prefix, tag), self.allocator))
}
};
// Compute full_name: "ComponentName:prefix:tag_name" or "ComponentName:tag_name"
let full_name = match &tag_name {
Some(tag) if tag.starts_with(':') => {
// Namespace format: "MyComp:svg:rect" (tag_name already has :prefix:)
Atom::from_in(&format!("{}{}", element.name, tag), self.allocator)
}
Some(tag) => {
// Simple format: "MyComp:div"
Atom::from_in(&format!("{}:{}", element.name, tag), self.allocator)
}
None => element.name.clone(),
};
// Create R3Component for uppercase element names
let r3_component = R3Component {
component_name: element.name.clone(),
tag_name,
full_name,
attributes,
inputs,
outputs,
directives,
children,
references,
is_self_closing,
source_span: element.span,
start_source_span: element.start_span,
end_source_span: element.end_span,
i18n: i18n_meta,
};
R3Node::Component(Box::new_in(r3_component, self.allocator))
} else {
// Regular element
let r3_element = R3Element {
name,
attributes,
inputs,
outputs,
directives,
children,
references,
is_self_closing,
source_span: element.span,
start_source_span: element.start_span,
end_source_span: element.end_span,
is_void: self.is_void_element(element.name.as_str()),
i18n: i18n_meta,
};
R3Node::Element(Box::new_in(r3_element, self.allocator))
};
// Wrap in template if has structural directive
if let Some(template_attr_info) = template_attr {
result = self.wrap_in_template(result, element, template_attr_info);
}
Some(result)
}
/// Visits an HTML component (selectorless component AST node).
fn visit_html_component(&mut self, component: &HtmlComponent<'a>) -> Option<R3Node<'a>> {
// Parse attributes
let (attributes, inputs, outputs, references, _variables, template_attr) =
self.parse_attributes(&component.attrs, component.full_name.as_str(), false);
// Resolve namespace for this component and its children.
let parent_namespace = self.current_namespace();
let element_namespace =
self.resolve_namespace(component.full_name.as_str(), parent_namespace);
self.namespace_stack.push(element_namespace);
// Check if component has ngNonBindable attribute
let has_non_bindable =
component.attrs.iter().any(|attr| attr.name.as_str() == "ngNonBindable");
// Check if component has i18n attribute
let has_i18n = component.attrs.iter().any(|attr| attr.name.as_str() == "i18n");
// Increment non_bindable depth if this component has ngNonBindable
if has_non_bindable {
self.non_bindable_depth += 1;
}
// Increment i18n depth if this component has i18n attribute.
// Also reset the placeholder registry when entering a new i18n root block.
if has_i18n {
if self.i18n_depth == 0 {
// Starting a new i18n root - reset the placeholder registry
self.i18n_placeholder_registry = PlaceholderRegistry::new();
}
self.i18n_depth += 1;
}
// Visit children
let children = self.visit_children(&component.children);
// Decrement non_bindable depth if we incremented it
if has_non_bindable {
self.non_bindable_depth -= 1;
}
// Decrement i18n depth if we incremented it
if has_i18n {
self.i18n_depth -= 1;
}
self.namespace_stack.pop();
// Transform selectorless directives from HTML AST
// For components, tag_name may be None (e.g., `<MyComp>`), in which case we use empty string
// which matches TypeScript's behavior where elementName can be null.
let element_name = component.tag_name.as_ref().map(|a| a.as_str()).unwrap_or("");
let directives = self.transform_directives(&component.directives, element_name);
// Validate selectorless references
self.validate_selectorless_references(&references);
// Create R3Component
let r3_component = R3Component {
component_name: component.component_name.clone(),
tag_name: component.tag_name.clone(),
full_name: component.full_name.clone(),
attributes,
inputs,
outputs,
directives,
children,
references,
is_self_closing: component.is_self_closing,
source_span: component.span,
start_source_span: component.start_span,
end_source_span: component.end_span,
i18n: None,
};
let mut result = R3Node::Component(Box::new_in(r3_component, self.allocator));
// Wrap in template if has structural directive
if let Some(template_attr_info) = template_attr {
result = self.wrap_component_in_template(result, component, template_attr_info);
}
Some(result)
}
fn current_namespace(&self) -> ElementNamespace {
self.namespace_stack.last().copied().unwrap_or(ElementNamespace::Html)
}
fn resolve_namespace(&self, raw_name: &str, parent: ElementNamespace) -> ElementNamespace {
if let Some(explicit) = Self::namespace_from_prefixed_name(raw_name) {
return explicit;
}
if raw_name.eq_ignore_ascii_case("svg") {
return ElementNamespace::Svg;
}
if raw_name.eq_ignore_ascii_case("math") {
return ElementNamespace::Math;
}
match parent {
ElementNamespace::Svg => {
if raw_name.eq_ignore_ascii_case("foreignObject") {
ElementNamespace::Html
} else {
ElementNamespace::Svg
}
}
ElementNamespace::Math => ElementNamespace::Math,
ElementNamespace::Html => ElementNamespace::Html,
}
}
fn namespace_from_prefixed_name(raw_name: &str) -> Option<ElementNamespace> {
if raw_name.starts_with(':') {
if let Some((prefix, _)) = raw_name[1..].split_once(':') {
return Self::namespace_from_prefix(prefix);
}
}
if let Some((prefix, _)) = raw_name.split_once(':') {
return Self::namespace_from_prefix(prefix);
}
None
}
fn namespace_from_prefix(prefix: &str) -> Option<ElementNamespace> {
if prefix.eq_ignore_ascii_case("svg") {
Some(ElementNamespace::Svg)
} else if prefix.eq_ignore_ascii_case("math") {
Some(ElementNamespace::Math)
} else {
None
}
}
fn qualify_element_name(&self, name: Atom<'a>, namespace: ElementNamespace) -> Atom<'a> {
if namespace == ElementNamespace::Html {
return name;
}
let name_str = name.as_str();
if name_str.starts_with(':') {
return name;
}
if let Some((prefix, local)) = name_str.split_once(':') {
if Self::namespace_from_prefix(prefix).is_some() {
let qualified = format!(":{}:{}", prefix, local);
return Atom::from_in(&qualified, self.allocator);
}
}
let ns = match namespace {
ElementNamespace::Svg => "svg",
ElementNamespace::Math => "math",
ElementNamespace::Html => return name,
};
let qualified = format!(":{}:{}", ns, name_str);
Atom::from_in(&qualified, self.allocator)
}
/// Transforms HTML directives to R3 directives.
/// Implements validation from Angular's `extractDirectives()` and `validateSelectorlessReferences()`.
fn transform_directives(
&mut self,
html_directives: &[HtmlDirective<'a>],
element_name: &str,
) -> Vec<'a, R3Directive<'a>> {
let mut directives = Vec::new_in(self.allocator);
let mut seen_directives: FxHashSet<&str> = FxHashSet::default();
for html_dir in html_directives {
let directive_name = html_dir.name.as_str();
// Check for duplicate directives
// Reference: r3_template_transform.ts lines 924-930
if seen_directives.contains(directive_name) {
self.report_error(
&format!(
"Cannot apply directive \"{}\" multiple times on the same element",
directive_name
),
html_dir.span,
);
continue;
}
seen_directives.insert(directive_name);
// Parse directive attributes similar to element attributes
let mut attributes = Vec::new_in(self.allocator);
let mut inputs = Vec::new_in(self.allocator);
let mut outputs = Vec::new_in(self.allocator);
let mut references = Vec::new_in(self.allocator);
let mut seen_reference_names: FxHashSet<&str> = FxHashSet::default();
let mut invalid = false;
for attr in html_dir.attrs.iter() {
let attr_name = attr.name.as_str();
let attr_value = attr.value.as_str();
// Check for unsupported attributes
// Reference: r3_template_transform.ts lines 908-922
if attr_name.starts_with(TEMPLATE_ATTR_PREFIX) {
self.report_error(
&format!(
"Shorthand template syntax \"{}\" is not supported inside a directive context",
attr_name
),
attr.span,
);
invalid = true;
continue;
}
if attr_name == "ngProjectAs" || attr_name == "ngNonBindable" {
self.report_error(
&format!(
"Attribute \"{}\" is not supported in a directive context",
attr_name
),
attr.span,
);
invalid = true;
continue;
}
// Check for reference syntax (#ref or ref-)
if attr_name.starts_with('#') || attr_name.starts_with("ref-") {
let ref_name =
if attr_name.starts_with('#') { &attr_name[1..] } else { &attr_name[4..] };
// Validate reference - no value allowed in directive context
// Reference: r3_template_transform.ts lines 1121-1140
if !attr_value.is_empty() {
self.report_error(
"Cannot specify a value for a local reference in this context",
attr.value_span.unwrap_or(attr.span),
);
invalid = true;
}
// Check for duplicate reference names
if seen_reference_names.contains(ref_name) {
self.report_error("Duplicate reference names are not allowed", attr.span);
invalid = true;
} else {
seen_reference_names.insert(ref_name);
references.push(R3Reference {
name: Atom::from_in(ref_name, self.allocator),
value: Atom::from_in("", self.allocator),
source_span: attr.span,
key_span: attr.name_span,
value_span: None,
});
}
continue;
}
// Check for binding prefix syntax (bind-, on-, bindon-)
if let Some((prefix, rest)) = self.parse_binding_prefix(attr_name) {
match prefix {
BindingPrefix::Bind => {
// bind-prop="value" - property binding
// Check for animation bindings: bind-@prop or bind-animate-prop
let (prop_name, binding_type) =
if let Some(anim_name) = rest.strip_prefix('@') {
(anim_name, BindingType::Animation)
} else if let Some(anim_name) = rest.strip_prefix("animate-") {
(anim_name, BindingType::Animation)
} else {
(rest, BindingType::Property)
};
// Check for non-property bindings which are not allowed
if prop_name.starts_with("attr.")
|| prop_name.starts_with("class.")
|| prop_name.starts_with("style.")
{
self.report_error(
"Binding is not supported in a directive context",
attr.span,
);
invalid = true;
continue;
}
let value_span = attr.value_span.unwrap_or(attr.span);
let parse_result =
self.binding_parser.parse_binding(attr_value, value_span);
inputs.push(R3BoundAttribute {
name: Atom::from_in(prop_name, self.allocator),
binding_type,
value: parse_result.ast,
unit: None,
source_span: attr.span,
key_span: attr.name_span,
value_span: Some(value_span),
i18n: None,
security_context: get_security_context(element_name, prop_name),
});
}
BindingPrefix::On => {
// on-event="handler" - event binding
let value_span = attr.value_span.unwrap_or(attr.span);
let parse_result =
self.binding_parser.parse_event(attr_value, value_span);
outputs.push(R3BoundEvent {
name: Atom::from_in(rest, self.allocator),
handler: parse_result.ast,
target: None,
event_type: ParsedEventType::Regular,
phase: None,
source_span: attr.span,
key_span: attr.name_span,
handler_span: value_span,
});
}
BindingPrefix::BindOn => {
// bindon-prop="value" - two-way binding
let value_span = attr.value_span.unwrap_or(attr.span);
let parse_result =
self.binding_parser.parse_binding(attr_value, value_span);
inputs.push(R3BoundAttribute {
name: Atom::from_in(rest, self.allocator),
binding_type: BindingType::TwoWay,
value: parse_result.ast,
unit: None,
source_span: attr.span,
key_span: attr.name_span,
value_span: Some(value_span),
i18n: None,
security_context: get_security_context(element_name, rest),
});
// Two-way binding also creates an output event
let event_name =
Atom::from_in(&format!("{}Change", rest), self.allocator);
let event_parse_result =
self.binding_parser.parse_event(attr_value, value_span);
outputs.push(R3BoundEvent {