Skip to main content

devpage_core/render/
markdown.rs

1//! Markdown to HTML: comrak with devpage's extensions, fenced code
2//! highlighted, frame ids kept free, designs embedded and diagrams drawn.
3
4use comrak::options::Plugins;
5use comrak::{Options, markdown_to_html_with_plugins};
6
7use crate::highlight::Highlighter;
8use crate::markup::split_front_matter;
9use crate::widgets::Widgets;
10
11/// GitHub-flavoured Markdown with raw HTML allowed. Fenced code goes through
12/// `highlight::Highlighter`, which keeps the language only on Mermaid blocks
13/// (`<pre lang="mermaid">`), so `markdown` can find and draw them.
14pub(crate) fn options() -> Options<'static> {
15    let mut options = Options::default();
16    options.extension.table = true;
17    options.extension.strikethrough = true;
18    options.extension.autolink = true;
19    options.extension.tasklist = true;
20    options.extension.footnotes = true;
21    options.extension.header_id_prefix = Some(String::new());
22    // A page may open with YAML front matter between `---` lines; it is
23    // never shown (see `front_matter`).
24    options.extension.front_matter_delimiter = Some("---".to_string());
25    options.render.r#unsafe = true;
26    options.render.github_pre_lang = true;
27    options
28}
29
30/// The ids of devpage's own frame — the page, the sidebar and its tree, the
31/// navbar, the theme corner and the comments — used by `assets/style.css` and
32/// `assets/devpage.js`. They all start with `devpage-`, so a heading's id,
33/// taken from its text, matches one only if the heading spells it out; such a
34/// heading's id gets `-heading` added, so a frame id is never a heading's.
35pub const FRAME_IDS: [&str; 8] = [
36    "devpage-page",
37    "devpage-nav",
38    "devpage-sidebar",
39    "devpage-navbar",
40    "devpage-corner",
41    "devpage-comments",
42    "devpage-comments-toggle",
43    "devpage-comment-mode",
44];
45
46/// Renders Markdown to HTML, highlighting fenced code (see `highlight`),
47/// turning an image of a design into its canvas (see `embed_designs`) and
48/// drawing each Mermaid fence (see `diagrams`).
49pub fn markdown(source: &str) -> String {
50    let mut plugins = Plugins::default();
51    plugins.render.codefence_syntax_highlighter = Some(&Highlighter);
52    // A wide table scrolls inside its own box rather than widening the page.
53    let mut html = markdown_to_html_with_plugins(source, &options(), &plugins)
54        .replace("<table>", "<div class=\"table-scroll\"><table>")
55        .replace("</table>", "</table></div>");
56    for id in FRAME_IDS {
57        if html.contains(&format!("id=\"{id}\"")) {
58            html = html
59                .replace(&format!("id=\"{id}\""), &format!("id=\"{id}-heading\""))
60                .replace(
61                    &format!("href=\"#{id}\""),
62                    &format!("href=\"#{id}-heading\""),
63                );
64        }
65    }
66    crate::diagrams::draw_fences(&embed_designs(&html))
67}
68
69/// Renders a page's Markdown, the tags of `widgets` expanded first.
70pub fn markdown_in(widgets: &Widgets, source: &str) -> String {
71    markdown(&crate::widgets::expand(
72        source,
73        widgets.names(),
74        &mut Vec::new(),
75    ))
76}
77
78/// `![Name](x.design)` embeds the design: comrak's `<img>` becomes the canvas
79/// the design script draws on. The canvas keeps the link in `src`, so links
80/// are rebased and checked as an image's are. A raw `<img>` in the page is an
81/// image like any other, with or without a closing `/`.
82fn embed_designs(html: &str) -> String {
83    let mut out = String::new();
84    // ASCII lowercasing keeps every byte where it was, so a position found in
85    // `lower` is the same position in `html`.
86    let lower = html.to_ascii_lowercase();
87    let mut from = 0;
88    while let Some(at) = lower[from..].find("<img").map(|at| from + at) {
89        out.push_str(&html[from..at]);
90        let rest = &html[at..];
91        if !rest[4..].starts_with(|c: char| c.is_ascii_whitespace()) {
92            out.push_str(&rest[..4]);
93            from = at + 4;
94            continue;
95        }
96        let end = tag_end(rest);
97        let tag = &rest[..end];
98        let attributes = attributes(&tag[4..]);
99        let attribute = |name: &str| {
100            attributes
101                .iter()
102                .find(|(n, _)| n.eq_ignore_ascii_case(name))
103                .map(|(_, value)| value.as_str())
104        };
105        match attribute("src") {
106            Some(src)
107                if src
108                    .split(['?', '#'])
109                    .next()
110                    .is_some_and(|p| p.ends_with(".design")) =>
111            {
112                out.push_str(&format!(
113                    "<span class=\"design-embed\"><canvas class=\"design\" src=\"{}\" role=\"img\" aria-label=\"{}\"></canvas>{}</span>",
114                    src.replace('"', "&quot;"),
115                    attribute("alt").unwrap_or_default().replace('"', "&quot;"),
116                    crate::navbar::design_theme_toggle()
117                ));
118            }
119            _ => out.push_str(tag),
120        }
121        from = at + end;
122    }
123    out.push_str(&html[from..]);
124    out
125}
126
127/// A tag's attributes, from just after its name up to its closing `>`: each
128/// name with its value — double-quoted, single-quoted, unquoted, or empty for
129/// a bare name — separated by any whitespace.
130fn attributes(tag: &str) -> Vec<(String, String)> {
131    let mut attributes = Vec::new();
132    let mut chars = tag.char_indices().peekable();
133    loop {
134        while chars
135            .next_if(|(_, c)| c.is_ascii_whitespace() || *c == '/')
136            .is_some()
137        {}
138        let Some(&(start, c)) = chars.peek() else {
139            break;
140        };
141        if c == '>' {
142            break;
143        }
144        let mut end = start;
145        while let Some((i, c)) =
146            chars.next_if(|(_, c)| !c.is_ascii_whitespace() && !matches!(c, '=' | '>' | '/'))
147        {
148            end = i + c.len_utf8();
149        }
150        let name = tag[start..end].to_string();
151        while chars.next_if(|(_, c)| c.is_ascii_whitespace()).is_some() {}
152        let mut value = String::new();
153        if chars.next_if(|(_, c)| *c == '=').is_some() {
154            while chars.next_if(|(_, c)| c.is_ascii_whitespace()).is_some() {}
155            match chars.peek() {
156                Some(&(_, quote @ ('"' | '\''))) => {
157                    chars.next();
158                    for (_, c) in chars.by_ref() {
159                        if c == quote {
160                            break;
161                        }
162                        value.push(c);
163                    }
164                }
165                _ => {
166                    while let Some((_, c)) =
167                        chars.next_if(|(_, c)| !c.is_ascii_whitespace() && *c != '>')
168                    {
169                        value.push(c);
170                    }
171                }
172            }
173        }
174        if name.is_empty() {
175            // Not a name at all (a stray `=`): skip one character and go on.
176            chars.next();
177            continue;
178        }
179        attributes.push((name, value));
180    }
181    attributes
182}
183
184/// The length of the tag `html` starts with: up to and including its closing
185/// `>`, skipping any `>` inside a quoted attribute value.
186fn tag_end(html: &str) -> usize {
187    let mut quote = None;
188    for (i, c) in html.char_indices() {
189        match (quote, c) {
190            (None, '"' | '\'') => quote = Some(c),
191            (Some(q), c) if c == q => quote = None,
192            (None, '>') => return i + 1,
193            _ => {}
194        }
195    }
196    html.len()
197}
198
199/// The YAML of a page's front matter: what lies between a `---` on its first
200/// line and the next line that is `---`, if the page opens with one.
201pub fn front_matter(source: &str) -> Option<&str> {
202    split_front_matter(source).map(|(yaml, _)| yaml)
203}