Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions crates/oxc_angular_compiler/src/parser/html/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,11 +680,15 @@ impl<'a> HtmlParser<'a> {
self.advance();

// Validate self-closing: only void, custom, and foreign elements can be self-closed
// Foreign elements include those with explicit namespace prefix (e.g., svg:rect)
// or those with implicit namespace prefix (e.g., <svg> has implicitNamespacePrefix='svg')
// Foreign elements include those with explicit namespace prefix (e.g., svg:rect),
// with implicit namespace prefix (e.g., <svg> has implicitNamespacePrefix='svg'),
// or one taken from the element they are in (`<div/>` in `<svg>` is `:svg:div`).
// Angular checks element tags only: a component tag is never reported.
let tag_def = get_html_tag_definition(&local_name);
let is_foreign = has_ns_prefix || tag_def.implicit_namespace_prefix.is_some();
if !(tag_def.can_self_close || is_foreign || tag_def.is_void) {
let is_foreign = has_ns_prefix
|| tag_def.implicit_namespace_prefix.is_some()
|| self.inherits_namespace();
if !is_component && !(tag_def.can_self_close || is_foreign || tag_def.is_void) {
let err = self.make_error(
start,
format!(
Expand Down
22 changes: 22 additions & 0 deletions crates/oxc_angular_compiler/src/parser/html/tags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,21 @@ pub fn get_html_tag_definition(tag_name: &str) -> HtmlTagDefinition {
..Default::default()
},

// The other elements of Angular's DOM schema (`allKnownElementNames()` without a
// namespace), which `html_tags.ts` defines as `canSelfClose: false`: `<div/>` is an error.
"a" | "abbr" | "address" | "article" | "aside" | "audio" | "b" | "bdi" | "bdo"
| "blockquote" | "body" | "button" | "canvas" | "caption" | "cite" | "code"
| "colgroup" | "content" | "data" | "datalist" | "del" | "details" | "dfn" | "dialog"
| "dir" | "div" | "dl" | "em" | "fieldset" | "figcaption" | "figure" | "font"
| "footer" | "form" | "frame" | "frameset" | "geolocation" | "h1" | "h2" | "h3" | "h4"
| "h5" | "h6" | "head" | "header" | "hgroup" | "html" | "i" | "iframe" | "ins" | "kbd"
| "keygen" | "label" | "legend" | "main" | "map" | "mark" | "marquee" | "media"
| "menu" | "menuitem" | "meter" | "nav" | "noscript" | "object" | "ol" | "output"
| "picture" | "progress" | "q" | "ruby" | "s" | "samp" | "search" | "section"
| "select" | "selectedcontent" | "slot" | "small" | "span" | "strong" | "sub"
| "summary" | "sup" | "table" | "template" | "time" | "u" | "ul" | "unknown" | "var"
| "video" => HtmlTagDefinition::default(),

// Default: unknown tags get canSelfClose: true
_ => default_tag_definition(),
}
Expand Down Expand Up @@ -457,4 +472,11 @@ mod tests {
let custom = get_html_tag_definition("my-custom-element");
assert!(custom.can_self_close);
}

#[test]
fn test_known_dom_elements_cannot_self_close() {
for name in ["div", "span", "button", "section", "table", "DIV", "video", "slot"] {
assert!(!get_html_tag_definition(name).can_self_close, "{name}");
}
}
}
44 changes: 22 additions & 22 deletions crates/oxc_angular_compiler/tests/hmr_fingerprint_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,23 @@ fn same(a: &str, b: &str, classes: &[&str]) -> bool {
// The HMR decision
// -----------------------------------------------------------------

const TWO: &str = "@Component({ selector: 'a', template: '<a/>', styles: ['.a{}'] })
const TWO: &str = "@Component({ selector: 'a', template: '<a></a>', styles: ['.a{}'] })
export class A { x = 1 }
@Component({ selector: 'b', template: `<b/>`, styles: '.b{}' })
@Component({ selector: 'b', template: `<b></b>`, styles: '.b{}' })
export class B {}
";

#[test]
fn an_edit_inside_template_or_styles_keeps_the_fingerprint() {
let classes = &["A", "B"];
for edited in [
TWO.replace("<a/>", "<a>changed</a>"),
TWO.replace("<a></a>", "<a>changed</a>"),
TWO.replace(".a{}", ".a{color:red}"),
TWO.replace("`<b/>`", "`<b>${'x'}</b>`"),
TWO.replace("`<b></b>`", "`<b>${'x'}</b>`"),
TWO.replace("'.b{}'", "'.b{} .c{}'"),
TWO.replace("['.a{}']", "['.a{}', '.more{}']"),
TWO.replace("['.a{}']", "[]"),
TWO.replace("<b/>", "<b>both</b>").replace(".a{}", ""),
TWO.replace("<b></b>", "<b>both</b>").replace(".a{}", ""),
] {
assert!(same(TWO, &edited, classes), "{edited}");
}
Expand All @@ -87,11 +87,11 @@ fn an_edit_anywhere_else_changes_the_fingerprint() {
TWO.replace("x = 1", "x = 2"),
TWO.replace("selector: 'a'", "selector: 'aa'"),
TWO.replace("export class B {}", "export class B {}\n// trailing comment"),
TWO.replace("template: '<a/>'", "templateUrl: './a.html'"),
TWO.replace("template: '<a></a>'", "templateUrl: './a.html'"),
// The shape of a value is kept: a string and an array are not the same.
TWO.replace("['.a{}']", "''"),
// The quote style is kept too.
TWO.replace("'<a/>'", "\"<a/>\""),
TWO.replace("'<a></a>'", "\"<a></a>\""),
] {
assert!(!same(TWO, &edited, classes), "{edited}");
}
Expand All @@ -114,17 +114,17 @@ fn resource_urls_stay_in_the_fingerprint() {
#[test]
fn only_the_named_classes_are_read() {
assert_eq!(components(TWO, &["A"]), ["A"]);
assert!(same(TWO, &TWO.replace("<a/>", "<a>x</a>"), &["A"]));
assert!(!same(TWO, &TWO.replace("<b/>", "<b>x</b>"), &["A"]));
assert!(!same(TWO, &TWO.replace("<a/>", "<a>x</a>"), &[]));
assert!(same(TWO, &TWO.replace("<a></a>", "<a>x</a>"), &["A"]));
assert!(!same(TWO, &TWO.replace("<b></b>", "<b>x</b>"), &["A"]));
assert!(!same(TWO, &TWO.replace("<a></a>", "<a>x</a>"), &[]));
assert_eq!(fingerprint(TWO, &["Nope"]).excluded, []);
}

/// A source the parser rejects excludes nothing, so a save that leaves the
/// file broken (here an unescaped quote inside the template) reloads.
#[test]
fn a_syntax_error_excludes_nothing() {
let broken = TWO.replace("<a/>", "<a>it's</a>");
let broken = TWO.replace("<a></a>", "<a>it's</a>");
let result = fingerprint(&broken, &["A", "B"]);
assert_eq!(result.excluded, []);
assert_eq!(result.components, NONE);
Expand Down Expand Up @@ -155,7 +155,7 @@ fn transform_reports_the_same_fingerprint() {
#[test]
fn transform_keeps_a_jit_components_template() {
let source = format!(
"{IMPORT}@Component({{ selector: 'a', template: '<a/>' }})\nexport class A {{}}\n@Component({{ selector: 'b', template: '<b/>', jit: true }})\nexport class B {{}}\n"
"{IMPORT}@Component({{ selector: 'a', template: '<a></a>' }})\nexport class A {{}}\n@Component({{ selector: 'b', template: '<b></b>', jit: true }})\nexport class B {{}}\n"
);
let allocator = Allocator::default();
let options = TransformOptions { hmr: true, ..TransformOptions::default() };
Expand All @@ -165,7 +165,7 @@ fn transform_keeps_a_jit_components_template() {
result.hmr_fingerprint.as_deref(),
Some(fingerprint_raw(&source, &["A"]).fingerprint.as_str())
);
let edited_jit = source.replace("<b/>", "<b>x</b>");
let edited_jit = source.replace("<b></b>", "<b>x</b>");
assert_ne!(
result.hmr_fingerprint.as_deref(),
Some(fingerprint_raw(&edited_jit, &["A"]).fingerprint.as_str())
Expand All @@ -180,11 +180,11 @@ fn transform_keeps_a_jit_components_template() {
fn reads_a_nested_component() {
let source = format!(
"{IMPORT}export function make() {{
@Component({{ selector: 'a', template: '<a/>', styles: ['.a{{}}'] }})
@Component({{ selector: 'a', template: '<a></a>', styles: ['.a{{}}'] }})
class A {{ x = 1 }}
return A;
}}
function one() {{ @Component({{ template: '<b/>' }}) class B {{}} return B; }}
function one() {{ @Component({{ template: '<b></b>' }}) class B {{}} return B; }}
function two() {{ @Component({{ template: '<c/>' }}) class B {{}} return B; }}
"
);
Expand All @@ -206,10 +206,10 @@ function two() {{ @Component({{ template: '<c/>' }}) class B {{}} return B; }}
assert_eq!(update.fingerprint.as_deref(), Some(fingerprint.as_str()));

let of = |edited: String| fingerprint_raw(&edited, &["A"]).fingerprint;
assert_eq!(of(source.replace("<a/>", "<a>x</a>")), fingerprint);
assert_eq!(of(source.replace("<a></a>", "<a>x</a>")), fingerprint);
assert_eq!(of(source.replace(".a{}", ".a{color:red}")), fingerprint);
assert_ne!(of(source.replace("x = 1", "x = 2")), fingerprint);
assert_ne!(of(source.replace("<b/>", "<b>x</b>")), fingerprint);
assert_ne!(of(source.replace("<b></b>", "<b>x</b>")), fingerprint);
}

// -----------------------------------------------------------------
Expand All @@ -225,7 +225,7 @@ fn leaves_a_namespace_member_out() {
@Component({{ selector: 'n', template: '<n/>' }})
export class App {{}}
}}
@Component({{ selector: 'app', template: '<a/>' }})
@Component({{ selector: 'app', template: '<a></a>' }})
export class App {{}}
"
);
Expand All @@ -238,7 +238,7 @@ export class App {{}}
assert_eq!(fingerprint_raw(&source, &["App"]).fingerprint, fingerprint);

let of = |edited: String| fingerprint_raw(&edited, &["App"]).fingerprint;
assert_eq!(of(source.replace("<a/>", "<a>x</a>")), fingerprint);
assert_eq!(of(source.replace("<a></a>", "<a>x</a>")), fingerprint);
assert_ne!(of(source.replace("<n/>", "<n>x</n>")), fingerprint);
}

Expand Down Expand Up @@ -623,11 +623,11 @@ fn ignores_decoys_elsewhere_in_the_source() {
] {
assert_eq!(fields(body, &["Foo"]), ["'<real/>'"], "{body}");
}
let body = "@Component({ template: '<a/>' })
let body = "@Component({ template: '<a></a>' })
class First {}
const helper = () => '@Component({...})'
@Component({ template: '<b/>' })
@Component({ template: '<b></b>' })
class Second {}";
assert_eq!(components(body, &["First", "Second"]), ["First", "Second"]);
assert_eq!(fields(body, &["First", "Second"]), ["'<a/>'", "'<b/>'"]);
assert_eq!(fields(body, &["First", "Second"]), ["'<a></a>'", "'<b></b>'"]);
}
54 changes: 50 additions & 4 deletions crates/oxc_angular_compiler/tests/html_parser_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2933,10 +2933,56 @@ mod more_error_tests {
fn should_report_self_closing_html_element() {
// TS: it("should report self closing html element")
// <p /> is self-closing but p is not a void element, not a custom element
let _errors = parse_errors("<p />");
// Angular reports: 'Only void, custom and foreign elements can be self closed "p"'
// Our parser may or may not report this
// For now, just verify parsing doesn't panic
assert_eq!(
parse_errors("<p />"),
vec!["Only void, custom and foreign elements can be self closed \"p\"".to_string()]
);
}

#[test]
fn should_report_self_closing_known_dom_element() {
// Angular defines every element of its DOM schema as `canSelfClose: false`
// (`html_tags.ts`), not only the ones with a definition of their own.
for (html, name) in [
("<div/>", "div"),
("<span/>x", "span"),
("<DIV/>", "DIV"),
("<template/>", "template"),
("@if (a) {<div/>}", "div"),
("<svg><foreignObject><div/></foreignObject></svg>", "div"),
] {
assert_eq!(
parse_errors(html),
vec![format!(
"Only void, custom and foreign elements can be self closed \"{name}\""
)],
"{html}"
);
}
}

#[test]
fn should_not_report_self_closing_element_in_a_namespace() {
// A known HTML name in svg or math takes its namespace: `:svg:div` is foreign.
for html in [
"<svg><div/></svg>",
"<math><span/></math>",
"<svg:div/>",
"<svg>@if (a) {<div/>}</svg>",
"<ng-container/>",
"<ng-template/>",
"<ng-content/>",
] {
assert!(parse_errors(html).is_empty(), "{html}: {:?}", parse_errors(html));
}
}

#[test]
fn should_not_report_self_closing_component_named_like_dom_element() {
// Angular only checks element tags: `<Button/>` is a component in selectorless mode.
let allocator = Allocator::default();
let result = HtmlParser::with_selectorless(&allocator, "<Button/>", "TestComp").parse();
assert!(result.errors.is_empty(), "{:?}", result.errors);
}

#[test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1277,10 +1277,10 @@ mod void_elements {

#[test]
fn should_parse_self_closing_element() {
// TS: expectFromHtml('<div/>')
let result = humanize("<div/>");
// A custom element: a known HTML element such as `<div/>` cannot be self closed.
let result = humanize("<my-cmp/>");
assert_eq!(result[0][0], HumanValue::from("Element"));
assert_eq!(result[0][1], HumanValue::from("div"));
assert_eq!(result[0][1], HumanValue::from("my-cmp"));
}
}

Expand Down