glory-html 0.10.0

Shared semantic to HTML mapping for Glory rendering hosts
Documentation
use crate::{Kind, Part, Property, Shape};
use glory_render::memory::Memory;
use glory_render::{Error, NodeId};
use std::fmt::Write;

pub fn escape(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    escape_into(value, &mut out);
    out
}
fn escape_into(value: &str, out: &mut String) {
    for ch in value.chars() {
        match ch {
            '&' => out.push_str("&"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            '\0' => out.push('\u{fffd}'),
            _ => out.push(ch),
        }
    }
}
pub fn serialize(tree: &Memory, key: impl Fn(NodeId) -> Option<u64>) -> Result<String, Error> {
    fn node(
        tree: &Memory,
        id: NodeId,
        key: &impl Fn(NodeId) -> Option<u64>,
        out: &mut String,
    ) -> Result<(), Error> {
        let model = tree.node(id)?;
        if model.suspended {
            return Ok(());
        }
        let key_value = key(id).ok_or(Error::NodeGone(id))?;
        let shape = crate::shape_in(tree, id)?;
        if shape.pieces.is_empty() {
            write!(out, "<!--gly:s:{key_value}-->").expect("writing to a String");
            if let Some(crate::display::Placement::Root(frame)) = &shape.display {
                for child in &model.children {
                    if !matches!(tree.node(*child)?.descriptor.view().options.get::<crate::display::Placement>(),Some(crate::display::Placement::Outlet{frame:other,..}) if std::rc::Rc::ptr_eq(frame,other))
                    {
                        return Err(Error::InvalidPlacement("display child has no outlet"));
                    }
                }
                fn display(
                    nodes: &[crate::display::Tree],
                    frame: &crate::display::Frame,
                    parent: u64,
                    out: &mut String,
                    outlet: &mut dyn FnMut(u16, &mut String) -> Result<(), Error>,
                ) -> Result<(), Error> {
                    for item in nodes {
                        match item {
                            crate::display::Tree::Text(text) => {
                                out.push_str("<!--gly:dt-->");
                                escape_into(text, out);
                            }
                            crate::display::Tree::Element {
                                tag,
                                attrs,
                                children,
                            } => {
                                out.push('<');
                                out.push_str(tag);
                                for (name, value) in attrs {
                                    out.push(' ');
                                    out.push_str(name);
                                    out.push_str("=\"");
                                    escape_into(value, out);
                                    out.push('"');
                                }
                                out.push('>');
                                display(children, frame, parent, out, outlet)?;
                                out.push_str("</");
                                out.push_str(tag);
                                out.push('>');
                            }
                            crate::display::Tree::Outlet(slot) => {
                                let marker = |out: &mut String| {
                                    write!(out, "<!--gly:slot:{parent}:{slot}-->")
                                        .expect("writing to a String");
                                };
                                if frame.compiled().slots[*slot as usize].kind
                                    == crate::template::Kind::Children
                                {
                                    marker(out);
                                    outlet(*slot, out)?;
                                } else {
                                    outlet(*slot, out)?;
                                    marker(out);
                                }
                            }
                        }
                    }
                    Ok(())
                }
                display(&frame.tree(), frame, key_value, out, &mut |slot, out| {
                    for child in &model.children {
                        if matches!(tree.node(*child)?.descriptor.view().options.get::<crate::display::Placement>(),Some(crate::display::Placement::Outlet{frame:other,slot:other_slot}) if std::rc::Rc::ptr_eq(frame,other) && slot==*other_slot)
                        {
                            node(tree, *child, key, out)?;
                        }
                    }
                    Ok(())
                })?;
            } else {
                for child in &model.children {
                    node(tree, *child, key, out)?;
                }
            }
            write!(out, "<!--gly:e:{key_value}-->").expect("writing to a String");
        } else {
            piece(&shape, shape.root_part()?, key_value, out, &mut |out| {
                for child in &model.children {
                    node(tree, *child, key, out)?;
                }
                Ok(())
            })?;
        }
        Ok(())
    }
    fn piece(
        shape: &Shape,
        part: Part,
        key: u64,
        out: &mut String,
        children: &mut dyn FnMut(&mut String) -> Result<(), Error>,
    ) -> Result<(), Error> {
        let item = shape
            .pieces
            .iter()
            .find(|piece| piece.part == part)
            .expect("HTML part");
        match &item.kind {
            Kind::Text(value) => {
                write!(out, "<!--gly:t:{key}-->").expect("writing to a String");
                escape_into(value, out);
            }
            Kind::Element {
                tag,
                attributes,
                properties,
            } => {
                out.push('<');
                out.push_str(tag);
                write!(
                    out,
                    " data-gly-key=\"{key}\" data-gly-part=\"{}\"",
                    part.name()
                )
                .expect("writing to a String");
                for (name, value) in attributes {
                    out.push(' ');
                    out.push_str(name);
                    out.push_str("=\"");
                    escape_into(value, out);
                    out.push('"');
                }
                out.push('>');
                if let Some(Property::RichDocument(document)) = properties.get("richDocument") {
                    rich_document_into(document, out);
                }
                if *tag == "select"
                    && let Some(options) = &shape.select_options
                {
                    let keys = match properties.get("selectedKeys") {
                        Some(Property::SelectedKeys(keys)) => keys.as_slice(),
                        _ => &[],
                    };
                    select_options_into(options, keys, out);
                }
                if matches!(*tag, "input" | "img") {
                    return Ok(());
                }
                if *tag == "textarea"
                    && let Some(Property::Text(value)) = properties.get("value")
                {
                    // HTML parsers drop one leading LF immediately after textarea.
                    if value.starts_with('\n') {
                        out.push('\n');
                    }
                    escape_into(value, out);
                }
                for child in shape
                    .pieces
                    .iter()
                    .filter(|piece| piece.parent == Some(part))
                {
                    piece(shape, child.part, key, out, &mut |_| Ok(()))?;
                }
                if shape.children == Some(part) {
                    children(out)?;
                }
                out.push_str("</");
                out.push_str(tag);
                out.push('>');
            }
        }
        Ok(())
    }
    let mut out = String::new();
    for root in tree.roots() {
        node(tree, *root, &key, &mut out)?;
    }
    Ok(out)
}

/// Serialize the finite intrinsic editor document; never accepts raw markup.
pub fn rich_document(document: &glory_render::RichDocument) -> String {
    let mut out = String::new();
    rich_document_into(document, &mut out);
    out
}

fn rich_document_into(document: &glory_render::RichDocument, out: &mut String) {
    use glory_render::RichBlockKind;
    for block in &document.blocks {
        let tag = match block.kind {
            RichBlockKind::Paragraph => "p",
            RichBlockKind::Heading(1) => "h1",
            RichBlockKind::Heading(2) => "h2",
            RichBlockKind::Heading(3) => "h3",
            RichBlockKind::Heading(4) => "h4",
            RichBlockKind::Heading(5) => "h5",
            RichBlockKind::Heading(6) => "h6",
            RichBlockKind::Quote => "blockquote",
            RichBlockKind::Heading(_) => unreachable!("validated rich heading"),
        };
        out.push('<');
        out.push_str(tag);
        out.push('>');
        for run in &block.runs {
            if let Some(link) = &run.marks.link {
                out.push_str("<a href=\"");
                escape_into(link, out);
                out.push_str("\">");
            }
            if run.marks.bold {
                out.push_str("<strong>");
            }
            if run.marks.italic {
                out.push_str("<em>");
            }
            if run.marks.code {
                out.push_str("<code>");
            }
            escape_into(&run.text, out);
            if run.marks.code {
                out.push_str("</code>");
            }
            if run.marks.italic {
                out.push_str("</em>");
            }
            if run.marks.bold {
                out.push_str("</strong>");
            }
            if run.marks.link.is_some() {
                out.push_str("</a>");
            }
        }
        if block.runs.iter().all(|run| run.text.is_empty()) {
            out.push_str("<br>");
        }
        out.push_str("</");
        out.push_str(tag);
        out.push('>');
    }
}

/// Serialize only the finite intrinsic children of a native select.
pub fn select_options(config: &crate::SelectOptions, keys: &[String]) -> String {
    let mut out = String::new();
    select_options_into(config, keys, &mut out);
    out
}

fn select_options_into(config: &crate::SelectOptions, keys: &[String], out: &mut String) {
    fn option(value: &glory_render::SelectOption, keys: &[String], out: &mut String) {
        out.push_str("<option data-gly-option=\"");
        escape_into(value.key.as_str(), out);
        out.push_str("\" value=\"");
        escape_into(&value.value, out);
        out.push('"');
        if value.disabled {
            out.push_str(" disabled");
        }
        if keys.iter().any(|key| key == value.key.as_str()) {
            out.push_str(" selected");
        }
        out.push('>');
        escape_into(&value.label, out);
        out.push_str("</option>");
    }
    if let Some(placeholder) = &config.placeholder {
        out.push_str("<option data-gly-placeholder=\"\" value=\"\" disabled hidden");
        if keys.is_empty() {
            out.push_str(" selected");
        }
        out.push('>');
        escape_into(placeholder, out);
        out.push_str("</option>");
    }
    for entry in config.entries.iter() {
        match entry {
            glory_render::SelectEntry::Divider => out.push_str("<hr>"),
            glory_render::SelectEntry::Option(value) => option(value, keys, out),
            glory_render::SelectEntry::Group(group) => {
                out.push_str("<optgroup label=\"");
                escape_into(&group.label, out);
                out.push('"');
                if group.disabled {
                    out.push_str(" disabled");
                }
                out.push('>');
                for value in &group.options {
                    option(value, keys, out);
                }
                out.push_str("</optgroup>");
            }
        }
    }
}