Skip to main content

webui_docs/
markdown.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT license.
3
4//! Markdown → HTML conversion with syntax highlighting.
5//! Uses comrak for GFM markdown and syntect for dual-theme code highlighting.
6
7use comrak::nodes::{NodeHtmlBlock, NodeValue};
8use comrak::{parse_document, Arena, Options};
9use syntect::parsing::SyntaxSet;
10use syntect::util::LinesWithEndings;
11
12use crate::error::Result;
13
14/// Highlighter with pre-loaded syntax definitions and theme.
15/// Outputs semantic CSS classes (`hl-keyword`, `hl-string`, etc.)
16/// instead of inline styles — colors are controlled via design tokens.
17pub struct Highlighter {
18    ss: SyntaxSet,
19    theme: syntect::highlighting::Theme,
20}
21
22impl Default for Highlighter {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl Highlighter {
29    pub fn new() -> Self {
30        use syntect::highlighting::ThemeSet;
31        let mut ts = ThemeSet::load_defaults();
32        // Move out of the map so we own it (avoids per-call clone).
33        let theme = ts
34            .themes
35            .remove("InspiredGitHub")
36            .unwrap_or_else(|| ts.themes.into_values().next().unwrap_or_default());
37        Self {
38            ss: SyntaxSet::load_defaults_newlines(),
39            theme,
40        }
41    }
42
43    /// Highlight a code block using semantic CSS classes.
44    /// Colors are controlled via CSS custom properties for dual light/dark
45    /// theme support (GitHub Light / GitHub Dark style).
46    fn highlight_code(&self, code: &str, lang: &str) -> String {
47        use syntect::easy::HighlightLines;
48
49        // Map language aliases — syntect's defaults lack TypeScript, TOML, etc.
50        let mapped_lang = match lang {
51            "ts" | "typescript" | "tsx" | "jsx" => "js",
52            "sh" | "shell" | "zsh" => "bash",
53            "yml" => "yaml",
54            "golang" => "go",
55            "csharp" => "cs",
56            "toml" => "ini", // closest available
57            other => other,
58        };
59
60        let syntax = self
61            .ss
62            .find_syntax_by_token(mapped_lang)
63            .unwrap_or_else(|| self.ss.find_syntax_plain_text());
64
65        let mut hl = HighlightLines::new(syntax, &self.theme);
66
67        let mut out = String::with_capacity(code.len() * 2);
68        out.push_str("<code-block><pre class=\"code-block\"><code>");
69
70        for line in LinesWithEndings::from(code) {
71            let regions = hl.highlight_line(line, &self.ss).unwrap_or_default();
72            for &(style, text) in &regions {
73                let cls = scope_to_css_class(style.foreground);
74                if cls.is_empty() {
75                    emit_escaped(&mut out, text);
76                } else {
77                    out.push_str("<span class=\"hl-");
78                    out.push_str(cls);
79                    out.push_str("\">");
80                    emit_escaped(&mut out, text);
81                    out.push_str("</span>");
82                }
83            }
84        }
85
86        out.push_str("</code></pre></code-block>");
87        out
88    }
89}
90
91fn emit_escaped(buf: &mut String, s: &str) {
92    // Byte-scan: find the next char needing escape, bulk-copy the rest.
93    // `{` and `}` are escaped so `{{...}}` inside code spans/blocks is not
94    // interpreted as a WebUI signal binding by the template parser.
95    let bytes = s.as_bytes();
96    let mut start = 0;
97    for (i, &b) in bytes.iter().enumerate() {
98        let esc = match b {
99            b'&' => "&amp;",
100            b'<' => "&lt;",
101            b'>' => "&gt;",
102            b'{' => "&#123;",
103            b'}' => "&#125;",
104            _ => continue,
105        };
106        // SAFETY: all matched bytes are ASCII so byte indices are valid char boundaries.
107        buf.push_str(&s[start..i]);
108        buf.push_str(esc);
109        start = i + 1;
110    }
111    buf.push_str(&s[start..]);
112}
113
114/// Map a highlight color from the InspiredGitHub theme to a semantic CSS class.
115/// The actual display colors come from CSS custom properties — this mapping
116/// just classifies tokens into semantic groups for theming.
117fn scope_to_css_class(fg: syntect::highlighting::Color) -> &'static str {
118    let hex = ((fg.r as u32) << 16) | ((fg.g as u32) << 8) | (fg.b as u32);
119    match hex {
120        // Keywords (if, else, return, import, export, const, let, fn, pub, use, etc.)
121        0xa71d5d => "keyword",
122        // Strings
123        0x183691 => "string",
124        // Comments
125        0x969896 => "comment",
126        // Numbers
127        0xed6a43 => "number",
128        // Tags (HTML)
129        0x63a35c => "tag",
130        // Attributes / decorators
131        0x795da3 => "attr",
132        // Properties / built-ins
133        0x0086b3 => "property",
134        // Functions
135        0x6f42c1 => "function",
136        // Types (in some themes)
137        0x333333 => "variable",
138        _ => "",
139    }
140}
141
142/// Convert heading text to a URL-friendly slug.
143fn slugify(text: &str) -> String {
144    let mut slug = String::with_capacity(text.len());
145    for ch in text.chars() {
146        if ch.is_ascii_alphanumeric() {
147            slug.push(ch.to_ascii_lowercase());
148        } else if (ch == ' ' || ch == '-' || ch == '_') && !slug.ends_with('-') {
149            slug.push('-');
150        }
151    }
152    slug.trim_end_matches('-').to_string()
153}
154
155/// Collect text from a comrak node's children (iterative).
156/// Returns `(plain_text, html_text)` — plain for slugs, HTML for display.
157fn collect_node_text<'a>(
158    node: &'a comrak::arena_tree::Node<'a, std::cell::RefCell<comrak::nodes::Ast>>,
159) -> (String, String) {
160    let mut plain = String::new();
161    let mut html = String::new();
162    let mut stack: Vec<&comrak::arena_tree::Node<'a, std::cell::RefCell<comrak::nodes::Ast>>> =
163        Vec::new();
164    // Push children in reverse for left-to-right traversal
165    let mut child = node.last_child();
166    while let Some(c) = child {
167        stack.push(c);
168        child = c.previous_sibling();
169    }
170    while let Some(n) = stack.pop() {
171        let data = n.data.borrow();
172        match &data.value {
173            NodeValue::Text(t) => {
174                plain.push_str(t);
175                html.push_str(t);
176            }
177            NodeValue::Code(code) => {
178                plain.push_str(&code.literal);
179                html.push_str("<code>");
180                // Escape HTML entities and template braces inside code spans
181                // so `{{...}}` is not interpreted as a WebUI signal binding.
182                emit_escaped(&mut html, &code.literal);
183                html.push_str("</code>");
184            }
185            _ => {
186                drop(data);
187                let mut c = n.last_child();
188                while let Some(ch) = c {
189                    stack.push(ch);
190                    c = ch.previous_sibling();
191                }
192            }
193        }
194    }
195    (plain, html)
196}
197
198/// Render markdown content to HTML with syntax-highlighted code blocks.
199/// Internal links (starting with `/`) are prefixed with `base_path`.
200///
201/// `page_url` is the current page's canonical URL path (base-prefixed, with a
202/// trailing slash — e.g. `/webui/guide/`). In-page fragment links (heading
203/// anchors and `[text](#section)` links) are emitted as absolute paths
204/// (`{page_url}#slug`) rather than bare `#slug`. A bare fragment would resolve
205/// against the document's `<base href>` — which points at the site root — and
206/// navigate away from the current page instead of scrolling within it.
207pub fn render_markdown(
208    content: &str,
209    highlighter: &Highlighter,
210    base_path: &str,
211    page_url: &str,
212) -> Result<String> {
213    let arena = Arena::new();
214    let mut options = Options::default();
215    options.extension.table = true;
216    options.extension.strikethrough = true;
217    options.extension.autolink = true;
218    options.render.r#unsafe = true; // Allow raw HTML passthrough
219
220    let root = parse_document(&arena, content, &options);
221
222    // Multi-pass approach: collect node pointers first, then modify.
223    // This avoids modifying the tree during iteration and lets heading
224    // rendering see original code-span nodes before they are converted to raw
225    // HTML for WebUI template-signal escaping.
226
227    // Pass 1: Rewrite internal links before custom heading rendering.
228    for node in root.descendants() {
229        let mut data = node.data.borrow_mut();
230        if let NodeValue::Link(ref mut link) = data.value {
231            if link.url.starts_with('#') {
232                // In-page fragment link. Make it absolute to the current page so
233                // it isn't resolved against `<base href>` (the site root).
234                link.url = format!("{page_url}{}", link.url);
235            } else if link.url.starts_with('/')
236                && !link.url.starts_with(base_path)
237                && base_path != "/"
238            {
239                // Prepend base_path to absolute internal links
240                link.url = format!("{}{}", base_path.trim_end_matches('/'), &link.url);
241            }
242        }
243    }
244
245    // Pass 2: Collect heading nodes, then replace them
246    let headings: Vec<_> = root
247        .descendants()
248        .filter(|node| matches!(node.data.borrow().value, NodeValue::Heading(_)))
249        .collect();
250
251    for node in headings {
252        let (level, plain_text, html_text) = {
253            let data = node.data.borrow();
254            if let NodeValue::Heading(ref h) = data.value {
255                let (plain, html) = collect_node_text(node);
256                (h.level, plain, html)
257            } else {
258                continue;
259            }
260        };
261        let slug = slugify(&plain_text);
262        let html = format!(
263            "<h{level} id=\"{slug}\">{html_text} <a class=\"header-anchor\" href=\"{page_url}#{slug}\">#</a></h{level}>"
264        );
265        // Detach children first, then replace value. The heading is a
266        // block-level node, so its raw-HTML replacement must be an
267        // `HtmlBlock` (not `HtmlInline`) — comrak 0.53 validates that block
268        // containers only hold block-level children.
269        while let Some(child) = node.first_child() {
270            child.detach();
271        }
272        node.data.borrow_mut().value = NodeValue::HtmlBlock(NodeHtmlBlock {
273            block_type: 6,
274            literal: html,
275        });
276    }
277
278    // Pass 3: Replace code blocks and inline code after heading extraction,
279    // so headings can still collect code-span literals for display and slugs.
280    for node in root.descendants() {
281        let mut data = node.data.borrow_mut();
282        match &mut data.value {
283            NodeValue::CodeBlock(ref mut block) => {
284                let lang = if block.info.is_empty() {
285                    "text"
286                } else {
287                    block.info.split_whitespace().next().unwrap_or("text")
288                };
289                let highlighted = highlighter.highlight_code(&block.literal, lang);
290                // A code block is block-level: replace with an `HtmlBlock` so
291                // comrak 0.53's AST validation accepts it as a block child.
292                data.value = NodeValue::HtmlBlock(NodeHtmlBlock {
293                    block_type: 6,
294                    literal: highlighted,
295                });
296            }
297            NodeValue::Code(ref code) => {
298                // Replace inline code with pre-escaped HTML so `{{...}}` inside
299                // code spans is not interpreted as a WebUI signal binding.
300                let mut html = String::with_capacity(code.literal.len() + 13);
301                html.push_str("<code>");
302                emit_escaped(&mut html, &code.literal);
303                html.push_str("</code>");
304                data.value = NodeValue::HtmlInline(html);
305            }
306            _ => {}
307        }
308    }
309
310    let mut html = String::with_capacity(content.len());
311    comrak::format_html(root, &options, &mut html)
312        .map_err(|e| crate::error::Error::Markdown(e.to_string()))?;
313
314    Ok(html)
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    #[test]
321    fn syntect_language_mapping() {
322        let ss = SyntaxSet::load_defaults_newlines();
323        // Languages we need for the docs site
324        for tok in &[
325            "js", "go", "python", "py", "cpp", "rust", "rs", "html", "css", "json", "bash", "yaml",
326            "cs",
327        ] {
328            assert!(
329                ss.find_syntax_by_token(tok).is_some(),
330                "syntect should support token '{tok}'"
331            );
332        }
333        // These are NOT in syntect defaults — we alias them
334        for tok in &["ts", "typescript", "tsx", "jsx", "toml", "csharp", "golang"] {
335            assert!(
336                ss.find_syntax_by_token(tok).is_none(),
337                "'{tok}' should NOT be in syntect defaults (we alias it)"
338            );
339        }
340    }
341
342    #[test]
343    fn inline_code_escapes_template_braces() {
344        // `{{value}}` inside inline code (e.g. in markdown tables or prose)
345        // must not be interpreted as a WebUI signal binding by the template
346        // parser — escape `{` and `}` to HTML entities.
347        let h = Highlighter::new();
348        let html = render_markdown("Use `{{value}}` for escaped output.", &h, "/", "/").unwrap();
349        assert!(
350            html.contains("&#123;&#123;value&#125;&#125;"),
351            "inline code braces should be escaped: {html}"
352        );
353        assert!(
354            !html.contains("{{value}}"),
355            "raw `{{{{value}}}}` must not survive: {html}"
356        );
357    }
358
359    #[test]
360    fn heading_inline_code_survives_custom_anchor_rendering() {
361        let h = Highlighter::new();
362        let html = match render_markdown("# `<for>` Loop Directive\n", &h, "/", "/") {
363            Ok(html) => html,
364            Err(e) => panic!("render_markdown should succeed: {e}"),
365        };
366
367        assert!(
368            html.contains(
369                r##"<h1 id="for-loop-directive"><code>&lt;for&gt;</code> Loop Directive"##
370            ),
371            "heading inline code should render as code: {html}"
372        );
373    }
374
375    #[test]
376    fn in_page_anchors_are_absolute_to_the_page() {
377        // With a `<base href>` set on every page, bare `#slug` fragment links
378        // resolve against the site root and navigate away from the page.
379        // Heading anchors and `[text](#section)` links must be emitted as
380        // absolute paths to the current page.
381        let h = Highlighter::new();
382        let html = render_markdown(
383            "# Hello\n\nSee [below](#hello).\n",
384            &h,
385            "/webui/",
386            "/webui/guide/",
387        )
388        .unwrap();
389
390        assert!(
391            html.contains(r##"href="/webui/guide/#hello""##),
392            "heading anchor should be absolute to the page: {html}"
393        );
394        assert!(
395            html.contains(r##"<a href="/webui/guide/#hello">below</a>"##),
396            "in-content fragment link should be absolute to the page: {html}"
397        );
398    }
399
400    #[test]
401    fn code_block_escapes_template_braces() {
402        // Fenced code blocks must also escape braces so example template
403        // snippets render literally instead of being parsed as bindings.
404        let h = Highlighter::new();
405        let html = render_markdown("```html\n<p>{{name}}</p>\n```\n", &h, "/", "/").unwrap();
406        assert!(
407            html.contains("&#123;&#123;name&#125;&#125;"),
408            "code block braces should be escaped: {html}"
409        );
410    }
411}