use std::cell::{Cell, RefCell};
use std::rc::Rc;
use lol_html::{HtmlRewriter, Settings, element, end_tag};
use crate::error::LivewireError;
pub fn insert_attributes(html: &str, attributes: &[(String, String)]) -> Result<String, LivewireError> {
if attributes.is_empty() {
return Ok(html.to_owned());
}
let start = first_element_start(html)?;
let mut insert_at = start + 1;
let bytes = html.as_bytes();
while insert_at < bytes.len() && !is_tag_name_terminator(bytes[insert_at]) {
insert_at += 1;
}
let mut output = String::with_capacity(
html.len()
+ attributes
.iter()
.map(|(name, value)| name.len() + value.len() + 4)
.sum::<usize>(),
);
output.push_str(&html[..insert_at]);
for (name, value) in attributes {
output.push(' ');
output.push_str(name);
output.push_str("=\"");
output.push_str(&escape_attribute(value));
output.push('"');
}
output.push_str(&html[insert_at..]);
Ok(output)
}
pub fn escape_attribute(value: &str) -> String {
const NEEDS_ESCAPE: [bool; 256] = {
let mut table = [false; 256];
table[b'&' as usize] = true;
table[b'<' as usize] = true;
table[b'>' as usize] = true;
table[b'"' as usize] = true;
table[b'\'' as usize] = true;
table
};
if !value.bytes().any(|byte| NEEDS_ESCAPE[byte as usize]) {
return value.to_owned();
}
let mut escaped = String::with_capacity(value.len() + 16);
for character in value.chars() {
match character {
'&' => escaped.push_str("&"),
'<' => escaped.push_str("<"),
'>' => escaped.push_str(">"),
'"' => escaped.push_str("""),
'\'' => escaped.push_str("'"),
other => escaped.push(other),
}
}
escaped
}
pub fn count_root_elements(html: &str) -> usize {
let state = Rc::new(RefCell::new(RootCount::default()));
let element_state = Rc::clone(&state);
let mut rewriter = HtmlRewriter::new(
Settings {
element_content_handlers: vec![element!("*", move |element| {
let opens = element.can_have_content() && !element.is_self_closing();
{
let mut state = element_state.borrow_mut();
if state.depth == 0 {
state.count += 1;
}
if opens {
state.depth += 1;
}
}
if opens {
let end_state = Rc::clone(&element_state);
element.on_end_tag(end_tag!(move |_| {
let mut state = end_state.borrow_mut();
state.depth = state.depth.saturating_sub(1);
Ok(())
}))?;
}
Ok(())
})],
..Settings::new()
},
|_: &[u8]| {},
);
let _ = rewriter.write(html.as_bytes());
let _ = rewriter.end();
let state = state.borrow();
state.count
}
#[derive(Default)]
struct RootCount {
depth: usize,
count: usize,
}
fn first_element_start(html: &str) -> Result<usize, LivewireError> {
let start = Rc::new(Cell::new(None));
let element_start = Rc::clone(&start);
let mut rewriter = HtmlRewriter::new(
Settings {
element_content_handlers: vec![element!("*", move |element| {
if element_start.get().is_none() {
element_start.set(Some(element.source_location().bytes().start));
}
Ok(())
})],
..Settings::new()
},
|_: &[u8]| {},
);
rewriter
.write(html.as_bytes())
.map_err(|error| LivewireError::MalformedPayload(error.to_string()))?;
rewriter
.end()
.map_err(|error| LivewireError::MalformedPayload(error.to_string()))?;
start.get().ok_or(LivewireError::RootTagMissing)
}
fn is_tag_name_terminator(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'\x0c' | b'/' | b'>')
}
#[cfg(test)]
mod tests {
use super::*;
fn attributes(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect()
}
#[test]
fn inserts_into_a_plain_root_element() {
let html = insert_attributes("<div></div>", &attributes(&[("wire:id", "abc")])).unwrap();
assert_eq!(html, "<div wire:id=\"abc\"></div>");
}
#[test]
fn inserts_before_existing_attributes() {
let html = insert_attributes(
"<div class=\"a\" data-b='c' hidden>text</div>",
&attributes(&[("wire:id", "abc"), ("wire:name", "counter")]),
)
.unwrap();
assert_eq!(
html,
"<div wire:id=\"abc\" wire:name=\"counter\" class=\"a\" data-b='c' hidden>text</div>"
);
}
#[test]
fn preserves_every_other_byte() {
let source = concat!(
"<div class=\"a\" >\n",
" <script>if (a < b && c > d) { x = \"<span>\"; }</script>\n",
" <!-- keep \"quotes\" & <tags> -->\n",
" <img src=\"x.png\" />\n",
"</div>\n",
);
let html = insert_attributes(source, &attributes(&[("wire:id", "abc")])).unwrap();
assert_eq!(html, source.replacen("<div", "<div wire:id=\"abc\"", 1));
}
#[test]
fn skips_leading_whitespace() {
let html = insert_attributes("\n\n <div></div>", &attributes(&[("wire:id", "abc")])).unwrap();
assert_eq!(html, "\n\n <div wire:id=\"abc\"></div>");
}
#[test]
fn skips_leading_comments_and_text() {
let html = insert_attributes(
"<!-- hello -->\n text\n <section id=\"s\"></section>",
&attributes(&[("wire:id", "abc")]),
)
.unwrap();
assert_eq!(
html,
"<!-- hello -->\n text\n <section wire:id=\"abc\" id=\"s\"></section>"
);
}
#[test]
fn targets_a_self_closing_element() {
let html = insert_attributes("<img src=\"x.png\" />", &attributes(&[("wire:id", "abc")])).unwrap();
assert_eq!(html, "<img wire:id=\"abc\" src=\"x.png\" />");
}
#[test]
fn missing_root_element_is_an_error() {
assert_eq!(
insert_attributes("", &attributes(&[("wire:id", "abc")])),
Err(LivewireError::RootTagMissing)
);
assert_eq!(
insert_attributes("just some text", &attributes(&[("wire:id", "abc")])),
Err(LivewireError::RootTagMissing)
);
assert_eq!(
insert_attributes("<!doctype html><!-- c -->", &attributes(&[("wire:id", "abc")])),
Err(LivewireError::RootTagMissing)
);
}
#[test]
fn empty_attributes_return_the_input_unchanged() {
assert_eq!(insert_attributes("<div></div>", &[]).unwrap(), "<div></div>");
assert_eq!(insert_attributes("", &[]).unwrap(), "");
}
#[test]
fn escapes_every_character_php_escapes() {
assert_eq!(escape_attribute("&"), "&");
assert_eq!(escape_attribute("<"), "<");
assert_eq!(escape_attribute(">"), ">");
assert_eq!(escape_attribute("\""), """);
assert_eq!(escape_attribute("'"), "'");
}
#[test]
fn leaves_everything_else_alone() {
assert_eq!(escape_attribute("a/b=c d?e#f"), "a/b=c d?e#f");
assert_eq!(escape_attribute("ação"), "ação");
assert_eq!(escape_attribute(""), "");
}
#[test]
fn does_not_double_escape() {
assert_eq!(escape_attribute("&"), "&amp;");
}
#[test]
fn escapes_real_attribute_values() {
let html = insert_attributes(
"<div></div>",
&attributes(&[
("data-quote", "\""),
("data-apostrophe", "'"),
("data-amp", "&"),
("data-lt", "<"),
("data-gt", ">"),
]),
)
.unwrap();
assert_eq!(
html,
"<div data-quote=\""\" data-apostrophe=\"'\" data-amp=\"&\" data-lt=\"<\" data-gt=\">\"></div>"
);
}
#[test]
fn escapes_a_snapshot_json_value() {
let snapshot = r#"{"data":{"count":1},"memo":{"id":"a","name":"counter"},"checksum":"ab<&"}"#;
let html = insert_attributes("<div></div>", &attributes(&[("wire:snapshot", snapshot)])).unwrap();
assert_eq!(
html,
"<div wire:snapshot=\"{"data":{"count":1},"memo":{"id":"a","name":"counter"},"checksum":"ab<&"}\"></div>"
);
}
#[test]
fn counts_sibling_roots() {
assert_eq!(count_root_elements("<div></div><div></div>"), 2);
}
#[test]
fn counts_nested_markup_as_one_root() {
assert_eq!(count_root_elements("<div><span></span></div>"), 1);
}
#[test]
fn ignores_leading_text() {
assert_eq!(count_root_elements("text<div></div>"), 1);
}
#[test]
fn ignores_comments() {
assert_eq!(count_root_elements("<!-- c --><div></div>"), 1);
}
#[test]
fn counts_void_elements_as_roots() {
assert_eq!(count_root_elements("<img src=\"x\"><br>"), 2);
assert_eq!(count_root_elements("<img src=\"x\"><div></div>"), 2);
}
#[test]
fn counts_nothing_in_empty_markup() {
assert_eq!(count_root_elements(""), 0);
assert_eq!(count_root_elements(" <!-- c --> text"), 0);
}
}