glory-ui 0.10.0

Pure Rust semantic widgets and windowed lists for Glory
Documentation
use glory_core::Vary;
use glory_render::{DocumentPart, Role, TextKind};
use glory_style::{Style, WhiteSpace};
use pulldown_cmark::{Event, Options, Parser, Tag};

use super::{MAX_MARKDOWN_BYTES, safe_destination};
use crate::{Result, Scope, Widget};

#[derive(Clone, Debug, Default)]
struct Node {
    kind: String,
    text: String,
    destination: String,
    children: Vec<Node>,
}
impl Node {
    fn plain(&self) -> String {
        let mut value = self.text.clone();
        for child in &self.children {
            value.push_str(&child.plain());
        }
        value
    }
}

fn parse(source: &str) -> Vec<Node> {
    let mut stack = vec![Node::default()];
    let mut count = 0;
    for event in Parser::new_ext(
        source,
        Options::ENABLE_TABLES
            | Options::ENABLE_STRIKETHROUGH
            | Options::ENABLE_TASKLISTS
            | Options::ENABLE_FOOTNOTES,
    ) {
        count += 1;
        if count > 16_384 || stack.len() > 64 {
            return vec![Node {
                kind: "literal".into(),
                text: source.into(),
                ..Default::default()
            }];
        }
        match event {
            Event::Start(tag) => {
                let (kind, destination) = match tag {
                    Tag::Paragraph => ("p".into(), String::new()),
                    Tag::Heading { level, .. } => (format!("h{}", level as u8), String::new()),
                    Tag::BlockQuote(_) => ("blockquote".into(), String::new()),
                    Tag::CodeBlock(_) => ("pre".into(), String::new()),
                    Tag::List(start) => (
                        if start.is_some() { "ol" } else { "ul" }.into(),
                        String::new(),
                    ),
                    Tag::Item => ("li".into(), String::new()),
                    Tag::Table(_) => ("table".into(), String::new()),
                    Tag::TableHead => ("thead".into(), String::new()),
                    Tag::TableRow => ("tr".into(), String::new()),
                    Tag::TableCell => (
                        if stack.iter().any(|n| n.kind == "thead") {
                            "th"
                        } else {
                            "td"
                        }
                        .into(),
                        String::new(),
                    ),
                    Tag::Emphasis => ("em".into(), String::new()),
                    Tag::Strong => ("strong".into(), String::new()),
                    Tag::Strikethrough => ("del".into(), String::new()),
                    Tag::Link { dest_url, .. } => ("a".into(), dest_url.into_string()),
                    Tag::Image { dest_url, .. } => ("img".into(), dest_url.into_string()),
                    Tag::FootnoteDefinition(label) => ("footnote".into(), label.into_string()),
                    _ => ("span".into(), String::new()),
                };
                stack.push(Node {
                    kind,
                    destination,
                    ..Default::default()
                });
            }
            Event::End(_) => {
                if stack.len() > 1 {
                    let mut node = stack.pop().unwrap();
                    if node.kind == "thead" {
                        node.children = vec![Node {
                            kind: "tr".into(),
                            children: node.children,
                            ..Default::default()
                        }];
                    }
                    if node.kind == "table" {
                        let rows = node
                            .children
                            .iter()
                            .filter(|n| n.kind != "thead")
                            .cloned()
                            .collect();
                        node.children.retain(|n| n.kind == "thead");
                        node.children.push(Node {
                            kind: "tbody".into(),
                            children: rows,
                            ..Default::default()
                        });
                    }
                    stack.last_mut().unwrap().children.push(node);
                }
            }
            event => {
                let (kind, text) = match event {
                    Event::Text(value) => ("text", value.into_string()),
                    Event::Code(value) => ("code", value.into_string()),
                    Event::Html(value) | Event::InlineHtml(value) => {
                        ("literal", value.into_string())
                    }
                    Event::SoftBreak => ("text", "\n".into()),
                    Event::HardBreak => ("break", "\n".into()),
                    Event::Rule => ("hr", String::new()),
                    Event::TaskListMarker(checked) => {
                        (if checked { "checked" } else { "unchecked" }, String::new())
                    }
                    Event::FootnoteReference(label) => ("footnote-ref", format!("[{}]", label)),
                    _ => ("text", String::new()),
                };
                stack.last_mut().unwrap().children.push(Node {
                    kind: kind.into(),
                    text,
                    ..Default::default()
                });
            }
        }
    }
    stack.pop().unwrap_or_default().children
}

