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    // Heading anchor ids (Wave 2c.6): every heading gains a slugified id so
48    // TOCs and deep links work. The opening tag is rewritten in place at
49    // End(Heading), once the plain text (and therefore the slug) is known.
50    // Duplicates get -2/-3 suffixes.
51    let mut slug_counts: std::collections::HashMap<String, usize> =
52        std::collections::HashMap::new();
53    let mut heading_text = String::new();
54    let mut heading_open: Option<(usize, u8)> = None; // (offset of "<hN>", level)
55
56    while let Some(event) = parser.next() {
57        match event {
58            Event::Start(Tag::Heading { level, .. }) => {
59                // pulldown's `level` Display already renders "h1".."h6".
60                headings.push(level as u8);
61                heading_text.clear();
62                heading_open = Some((out.len(), level as u8));
63                let _ = write!(out, "<{level}>");
64            }
65            Event::End(TagEnd::Heading(_)) => {
66                let level = headings.pop().unwrap_or(1);
67                let slug = slugify(&heading_text);
68                let count = slug_counts.entry(slug.clone()).or_insert(0);
69                *count += 1;
70                let id = if *count == 1 {
71                    slug
72                } else {
73                    format!("{slug}-{count}")
74                };
75                if let Some((offset, _)) = heading_open.take() {
76                    let tag = format!("<h{level}>");
77                    let with_id = format!("<h{level} id=\"{id}\">");
78                    out.replace_range(offset..offset + tag.len(), &with_id);
79                }
80                let _ = write!(out, "</h{level}>");
81            }
82            Event::Start(Tag::Paragraph) => {
83                if list_stack.is_empty() {
84                    out.push_str("<p>");
85                }
86            }
87            Event::End(TagEnd::Paragraph) => {
88                if list_stack.is_empty() {
89                    out.push_str("</p>");
90                }
91            }
92            Event::Start(Tag::Emphasis) => out.push_str("<em>"),
93            Event::End(TagEnd::Emphasis) => out.push_str("</em>"),
94            Event::Start(Tag::Strong) => out.push_str("<strong>"),
95            Event::End(TagEnd::Strong) => out.push_str("</strong>"),
96            Event::Start(Tag::Strikethrough) => out.push_str("<del>"),
97            Event::End(TagEnd::Strikethrough) => out.push_str("</del>"),
98            Event::Code(code) => {
99                let _ = write!(out, "<code>{}</code>", escape_html(&code));
100            }
101            Event::Start(Tag::Link { dest_url, .. }) => {
102                let _ = write!(out, "<a href=\"{}\">", escape_attr(&dest_url));
103            }
104            Event::End(TagEnd::Link) => out.push_str("</a>"),
105            Event::Start(Tag::Image {
106                dest_url, title, ..
107            }) => {
108                // The alt text arrives as a Text event between Start and End;
109                // capture it into the attribute instead of leaking it into
110                // the output as visible body text.
111                let mut alt = String::new();
112                for inner in parser.by_ref() {
113                    match inner {
114                        Event::Text(t) => alt.push_str(&t),
115                        Event::End(TagEnd::Image) => break,
116                        _ => {}
117                    }
118                }
119                let _ = write!(
120                    out,
121                    "<img src=\"{}\" alt=\"{}\"{}>",
122                    escape_attr(&dest_url),
123                    escape_attr(&alt),
124                    if title.is_empty() {
125                        String::new()
126                    } else {
127                        format!(" title=\"{}\"", escape_attr(&title))
128                    }
129                );
130            }
131            Event::End(TagEnd::Image) => {}
132            Event::Start(Tag::BlockQuote(_)) => out.push_str("<blockquote>"),
133            Event::End(TagEnd::BlockQuote(_)) => out.push_str("</blockquote>"),
134            Event::Start(Tag::CodeBlock(kind)) => match kind {
135                CodeBlockKind::Fenced(info) if info.starts_with("island") => {
136                    // Island props are raw JSON, not prose: consume the fence
137                    // body verbatim, emit the custom element, and swallow the
138                    // matching End event.
139                    let mut body = String::new();
140                    for inner in parser.by_ref() {
141                        match inner {
142                            Event::Text(t) => {
143                                body.push_str(&t);
144                                break;
145                            }
146                            Event::End(TagEnd::CodeBlock) => break,
147                            _ => {}
148                        }
149                    }
150                    if allow_islands {
151                        let island = Island::parse(&info, &body)?;
152                        out.push_str(&island.to_html(base));
153                    }
154                    // Untrusted content: the fence (and its props) simply
155                    // disappears - documented `render_untrusted` behaviour.
156                    let _ = parser.next(); // the End(CodeBlock) we did not consume
157                }
158                _ => {
159                    in_code_block = true;
160                    out.push_str("<pre><code>");
161                }
162            },
163            Event::End(TagEnd::CodeBlock) => {
164                if in_code_block {
165                    in_code_block = false;
166                    out.push_str("</code></pre>");
167                }
168            }
169            Event::Start(Tag::List(start)) => {
170                let ordered = start.is_some();
171                let _ = write!(out, "<{}>", if ordered { "ol" } else { "ul" });
172                list_stack.push(ordered);
173            }
174            Event::End(TagEnd::List(_)) => {
175                // Close the element that was actually opened — the event does
176                // not carry the ordered flag, so the stack is the source of
177                // truth. Empty pop = unbalanced end; emit nothing.
178                match list_stack.pop() {
179                    Some(true) => out.push_str("</ol>"),
180                    Some(false) => out.push_str("</ul>"),
181                    None => {}
182                }
183            }
184            Event::Start(Tag::Item) => out.push_str("<li>"),
185            Event::End(TagEnd::Item) => out.push_str("</li>"),
186            Event::TaskListMarker(checked) => {
187                let _ = write!(
188                    out,
189                    "<input type=\"checkbox\" disabled{}>",
190                    if checked { " checked" } else { "" }
191                );
192            }
193            Event::Rule => out.push_str("<hr>"),
194            // Standard Markdown policy: raw HTML (block *and* inline) passes
195            // through — docs content is first-party repository content, the
196            // same contract mdBook/Zola/Starlight ship. Text nodes are
197            // escaped. If content ever becomes untrusted, sanitize the
198            // *output* with `ammonia` (Wave 2, §Scope in lib.rs) — do not
199            // silently narrow here.
200            Event::Text(text) => {
201                // Inside a heading the raw text also feeds the anchor slug.
202                if !headings.is_empty() {
203                    heading_text.push_str(&text);
204                }
205                out.push_str(&escape_html(&text));
206            }
207            Event::Html(text) | Event::InlineHtml(text) => out.push_str(&text),
208            Event::SoftBreak => out.push('\n'),
209            Event::HardBreak => out.push_str("<br>"),
210            // Wave 2 math: build-time LaTeX -> MathML. A malformed span
211            // fails the render (BadMath names the offending input) - the
212            // same fail-the-build contract as a malformed island fence.
213            Event::InlineMath(tex) => {
214                let mathml = mathml(&tex, latex2mathml::DisplayStyle::Inline)?;
215                out.push_str(&mathml);
216            }
217            Event::DisplayMath(tex) => {
218                let mathml = mathml(&tex, latex2mathml::DisplayStyle::Block)?;
219                out.push_str(&mathml);
220            }
221            _ => {}
222        }
223    }
224    Ok(out)
225}
226
227fn escape_html(src: &str) -> String {
228    src.replace('&', "&amp;")
229        .replace('<', "&lt;")
230        .replace('>', "&gt;")
231}
232
233/// Slugify heading text for anchor ids: lowercase, alphanumerics and
234/// hyphens only, runs collapsed, trimmed. Empty text yields `heading`.
235fn slugify(text: &str) -> String {
236    let mut slug = String::with_capacity(text.len());
237    let mut last_hyphen = true;
238    for c in text.chars() {
239        if c.is_alphanumeric() {
240            for lower in c.to_lowercase() {
241                slug.push(lower);
242            }
243            last_hyphen = false;
244        } else if !last_hyphen {
245            slug.push('-');
246            last_hyphen = true;
247        }
248    }
249    let slug = slug.trim_end_matches('-').to_string();
250    if slug.is_empty() {
251        "heading".to_string()
252    } else {
253        slug
254    }
255}
256
257/// Convert one math span to MathML. The output is generated, trusted
258/// markup; only the *input* can fail, and it fails loudly.
259fn mathml(latex: &str, style: latex2mathml::DisplayStyle) -> Result<String, DocsError> {
260    latex2mathml::latex_to_mathml(latex, style).map_err(|_| DocsError::BadMath(latex.to_owned()))
261}
262
263fn escape_attr(src: &str) -> String {
264    escape_html(src).replace('"', "&quot;")
265}