Skip to main content

reflex/pulse/render/
html.rs

1//! Docs Model → HTML.
2//!
3//! Rust renders every block, including the Markdown in doc comments, READMEs and LLM
4//! prose, so the site generator only lays pages out. That keeps the Astro build fast at
5//! scale (see `.context/PULSE_RENDERER_SPIKE.md`, design D) and puts every piece of
6//! markup under Rust tests.
7//!
8//! Markdown is untrusted. Raw HTML becomes text (a short allowlist of inline tags
9//! survives), links keep only `http`, `https`, `mailto`, fragments and site routes,
10//! images become their alt text, and headings get ids that cannot collide on the page.
11
12use crate::pulse::model::content::{CalloutKind, DiagramKind, SymbolBlock};
13use crate::pulse::model::{Block, Inline, Linker, MarkdownOrigin, MarkdownText, Page, Site};
14use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd};
15use serde::Serialize;
16use std::collections::HashSet;
17use std::fmt::Write as _;
18use std::sync::LazyLock;
19use syntect::html::{ClassStyle, ClassedHTMLGenerator, css_for_theme_with_class_style};
20use syntect::parsing::SyntaxSet;
21use syntect::util::LinesWithEndings;
22
23/// A table-of-contents entry.
24#[derive(Debug, Clone, PartialEq, Serialize)]
25pub struct Heading {
26    pub depth: u8,
27    pub slug: String,
28    pub text: String,
29}
30
31#[derive(Debug, Clone, PartialEq)]
32pub struct RenderedPage {
33    pub html: String,
34    pub headings: Vec<Heading>,
35    pub has_mermaid: bool,
36}
37
38pub fn esc(s: &str) -> String {
39    let mut out = String::with_capacity(s.len());
40    for c in s.chars() {
41        match c {
42            '&' => out.push_str("&amp;"),
43            '<' => out.push_str("&lt;"),
44            '>' => out.push_str("&gt;"),
45            '"' => out.push_str("&quot;"),
46            '\'' => out.push_str("&#39;"),
47            c => out.push(c),
48        }
49    }
50    out
51}
52
53// ── Syntax highlighting ─────────────────────────────────────────────────────
54
55const HL: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" };
56
57static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
58
59/// Highlighted HTML for `code` (the inside of a `<pre>`), or escaped text.
60pub fn highlight(code: &str, lang: &str) -> String {
61    let token = match lang {
62        "" | "text" | "txt" | "plain" | "console" | "output" => return esc(code),
63        "sh" | "shell" | "bash" | "zsh" => "bash",
64        "ts" | "typescript" | "tsx" => "js",
65        "yml" => "yaml",
66        other => other,
67    };
68    let Some(syntax) = SYNTAXES.find_syntax_by_token(token) else {
69        return esc(code);
70    };
71    let mut generator = ClassedHTMLGenerator::new_with_class_style(syntax, &SYNTAXES, HL);
72    for line in LinesWithEndings::from(code) {
73        if generator
74            .parse_html_for_line_which_includes_newline(line)
75            .is_err()
76        {
77            return esc(code);
78        }
79    }
80    generator.finalize()
81}
82
83/// CSS for highlighted code in both Starlight themes.
84pub fn highlight_css() -> String {
85    let themes = syntect::highlighting::ThemeSet::load_defaults();
86    let mut out = String::from("/* Generated by rfx pulse from syntect themes. */\n");
87    for (selector, name) in [
88        (":root[data-theme='light']", "InspiredGitHub"),
89        (":root[data-theme='dark']", "base16-ocean.dark"),
90    ] {
91        let Some(theme) = themes.themes.get(name) else {
92            continue;
93        };
94        let Ok(css) = css_for_theme_with_class_style(theme, HL) else {
95            continue;
96        };
97        for line in css.lines() {
98            let t = line.trim_end();
99            if t.ends_with('{') && !t.starts_with("/*") && !t.starts_with(' ') {
100                let sels = t.trim_end_matches('{').trim();
101                let scoped: Vec<String> = sels
102                    .split(',')
103                    .map(|s| format!("{selector} {}", s.trim()))
104                    .collect();
105                let _ = writeln!(out, "{} {{", scoped.join(", "));
106            } else {
107                let _ = writeln!(out, "{t}");
108            }
109        }
110    }
111    out
112}
113
114// ── Markdown ────────────────────────────────────────────────────────────────
115
116/// Inline tags kept from raw HTML in Markdown.
117const HTML_ALLOW: &[&str] = &[
118    "<br>", "<br/>", "<br />", "<kbd>", "</kbd>", "<sub>", "</sub>", "<sup>", "</sup>",
119];
120
121/// How one Markdown text renders.
122struct MdOptions<'a> {
123    /// Prefix for heading ids (`method.new-`); empty for page-level prose.
124    id_prefix: &'a str,
125    /// Levels added to every heading (doc comments inside a symbol start at h4).
126    demote: u8,
127    /// Whether headings go into the page's table of contents.
128    toc: bool,
129    /// Language of bare code fences (`rust` for Rust doc comments).
130    default_lang: &'a str,
131}
132
133/// Renders pages of one site.
134pub struct Renderer<'a> {
135    site: &'a Site,
136    linker: Linker<'a>,
137    /// Site base path without a trailing slash (`""` or `/reflex`).
138    base: String,
139}
140
141/// Per-page state: headings and used ids.
142struct PageState {
143    headings: Vec<Heading>,
144    ids: HashSet<String>,
145    mermaid: bool,
146}
147
148impl PageState {
149    fn unique(&mut self, want: &str) -> String {
150        let mut id = want.to_string();
151        let mut n = 2;
152        while !self.ids.insert(id.clone()) {
153            id = format!("{want}-{n}");
154            n += 1;
155        }
156        id
157    }
158}
159
160fn slug(text: &str) -> String {
161    crate::pulse::model::ids::slugify(text)
162}
163
164impl<'a> Renderer<'a> {
165    pub fn new(site: &'a Site, base: &str) -> Self {
166        Self {
167            site,
168            linker: Linker::new(site),
169            base: base.trim_end_matches('/').to_string(),
170        }
171    }
172
173    /// A base-less route (`/docs/x/`) as an href under the site base.
174    fn route(&self, route: &str) -> String {
175        format!("{}{route}", self.base)
176    }
177
178    fn safe_href(&self, dest: &str) -> Option<String> {
179        let d = dest.trim();
180        let lower = d.to_ascii_lowercase();
181        if lower.starts_with("http://")
182            || lower.starts_with("https://")
183            || lower.starts_with("mailto:")
184            || d.starts_with('#')
185        {
186            Some(d.to_string())
187        } else if d.starts_with('/') && !d.starts_with("//") {
188            Some(self.route(d))
189        } else {
190            None
191        }
192    }
193
194    pub fn render_page(&self, page: &Page) -> RenderedPage {
195        let mut st = PageState {
196            headings: Vec::new(),
197            ids: HashSet::new(),
198            mermaid: false,
199        };
200        let mut html = String::new();
201        self.blocks(&page.blocks, &mut st, &mut html);
202        RenderedPage {
203            html,
204            headings: st.headings,
205            has_mermaid: st.mermaid,
206        }
207    }
208
209    fn blocks(&self, blocks: &[Block], st: &mut PageState, out: &mut String) {
210        for b in blocks {
211            self.block(b, st, out);
212        }
213    }
214
215    fn inlines(&self, inlines: &[Inline], out: &mut String) {
216        for i in inlines {
217            match i {
218                Inline::Text { text } => out.push_str(&esc(text)),
219                Inline::Code { code } => {
220                    let _ = write!(out, "<code>{}</code>", esc(code));
221                }
222                Inline::Strong { content } => {
223                    out.push_str("<strong>");
224                    self.inlines(content, out);
225                    out.push_str("</strong>");
226                }
227                Inline::Emph { content } => {
228                    out.push_str("<em>");
229                    self.inlines(content, out);
230                    out.push_str("</em>");
231                }
232                Inline::Link { to, content } => match self.linker.resolve(to) {
233                    Some(r) if r.external => {
234                        let _ = write!(out, "<a href=\"{}\" rel=\"noopener\">", esc(&r.href));
235                        self.inlines(content, out);
236                        out.push_str("</a>");
237                    }
238                    Some(r) => {
239                        let _ = write!(out, "<a href=\"{}\">", esc(&self.route(&r.href)));
240                        self.inlines(content, out);
241                        out.push_str("</a>");
242                    }
243                    None => self.inlines(content, out),
244                },
245                Inline::Fact { fact } => match self.site.facts.get(fact) {
246                    Some(f) => {
247                        let _ = write!(
248                            out,
249                            "<span class=\"pulse-fact\" data-fact=\"{}\">{}</span>",
250                            esc(fact.as_str()),
251                            esc(&f.value.display())
252                        );
253                    }
254                    None => out.push('?'),
255                },
256            }
257        }
258    }
259
260    fn block(&self, b: &Block, st: &mut PageState, out: &mut String) {
261        match b {
262            Block::Heading {
263                level,
264                text,
265                anchor,
266            } => {
267                let l = (*level).clamp(2, 6);
268                let id = st.unique(anchor.as_str());
269                if l <= 3 {
270                    st.headings.push(Heading {
271                        depth: l,
272                        slug: id.clone(),
273                        text: text.clone(),
274                    });
275                }
276                let _ = write!(out, "<h{l} id=\"{}\">{}</h{l}>", esc(&id), esc(text));
277            }
278            Block::Paragraph { content } => {
279                out.push_str("<p>");
280                self.inlines(content, out);
281                out.push_str("</p>");
282            }
283            Block::Markdown { markdown } => self.markdown_block(markdown, st, out),
284            Block::Code { lang, code, title } => {
285                out.push_str("<figure class=\"pulse-code\">");
286                if let Some(t) = title {
287                    let _ = write!(out, "<figcaption>{}</figcaption>", esc(t));
288                }
289                let _ = write!(
290                    out,
291                    "<pre class=\"hl-code\" data-lang=\"{}\"><code>{}</code></pre></figure>",
292                    esc(lang),
293                    highlight(code, lang)
294                );
295            }
296            Block::List { ordered, items } => {
297                let tag = if *ordered { "ol" } else { "ul" };
298                let _ = write!(out, "<{tag}>");
299                for item in items {
300                    out.push_str("<li>");
301                    self.inlines(item, out);
302                    out.push_str("</li>");
303                }
304                let _ = write!(out, "</{tag}>");
305            }
306            Block::Table { columns, rows } => {
307                out.push_str("<div class=\"pulse-table\"><table><thead><tr>");
308                for c in columns {
309                    let _ = write!(out, "<th>{}</th>", esc(c));
310                }
311                out.push_str("</tr></thead><tbody>");
312                for row in rows {
313                    out.push_str("<tr>");
314                    for cell in row {
315                        out.push_str("<td>");
316                        self.inlines(cell, out);
317                        out.push_str("</td>");
318                    }
319                    out.push_str("</tr>");
320                }
321                out.push_str("</tbody></table></div>");
322            }
323            Block::Callout { kind, title, body } => {
324                let (class, label) = match kind {
325                    CalloutKind::Note => ("note", "Note"),
326                    CalloutKind::Tip => ("tip", "Tip"),
327                    CalloutKind::Caution => ("caution", "Caution"),
328                    CalloutKind::Danger => ("danger", "Danger"),
329                };
330                let t = title.as_deref().unwrap_or(label);
331                let _ = write!(
332                    out,
333                    "<aside aria-label=\"{t}\" class=\"starlight-aside starlight-aside--{class}\"><p class=\"starlight-aside__title\" aria-hidden=\"true\">{t}</p><div class=\"starlight-aside__content\">",
334                    t = esc(t)
335                );
336                self.blocks(body, st, out);
337                out.push_str("</div></aside>");
338            }
339            Block::Diagram {
340                kind: DiagramKind::Mermaid,
341                source,
342                links,
343                caption,
344            } => {
345                st.mermaid = true;
346                let map: serde_json::Map<String, serde_json::Value> = links
347                    .iter()
348                    .filter_map(|(node, t)| {
349                        let r = self.linker.resolve(t)?;
350                        let href = if r.external {
351                            r.href
352                        } else {
353                            self.route(&r.href)
354                        };
355                        Some((node.clone(), serde_json::Value::String(href)))
356                    })
357                    .collect();
358                let _ = write!(
359                    out,
360                    "<figure class=\"pulse-diagram\"><pre class=\"pulse-mermaid\" data-links=\"{}\">{}</pre>",
361                    esc(&serde_json::Value::Object(map).to_string()),
362                    esc(source)
363                );
364                if let Some(c) = caption {
365                    let _ = write!(out, "<figcaption>{}</figcaption>", esc(c));
366                }
367                out.push_str("</figure>");
368            }
369            Block::Cards { cards } => {
370                out.push_str("<div class=\"pulse-cards\">");
371                for c in cards {
372                    let href = self.linker.resolve(&c.to).map(|r| {
373                        if r.external {
374                            r.href
375                        } else {
376                            self.route(&r.href)
377                        }
378                    });
379                    let close = match &href {
380                        Some(h) => {
381                            let _ = write!(out, "<a class=\"pulse-card\" href=\"{}\">", esc(h));
382                            "</a>"
383                        }
384                        None => {
385                            out.push_str("<div class=\"pulse-card\">");
386                            "</div>"
387                        }
388                    };
389                    let _ = write!(
390                        out,
391                        "<span class=\"pulse-card-title\">{}</span>",
392                        esc(&c.title)
393                    );
394                    if let Some(d) = &c.description {
395                        let _ = write!(out, "<span class=\"pulse-card-body\">{}</span>", esc(d));
396                    }
397                    out.push_str(close);
398                }
399                out.push_str("</div>");
400            }
401            Block::Stats { stats } => {
402                out.push_str("<dl class=\"pulse-stats\">");
403                for s in stats {
404                    let value = self
405                        .site
406                        .facts
407                        .get(&s.fact)
408                        .map(|f| f.value.display())
409                        .unwrap_or_else(|| "?".into());
410                    let _ = write!(
411                        out,
412                        "<div><dt>{}</dt><dd>{}</dd></div>",
413                        esc(&s.label),
414                        esc(&value)
415                    );
416                }
417                out.push_str("</dl>");
418            }
419            Block::Narrative { text, fallback, .. } => match text {
420                Some(md) => {
421                    out.push_str("<div class=\"pulse-narrative\" data-origin=\"llm\">");
422                    self.markdown_block(md, st, out);
423                    out.push_str(
424                        "<p class=\"pulse-provenance\">Written by an LLM from facts in the index.</p></div>",
425                    );
426                }
427                None => self.blocks(fallback, st, out),
428            },
429            Block::Symbol { symbol } => self.symbol(symbol, st, out),
430        }
431    }
432
433    fn markdown_block(&self, md: &MarkdownText, st: &mut PageState, out: &mut String) {
434        let opts = match md.origin {
435            MarkdownOrigin::Comment => MdOptions {
436                id_prefix: "",
437                demote: 0,
438                toc: true,
439                default_lang: "rust",
440            },
441            _ => MdOptions {
442                id_prefix: "",
443                demote: 0,
444                toc: true,
445                default_lang: "text",
446            },
447        };
448        self.markdown(&md.source, &opts, st, out);
449    }
450
451    fn symbol(&self, s: &SymbolBlock, st: &mut PageState, out: &mut String) {
452        let id = st.unique(s.anchor.as_str());
453        st.headings.push(Heading {
454            depth: 3,
455            slug: id.clone(),
456            text: s.name.clone(),
457        });
458        let _ = write!(
459            out,
460            "<section class=\"pulse-symbol\" data-kind=\"{}\"><h3 id=\"{}\"><code>{}</code><span class=\"pulse-kind\">{}</span>",
461            esc(&s.kind),
462            esc(&id),
463            esc(&s.name),
464            esc(&s.kind)
465        );
466        for badge in &s.badges {
467            let _ = write!(out, "<span class=\"pulse-badge\">{}</span>", esc(badge));
468        }
469        out.push_str("</h3>");
470        if let Some(d) = &s.deprecated {
471            let _ = write!(out, "<p class=\"pulse-deprecated\">{}</p>", esc(d));
472        }
473        let _ = write!(
474            out,
475            "<pre class=\"hl-code pulse-signature\" data-lang=\"{}\"><code>{}</code></pre>",
476            esc(&s.lang),
477            highlight(&s.signature, &s.lang)
478        );
479        if let Some(doc) = &s.doc {
480            let opts = MdOptions {
481                id_prefix: &format!("{id}-"),
482                demote: 2,
483                toc: false,
484                default_lang: if doc.origin == MarkdownOrigin::Comment {
485                    &s.lang
486                } else {
487                    "text"
488                },
489            };
490            out.push_str("<div class=\"pulse-doc\">");
491            self.markdown(&doc.source, &opts, st, out);
492            out.push_str("</div>");
493        }
494        let source = crate::pulse::model::Target::Source {
495            loc: s.source.clone(),
496        };
497        out.push_str("<p class=\"pulse-meta\">");
498        match self.linker.resolve(&source) {
499            Some(r) => {
500                let _ = write!(
501                    out,
502                    "<a href=\"{}\" rel=\"noopener\"><code>{}</code></a>",
503                    esc(&r.href),
504                    esc(&s.source.label())
505                );
506            }
507            None => {
508                let _ = write!(out, "<code>{}</code>", esc(&s.source.label()));
509            }
510        }
511        out.push_str("</p></section>");
512    }
513
514    fn markdown(&self, src: &str, o: &MdOptions<'_>, st: &mut PageState, out: &mut String) {
515        let options =
516            Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS;
517        let mut events: Vec<Event> = Vec::new();
518        let mut code: Option<(String, String)> = None; // (lang, text)
519        let mut heading: Option<(u8, Vec<Event>, String)> = None; // (level, inner, text)
520        let mut image_depth = 0usize;
521        let mut link_open: Vec<bool> = Vec::new();
522
523        for ev in Parser::new_ext(src, options) {
524            if let Some((_, text)) = code.as_mut() {
525                match ev {
526                    Event::Text(t) => {
527                        text.push_str(&t);
528                        continue;
529                    }
530                    Event::End(TagEnd::CodeBlock) => {
531                        let (lang, text) = code.take().unwrap();
532                        let html = if lang == "mermaid" {
533                            st.mermaid = true;
534                            format!(
535                                "<pre class=\"pulse-mermaid\" data-links=\"{{}}\">{}</pre>",
536                                esc(&text)
537                            )
538                        } else {
539                            format!(
540                                "<pre class=\"hl-code\" data-lang=\"{}\"><code>{}</code></pre>",
541                                esc(&lang),
542                                highlight(text.trim_end_matches('\n'), &lang)
543                            )
544                        };
545                        events.push(Event::Html(CowStr::from(html)));
546                        continue;
547                    }
548                    _ => continue,
549                }
550            }
551            if image_depth > 0 {
552                match ev {
553                    Event::Start(Tag::Image { .. }) => image_depth += 1,
554                    Event::End(TagEnd::Image) => {
555                        image_depth -= 1;
556                        if image_depth == 0 {
557                            events.push(Event::Html(CowStr::from("]</span>")));
558                        }
559                    }
560                    Event::Text(t) | Event::Code(t) => events.push(Event::Text(t)),
561                    _ => {}
562                }
563                continue;
564            }
565            let ev = match ev {
566                Event::Start(Tag::CodeBlock(kind)) => {
567                    let lang = match kind {
568                        CodeBlockKind::Fenced(info) => info
569                            .split(|c: char| c == ',' || c.is_whitespace())
570                            .next()
571                            .unwrap_or("")
572                            .to_string(),
573                        CodeBlockKind::Indented => String::new(),
574                    };
575                    let lang = if lang.is_empty() {
576                        o.default_lang.to_string()
577                    } else {
578                        lang
579                    };
580                    code = Some((lang, String::new()));
581                    continue;
582                }
583                Event::Start(Tag::Image { .. }) => {
584                    image_depth = 1;
585                    Event::Html(CowStr::from("<span class=\"pulse-image\">[image: "))
586                }
587                Event::Html(h) | Event::InlineHtml(h) => {
588                    let t = h.trim();
589                    if HTML_ALLOW.iter().any(|a| a.eq_ignore_ascii_case(t)) {
590                        Event::InlineHtml(CowStr::from(t.to_ascii_lowercase()))
591                    } else {
592                        Event::Text(h)
593                    }
594                }
595                Event::Start(Tag::Link {
596                    link_type,
597                    dest_url,
598                    title,
599                    id,
600                }) => match self.safe_href(&dest_url) {
601                    Some(href) => {
602                        link_open.push(true);
603                        Event::Start(Tag::Link {
604                            link_type,
605                            dest_url: CowStr::from(href),
606                            title,
607                            id,
608                        })
609                    }
610                    None => {
611                        link_open.push(false);
612                        continue;
613                    }
614                },
615                Event::End(TagEnd::Link) => {
616                    if link_open.pop().unwrap_or(false) {
617                        Event::End(TagEnd::Link)
618                    } else {
619                        continue;
620                    }
621                }
622                Event::Start(Tag::Heading { level, .. }) => {
623                    let l = (level as u8 + o.demote).min(6);
624                    heading = Some((l, Vec::new(), String::new()));
625                    continue;
626                }
627                Event::End(TagEnd::Heading(_)) => {
628                    if let Some((l, inner, text)) = heading.take() {
629                        let id = st.unique(&format!("{}{}", o.id_prefix, slug(&text)));
630                        if o.toc && (2..=3).contains(&l) {
631                            st.headings.push(Heading {
632                                depth: l,
633                                slug: id.clone(),
634                                text: text.clone(),
635                            });
636                        }
637                        let mut inner_html = String::new();
638                        pulldown_cmark::html::push_html(&mut inner_html, inner.into_iter());
639                        events.push(Event::Html(CowStr::from(format!(
640                            "<h{l} id=\"{}\">{}</h{l}>",
641                            esc(&id),
642                            inner_html
643                        ))));
644                    }
645                    continue;
646                }
647                other => other,
648            };
649            if let Some((_, inner, text)) = heading.as_mut() {
650                if let Event::Text(t) | Event::Code(t) = &ev {
651                    text.push_str(t);
652                }
653                inner.push(ev);
654                continue;
655            }
656            events.push(ev);
657        }
658        pulldown_cmark::html::push_html(out, events.into_iter());
659    }
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665    use crate::pulse::model::{
666        BuildReport, FactStore, MarkdownOrigin, PageId, PageKind, SCHEMA_VERSION, SiteMeta, TabId,
667    };
668    use std::collections::BTreeMap;
669
670    fn site_with(blocks: Vec<Block>) -> Site {
671        let page = Page {
672            id: PageId::new("p"),
673            tab: TabId::Docs,
674            kind: PageKind::Changelog,
675            title: "P".into(),
676            description: None,
677            route: "/docs/p/".into(),
678            badges: vec![],
679            blocks,
680        };
681        Site {
682            schema_version: SCHEMA_VERSION,
683            meta: SiteMeta {
684                title: "T".into(),
685                description: None,
686                repo: None,
687                generator: "test".into(),
688            },
689            tabs: vec![],
690            pages: BTreeMap::from([(PageId::new("p"), page)]),
691            symbols: BTreeMap::new(),
692            facts: FactStore::default(),
693            report: BuildReport::default(),
694            evidence: BTreeMap::new(),
695            known_names: Vec::new(),
696        }
697    }
698
699    fn md(src: &str) -> String {
700        let site = site_with(vec![Block::Markdown {
701            markdown: MarkdownText {
702                source: src.into(),
703                origin: MarkdownOrigin::Comment,
704                from: None,
705            },
706        }]);
707        Renderer::new(&site, "/reflex/")
708            .render_page(&site.pages[&PageId::new("p")])
709            .html
710    }
711
712    #[test]
713    fn raw_html_and_scripts_become_text() {
714        let h = md(
715            "Uses `Vec<String>` and <T> and {x}.\n\n<script>alert(1)</script>\n\n<!-- hidden -->\n\nA<br>B <kbd>Ctrl</kbd>",
716        );
717        assert!(h.contains("<code>Vec&lt;String&gt;</code>"), "{h}");
718        assert!(h.contains("&lt;T&gt;"), "{h}");
719        assert!(!h.contains("<script"), "{h}");
720        assert!(h.contains("&lt;script&gt;"), "{h}");
721        assert!(h.contains("&lt;!-- hidden --&gt;"), "{h}");
722        assert!(h.contains("<br>") && h.contains("<kbd>Ctrl</kbd>"), "{h}");
723        assert!(h.contains("{x}"));
724    }
725
726    #[test]
727    fn links_are_sanitised_and_prefixed() {
728        let h = md(
729            "[a](javascript:alert(1)) [b](https://x.dev) [c](/docs/q/#m) [d](data:text/html,x) [e](docs/API.md) ![logo](x.png)",
730        );
731        assert!(!h.contains("javascript:"), "{h}");
732        assert!(!h.contains("data:"), "{h}");
733        assert!(h.contains("href=\"https://x.dev\""), "{h}");
734        assert!(h.contains("href=\"/reflex/docs/q/#m\""), "{h}");
735        assert!(h.starts_with("<p>a <a"), "unsafe link keeps its text: {h}");
736        assert!(h.contains("[image: logo]"), "{h}");
737        assert!(!h.contains("<img"), "{h}");
738    }
739
740    #[test]
741    fn code_is_highlighted_and_mermaid_kept() {
742        let h = md(
743            "```\nlet x = 1;\n```\n\n```mermaid\ngraph LR; a-->b\n```\n\n```text\n--json <b>\n```",
744        );
745        assert!(
746            h.contains("data-lang=\"rust\""),
747            "bare fence in a doc comment is rust: {h}"
748        );
749        assert!(h.contains("hl-"), "{h}");
750        assert!(h.contains("<pre class=\"pulse-mermaid\""), "{h}");
751        assert!(h.contains("a--&gt;b"), "{h}");
752        assert!(
753            h.contains("--json &lt;b&gt;"),
754            "no smart punctuation, escaped: {h}"
755        );
756    }
757
758    #[test]
759    fn headings_get_unique_ids_and_toc_entries() {
760        let site = site_with(vec![
761            Block::heading(2, "Errors"),
762            Block::Markdown {
763                markdown: MarkdownText {
764                    source: "## Errors\n\ntext".into(),
765                    origin: MarkdownOrigin::Doc,
766                    from: None,
767                },
768            },
769        ]);
770        let r = Renderer::new(&site, "").render_page(&site.pages[&PageId::new("p")]);
771        let ids: Vec<&str> = r.headings.iter().map(|h| h.slug.as_str()).collect();
772        assert_eq!(ids, vec!["errors", "errors-2"]);
773    }
774
775    #[test]
776    fn highlight_css_covers_both_themes() {
777        let css = highlight_css();
778        assert!(
779            css.contains(":root[data-theme='light'] .hl-"),
780            "{}",
781            &css[..200.min(css.len())]
782        );
783        assert!(css.contains(":root[data-theme='dark'] .hl-"));
784    }
785}