fn lower(node: Node, images: bool) -> Box<dyn Widget> {
    let class = format!("glory-markdown-{}", node.kind);
    if node.kind == "hr" {
        return Box::new(crate::view().class(class).role(Role::Separator));
    }
    if node.kind == "checked" || node.kind == "unchecked" {
        return Box::new(
            crate::check()
                .class(class)
                .checked(node.kind == "checked")
                .enabled(false),
        );
    }
    if node.kind == "a" || node.kind == "img" {
        let label = node.plain();
        if safe_destination(&node.destination) {
            if node.kind == "img" && images && !node.destination.starts_with("mailto:") {
                return Box::new(
                    crate::image()
                        .class(class)
                        .alt(label)
                        .source(node.destination),
                );
            }
            return Box::new(crate::link().class(class).target(node.destination).label(
                if node.kind == "img" {
                    format!("[Image: {label}]")
                } else {
                    label
                },
            ));
        }
        return Box::new(crate::text().class(class).content(label));
    }
    if node.kind == "pre" || node.kind == "code" || node.kind == "literal" {
        return Box::new(
            crate::text()
                .class(class)
                .kind(TextKind::Code)
                .content(node.plain())
                .style(Style::new().white_space(WhiteSpace::PreWrap)),
        );
    }
    if node.kind.starts_with('h')
        && node.kind.len() == 2
        && let Ok(level) = node.kind[1..].parse::<u8>()
    {
        return Box::new(
            crate::text()
                .class(class)
                .kind(TextKind::Heading(level))
                .content(node.plain()),
        );
    }
    if node.children.is_empty() {
        return Box::new(crate::text().class(class).content(node.text));
    }
    let part = match node.kind.as_str() {
        "blockquote" => Some(DocumentPart::Blockquote),
        "ol" => Some(DocumentPart::OrderedList),
        "ul" => Some(DocumentPart::UnorderedList),
        "li" => Some(DocumentPart::ListItem),
        "table" => Some(DocumentPart::Table),
        "thead" => Some(DocumentPart::TableHead),
        "tbody" => Some(DocumentPart::TableBody),
        "tr" => Some(DocumentPart::TableRow),
        "th" => Some(DocumentPart::ColumnHeader),
        "td" => Some(DocumentPart::TableCell),
        "strong" => Some(DocumentPart::Strong),
        "em" => Some(DocumentPart::Emphasis),
        "del" => Some(DocumentPart::Strikethrough),
        _ => None,
    };
    let mut view = crate::view().class(class).fill(
        node.children
            .into_iter()
            .map(|n| lower(n, images))
            .collect::<Vec<_>>(),
    );
    if let Some(part) = part {
        view = view.document_part(part);
    }
    Box::new(view)
}

pub struct MarkdownPreview {
    source: Vary<String>,
    class: Vary<String>,
    images: bool,
}
pub fn markdown_preview(source: impl Into<Vary<String>>) -> MarkdownPreview {
    MarkdownPreview {
        source: source.into(),
        class: String::new().into(),
        images: false,
    }
}
impl MarkdownPreview {
    pub fn class(mut self, class: impl Into<Vary<String>>) -> Self {
        self.class = class.into();
        self
    }
    /// Remote images are opt-in; applications may use their own authenticated preview instead.
    pub fn images(mut self, allowed: bool) -> Self {
        self.images = allowed;
        self
    }
}
impl Widget for MarkdownPreview {
    fn build(&mut self, scope: &Scope) -> Result {
        let source = self.source.clone();
        let rows = scope.bond(move || vec![source.get()]);
        let images = self.images;
        crate::view()
            .class(self.class.clone())
            .fill(
                crate::each(rows)
                    .key(|source| source.clone())
                    .seed(move |source| {
                        let children = if source.len() <= MAX_MARKDOWN_BYTES {
                            parse(&source)
                                .into_iter()
                                .map(|node| lower(node, images))
                                .collect::<Vec<_>>()
                        } else {
                            vec![Box::new(
                                crate::text().content("Markdown preview exceeds its source budget"),
                            ) as Box<dyn Widget>]
                        };
                        crate::view()
                            .class("glory-markdown-document")
                            .fill(children)
                    }),
            )
            .build(scope)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn commonmark_gfm_builds_valid_semantic_tree_without_html_execution() {
        let app = crate::App::memory();
        app.mount(markdown_preview("# Heading\n\n**bold** *em* ~~deleted~~\n\n> quote\n\n- [x] done\n  - nested\n\n| a | b |\n|---|---|\n| x | y |\n\n```rust\nlet x = 1;\n```\n\n<script>alert(1)</script>\n\n[x](javascript:evil)\n\n![alt](https://example.com/image.png)" )).unwrap();
        let tree = app.tree();
        let mut pending = tree.roots().to_vec();
        let mut table = false;
        let mut task = false;
        while let Some(id) = pending.pop() {
            let node = tree.node(id).unwrap();
            let descriptor = node.descriptor.view();
            table |= descriptor.document_part() == Some(DocumentPart::Table);
            if let glory_render::Props::Check(check) = descriptor.props {
                task |= check.checked && !check.enabled;
            }
            if let glory_render::Props::Link(link) = descriptor.props {
                assert!(!link.target.starts_with("javascript:"));
            }
            assert!(!matches!(descriptor.props, glory_render::Props::Image(_)));
            pending.extend(node.children.iter().copied());
        }
        assert!(table && task);
    }
}