aster-ssg 0.3.0

A typst-native static site generator, inspired by Astro.
Documentation
//! DOM helpers for HTML element access and document structure.

use typst::ecow::EcoString;
use typst_html::{HtmlDocument, HtmlElement, HtmlNode};

/// Extension methods on [`HtmlElement`] for common attribute and text access.
pub trait HtmlElementExt {
    /// Check if the element's tag matches `tag`.
    fn is_tag(&self, tag: typst_html::HtmlTag) -> bool;

    /// Return a clone of the value of the first attribute matching `name`.
    fn get_attr(&self, name: &str) -> Option<EcoString>;

    /// Mutate the first attribute whose name is `name` with `f`.
    fn update_attr(&mut self, name: &str, f: impl FnOnce(&mut EcoString));

    /// Collect the text of all descendant `HtmlNode::Text` nodes,
    /// inserting `\n` for `<br>` elements so the result reflects
    /// multi-line content in source order.
    fn inner_text(&self) -> EcoString;
}

/// Append one generated element to the document head, creating it if needed.
pub fn append_to_head(document: &mut HtmlDocument, element: HtmlElement) {
    let root = document.root_mut();
    debug_assert_eq!(root.tag, typst_html::tag::html);

    let head_index = root
        .children
        .iter()
        .position(|node| matches!(node, HtmlNode::Element(element) if element.is_tag(typst_html::tag::head)))
        .unwrap_or_else(|| {
            let body_index = root
                .children
                .iter()
                .position(|node| matches!(node, HtmlNode::Element(element) if element.is_tag(typst_html::tag::body)))
                .unwrap_or(0);
            root.children
                .insert(body_index, HtmlElement::new(typst_html::tag::head).into());
            body_index
        });

    let HtmlNode::Element(head) = &mut root.children.make_mut()[head_index] else {
        unreachable!("head index must identify an element");
    };
    head.children.push(HtmlNode::Element(element));
}

impl HtmlElementExt for HtmlElement {
    #[inline]
    fn is_tag(&self, tag: typst_html::HtmlTag) -> bool {
        self.tag == tag
    }

    fn get_attr(&self, name: &str) -> Option<EcoString> {
        self.attrs
            .0
            .iter()
            .find(|(a, _)| a.resolve().as_str() == name)
            .map(|(_, v)| v.clone())
    }

    fn update_attr(&mut self, name: &str, f: impl FnOnce(&mut EcoString)) {
        for (a, v) in self.attrs.0.make_mut().iter_mut() {
            if a.resolve().as_str() == name {
                return f(v);
            }
        }
    }

    fn inner_text(&self) -> EcoString {
        fn collect(elem: &HtmlElement, out: &mut EcoString) {
            for child in &elem.children {
                match child {
                    HtmlNode::Text(t, _) => out.push_str(t.as_str()),
                    HtmlNode::Element(e) if e.tag == typst_html::tag::br => out.push('\n'),
                    HtmlNode::Element(e) => collect(e, out),
                    _ => {}
                }
            }
        }

        let mut out = EcoString::new();
        collect(self, &mut out);
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn updates_only_the_first_matching_attribute() {
        let mut element = HtmlElement::new(typst_html::tag::link)
            .with_attr(typst_html::attr::href, "first")
            .with_attr(typst_html::attr::href, "second");

        element.update_attr("href", |value| *value = "updated".into());

        let values = element
            .attrs
            .0
            .iter()
            .map(|(_, value)| value.as_str())
            .collect::<Vec<_>>();
        assert_eq!(values, ["updated", "second"]);
    }
}