livewire-rust 0.1.3

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! Injecting Livewire's wire attributes into rendered component HTML.
//!
//! A component's view renders one root element. The framework adds `wire:id`, `wire:name`,
//! `wire:snapshot`, and `wire:effects` to that element's start tag, right after the tag name,
//! leaving every other byte of the rendered document untouched. Upstream does that with a regular
//! expression and `substr_replace`; here the element is located with `lol_html`, which understands
//! comments, doctypes, and raw-text elements, and the attributes are spliced in at the byte the
//! scanner reports.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use lol_html::{HtmlRewriter, Settings, element, end_tag};

use crate::error::LivewireError;

/// Inserts the attributes into the first element of `html`.
///
/// The attributes go right after the tag name, so `<div class="a">` becomes
/// `<div wire:id="x" class="a">`. Nothing else in the document is rewritten: attribute quoting,
/// whitespace, comments, script bodies, and self-closing forms keep their exact bytes.
///
/// Values are escaped with [`escape_attribute`]. Attribute names are written verbatim.
///
/// # Errors
///
/// Returns [`LivewireError::RootTagMissing`] when the document contains no element at all, and
/// [`LivewireError::MalformedPayload`] when the HTML scanner rejects the document.
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)
}

/// Escapes a value for a double-quoted HTML attribute.
///
/// This matches PHP's `htmlspecialchars($value, ENT_QUOTES|ENT_SUBSTITUTE)`: `&`, `<`, `>`, `"`,
/// and `'` become `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#039;`. No other character changes, and
/// `&` is escaped first so that an existing entity is not rewritten twice.
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("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#039;"),
            other => escaped.push(other),
        }
    }

    escaped
}

/// Counts the top-level elements in rendered component HTML.
///
/// Text, whitespace, comments, and doctypes are ignored, and elements nested inside another
/// element are not counted: `"<div></div><div></div>"` is 2 while `"<div><span></span></div>"` is
/// 1.
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
}

/// The running root count while the scanner walks the document.
#[derive(Default)]
struct RootCount {
    /// How many elements are open right now.
    depth: usize,
    /// How many elements started while nothing was open.
    count: usize,
}

/// Returns the byte offset of the `<` of the first element in `html`.
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)
}

/// Whether `byte` ends an HTML tag name.
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("&"), "&amp;");
        assert_eq!(escape_attribute("<"), "&lt;");
        assert_eq!(escape_attribute(">"), "&gt;");
        assert_eq!(escape_attribute("\""), "&quot;");
        assert_eq!(escape_attribute("'"), "&#039;");
    }

    #[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;"), "&amp;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=\"&quot;\" data-apostrophe=\"&#039;\" data-amp=\"&amp;\" data-lt=\"&lt;\" data-gt=\"&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=\"{&quot;data&quot;:{&quot;count&quot;:1},&quot;memo&quot;:{&quot;id&quot;:&quot;a&quot;,&quot;name&quot;:&quot;counter&quot;},&quot;checksum&quot;:&quot;ab&lt;&amp;&quot;}\"></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);
    }
}