Skip to main content

docs_core/
render.rs

1//! The renderer: CommonMark+GFM to static HTML, with island fences routed
2//! through [`crate::island`]. M1 scope is the element set the estate's docs
3//! actually use; the rest of the spec (search indexing, versioning, i18n)
4//! is the Wave-2 roadmap in the crate README, not silently absent.
5
6use crate::error::DocsError;
7use crate::island::Island;
8use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
9use std::fmt::Write as _;
10
11/// Render Markdown to HTML. Islands in ```` ```island ```` fences become
12/// astro-island-compatible custom elements (`base` prefixes component URLs).
13///
14/// # Errors
15/// [`DocsError`] for malformed island fences; Markdown itself never fails —
16/// unknown constructs render their inner content (documented M1 behaviour).
17pub fn render(markdown: &str, base: &str) -> Result<String, DocsError> {
18    render_inner(markdown, base, true)
19}
20
21/// The renderer proper. `allow_islands = false` drops island fences
22/// entirely (untrusted content, Wave 2 sanitization: hydration is a
23/// trusted-author surface).
24pub(crate) fn render_inner(
25    markdown: &str,
26    base: &str,
27    allow_islands: bool,
28) -> Result<String, DocsError> {
29    let mut options = Options::empty();
30    options.insert(Options::ENABLE_TABLES);
31    options.insert(Options::ENABLE_STRIKETHROUGH);
32    options.insert(Options::ENABLE_TASKLISTS);
33    options.insert(Options::ENABLE_FOOTNOTES);
34    // Wave 2 math: `$...$` and `$$...$$` arrive as InlineMath/DisplayMath
35    // events and leave as build-time MathML (no client JS).
36    options.insert(Options::ENABLE_MATH);
37
38    let mut out = String::new();
39    let mut headings: Vec<u8> = Vec::new();
40    // Open lists, innermost last, with their ordered flags — the closing tag
41    // must match the element actually opened, and paragraphs are suppressed
42    // only while *some* list is open.
43    let mut list_stack: Vec<bool> = Vec::new();
44    let mut in_code_block = false;
45    let mut parser = Parser::new_ext(markdown, options);
46
47    while let Some(event) = parser.next() {
48        match event {
49            Event::Start(Tag::Heading { level, .. }) => {
50                // pulldown's `level` Display already renders "h1".."h6".
51                headings.push(level as u8);
52                let _ = write!(out, "<{level}>");
53            }
54            Event::End(TagEnd::Heading(_)) => {
55                let level = headings.pop().unwrap_or(1);
56                let _ = write!(out, "</h{level}>");
57            }
58            Event::Start(Tag::Paragraph) => {
59                if list_stack.is_empty() {
60                    out.push_str("<p>");
61                }
62            }
63            Event::End(TagEnd::Paragraph) => {
64                if list_stack.is_empty() {
65                    out.push_str("</p>");
66                }
67            }
68            Event::Start(Tag::Emphasis) => out.push_str("<em>"),
69            Event::End(TagEnd::Emphasis) => out.push_str("</em>"),
70            Event::Start(Tag::Strong) => out.push_str("<strong>"),
71            Event::End(TagEnd::Strong) => out.push_str("</strong>"),
72            Event::Start(Tag::Strikethrough) => out.push_str("<del>"),
73            Event::End(TagEnd::Strikethrough) => out.push_str("</del>"),
74            Event::Code(code) => {
75                let _ = write!(out, "<code>{}</code>", escape_html(&code));
76            }
77            Event::Start(Tag::Link { dest_url, .. }) => {
78                let _ = write!(out, "<a href=\"{}\">", escape_attr(&dest_url));
79            }
80            Event::End(TagEnd::Link) => out.push_str("</a>"),
81            Event::Start(Tag::Image {
82                dest_url, title, ..
83            }) => {
84                // The alt text arrives as a Text event between Start and End;
85                // capture it into the attribute instead of leaking it into
86                // the output as visible body text.
87                let mut alt = String::new();
88                for inner in parser.by_ref() {
89                    match inner {
90                        Event::Text(t) => alt.push_str(&t),
91                        Event::End(TagEnd::Image) => break,
92                        _ => {}
93                    }
94                }
95                let _ = write!(
96                    out,
97                    "<img src=\"{}\" alt=\"{}\"{}>",
98                    escape_attr(&dest_url),
99                    escape_attr(&alt),
100                    if title.is_empty() {
101                        String::new()
102                    } else {
103                        format!(" title=\"{}\"", escape_attr(&title))
104                    }
105                );
106            }
107            Event::End(TagEnd::Image) => {}
108            Event::Start(Tag::BlockQuote(_)) => out.push_str("<blockquote>"),
109            Event::End(TagEnd::BlockQuote(_)) => out.push_str("</blockquote>"),
110            Event::Start(Tag::CodeBlock(kind)) => match kind {
111                CodeBlockKind::Fenced(info) if info.starts_with("island") => {
112                    // Island props are raw JSON, not prose: consume the fence
113                    // body verbatim, emit the custom element, and swallow the
114                    // matching End event.
115                    let mut body = String::new();
116                    for inner in parser.by_ref() {
117                        match inner {
118                            Event::Text(t) => {
119                                body.push_str(&t);
120                                break;
121                            }
122                            Event::End(TagEnd::CodeBlock) => break,
123                            _ => {}
124                        }
125                    }
126                    if allow_islands {
127                        let island = Island::parse(&info, &body)?;
128                        out.push_str(&island.to_html(base));
129                    }
130                    // Untrusted content: the fence (and its props) simply
131                    // disappears - documented `render_untrusted` behaviour.
132                    let _ = parser.next(); // the End(CodeBlock) we did not consume
133                }
134                _ => {
135                    in_code_block = true;
136                    out.push_str("<pre><code>");
137                }
138            },
139            Event::End(TagEnd::CodeBlock) => {
140                if in_code_block {
141                    in_code_block = false;
142                    out.push_str("</code></pre>");
143                }
144            }
145            Event::Start(Tag::List(start)) => {
146                let ordered = start.is_some();
147                let _ = write!(out, "<{}>", if ordered { "ol" } else { "ul" });
148                list_stack.push(ordered);
149            }
150            Event::End(TagEnd::List(_)) => {
151                // Close the element that was actually opened — the event does
152                // not carry the ordered flag, so the stack is the source of
153                // truth. Empty pop = unbalanced end; emit nothing.
154                match list_stack.pop() {
155                    Some(true) => out.push_str("</ol>"),
156                    Some(false) => out.push_str("</ul>"),
157                    None => {}
158                }
159            }
160            Event::Start(Tag::Item) => out.push_str("<li>"),
161            Event::End(TagEnd::Item) => out.push_str("</li>"),
162            Event::TaskListMarker(checked) => {
163                let _ = write!(
164                    out,
165                    "<input type=\"checkbox\" disabled{}>",
166                    if checked { " checked" } else { "" }
167                );
168            }
169            Event::Rule => out.push_str("<hr>"),
170            // Standard Markdown policy: raw HTML (block *and* inline) passes
171            // through — docs content is first-party repository content, the
172            // same contract mdBook/Zola/Starlight ship. Text nodes are
173            // escaped. If content ever becomes untrusted, sanitize the
174            // *output* with `ammonia` (Wave 2, §Scope in lib.rs) — do not
175            // silently narrow here.
176            Event::Text(text) => out.push_str(&escape_html(&text)),
177            Event::Html(text) | Event::InlineHtml(text) => out.push_str(&text),
178            Event::SoftBreak => out.push('\n'),
179            Event::HardBreak => out.push_str("<br>"),
180            // Wave 2 math: build-time LaTeX -> MathML. A malformed span
181            // fails the render (BadMath names the offending input) - the
182            // same fail-the-build contract as a malformed island fence.
183            Event::InlineMath(tex) => {
184                let mathml = mathml(&tex, latex2mathml::DisplayStyle::Inline)?;
185                out.push_str(&mathml);
186            }
187            Event::DisplayMath(tex) => {
188                let mathml = mathml(&tex, latex2mathml::DisplayStyle::Block)?;
189                out.push_str(&mathml);
190            }
191            _ => {}
192        }
193    }
194    Ok(out)
195}
196
197fn escape_html(src: &str) -> String {
198    src.replace('&', "&amp;")
199        .replace('<', "&lt;")
200        .replace('>', "&gt;")
201}
202
203/// Convert one math span to MathML. The output is generated, trusted
204/// markup; only the *input* can fail, and it fails loudly.
205fn mathml(latex: &str, style: latex2mathml::DisplayStyle) -> Result<String, DocsError> {
206    latex2mathml::latex_to_mathml(latex, style).map_err(|_| DocsError::BadMath(latex.to_owned()))
207}
208
209fn escape_attr(src: &str) -> String {
210    escape_html(src).replace('"', "&quot;")
211}