Skip to content

Commit

Permalink
Remove invalid /> when content is added to an element
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Dec 24, 2024
1 parent 3275280 commit c20cefb
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/rewritable_units/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ impl<'r, 't, H: HandlerTypes> Element<'r, 't, H> {

fn prepend_chunk(&mut self, chunk: StringChunk) {
if self.can_have_content {
self.start_tag.set_self_closing_syntax(false);
self.start_tag
.mutations
.mutate()
Expand Down Expand Up @@ -434,6 +435,7 @@ impl<'r, 't, H: HandlerTypes> Element<'r, 't, H> {

fn append_chunk(&mut self, chunk: StringChunk) {
if self.can_have_content {
self.start_tag.set_self_closing_syntax(false);
self.end_tag_mutations_mut().content_before.push_back(chunk);
}
}
Expand Down Expand Up @@ -492,6 +494,7 @@ impl<'r, 't, H: HandlerTypes> Element<'r, 't, H> {

fn set_inner_content_chunk(&mut self, chunk: StringChunk) {
if self.can_have_content {
self.start_tag.set_self_closing_syntax(false);
self.remove_content();
self.start_tag
.mutations
Expand Down
4 changes: 4 additions & 0 deletions src/rewritable_units/tokens/start_tag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ impl<'i> StartTag<'i> {
self.self_closing
}

pub(crate) fn set_self_closing_syntax(&mut self, has_slash: bool) {
self.self_closing = has_slash;
}

/// Inserts `content` before the start tag.
///
/// Consequent calls to the method append `content` to the previously inserted content.
Expand Down
24 changes: 24 additions & 0 deletions src/rewriter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,30 @@ mod tests {
assert_eq!(res, "<!-- 42 --><span><!--hello--></span>");
}

#[test]
fn rewrite_incorrect_self_closing() {
let res = rewrite_str::<LocalHandlerTypes>(
"<title /></title><div/></div><style /></style><script /></script>
<br/><br><embed/><embed> <svg><a/><path/><path></path></svg>",
RewriteStrSettings {
element_content_handlers: vec![element!("*:not(svg)", |el| {
el.set_attribute("s", if el.is_self_closing() { "y" } else { "n" })?;
el.set_attribute("c", if el.can_have_content() { "y" } else { "n" })?;
el.append("…", ContentType::Text);
Ok(())
})],
..RewriteStrSettings::new()
},
)
.unwrap();

assert_eq!(
res,
r#"<title s="y" c="y">…</title><div s="y" c="y">…</div><style s="y" c="y">…</style><script s="y" c="y">…</script>
<br s="y" c="n" /><br s="n" c="n"><embed s="y" c="n" /><embed s="n" c="n"> <svg><a s="y" c="n" /><path s="y" c="n" /><path s="n" c="y">…</path></svg>"#
);
}

#[test]
fn rewrite_arbitrary_settings() {
let res = rewrite_str("<span>Some text</span>", Settings::new()).unwrap();
Expand Down

0 comments on commit c20cefb

Please sign in to comment.