Skip to main content

euv_docs/generator/
fn.rs

1use super::*;
2
3/// Loads all Markdown files beneath `src_dir` (excluding `out_dir`) and builds a complete static docs site.
4///
5/// # Arguments
6///
7/// - `&Path` - Source project or Markdown directory.
8/// - `&Path` - Output static site directory.
9/// - `&DocsBuildOptions` - Site title, base URL, clean URL, asset copy, and optional dev HMR configuration.
10///
11/// # Returns
12///
13/// - `io::Result<GeneratedSiteReport>` - Summary of generated artifacts or I/O error.
14pub fn build_docs_bundle(
15    src_dir: &Path,
16    out_dir: &Path,
17    options: &DocsBuildOptions,
18) -> io::Result<GeneratedSiteReport> {
19    let site: DocSite =
20        load_doc_site_excluding(src_dir, options.try_get_title().as_deref(), Some(out_dir))?;
21    if site.get_pages().is_empty() {
22        return Err(Error::new(ErrorKind::NotFound, ERR_NO_MARKDOWN_FOUND));
23    }
24    let mut resolved: DocsBuildOptions = options.clone();
25    if resolved.try_get_assets_root().is_none() {
26        resolved.set_assets_root(Some(src_dir.to_path_buf()));
27    }
28    generate_static_docs_with_options(&site, out_dir, &resolved)
29}
30
31/// Generates static HTML pages, search index, and sitemap for `site` into `out_dir` using default options.
32///
33/// # Arguments
34///
35/// - `&DocSite` - Loaded documentation site.
36/// - `&Path` - Destination output directory.
37///
38/// # Returns
39///
40/// - `io::Result<GeneratedSiteReport>` - Summary of written artifacts or I/O error.
41pub fn generate_static_docs(site: &DocSite, out_dir: &Path) -> io::Result<GeneratedSiteReport> {
42    let opts: DocsBuildOptions = DocsBuildOptions::default();
43    generate_static_docs_with_options(site, out_dir, &opts)
44}
45
46/// Generates a complete static documentation site with clean URLs, instant search, TOC, asset copying, and optional dev HMR.
47///
48/// # Arguments
49///
50/// - `&DocSite` - Loaded documentation site.
51/// - `&Path` - Destination output directory.
52/// - `&DocsBuildOptions` - Build options controlling base URL, asset copying, clean URLs, and dev HMR.
53///
54/// # Returns
55///
56/// - `io::Result<GeneratedSiteReport>` - Summary of written artifacts or I/O error.
57pub fn generate_static_docs_with_options(
58    site: &DocSite,
59    out_dir: &Path,
60    options: &DocsBuildOptions,
61) -> io::Result<GeneratedSiteReport> {
62    fs::create_dir_all(out_dir)?;
63    let generated_at: String = Utc::now().to_rfc3339();
64    let entries: Vec<SearchIndexEntry> = site.search_entries();
65    let search_json_compact: String = match to_string(&entries) {
66        Ok(text) => text.replace(SCRIPT_ESC_CLOSE_FROM, SCRIPT_ESC_CLOSE_TO),
67        Err(err) => return Err(Error::other(err.to_string())),
68    };
69    let ordered_pages: Vec<&DocPage> = ordered_site_pages(site);
70    let base: &str = options.get_base_url().trim_end_matches('/');
71    let sidebar_entries: Vec<SidebarNavEntry<'_>> = build_sidebar_entries(&ordered_pages, base);
72    let site_title_escaped: String = escape_html(site.get_title());
73    let home_href: String = href_for_route(base, ROOT_ROUTE_STR);
74    let home_href_escaped: String = escape_html(&home_href);
75    let generated_at_escaped: String = escape_html(&generated_at);
76    let base_json: String = to_string(base).unwrap_or_else(|_| EMPTY_JSON_STRING.to_string());
77    for (idx, page) in ordered_pages.iter().enumerate() {
78        let prev_page: Option<&DocPage> = if idx > 0 {
79            ordered_pages.get(idx - 1).copied()
80        } else {
81            None
82        };
83        let next_page: Option<&DocPage> = ordered_pages.get(idx + 1).copied();
84        let ctx: PageRenderContext<'_> = PageRenderContext {
85            site,
86            sidebar_entries: sidebar_entries.as_slice(),
87            site_title_escaped: &site_title_escaped,
88            home_href_escaped: &home_href_escaped,
89            generated_at_escaped: &generated_at_escaped,
90            base_json: &base_json,
91            prev_page,
92            next_page,
93            search_json_compact: &search_json_compact,
94            options,
95        };
96        let html: String = render_page_html_with_context(page, &ctx);
97        let rel_file: PathBuf = html_path_for_route(out_dir, page.get_route());
98        if let Some(parent) = rel_file.parent() {
99            fs::create_dir_all(parent)?;
100        }
101        fs::write(&rel_file, &html)?;
102        if options.get_clean_urls() && page.get_route() != ROOT_ROUTE_STR {
103            let clean_file: PathBuf = clean_html_path_for_route(out_dir, page.get_route());
104            if let Some(parent) = clean_file.parent() {
105                fs::create_dir_all(parent)?;
106            }
107            fs::write(&clean_file, &html)?;
108        }
109    }
110    if let Some(first_page) = ordered_pages.first().copied()
111        && !out_dir.join(INDEX_HTML_NAME).exists()
112    {
113        let fallback_ctx: PageRenderContext<'_> = PageRenderContext {
114            site,
115            sidebar_entries: sidebar_entries.as_slice(),
116            site_title_escaped: &site_title_escaped,
117            home_href_escaped: &home_href_escaped,
118            generated_at_escaped: &generated_at_escaped,
119            base_json: &base_json,
120            prev_page: None,
121            next_page: ordered_pages.get(1).copied(),
122            search_json_compact: &search_json_compact,
123            options,
124        };
125        let fallback_html: String = render_page_html_with_context(first_page, &fallback_ctx);
126        fs::write(out_dir.join(INDEX_HTML_NAME), fallback_html)?;
127    }
128    let index_path: PathBuf = out_dir.join(INDEX_JSON_NAME);
129    let json: String = match to_string_pretty(&entries) {
130        Ok(text) => text,
131        Err(err) => return Err(Error::other(err.to_string())),
132    };
133    fs::write(&index_path, json)?;
134    let sitemap_xml: String = build_sitemap_xml(&ordered_pages, options.get_base_url());
135    fs::write(out_dir.join(SITEMAP_XML_NAME), sitemap_xml)?;
136    if let Some(assets_root) = options.try_get_assets_root() {
137        copy_static_assets(assets_root, out_dir)?;
138    }
139    Ok(GeneratedSiteReport::new(
140        site.get_pages().len(),
141        generated_at,
142        index_path.display().to_string(),
143    ))
144}
145
146/// Renders a single `DocPage` into a self-contained static HTML document using default build options.
147///
148/// # Arguments
149///
150/// - `&DocSite` - Parent site for navigation links.
151/// - `&DocPage` - Page to render.
152/// - `&str` - Build timestamp string.
153///
154/// # Returns
155///
156/// - `String` - Complete HTML document string.
157#[must_use]
158pub fn render_page_html(site: &DocSite, page: &DocPage, generated_at: &str) -> String {
159    let entries: Vec<SearchIndexEntry> = site.search_entries();
160    let compact: String = to_string(&entries)
161        .unwrap_or_else(|_| EMPTY_JSON_ARRAY.to_string())
162        .replace(SCRIPT_ESC_CLOSE_FROM, SCRIPT_ESC_CLOSE_TO);
163    let opts: DocsBuildOptions = DocsBuildOptions::default();
164    let base: &str = opts.get_base_url().trim_end_matches('/');
165    let ordered_pages: Vec<&DocPage> = ordered_site_pages(site);
166    let sidebar_entries: Vec<SidebarNavEntry<'_>> = build_sidebar_entries(&ordered_pages, base);
167    let site_title_escaped: String = escape_html(site.get_title());
168    let home_href: String = href_for_route(base, ROOT_ROUTE_STR);
169    let home_href_escaped: String = escape_html(&home_href);
170    let generated_at_escaped: String = escape_html(generated_at);
171    let base_json: String = to_string(base).unwrap_or_else(|_| EMPTY_JSON_STRING.to_string());
172    let ctx: PageRenderContext<'_> = PageRenderContext {
173        site,
174        sidebar_entries: sidebar_entries.as_slice(),
175        site_title_escaped: &site_title_escaped,
176        home_href_escaped: &home_href_escaped,
177        generated_at_escaped: &generated_at_escaped,
178        base_json: &base_json,
179        prev_page: None,
180        next_page: None,
181        search_json_compact: &compact,
182        options: &opts,
183    };
184    render_page_html_with_context(page, &ctx)
185}
186
187/// Precomputes sorted, pre-escaped sidebar navigation entries shared across every rendered page.
188///
189/// # Arguments
190///
191/// - `&[&'a DocPage]` - Site pages already sorted in canonical sidebar order.
192/// - `&str` - Normalized base URL without trailing slash.
193///
194/// # Returns
195///
196/// - `Vec<SidebarNavEntry<'a>>` - Pre-escaped sidebar entries ready for direct HTML emission.
197fn build_sidebar_entries<'a>(ordered: &[&'a DocPage], base: &str) -> Vec<SidebarNavEntry<'a>> {
198    let mut entries: Vec<SidebarNavEntry<'a>> = Vec::with_capacity(ordered.len());
199    let mut current_section: Option<&str> = None;
200    for &nav_page in ordered.iter() {
201        let sec: &str = nav_page.get_section().as_str();
202        let section_header_html: Option<String> = if current_section != Some(sec) {
203            current_section = Some(sec);
204            let mut sec_buf: String =
205                String::with_capacity(HTML_SEC_OPEN.len() + sec.len() + HTML_SEC_CLOSE.len());
206            sec_buf.push_str(HTML_SEC_OPEN);
207            push_escaped_html(&mut sec_buf, sec);
208            sec_buf.push_str(HTML_SEC_CLOSE);
209            Some(sec_buf)
210        } else {
211            None
212        };
213        let href: String = href_for_route(base, nav_page.get_route());
214        let title: &str = nav_page.get_title().as_str();
215        let mut tail: String = String::with_capacity(
216            href.len() + HTML_LINK_MID.len() + title.len() + HTML_LINK_CLOSE.len(),
217        );
218        push_escaped_html(&mut tail, &href);
219        tail.push_str(HTML_LINK_MID);
220        push_escaped_html(&mut tail, title);
221        tail.push_str(HTML_LINK_CLOSE);
222        entries.push(SidebarNavEntry {
223            route: nav_page.get_route().as_str(),
224            section_header_html,
225            link_tail_html: tail,
226        });
227    }
228    entries
229}
230
231/// Returns all site pages in canonical sidebar and pagination order.
232///
233/// # Arguments
234///
235/// - `&DocSite` - Loaded documentation site.
236///
237/// # Returns
238///
239/// - `Vec<&DocPage>` - Pages ordered by section rank, section label, page order, and route.
240fn ordered_site_pages(site: &DocSite) -> Vec<&DocPage> {
241    let mut ordered: Vec<&DocPage> = site.get_pages().iter().collect();
242    ordered.sort_by(|a: &&DocPage, b: &&DocPage| {
243        section_sort_rank(a.get_section())
244            .cmp(&section_sort_rank(b.get_section()))
245            .then_with(|| a.get_section().cmp(b.get_section()))
246            .then_with(|| a.get_order().cmp(&b.get_order()))
247            .then_with(|| a.get_route().cmp(b.get_route()))
248    });
249    ordered
250}
251
252/// Renders a full styled HTML page with sidebar sections, TOC, live search index, pagination, and optional HMR.
253///
254/// # Arguments
255///
256/// - `&DocPage` - Active page being rendered.
257/// - `&PageRenderContext<'_>` - Shared site, pagination, timestamp, search index, and build options context.
258///
259/// # Returns
260///
261/// - `String` - Complete HTML document string.
262fn render_page_html_with_context(page: &DocPage, ctx: &PageRenderContext<'_>) -> String {
263    let site: &DocSite = ctx.get_site();
264    let options: &DocsBuildOptions = ctx.get_options();
265    let base: &str = options.get_base_url().trim_end_matches('/');
266    let has_toc: bool = !page.get_toc().is_empty();
267    let brand_char: char = brand_monogram(site.get_title());
268    let is_euv_brand: bool = site
269        .get_title()
270        .trim()
271        .to_ascii_lowercase()
272        .starts_with(BRAND_PREFIX_EUV);
273    let mut out: String = String::with_capacity(
274        16384 + ctx.get_search_json_compact().len() + page.get_markdown_body().len() * 2,
275    );
276    out.push_str(HTML_DOCTYPE);
277    push_escaped_html(&mut out, page.get_title());
278    out.push_str(HTML_TITLE_SEP);
279    out.push_str(ctx.get_site_title_escaped());
280    out.push_str(HTML_STYLES_AND_HEAD_END);
281    out.push_str(HTML_TOPBAR_START);
282    out.push_str(ctx.get_home_href_escaped());
283    if is_euv_brand {
284        out.push_str(HTML_TOPBAR_LOGO_IMG);
285    } else {
286        out.push_str(HTML_TOPBAR_MARK_OPEN);
287        out.push(brand_char);
288        out.push_str(HTML_TOPBAR_MARK_CLOSE);
289    }
290    out.push_str(ctx.get_site_title_escaped());
291    out.push_str(HTML_TOPBAR_END);
292    if has_toc {
293        out.push_str(HTML_SHELL_OPEN);
294    } else {
295        out.push_str(HTML_SHELL_NO_TOC_OPEN);
296    }
297    out.push_str(HTML_SIDEBAR_OPEN);
298    render_sidebar_nav(ctx.get_sidebar_entries(), page.get_route(), &mut out);
299    out.push_str(HTML_SIDEBAR_CLOSE);
300    out.push_str(HTML_BADGE_OPEN);
301    push_escaped_html(&mut out, page.get_section());
302    out.push_str(HTML_BADGE_CLOSE);
303    push_escaped_html(&mut out, page.get_title());
304    out.push_str(HTML_H1_CLOSE);
305    if should_render_lead(page) {
306        out.push_str(HTML_LEAD_OPEN);
307        push_escaped_html(&mut out, page.get_summary());
308        out.push_str(HTML_P_CLOSE);
309    }
310    if !page.get_markdown_body().is_empty() {
311        render_markdown_body_html(page, base, &mut out);
312    } else {
313        render_fallback_blocks_html(page, &mut out);
314    }
315    render_pager_nav(ctx.get_prev_page(), ctx.get_next_page(), base, &mut out);
316    out.push_str(HTML_FOOTER_PREFIX);
317    out.push_str(ctx.get_generated_at_escaped());
318    out.push_str(HTML_FOOTER_SUFFIX);
319    if has_toc {
320        out.push_str(HTML_TOC_OPEN);
321        for item in page.get_toc().iter() {
322            let cls: &str = match item.get_level() {
323                3 => TOC_LVL3_CLASS,
324                lvl if lvl >= 4 => TOC_LVL4_CLASS,
325                _ => "",
326            };
327            out.push_str(HTML_TOC_A_OPEN);
328            out.push_str(cls);
329            out.push_str(HTML_TOC_HREF_HASH);
330            push_escaped_html(&mut out, item.get_slug());
331            out.push_str(HTML_LINK_MID);
332            push_escaped_html(&mut out, item.get_title());
333            out.push_str(HTML_LINK_CLOSE);
334        }
335        out.push_str(HTML_TOC_CLOSE);
336    }
337    out.push_str(HTML_SHELL_CLOSE);
338    out.push_str(HTML_SCRIPT_PREFIX);
339    out.push_str(ctx.get_search_json_compact());
340    out.push_str(HTML_SCRIPT_BASE_PREFIX);
341    out.push_str(ctx.get_base_json());
342    out.push_str(HTML_SCRIPT_BODY);
343    if let Some(hmr_url) = options.try_get_hmr_endpoint() {
344        out.push_str(HTML_HMR_PREFIX);
345        push_escaped_html(&mut out, hmr_url);
346        out.push_str(HTML_HMR_SUFFIX);
347    }
348    out.push_str(HTML_BODY_END);
349    out
350}
351
352/// Renders the grouped section-ordered sidebar links from pre-escaped entries into `out`.
353///
354/// # Arguments
355///
356/// - `&[SidebarNavEntry<'_>]` - Pre-sorted and pre-escaped sidebar navigation entries.
357/// - `&str` - Canonical route of the currently active page.
358/// - `&mut String` - HTML output buffer.
359fn render_sidebar_nav(
360    sidebar_entries: &[SidebarNavEntry<'_>],
361    active_route: &str,
362    out: &mut String,
363) {
364    for entry in sidebar_entries.iter() {
365        if let Some(sec_html) = entry.try_get_section_header_html() {
366            out.push_str(sec_html);
367        }
368        if entry.get_route() == active_route {
369            out.push_str(HTML_NAV_LINK_ACTIVE_OPEN);
370        } else {
371            out.push_str(HTML_NAV_LINK_OPEN);
372        }
373        out.push_str(entry.get_link_tail_html());
374    }
375}
376
377/// Renders previous and next pagination cards when either neighbor exists.
378///
379/// # Arguments
380///
381/// - `Option<&DocPage>` - Previous page in reading order.
382/// - `Option<&DocPage>` - Next page in reading order.
383/// - `&str` - Normalized base URL without trailing slash.
384/// - `&mut String` - HTML output buffer.
385fn render_pager_nav(
386    prev_page: Option<&DocPage>,
387    next_page: Option<&DocPage>,
388    base: &str,
389    out: &mut String,
390) {
391    if prev_page.is_none() && next_page.is_none() {
392        return;
393    }
394    out.push_str(HTML_PAGER_OPEN);
395    if let Some(prev) = prev_page {
396        out.push_str(HTML_PAGER_PREV_OPEN);
397        let prev_href: String = href_for_route(base, prev.get_route());
398        push_escaped_html(out, &prev_href);
399        out.push_str(HTML_PAGER_PREV_LABEL);
400        push_escaped_html(out, prev.get_title());
401        out.push_str(HTML_PAGER_CARD_CLOSE);
402    } else {
403        out.push_str(HTML_PAGER_EMPTY);
404    }
405    if let Some(next) = next_page {
406        out.push_str(HTML_PAGER_NEXT_OPEN);
407        let next_href: String = href_for_route(base, next.get_route());
408        push_escaped_html(out, &next_href);
409        out.push_str(HTML_PAGER_NEXT_LABEL);
410        push_escaped_html(out, next.get_title());
411        out.push_str(HTML_PAGER_CARD_CLOSE);
412    } else {
413        out.push_str(HTML_PAGER_EMPTY);
414    }
415    out.push_str(HTML_PAGER_CLOSE);
416}
417
418/// Returns `true` when `page.summary` is non-empty and does not duplicate the first body paragraph.
419///
420/// # Arguments
421///
422/// - `&DocPage` - Candidate documentation page.
423///
424/// # Returns
425///
426/// - `bool` - Whether a separate `<p class="lead">` should be rendered.
427fn should_render_lead(page: &DocPage) -> bool {
428    let summary: &str = page.get_summary().trim();
429    if summary.is_empty() {
430        return false;
431    }
432    let first_prose: Option<&str> = page.get_blocks().iter().find_map(|b: &DocBlock| match b {
433        DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.trim()),
434        _ => None,
435    });
436    first_prose != Some(summary)
437}
438
439/// Computes the uppercase single-character brand monogram for the topbar badge.
440///
441/// # Arguments
442///
443/// - `&str` - Site brand title.
444///
445/// # Returns
446///
447/// - `char` - Uppercase alphanumeric initial or `'E'`.
448fn brand_monogram(title: &str) -> char {
449    title
450        .chars()
451        .find(|ch: &char| ch.is_alphanumeric())
452        .and_then(|ch: char| ch.to_uppercase().next())
453        .unwrap_or(DEFAULT_BRAND_MONOGRAM)
454}
455
456/// Renders full-fidelity Markdown HTML preserving inline formatting, links, images, lists, tables, code blocks, and custom containers.
457///
458/// # Arguments
459///
460/// - `&DocPage` - Parsed page carrying raw Markdown body text.
461/// - `&str` - Normalized base URL prefix.
462/// - `&mut String` - HTML output buffer.
463fn render_markdown_body_html(page: &DocPage, base: &str, out: &mut String) {
464    let body_raw: &str = page.get_markdown_body();
465    let mut state: MarkdownRenderState<'_> = MarkdownRenderState {
466        page,
467        base,
468        seen_slugs: BTreeMap::new(),
469        skipped_title_h1: false,
470        out,
471    };
472    if !body_raw.contains(CALLOUT_FENCE) {
473        render_markdown_chunk(body_raw, &mut state);
474        return;
475    }
476    let segments: Vec<BodySegment> = split_custom_containers(body_raw);
477    for seg in segments.into_iter() {
478        match seg {
479            BodySegment::Markdown(md) => {
480                render_markdown_chunk(&md, &mut state);
481            }
482            BodySegment::Callout { kind, title, body } => {
483                if kind == CALLOUT_KIND_DETAILS {
484                    state.out.push_str(HTML_CALLOUT_DETAILS_OPEN);
485                    push_escaped_html(state.out, &title);
486                    state.out.push_str(HTML_SUMMARY_CLOSE);
487                    render_markdown_chunk(&body, &mut state);
488                    state.out.push_str(HTML_DETAILS_CLOSE);
489                } else {
490                    state.out.push_str(HTML_CALLOUT_DIV_OPEN);
491                    push_escaped_html(state.out, &kind);
492                    state.out.push_str(HTML_CALLOUT_TITLE_MID);
493                    push_escaped_html(state.out, &title);
494                    state.out.push_str(HTML_DIV_CLOSE);
495                    render_markdown_chunk(&body, &mut state);
496                    state.out.push_str(HTML_DIV_CLOSE);
497                }
498            }
499        }
500    }
501}
502
503/// Splits VuePress-style `::: kind [title]` custom containers while ignoring fenced code blocks.
504///
505/// # Arguments
506///
507/// - `&str` - Raw Markdown document body.
508///
509/// # Returns
510///
511/// - `Vec<BodySegment>` - Ordered plain Markdown and callout segments.
512fn split_custom_containers(body: &str) -> Vec<BodySegment> {
513    let mut segments: Vec<BodySegment> = Vec::new();
514    let mut plain: String = String::new();
515    let mut active: Option<(String, String, String)> = None;
516    let mut in_fence: bool = false;
517    for line in body.lines() {
518        let trimmed: &str = line.trim();
519        if trimmed.starts_with(FENCE_BACKTICK) || trimmed.starts_with(FENCE_TILDE) {
520            in_fence = !in_fence;
521        }
522        if let Some((kind, title, inner)) = active.as_mut() {
523            if !in_fence && trimmed == CALLOUT_FENCE {
524                let done_kind: String = take(kind);
525                let done_title: String = take(title);
526                let done_body: String = take(inner);
527                active = None;
528                segments.push(BodySegment::Callout {
529                    kind: done_kind,
530                    title: done_title,
531                    body: done_body,
532                });
533                continue;
534            }
535            inner.push_str(line);
536            inner.push('\n');
537            continue;
538        }
539        if !in_fence && let Some(after) = trimmed.strip_prefix(CALLOUT_FENCE) {
540            let spec: &str = after.trim();
541            let (raw_kind, custom_title): (&str, &str) = match spec.find(char::is_whitespace) {
542                Some(pos) => (&spec[..pos], spec[pos..].trim()),
543                None => (spec, ""),
544            };
545            let normalized: Option<(&str, &str)> =
546                if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_TIP) {
547                    Some((CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP))
548                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_WARNING) {
549                    Some((CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING))
550                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_DANGER) {
551                    Some((CALLOUT_KIND_DANGER, CALLOUT_TITLE_DANGER))
552                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_INFO) {
553                    Some((CALLOUT_KIND_INFO, CALLOUT_TITLE_INFO))
554                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_NOTE) {
555                    Some((CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE))
556                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_DETAILS) {
557                    Some((CALLOUT_KIND_DETAILS, CALLOUT_TITLE_DETAILS))
558                } else {
559                    None
560                };
561            if let Some((kind_str, default_title)) = normalized {
562                if !plain.is_empty() {
563                    segments.push(BodySegment::Markdown(take(&mut plain)));
564                }
565                let title: String = if custom_title.is_empty() {
566                    default_title.to_string()
567                } else {
568                    custom_title.to_string()
569                };
570                active = Some((kind_str.to_string(), title, String::new()));
571                continue;
572            }
573        }
574        plain.push_str(line);
575        plain.push('\n');
576    }
577    if let Some((kind, title, inner)) = active {
578        segments.push(BodySegment::Callout {
579            kind,
580            title,
581            body: inner,
582        });
583    }
584    if !plain.is_empty() {
585        segments.push(BodySegment::Markdown(plain));
586    }
587    segments
588}
589
590/// Renders a single Markdown chunk through `pulldown_cmark` into semantic, XSS-safe HTML.
591///
592/// # Arguments
593///
594/// - `&str` - Markdown chunk text.
595/// - `&mut MarkdownRenderState<'_>` - Mutable page rendering state and HTML output buffer.
596fn render_markdown_chunk(chunk: &str, state: &mut MarkdownRenderState<'_>) {
597    let parser: Parser<'_> = Parser::new_ext(chunk, Options::all());
598    let mut active_heading: Option<(u8, Option<String>, String, String)> = None;
599    let mut active_code: Option<(String, String)> = None;
600    let mut active_image: Option<(String, String, String)> = None;
601    let mut table_alignments: Vec<Alignment> = Vec::new();
602    let mut blockquote_alerts: Vec<bool> = Vec::new();
603    let mut in_table_head: bool = false;
604    let mut cell_index: usize = 0;
605    let mut pending_text: String = String::new();
606    for event in parser {
607        if let Some((_, _, ref mut heading_html, ref mut heading_plain)) = active_heading {
608            match event {
609                Event::End(TagEnd::Heading(_)) => {
610                    if let Some((level, custom_id, inner_html, plain)) = active_heading.take() {
611                        let trimmed_plain: &str = plain.trim();
612                        if !trimmed_plain.is_empty() {
613                            let raw_slug: String = custom_id
614                                .map(|s: String| slugify(&s))
615                                .filter(|s: &String| !s.is_empty())
616                                .unwrap_or_else(|| slugify(trimmed_plain));
617                            let slug: String = deduplicate_slug(raw_slug, &mut state.seen_slugs);
618                            if level <= 2
619                                && !state.skipped_title_h1
620                                && state.seen_slugs.len() == 1
621                                && trimmed_plain.eq_ignore_ascii_case(state.page.get_title().trim())
622                            {
623                                state.skipped_title_h1 = true;
624                            } else {
625                                let tag_lvl: u8 = level.clamp(2, 6);
626                                let _: fmt::Result =
627                                    write!(state.out, "<h{tag_lvl}{HTML_HEADING_ID_MID}");
628                                push_escaped_html(state.out, &slug);
629                                state.out.push_str(HTML_LINK_MID);
630                                state.out.push_str(&inner_html);
631                                state.out.push_str(HTML_ANCHOR_MID);
632                                push_escaped_html(state.out, &slug);
633                                state.out.push_str(HTML_ANCHOR_CLOSE);
634                                let _: fmt::Result = write!(state.out, "</h{tag_lvl}>");
635                            }
636                        }
637                    }
638                }
639                Event::Text(text) => {
640                    heading_plain.push_str(&text);
641                    push_escaped_html(heading_html, &text);
642                }
643                Event::Code(text) => {
644                    heading_plain.push_str(&text);
645                    heading_html.push_str(HTML_INLINE_CODE_OPEN);
646                    push_escaped_html(heading_html, &text);
647                    heading_html.push_str(HTML_INLINE_CODE_CLOSE);
648                }
649                Event::Start(Tag::Strong) => heading_html.push_str(HTML_STRONG_OPEN),
650                Event::End(TagEnd::Strong) => heading_html.push_str(HTML_STRONG_CLOSE),
651                Event::Start(Tag::Emphasis) => heading_html.push_str(HTML_EM_OPEN),
652                Event::End(TagEnd::Emphasis) => heading_html.push_str(HTML_EM_CLOSE),
653                Event::Start(Tag::Strikethrough) => heading_html.push_str(HTML_DEL_OPEN),
654                Event::End(TagEnd::Strikethrough) => heading_html.push_str(HTML_DEL_CLOSE),
655                Event::SoftBreak | Event::HardBreak => {
656                    heading_plain.push(' ');
657                    heading_html.push(' ');
658                }
659                _ => {}
660            }
661            continue;
662        }
663        if let Some((_, ref mut code_buf)) = active_code {
664            match event {
665                Event::End(TagEnd::CodeBlock) => {
666                    if let Some((lang, code)) = active_code.take() {
667                        let trimmed: &str = code.trim_end_matches('\n');
668                        if lang.eq_ignore_ascii_case(CODE_LANG_MERMAID) {
669                            render_mermaid_svg_html(trimmed, state.out);
670                        } else {
671                            render_highlighted_code_html(&lang, trimmed, state.out);
672                        }
673                    }
674                }
675                Event::Text(text) | Event::Code(text) => code_buf.push_str(&text),
676                Event::SoftBreak | Event::HardBreak => code_buf.push('\n'),
677                _ => {}
678            }
679            continue;
680        }
681        if let Some((_, _, ref mut alt_buf)) = active_image {
682            match event {
683                Event::End(TagEnd::Image) => {
684                    if let Some((src, title, alt)) = active_image.take()
685                        && let Some(resolved) =
686                            resolve_asset_src(state.base, state.page.get_route(), &src)
687                    {
688                        state.out.push_str(HTML_IMG_SRC_OPEN);
689                        push_escaped_html(state.out, &resolved);
690                        state.out.push_str(HTML_IMG_ALT_MID);
691                        push_escaped_html(state.out, alt.trim());
692                        if !title.is_empty() {
693                            state.out.push_str(HTML_IMG_TITLE_MID);
694                            push_escaped_html(state.out, &title);
695                        }
696                        state.out.push_str(HTML_IMG_LAZY_CLOSE);
697                    }
698                }
699                Event::Text(text) | Event::Code(text) => alt_buf.push_str(&text),
700                Event::SoftBreak | Event::HardBreak => alt_buf.push(' '),
701                _ => {}
702            }
703            continue;
704        }
705        if let Event::Text(text) = event {
706            pending_text.push_str(&text);
707            continue;
708        }
709        if !pending_text.is_empty() {
710            render_extended_inline_text_html(&pending_text, state.out);
711            pending_text.clear();
712        }
713        match event {
714            Event::Start(Tag::Heading { level, id, .. }) => {
715                active_heading = Some((
716                    heading_level_num(level),
717                    id.map(CowStr::into_string),
718                    String::new(),
719                    String::new(),
720                ));
721            }
722            Event::Start(Tag::Paragraph) => state.out.push_str(HTML_P_OPEN),
723            Event::End(TagEnd::Paragraph) => state.out.push_str(HTML_P_CLOSE),
724            Event::Start(Tag::BlockQuote(kind_opt)) => {
725                if let Some(kind) = kind_opt {
726                    let (cls, title): (&str, &str) = match kind {
727                        BlockQuoteKind::Note => (CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE),
728                        BlockQuoteKind::Tip => (CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP),
729                        BlockQuoteKind::Important => {
730                            (CALLOUT_KIND_IMPORTANT, CALLOUT_TITLE_IMPORTANT)
731                        }
732                        BlockQuoteKind::Warning => (CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING),
733                        BlockQuoteKind::Caution => (CALLOUT_KIND_CAUTION, CALLOUT_TITLE_CAUTION),
734                    };
735                    state.out.push_str(HTML_CALLOUT_DIV_OPEN);
736                    state.out.push_str(cls);
737                    state.out.push_str(HTML_CALLOUT_TITLE_MID);
738                    state.out.push_str(title);
739                    state.out.push_str(HTML_DIV_CLOSE);
740                    blockquote_alerts.push(true);
741                } else {
742                    state.out.push_str(HTML_QUOTE_OPEN);
743                    blockquote_alerts.push(false);
744                }
745            }
746            Event::End(TagEnd::BlockQuote(_)) => {
747                if blockquote_alerts.pop().unwrap_or(false) {
748                    state.out.push_str(HTML_DIV_CLOSE);
749                } else {
750                    state.out.push_str(HTML_QUOTE_CLOSE);
751                }
752            }
753            Event::Start(Tag::List(None)) => state.out.push_str(HTML_UL_OPEN),
754            Event::Start(Tag::List(Some(start))) => {
755                if start == 1 {
756                    state.out.push_str(HTML_OL_OPEN);
757                } else {
758                    state.out.push_str(HTML_OL_START_OPEN);
759                    let _: fmt::Result = write!(state.out, "{start}");
760                    state.out.push_str(HTML_LINK_MID);
761                }
762            }
763            Event::End(TagEnd::List(ordered)) => {
764                if ordered {
765                    state.out.push_str(HTML_OL_CLOSE);
766                } else {
767                    state.out.push_str(HTML_UL_CLOSE);
768                }
769            }
770            Event::Start(Tag::Item) => state.out.push_str(HTML_LI_OPEN),
771            Event::End(TagEnd::Item) => state.out.push_str(HTML_LI_CLOSE),
772            Event::Start(Tag::Strong) => state.out.push_str(HTML_STRONG_OPEN),
773            Event::End(TagEnd::Strong) => state.out.push_str(HTML_STRONG_CLOSE),
774            Event::Start(Tag::Emphasis) => state.out.push_str(HTML_EM_OPEN),
775            Event::End(TagEnd::Emphasis) => state.out.push_str(HTML_EM_CLOSE),
776            Event::Start(Tag::Strikethrough) => state.out.push_str(HTML_DEL_OPEN),
777            Event::End(TagEnd::Strikethrough) => state.out.push_str(HTML_DEL_CLOSE),
778            Event::Start(Tag::Superscript) => state.out.push_str(HTML_SUP_OPEN),
779            Event::End(TagEnd::Superscript) => state.out.push_str(HTML_SUP_CLOSE),
780            Event::Start(Tag::Subscript) => state.out.push_str(HTML_SUB_OPEN),
781            Event::End(TagEnd::Subscript) => state.out.push_str(HTML_SUB_CLOSE),
782            Event::Start(Tag::DefinitionList) => state.out.push_str(HTML_DL_OPEN),
783            Event::End(TagEnd::DefinitionList) => state.out.push_str(HTML_DL_CLOSE),
784            Event::Start(Tag::DefinitionListTitle) => state.out.push_str(HTML_DT_OPEN),
785            Event::End(TagEnd::DefinitionListTitle) => state.out.push_str(HTML_DT_CLOSE),
786            Event::Start(Tag::DefinitionListDefinition) => state.out.push_str(HTML_DD_OPEN),
787            Event::End(TagEnd::DefinitionListDefinition) => state.out.push_str(HTML_DD_CLOSE),
788            Event::Start(Tag::CodeBlock(kind)) => {
789                let lang: String = match kind {
790                    CodeBlockKind::Fenced(tag) => {
791                        let first: &str = tag.split_whitespace().next().unwrap_or("");
792                        if first.is_empty() {
793                            DEFAULT_CODE_LABEL.to_string()
794                        } else {
795                            first.to_string()
796                        }
797                    }
798                    CodeBlockKind::Indented => DEFAULT_CODE_LABEL.to_string(),
799                };
800                active_code = Some((lang, String::new()));
801            }
802            Event::Start(Tag::Link {
803                dest_url, title, ..
804            }) => {
805                let resolved: String =
806                    resolve_link_href(state.base, state.page.get_route(), &dest_url);
807                let external: bool = is_external_url(&resolved);
808                state.out.push_str(HTML_A_HREF_OPEN);
809                push_escaped_html(state.out, &resolved);
810                state.out.push('"');
811                if !title.is_empty() {
812                    state.out.push_str(HTML_TITLE_ATTR_OPEN);
813                    push_escaped_html(state.out, &title);
814                    state.out.push('"');
815                }
816                if external {
817                    state.out.push_str(HTML_EXTERNAL_LINK_ATTRS);
818                }
819                state.out.push('>');
820            }
821            Event::End(TagEnd::Link) => state.out.push_str(HTML_LINK_CLOSE),
822            Event::Start(Tag::Image {
823                dest_url, title, ..
824            }) => {
825                active_image = Some((dest_url.into_string(), title.into_string(), String::new()));
826            }
827            Event::Start(Tag::Table(aligns)) => {
828                table_alignments = aligns;
829                in_table_head = false;
830                state.out.push_str(HTML_TABLE_OPEN);
831            }
832            Event::End(TagEnd::Table) => {
833                table_alignments.clear();
834                state.out.push_str(HTML_TBODY_CLOSE);
835                state.out.push_str(HTML_TABLE_CLOSE);
836            }
837            Event::Start(Tag::TableHead) => {
838                in_table_head = true;
839                cell_index = 0;
840                state.out.push_str(HTML_THEAD_OPEN);
841            }
842            Event::End(TagEnd::TableHead) => {
843                in_table_head = false;
844                state.out.push_str(HTML_THEAD_CLOSE);
845                state.out.push_str(HTML_TBODY_OPEN);
846            }
847            Event::Start(Tag::TableRow) => {
848                cell_index = 0;
849                state.out.push_str(HTML_TR_OPEN);
850            }
851            Event::End(TagEnd::TableRow) => state.out.push_str(HTML_TR_CLOSE),
852            Event::Start(Tag::TableCell) => {
853                let align_attr: &str = match table_alignments.get(cell_index).copied() {
854                    Some(Alignment::Center) => HTML_ALIGN_CENTER,
855                    Some(Alignment::Right) => HTML_ALIGN_RIGHT,
856                    _ => "",
857                };
858                cell_index += 1;
859                if in_table_head {
860                    state.out.push_str(HTML_TH_PREFIX);
861                } else {
862                    state.out.push_str(HTML_TD_PREFIX);
863                }
864                state.out.push_str(align_attr);
865                state.out.push('>');
866            }
867            Event::End(TagEnd::TableCell) => {
868                if in_table_head {
869                    state.out.push_str(HTML_TH_CLOSE);
870                } else {
871                    state.out.push_str(HTML_TD_CLOSE);
872                }
873            }
874            Event::Start(Tag::FootnoteDefinition(label)) => {
875                let fn_slug: String = slugify(&label);
876                state.out.push_str(HTML_FOOTNOTE_DEF_OPEN);
877                push_escaped_html(state.out, &fn_slug);
878                state.out.push_str(HTML_FOOTNOTE_DEF_MID);
879                push_escaped_html(state.out, &label);
880                state.out.push_str(HTML_FOOTNOTE_DEF_CLOSE);
881            }
882            Event::End(TagEnd::FootnoteDefinition) => state.out.push_str(HTML_QUOTE_CLOSE),
883            Event::FootnoteReference(label) => {
884                let fn_slug: String = slugify(&label);
885                state.out.push_str(HTML_FOOTNOTE_REF_OPEN);
886                push_escaped_html(state.out, &fn_slug);
887                state.out.push_str(HTML_FOOTNOTE_REF_MID);
888                push_escaped_html(state.out, &label);
889                state.out.push_str(HTML_FOOTNOTE_REF_CLOSE);
890            }
891            Event::TaskListMarker(checked) => {
892                if checked {
893                    state.out.push_str(HTML_TASK_CHECKED);
894                } else {
895                    state.out.push_str(HTML_TASK_UNCHECKED);
896                }
897            }
898            Event::Rule => state.out.push_str(HTML_HR),
899            Event::Code(text) => {
900                state.out.push_str(HTML_INLINE_CODE_OPEN);
901                push_escaped_html(state.out, &text);
902                state.out.push_str(HTML_INLINE_CODE_CLOSE);
903            }
904            Event::SoftBreak => state.out.push(' '),
905            Event::HardBreak => state.out.push_str(HTML_BR),
906            Event::InlineMath(math) => {
907                let formatted: String = format_latex_math(&math);
908                state.out.push_str(HTML_MATH_INLINE_OPEN);
909                push_escaped_html(state.out, &formatted);
910                state.out.push_str(HTML_MATH_INLINE_CLOSE);
911            }
912            Event::DisplayMath(math) => {
913                let formatted: String = format_latex_math(&math);
914                state.out.push_str(HTML_MATH_DISPLAY_OPEN);
915                push_escaped_html(state.out, &formatted);
916                state.out.push_str(HTML_MATH_DISPLAY_CLOSE);
917            }
918            Event::Html(raw_html) | Event::InlineHtml(raw_html) => {
919                if is_safe_raw_html(&raw_html) {
920                    state.out.push_str(&raw_html);
921                } else {
922                    push_escaped_html(state.out, &raw_html);
923                }
924            }
925            _ => {}
926        }
927    }
928    if !pending_text.is_empty() {
929        render_extended_inline_text_html(&pending_text, state.out);
930    }
931}
932
933/// Renders structured `DocBlock` entries when a `DocPage` was constructed without raw Markdown text.
934///
935/// # Arguments
936///
937/// - `&DocPage` - Documentation page containing structured blocks.
938/// - `&mut String` - HTML output buffer.
939fn render_fallback_blocks_html(page: &DocPage, out: &mut String) {
940    let mut in_ul: bool = false;
941    for block in page.get_blocks().iter() {
942        let is_item: bool = matches!(block, DocBlock::ListItem(_));
943        if is_item && !in_ul {
944            out.push_str(HTML_UL_OPEN);
945            in_ul = true;
946        } else if !is_item && in_ul {
947            out.push_str(HTML_UL_CLOSE);
948            in_ul = false;
949        }
950        match block {
951            DocBlock::Heading { level, slug, text } => {
952                let tag_lvl: u8 = (*level).clamp(2, 6);
953                let _: fmt::Result = write!(out, "<h{tag_lvl}{HTML_HEADING_ID_MID}");
954                push_escaped_html(out, slug);
955                out.push_str(HTML_LINK_MID);
956                push_escaped_html(out, text);
957                let _: fmt::Result = write!(out, "</h{tag_lvl}>");
958            }
959            DocBlock::Paragraph(text) => {
960                out.push_str(HTML_P_OPEN);
961                push_escaped_html(out, text);
962                out.push_str(HTML_P_CLOSE);
963            }
964            DocBlock::ListItem(text) => {
965                out.push_str(HTML_LI_OPEN);
966                push_escaped_html(out, text);
967                out.push_str(HTML_LI_CLOSE);
968            }
969            DocBlock::BlockQuote(text) => {
970                out.push_str(HTML_QUOTE_OPEN);
971                push_escaped_html(out, text);
972                out.push_str(HTML_QUOTE_CLOSE);
973            }
974            DocBlock::Image { alt, src } => {
975                out.push_str(HTML_P_IMG_OPEN);
976                push_escaped_html(out, src);
977                out.push_str(HTML_IMG_ALT_MID);
978                push_escaped_html(out, alt);
979                out.push_str(HTML_P_IMG_CLOSE);
980            }
981            DocBlock::HorizontalRule => out.push_str(HTML_HR),
982            DocBlock::Code { language, code } => {
983                render_highlighted_code_html(language, code, out);
984            }
985            DocBlock::Table { headers, rows } => {
986                out.push_str(HTML_TABLE_OPEN);
987                if !headers.is_empty() {
988                    out.push_str(HTML_THEAD_OPEN);
989                    for h in headers.iter() {
990                        out.push_str(HTML_TH_OPEN);
991                        push_escaped_html(out, h);
992                        out.push_str(HTML_TH_CLOSE);
993                    }
994                    out.push_str(HTML_THEAD_CLOSE);
995                }
996                out.push_str(HTML_TBODY_OPEN);
997                for row in rows.iter() {
998                    out.push_str(HTML_TR_OPEN);
999                    for cell in row.iter() {
1000                        out.push_str(HTML_TD_OPEN);
1001                        push_escaped_html(out, cell);
1002                        out.push_str(HTML_TD_CLOSE);
1003                    }
1004                    out.push_str(HTML_TR_CLOSE);
1005                }
1006                out.push_str(HTML_TBODY_CLOSE);
1007                out.push_str(HTML_TABLE_CLOSE);
1008            }
1009        }
1010    }
1011    if in_ul {
1012        out.push_str(HTML_UL_CLOSE);
1013    }
1014}
1015
1016/// Returns `true` when `haystack` starts with `prefix` ignoring ASCII letter case without heap allocation.
1017///
1018/// # Arguments
1019///
1020/// - `&str` - Source UTF-8 string.
1021/// - `&str` - ASCII prefix to match.
1022///
1023/// # Returns
1024///
1025/// - `bool` - `true` when `haystack` begins with `prefix` ignoring ASCII case.
1026fn starts_with_ascii_ignore_case(haystack: &str, prefix: &str) -> bool {
1027    let h: &[u8] = haystack.as_bytes();
1028    let p: &[u8] = prefix.as_bytes();
1029    h.len() >= p.len() && h[..p.len()].eq_ignore_ascii_case(p)
1030}
1031
1032/// Returns `true` when `haystack` ends with `suffix` ignoring ASCII letter case without heap allocation.
1033///
1034/// # Arguments
1035///
1036/// - `&str` - Source UTF-8 string.
1037/// - `&str` - ASCII suffix to match.
1038///
1039/// # Returns
1040///
1041/// - `bool` - `true` when `haystack` ends with `suffix` ignoring ASCII case.
1042fn ends_with_ascii_ignore_case(haystack: &str, suffix: &str) -> bool {
1043    let h: &[u8] = haystack.as_bytes();
1044    let s: &[u8] = suffix.as_bytes();
1045    h.len() >= s.len() && h[h.len() - s.len()..].eq_ignore_ascii_case(s)
1046}
1047
1048/// Returns `true` when `haystack` contains lowercase ASCII `needle` ignoring ASCII letter case without heap allocation.
1049///
1050/// # Arguments
1051///
1052/// - `&str` - Source UTF-8 string.
1053/// - `&str` - Lowercase ASCII needle to search for.
1054///
1055/// # Returns
1056///
1057/// - `bool` - `true` when `needle` occurs inside `haystack` ignoring ASCII case.
1058fn contains_ascii_ignore_case(haystack: &str, needle: &str) -> bool {
1059    let h: &[u8] = haystack.as_bytes();
1060    let n: &[u8] = needle.as_bytes();
1061    let n_len: usize = n.len();
1062    if n_len == 0 {
1063        return true;
1064    }
1065    if n_len > h.len() {
1066        return false;
1067    }
1068    let first: u8 = n[0];
1069    let tail: &[u8] = &n[1..];
1070    let limit: usize = h.len() - n_len;
1071    let mut pos: usize = 0;
1072    while pos <= limit {
1073        if h[pos].to_ascii_lowercase() == first
1074            && h[pos + 1..pos + n_len].eq_ignore_ascii_case(tail)
1075        {
1076            return true;
1077        }
1078        pos += 1;
1079    }
1080    false
1081}
1082
1083/// Checks whether a raw Markdown HTML fragment is free of active script or event-handler vectors.
1084///
1085/// # Arguments
1086///
1087/// - `&str` - Raw HTML fragment emitted by `pulldown_cmark`.
1088///
1089/// # Returns
1090///
1091/// - `bool` - `true` when safe to pass through verbatim.
1092fn is_safe_raw_html(raw: &str) -> bool {
1093    if UNSAFE_HTML_TAGS
1094        .iter()
1095        .any(|tag: &&str| contains_ascii_ignore_case(raw, tag))
1096    {
1097        return false;
1098    }
1099    if contains_ascii_ignore_case(raw, SCHEME_JAVASCRIPT)
1100        || contains_ascii_ignore_case(raw, SCHEME_VBSCRIPT)
1101    {
1102        return false;
1103    }
1104    let bytes: &[u8] = raw.as_bytes();
1105    for i in 0..bytes.len().saturating_sub(3) {
1106        let before_ok: bool = i == 0 || bytes[i - 1].is_ascii_whitespace();
1107        if before_ok
1108            && bytes[i].to_ascii_lowercase() == BYTE_LOWER_O
1109            && bytes[i + 1].to_ascii_lowercase() == BYTE_LOWER_N
1110            && bytes[i + 2].is_ascii_alphabetic()
1111        {
1112            let rest: &str = &raw[i + 2..];
1113            let attr_len: usize = rest
1114                .bytes()
1115                .take_while(|b: &u8| b.is_ascii_alphabetic())
1116                .count();
1117            if rest[attr_len..].trim_start().starts_with('=') {
1118                return false;
1119            }
1120        }
1121    }
1122    true
1123}
1124
1125/// Resolves Markdown link targets, rewriting relative `.md` links to clean URLs and blocking unsafe schemes.
1126///
1127/// # Arguments
1128///
1129/// - `&str` - Normalized base URL prefix.
1130/// - `&str` - Current page canonical route.
1131/// - `&str` - Raw Markdown link destination.
1132///
1133/// # Returns
1134///
1135/// - `String` - Safe navigable HTML `href` attribute value.
1136fn resolve_link_href(base: &str, current_route: &str, raw_dest: &str) -> String {
1137    let dest: &str = raw_dest.trim();
1138    if starts_with_ascii_ignore_case(dest, SCHEME_JAVASCRIPT)
1139        || starts_with_ascii_ignore_case(dest, SCHEME_VBSCRIPT)
1140    {
1141        return "#".to_string();
1142    }
1143    if dest.starts_with('#')
1144        || starts_with_ascii_ignore_case(dest, SCHEME_HTTP)
1145        || starts_with_ascii_ignore_case(dest, SCHEME_HTTPS)
1146        || starts_with_ascii_ignore_case(dest, SCHEME_MAILTO)
1147    {
1148        return dest.to_string();
1149    }
1150    let (path_part, fragment): (&str, Option<&str>) = match dest.split_once('#') {
1151        Some((p, f)) => (p, Some(f)),
1152        None => (dest, None),
1153    };
1154    if ends_with_ascii_ignore_case(path_part, MARKDOWN_EXT_SUFFIX) {
1155        let joined: String = join_relative_route(current_route, path_part);
1156        let stripped: &str = joined
1157            .strip_suffix(MARKDOWN_EXT_SUFFIX)
1158            .or_else(|| joined.strip_suffix(MARKDOWN_EXT_UPPER))
1159            .unwrap_or(&joined);
1160        let mut segs: Vec<String> = stripped
1161            .split('/')
1162            .filter(|s: &&str| !s.is_empty())
1163            .map(|seg: &str| {
1164                let cleaned: String = slugify(seg);
1165                if cleaned.is_empty() {
1166                    seg.to_ascii_lowercase()
1167                } else {
1168                    cleaned
1169                }
1170            })
1171            .collect();
1172        if let Some(last) = segs.last()
1173            && (last.eq_ignore_ascii_case(STEM_README_LOWER)
1174                || last.eq_ignore_ascii_case(STEM_INDEX_LOWER))
1175        {
1176            let _: Option<String> = segs.pop();
1177        }
1178        let route: String = if segs.is_empty() {
1179            ROOT_ROUTE_STR.to_string()
1180        } else {
1181            format!("/{}", segs.join("/"))
1182        };
1183        let clean: String = href_for_route(base, &route);
1184        return match fragment {
1185            Some(frag) if !frag.is_empty() => format!("{clean}#{frag}"),
1186            _ => clean,
1187        };
1188    }
1189    if dest.starts_with('/') {
1190        if base.is_empty() {
1191            dest.to_string()
1192        } else {
1193            format!("{base}{dest}")
1194        }
1195    } else {
1196        dest.to_string()
1197    }
1198}
1199
1200/// Resolves Markdown image `src` attributes against `current_route` and `base`, blocking unsafe schemes.
1201///
1202/// # Arguments
1203///
1204/// - `&str` - Normalized base URL prefix.
1205/// - `&str` - Current page canonical route.
1206/// - `&str` - Raw Markdown image destination.
1207///
1208/// # Returns
1209///
1210/// - `Option<String>` - Safe `src` attribute value or `None` when blocked.
1211fn resolve_asset_src(base: &str, current_route: &str, raw_src: &str) -> Option<String> {
1212    let src: &str = raw_src.trim();
1213    if src.is_empty()
1214        || starts_with_ascii_ignore_case(src, SCHEME_JAVASCRIPT)
1215        || starts_with_ascii_ignore_case(src, SCHEME_VBSCRIPT)
1216    {
1217        return None;
1218    }
1219    if starts_with_ascii_ignore_case(src, SCHEME_HTTP)
1220        || starts_with_ascii_ignore_case(src, SCHEME_HTTPS)
1221        || starts_with_ascii_ignore_case(src, SCHEME_DATA)
1222    {
1223        return Some(src.to_string());
1224    }
1225    if src.starts_with('/') {
1226        return Some(if base.is_empty() {
1227            src.to_string()
1228        } else {
1229            format!("{base}{src}")
1230        });
1231    }
1232    let resolved: String = join_relative_route(current_route, src);
1233    Some(if base.is_empty() {
1234        resolved
1235    } else {
1236        format!("{base}{resolved}")
1237    })
1238}
1239
1240/// Resolves a relative link or asset path against a page's canonical directory route.
1241///
1242/// # Arguments
1243///
1244/// - `&str` - Canonical page route (for example `/guide/markdown`).
1245/// - `&str` - Relative path reference (for example `./getting-started.md` or `../img/logo.png`).
1246///
1247/// # Returns
1248///
1249/// - `String` - Normalized root-relative path beginning with `/`.
1250fn join_relative_route(current_route: &str, rel_path: &str) -> String {
1251    let mut stack: Vec<&str> = current_route
1252        .trim_matches('/')
1253        .split('/')
1254        .filter(|s: &&str| !s.is_empty())
1255        .collect();
1256    if !stack.is_empty() {
1257        let _: Option<&str> = stack.pop();
1258    }
1259    for seg in rel_path.split('/') {
1260        if seg.is_empty() || seg == "." {
1261            continue;
1262        }
1263        if seg == ".." {
1264            let _: Option<&str> = stack.pop();
1265        } else {
1266            stack.push(seg);
1267        }
1268    }
1269    if stack.is_empty() {
1270        ROOT_ROUTE_STR.to_string()
1271    } else {
1272        format!("/{}", stack.join("/"))
1273    }
1274}
1275
1276/// Returns `true` when `href` points to an external HTTP(S) origin.
1277///
1278/// # Arguments
1279///
1280/// - `&str` - Resolved href string.
1281///
1282/// # Returns
1283///
1284/// - `bool` - Whether the link should open in a new tab.
1285fn is_external_url(href: &str) -> bool {
1286    starts_with_ascii_ignore_case(href, SCHEME_HTTP)
1287        || starts_with_ascii_ignore_case(href, SCHEME_HTTPS)
1288}
1289
1290/// Builds a standard XML sitemap containing every generated page route in canonical order.
1291///
1292/// # Arguments
1293///
1294/// - `&[&DocPage]` - Ordered site pages.
1295/// - `&str` - Optional base URL prefix.
1296///
1297/// # Returns
1298///
1299/// - `String` - Complete `sitemap.xml` document.
1300fn build_sitemap_xml(pages: &[&DocPage], base_url: &str) -> String {
1301    let base: &str = base_url.trim_end_matches('/');
1302    let mut xml: String = String::with_capacity(SITEMAP_HEADER.len() + pages.len() * 64 + 16);
1303    xml.push_str(SITEMAP_HEADER);
1304    for page in pages.iter() {
1305        let loc: String = href_for_route(base, page.get_route());
1306        xml.push_str(SITEMAP_URL_OPEN);
1307        push_escaped_html(&mut xml, &loc);
1308        xml.push_str(SITEMAP_URL_CLOSE);
1309    }
1310    xml.push_str(SITEMAP_FOOTER);
1311    xml
1312}
1313
1314/// Copies recognized static asset directories and co-located media assets into `out_dir`.
1315///
1316/// # Arguments
1317///
1318/// - `&Path` - Source project or docs root directory.
1319/// - `&Path` - Output site directory.
1320///
1321/// # Returns
1322///
1323/// - `io::Result<()>` - Copy result.
1324fn copy_static_assets(src_root: &Path, out_dir: &Path) -> io::Result<()> {
1325    let canonical_out: PathBuf =
1326        fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
1327    for dir_name in ASSET_COPY_DIRS.iter() {
1328        let candidate: PathBuf = src_root.join(dir_name);
1329        if candidate.is_dir() {
1330            copy_dir_recursive(&candidate, &out_dir.join(dir_name), &canonical_out)?;
1331        }
1332    }
1333    copy_colocated_media(src_root, src_root, out_dir, &canonical_out)
1334}
1335
1336/// Recursively copies non-Markdown static asset files from `src` into `dst`.
1337///
1338/// # Arguments
1339///
1340/// - `&Path` - Source directory.
1341/// - `&Path` - Destination directory.
1342/// - `&Path` - Canonical output root skipped to avoid self-recursion.
1343///
1344/// # Returns
1345///
1346/// - `io::Result<()>` - Copy result.
1347fn copy_dir_recursive(src: &Path, dst: &Path, canonical_out: &Path) -> io::Result<()> {
1348    let src_canon: PathBuf = fs::canonicalize(src).unwrap_or_else(|_| src.to_path_buf());
1349    if src_canon == canonical_out || src_canon.starts_with(canonical_out) {
1350        return Ok(());
1351    }
1352    fs::create_dir_all(dst)?;
1353    for entry_res in fs::read_dir(src)? {
1354        let entry: DirEntry = entry_res?;
1355        let path: PathBuf = entry.path();
1356        let target: PathBuf = dst.join(entry.file_name());
1357        if path.is_dir() {
1358            copy_dir_recursive(&path, &target, canonical_out)?;
1359        } else if path
1360            .extension()
1361            .and_then(|s: &OsStr| s.to_str())
1362            .is_none_or(|ext: &str| !ext.eq_ignore_ascii_case(MARKDOWN_EXT_CHECK))
1363        {
1364            let _: u64 = fs::copy(&path, &target)?;
1365        }
1366    }
1367    Ok(())
1368}
1369
1370/// Recursively copies co-located media files alongside Markdown documents while skipping ignored dirs and `out_dir`.
1371///
1372/// # Arguments
1373///
1374/// - `&Path` - Original source root directory.
1375/// - `&Path` - Current directory being walked.
1376/// - `&Path` - Output site directory.
1377/// - `&Path` - Canonical output root skipped to avoid self-recursion.
1378///
1379/// # Returns
1380///
1381/// - `io::Result<()>` - Copy result.
1382fn copy_colocated_media(
1383    src_root: &Path,
1384    cur_dir: &Path,
1385    out_dir: &Path,
1386    canonical_out: &Path,
1387) -> io::Result<()> {
1388    for entry_res in fs::read_dir(cur_dir)? {
1389        let entry: DirEntry = entry_res?;
1390        let path: PathBuf = entry.path();
1391        if path.is_dir() {
1392            let name: String = entry.file_name().to_string_lossy().into_owned();
1393            if should_skip_dir(&name) {
1394                continue;
1395            }
1396            if cur_dir == src_root
1397                && ASSET_COPY_DIRS
1398                    .iter()
1399                    .any(|d: &&str| name.eq_ignore_ascii_case(d))
1400            {
1401                continue;
1402            }
1403            let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
1404            if canon == canonical_out || canon.starts_with(canonical_out) {
1405                continue;
1406            }
1407            copy_colocated_media(src_root, &path, out_dir, canonical_out)?;
1408        } else if path
1409            .extension()
1410            .and_then(|s: &OsStr| s.to_str())
1411            .is_some_and(|ext: &str| {
1412                CO_LOCATED_ASSET_EXTS
1413                    .iter()
1414                    .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
1415            })
1416            && let Ok(rel) = path.strip_prefix(src_root)
1417        {
1418            let target: PathBuf = out_dir.join(rel);
1419            if let Some(parent) = target.parent() {
1420                fs::create_dir_all(parent)?;
1421            }
1422            let _: u64 = fs::copy(&path, &target)?;
1423        }
1424    }
1425    Ok(())
1426}
1427
1428/// Formats a clean link href for `route` under `base`.
1429///
1430/// # Arguments
1431///
1432/// - `&str` - Normalized base URL without trailing slash.
1433/// - `&str` - Canonical route path.
1434///
1435/// # Returns
1436///
1437/// - `String` - Clean navigable href string.
1438fn href_for_route(base: &str, route: &str) -> String {
1439    let trimmed: &str = route.trim_matches('/');
1440    if trimmed.is_empty() {
1441        if base.is_empty() {
1442            ROOT_ROUTE_STR.to_string()
1443        } else {
1444            format!("{base}/")
1445        }
1446    } else if base.is_empty() {
1447        format!("/{trimmed}/")
1448    } else {
1449        format!("{base}/{trimmed}/")
1450    }
1451}
1452
1453/// Computes the filesystem output `.html` path for a canonical documentation route.
1454///
1455/// # Arguments
1456///
1457/// - `&Path` - Output root directory.
1458/// - `&str` - Canonical route path.
1459///
1460/// # Returns
1461///
1462/// - `PathBuf` - Destination `.html` file path.
1463fn html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1464    let trimmed: &str = route.trim_matches('/');
1465    if trimmed.is_empty() {
1466        out_dir.join(INDEX_HTML_NAME)
1467    } else {
1468        out_dir.join(format!("{trimmed}{HTML_EXT}"))
1469    }
1470}
1471
1472/// Computes the clean directory-index `<route>/index.html` path for a canonical route.
1473///
1474/// # Arguments
1475///
1476/// - `&Path` - Output root directory.
1477/// - `&str` - Canonical route path.
1478///
1479/// # Returns
1480///
1481/// - `PathBuf` - Destination `<route>/index.html` path.
1482fn clean_html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1483    let trimmed: &str = route.trim_matches('/');
1484    if trimmed.is_empty() {
1485        out_dir.join(INDEX_HTML_NAME)
1486    } else {
1487        out_dir.join(trimmed).join(INDEX_HTML_NAME)
1488    }
1489}
1490
1491/// Renders a fenced code block with line numbers and exact VS Code Eva Light/Dark Bold syntax classes.
1492///
1493/// # Arguments
1494///
1495/// - `&str` - Language label from the fenced code info string.
1496/// - `&str` - Trimmed source code body.
1497/// - `&mut String` - HTML output buffer.
1498fn render_highlighted_code_html(language: &str, code: &str, out: &mut String) {
1499    let resolved_lang: CodeLang = CodeLang::from_name(language);
1500    out.push_str(HTML_CODE_WRAP_OPEN);
1501    push_escaped_html(out, language);
1502    out.push_str(HTML_CODE_HEAD_MID);
1503    push_escaped_html(out, language);
1504    out.push_str(HTML_LINK_MID);
1505    for (idx, line) in code.split('\n').enumerate() {
1506        out.push_str(HTML_CODE_LINE_OPEN);
1507        let _: fmt::Result = write!(out, "{}", idx + 1);
1508        out.push_str(HTML_CODE_LINE_MID);
1509        let spans: Vec<CodeSpan> = tokenize_code_line_with_lang(line, resolved_lang);
1510        for span in spans.iter() {
1511            let class_opt: Option<&str> = match span.get_kind() {
1512                CodeTokenKind::Keyword => Some(TOK_CLASS_KW),
1513                CodeTokenKind::Control => Some(TOK_CLASS_CTRL),
1514                CodeTokenKind::Operator => Some(TOK_CLASS_OP),
1515                CodeTokenKind::Function => Some(TOK_CLASS_FN),
1516                CodeTokenKind::Type => Some(TOK_CLASS_TY),
1517                CodeTokenKind::PrimitiveType => Some(TOK_CLASS_PRIM),
1518                CodeTokenKind::String => Some(TOK_CLASS_STR),
1519                CodeTokenKind::Number => Some(TOK_CLASS_NUM),
1520                CodeTokenKind::Comment => Some(TOK_CLASS_CMT),
1521                CodeTokenKind::Macro => Some(TOK_CLASS_MAC),
1522                CodeTokenKind::Property => Some(TOK_CLASS_PROP),
1523                CodeTokenKind::Constant => Some(TOK_CLASS_CONST),
1524                CodeTokenKind::Punctuation => Some(TOK_CLASS_PUNC),
1525                CodeTokenKind::DiffAdd => Some(TOK_CLASS_ADD),
1526                CodeTokenKind::DiffDel => Some(TOK_CLASS_DEL),
1527                CodeTokenKind::Plain => None,
1528            };
1529            if let Some(cls) = class_opt {
1530                out.push_str(HTML_SPAN_CLASS_OPEN);
1531                out.push_str(cls);
1532                out.push_str(HTML_LINK_MID);
1533                push_escaped_html(out, span.get_text());
1534                out.push_str(HTML_SPAN_CLOSE);
1535            } else {
1536                push_escaped_html(out, span.get_text());
1537            }
1538        }
1539        out.push_str(HTML_CODE_LINE_CLOSE);
1540    }
1541    out.push_str(HTML_CODE_CLOSE);
1542}
1543
1544/// Appends HTML-escaped text directly into `out` via bulk slice copies with zero intermediate allocations.
1545///
1546/// # Arguments
1547///
1548/// - `&mut String` - Destination HTML buffer.
1549/// - `&str` - Raw UTF-8 input slice.
1550fn push_escaped_html(out: &mut String, input: &str) {
1551    let bytes: &[u8] = input.as_bytes();
1552    let mut start: usize = 0;
1553    for (idx, &byte) in bytes.iter().enumerate() {
1554        let esc: &str = match byte {
1555            b'&' => HTML_ESC_AMP,
1556            b'<' => HTML_ESC_LT,
1557            b'>' => HTML_ESC_GT,
1558            b'"' => HTML_ESC_QUOT,
1559            _ => continue,
1560        };
1561        if start < idx {
1562            out.push_str(&input[start..idx]);
1563        }
1564        out.push_str(esc);
1565        start = idx + 1;
1566    }
1567    if start < bytes.len() {
1568        out.push_str(&input[start..]);
1569    }
1570}
1571
1572/// Escapes special HTML characters in text content.
1573///
1574/// # Arguments
1575///
1576/// - `&str` - Raw UTF-8 text.
1577///
1578/// # Returns
1579///
1580/// - `String` - Escaped HTML-safe string.
1581fn escape_html(input: &str) -> String {
1582    let mut out: String = String::with_capacity(input.len());
1583    push_escaped_html(&mut out, input);
1584    out
1585}
1586
1587/// Pushes a single HTML-escaped character into `out`.
1588///
1589/// # Arguments
1590///
1591/// - `char` - Source UTF-8 character.
1592/// - `&mut String` - Destination HTML buffer.
1593fn push_escaped_html_char(ch: char, out: &mut String) {
1594    match ch {
1595        '&' => out.push_str(HTML_ESC_AMP),
1596        '<' => out.push_str(HTML_ESC_LT),
1597        '>' => out.push_str(HTML_ESC_GT),
1598        '"' => out.push_str(HTML_ESC_QUOT),
1599        _ => out.push(ch),
1600    }
1601}
1602
1603/// Returns `true` when `bytes` contains any extended inline Markdown delimiter (`=`, `^`, `~`, `:`).
1604///
1605/// # Arguments
1606///
1607/// - `&[u8]` - Raw UTF-8 input bytes.
1608///
1609/// # Returns
1610///
1611/// - `bool` - `true` when extended inline parsing is required.
1612fn has_extended_inline_trigger(bytes: &[u8]) -> bool {
1613    for &byte in bytes.iter() {
1614        if byte == b'=' || byte == b'^' || byte == b'~' || byte == b':' {
1615            return true;
1616        }
1617    }
1618    false
1619}
1620
1621/// Renders extended inline Markdown syntax (`==mark==`, `^sup^`, `~sub~`, `:emoji:`) into XSS-safe HTML.
1622///
1623/// # Arguments
1624///
1625/// - `&str` - Raw inline Markdown text slice.
1626/// - `&mut String` - Destination HTML buffer.
1627fn render_extended_inline_text_html(raw: &str, out: &mut String) {
1628    let bytes: &[u8] = raw.as_bytes();
1629    if !has_extended_inline_trigger(bytes) {
1630        push_escaped_html(out, raw);
1631        return;
1632    }
1633    let len: usize = bytes.len();
1634    let mut i: usize = 0;
1635    while i < len {
1636        if i + 1 < len && bytes[i] == b'=' && bytes[i + 1] == b'=' {
1637            let rest: &str = &raw[i + 2..];
1638            if let Some(close_rel) = rest.find("==")
1639                && !rest[..close_rel].trim().is_empty()
1640            {
1641                out.push_str(HTML_MARK_OPEN);
1642                render_extended_inline_text_html(&rest[..close_rel], out);
1643                out.push_str(HTML_MARK_CLOSE);
1644                i += 2 + close_rel + 2;
1645                continue;
1646            }
1647        }
1648        if bytes[i] == b'^' {
1649            let rest: &str = &raw[i + 1..];
1650            if let Some(close_rel) = rest.find('^') {
1651                let inner: &str = &rest[..close_rel];
1652                if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
1653                    out.push_str(HTML_SUP_OPEN);
1654                    push_escaped_html(out, inner);
1655                    out.push_str(HTML_SUP_CLOSE);
1656                    i += 1 + close_rel + 1;
1657                    continue;
1658                }
1659            }
1660        }
1661        if bytes[i] == b'~' && !(i + 1 < len && bytes[i + 1] == b'~') {
1662            let rest: &str = &raw[i + 1..];
1663            if let Some(close_rel) = rest.find('~') {
1664                let inner: &str = &rest[..close_rel];
1665                if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
1666                    out.push_str(HTML_SUB_OPEN);
1667                    push_escaped_html(out, inner);
1668                    out.push_str(HTML_SUB_CLOSE);
1669                    i += 1 + close_rel + 1;
1670                    continue;
1671                }
1672            }
1673        }
1674        if bytes[i] == b':' {
1675            let rest: &str = &raw[i + 1..];
1676            if let Some(close_rel) = rest.find(':') {
1677                let code: &str = &rest[..close_rel];
1678                if !code.is_empty()
1679                    && code.len() <= 32
1680                    && code
1681                        .bytes()
1682                        .all(|b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
1683                    && let Some(emoji) = resolve_emoji_shortcode(code)
1684                {
1685                    out.push_str(emoji);
1686                    i += 1 + close_rel + 1;
1687                    continue;
1688                }
1689            }
1690        }
1691        if let Some(ch) = raw[i..].chars().next() {
1692            push_escaped_html_char(ch, out);
1693            i += ch.len_utf8();
1694        } else {
1695            break;
1696        }
1697    }
1698}
1699
1700/// Renders a fenced Mermaid diagram block into a zero-JS themed inline SVG card.
1701///
1702/// # Arguments
1703///
1704/// - `&str` - Raw Mermaid diagram source text.
1705/// - `&mut String` - Destination HTML output buffer.
1706fn render_mermaid_svg_html(source: &str, out: &mut String) {
1707    let diagram: MermaidDiagram = parse_mermaid_diagram(source);
1708    let badge: &str = match &diagram {
1709        MermaidDiagram::Flowchart(_) => MERMAID_BADGE_FLOWCHART,
1710        MermaidDiagram::Sequence(_) => MERMAID_BADGE_SEQUENCE,
1711        MermaidDiagram::State(_) => MERMAID_BADGE_STATE,
1712        MermaidDiagram::Class(_) => MERMAID_BADGE_CLASS,
1713        MermaidDiagram::Er(_) => MERMAID_BADGE_ER,
1714        MermaidDiagram::Pie(_) => MERMAID_BADGE_PIE,
1715        MermaidDiagram::Gantt(_) => MERMAID_BADGE_GANTT,
1716    };
1717    out.push_str(MERMAID_CARD_OPEN);
1718    out.push_str(badge);
1719    out.push_str(MERMAID_CARD_MID);
1720    match &diagram {
1721        MermaidDiagram::Flowchart(fc) | MermaidDiagram::State(fc) => {
1722            render_mermaid_flow_svg(fc, out);
1723        }
1724        MermaidDiagram::Sequence(seq) => {
1725            render_mermaid_sequence_svg(seq, out);
1726        }
1727        MermaidDiagram::Class(cls) => {
1728            render_mermaid_class_svg(cls, out);
1729        }
1730        MermaidDiagram::Er(er) => {
1731            render_mermaid_er_svg(er, out);
1732        }
1733        MermaidDiagram::Pie(pie) => {
1734            render_mermaid_pie_svg(pie, out);
1735        }
1736        MermaidDiagram::Gantt(gantt) => {
1737            render_mermaid_gantt_svg(gantt, out);
1738        }
1739    }
1740    out.push_str(MERMAID_CARD_CLOSE);
1741}
1742
1743/// Runs 3-color DFS from `u` to collect acyclic forward edges for static Mermaid SVG layout.
1744///
1745/// # Arguments
1746///
1747/// - `usize` - Current node index.
1748/// - `&[Vec<usize>]` - Directed adjacency lists.
1749/// - `&mut [u8]` - Visitation state (`0` unvisited, `1` active stack, `2` done).
1750/// - `&mut Vec<(usize, usize)>` - Collected DAG edges.
1751fn dfs_svg_dag_edges(
1752    u: usize,
1753    adj: &[Vec<usize>],
1754    state: &mut [u8],
1755    dag_edges: &mut Vec<(usize, usize)>,
1756) {
1757    state[u] = 1;
1758    for &v in adj[u].iter() {
1759        if u == v || state[v] == 1 {
1760            continue;
1761        }
1762        dag_edges.push((u, v));
1763        if state[v] == 0 {
1764            dfs_svg_dag_edges(v, adj, state, dag_edges);
1765        }
1766    }
1767    state[u] = 2;
1768}
1769
1770/// Renders a Mermaid flowchart or state machine AST as a themed inline SVG.
1771///
1772/// # Arguments
1773///
1774/// - `&MermaidFlowchart` - Parsed flowchart or state graph.
1775/// - `&mut String` - Destination HTML/SVG buffer.
1776fn render_mermaid_flow_svg(fc: &MermaidFlowchart, out: &mut String) {
1777    let n: usize = fc.get_nodes().len();
1778    if n == 0 {
1779        return;
1780    }
1781    let mut id_map: HashMap<&str, usize> = HashMap::with_capacity(n);
1782    for (idx, node) in fc.get_nodes().iter().enumerate() {
1783        let _: Option<usize> = id_map.insert(node.get_id().as_str(), idx);
1784    }
1785    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
1786    let mut in_deg: Vec<usize> = vec![0; n];
1787    for edge in fc.get_edges().iter() {
1788        if let (Some(&u), Some(&v)) = (
1789            id_map.get(edge.get_from().as_str()),
1790            id_map.get(edge.get_to().as_str()),
1791        ) && u != v
1792        {
1793            adj[u].push(v);
1794            in_deg[v] += 1;
1795        }
1796    }
1797    let mut visit_state: Vec<u8> = vec![0; n];
1798    let mut dag_edges: Vec<(usize, usize)> = Vec::with_capacity(fc.get_edges().len());
1799    for (idx, node) in fc.get_nodes().iter().enumerate() {
1800        if node.get_shape() == MermaidNodeShape::StateStart && visit_state[idx] == 0 {
1801            dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
1802        }
1803    }
1804    for (idx, node) in fc.get_nodes().iter().enumerate() {
1805        if in_deg[idx] == 0
1806            && node.get_shape() != MermaidNodeShape::StateEnd
1807            && visit_state[idx] == 0
1808        {
1809            dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
1810        }
1811    }
1812    for idx in 0..n {
1813        if visit_state[idx] == 0 {
1814            dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
1815        }
1816    }
1817    let mut layers: Vec<usize> = vec![0; n];
1818    for _ in 0..n {
1819        let mut changed: bool = false;
1820        for &(u, v) in dag_edges.iter() {
1821            if layers[v] <= layers[u] && layers[u] + 1 < n {
1822                layers[v] = layers[u] + 1;
1823                changed = true;
1824            }
1825        }
1826        if !changed {
1827            break;
1828        }
1829    }
1830    for edge in fc.get_edges().iter() {
1831        if let (Some(&u), Some(&v)) = (
1832            id_map.get(edge.get_from().as_str()),
1833            id_map.get(edge.get_to().as_str()),
1834        ) && u != v
1835            && fc.get_nodes()[v].get_shape() == MermaidNodeShape::StateEnd
1836            && layers[v] <= layers[u]
1837        {
1838            layers[v] = layers[u] + 1;
1839        }
1840    }
1841    let max_layer: usize = layers.iter().copied().max().unwrap_or(0);
1842    let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); max_layer + 1];
1843    for (idx, &lay) in layers.iter().enumerate() {
1844        buckets[lay].push(idx);
1845    }
1846    let horiz: bool = matches!(
1847        fc.get_direction(),
1848        MermaidFlowDirection::LeftRight | MermaidFlowDirection::RightLeft
1849    );
1850    let reversed: bool = matches!(
1851        fc.get_direction(),
1852        MermaidFlowDirection::RightLeft | MermaidFlowDirection::BottomTop
1853    );
1854    let node_sizes: Vec<(f32, f32)> = fc
1855        .get_nodes()
1856        .iter()
1857        .map(|node: &MermaidFlowNode| match node.get_shape() {
1858            MermaidNodeShape::StateStart | MermaidNodeShape::StateEnd => (24.0, 24.0),
1859            MermaidNodeShape::Circle => {
1860                let d: f32 =
1861                    ((node.get_label().chars().count() as f32) * 7.6 + 26.0).clamp(52.0, 96.0);
1862                (d, d)
1863            }
1864            MermaidNodeShape::Diamond => {
1865                let w: f32 =
1866                    ((node.get_label().chars().count() as f32) * 8.0 + 46.0).clamp(108.0, 196.0);
1867                (w, 58.0)
1868            }
1869            _ => {
1870                let w: f32 =
1871                    ((node.get_label().chars().count() as f32) * 7.6 + 34.0).clamp(96.0, 210.0);
1872                (w, 40.0)
1873            }
1874        })
1875        .collect();
1876    let pad: f32 = 28.0;
1877    let main_gap: f32 = if horiz { 54.0 } else { 44.0 };
1878    let cross_gap: f32 = 24.0;
1879    let layer_count: usize = buckets.len();
1880    let mut layer_main: Vec<f32> = vec![0.0; layer_count];
1881    let mut layer_cross: Vec<f32> = vec![0.0; layer_count];
1882    for (li, items) in buckets.iter().enumerate() {
1883        let mut max_m: f32 = 0.0;
1884        let mut sum_c: f32 = 0.0;
1885        for (pos, &ni) in items.iter().enumerate() {
1886            let (nw, nh): (f32, f32) = node_sizes[ni];
1887            if horiz {
1888                max_m = max_m.max(nw);
1889                sum_c += nh;
1890            } else {
1891                max_m = max_m.max(nh);
1892                sum_c += nw;
1893            }
1894            if pos + 1 < items.len() {
1895                sum_c += cross_gap;
1896            }
1897        }
1898        layer_main[li] = max_m;
1899        layer_cross[li] = sum_c;
1900    }
1901    let total_main: f32 =
1902        layer_main.iter().sum::<f32>() + (layer_count.saturating_sub(1) as f32) * main_gap;
1903    let total_cross: f32 = layer_cross.iter().copied().fold(0.0_f32, f32::max);
1904    let mut rects: Vec<(f32, f32, f32, f32)> = vec![(0.0, 0.0, 0.0, 0.0); n];
1905    let mut main_cur: f32 = pad;
1906    let order: Vec<usize> = if reversed {
1907        (0..layer_count).rev().collect()
1908    } else {
1909        (0..layer_count).collect()
1910    };
1911    for li in order.into_iter() {
1912        let items: &[usize] = &buckets[li];
1913        let band_m: f32 = layer_main[li];
1914        let band_c: f32 = layer_cross[li];
1915        let mut cross_cur: f32 = pad + (total_cross - band_c) * 0.5;
1916        for &ni in items.iter() {
1917            let (nw, nh): (f32, f32) = node_sizes[ni];
1918            if horiz {
1919                rects[ni] = (main_cur + (band_m - nw) * 0.5, cross_cur, nw, nh);
1920                cross_cur += nh + cross_gap;
1921            } else {
1922                rects[ni] = (cross_cur, main_cur + (band_m - nh) * 0.5, nw, nh);
1923                cross_cur += nw + cross_gap;
1924            }
1925        }
1926        main_cur += band_m + main_gap;
1927    }
1928    let (svg_w, svg_h): (f32, f32) = if horiz {
1929        (
1930            (total_main + pad * 2.0).max(360.0),
1931            (total_cross + pad * 2.0).max(140.0),
1932        )
1933    } else {
1934        (
1935            (total_cross + pad * 2.0).max(360.0),
1936            (total_main + pad * 2.0).max(140.0),
1937        )
1938    };
1939    let _: fmt::Result = write!(
1940        out,
1941        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {svg_w:.1} {svg_h:.1}\" width=\"{svg_w:.0}\" height=\"{svg_h:.0}\" role=\"img\" aria-label=\"Mermaid diagram\">"
1942    );
1943    out.push_str(MERMAID_SVG_ARROW_MARKER);
1944    for edge in fc.get_edges().iter() {
1945        if let (Some(&u), Some(&v)) = (
1946            id_map.get(edge.get_from().as_str()),
1947            id_map.get(edge.get_to().as_str()),
1948        ) {
1949            let (ux, uy, uw, uh): (f32, f32, f32, f32) = rects[u];
1950            let (vx, vy, vw, vh): (f32, f32, f32, f32) = rects[v];
1951            let (x1, y1, x2, y2): (f32, f32, f32, f32) = if horiz {
1952                let sx: f32 = if vx >= ux { ux + uw } else { ux };
1953                let tx: f32 = if vx >= ux { vx } else { vx + vw };
1954                (sx, uy + uh * 0.5, tx, vy + vh * 0.5)
1955            } else {
1956                let sy: f32 = if vy >= uy { uy + uh } else { uy };
1957                let ty: f32 = if vy >= uy { vy } else { vy + vh };
1958                (ux + uw * 0.5, sy, vx + vw * 0.5, ty)
1959            };
1960            let dash: &str = match edge.get_style() {
1961                MermaidEdgeStyle::Dashed => MERMAID_SVG_DASH_ATTR,
1962                _ => "",
1963            };
1964            let sw: f32 = if edge.get_style() == MermaidEdgeStyle::Thick {
1965                2.6
1966            } else {
1967                1.6
1968            };
1969            let marker: &str = if edge.get_style() == MermaidEdgeStyle::Plain {
1970                ""
1971            } else {
1972                MERMAID_SVG_MARKER_ATTR
1973            };
1974            let _: fmt::Result = write!(
1975                out,
1976                "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"{sw:.1}\"{dash}{marker}/>"
1977            );
1978            let lbl: &str = edge.get_label().trim();
1979            if !lbl.is_empty() {
1980                let mx: f32 = (x1 + x2) * 0.5;
1981                let my: f32 = (y1 + y2) * 0.5;
1982                let bw: f32 = ((lbl.chars().count() as f32) * 6.8 + 12.0).max(28.0);
1983                let bx: f32 = mx - bw * 0.5;
1984                let by: f32 = my - 10.0;
1985                let _: fmt::Result = write!(
1986                    out,
1987                    "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{bw:.1}\" height=\"20\" rx=\"4\" fill=\"var(--muted)\" stroke=\"var(--border)\" stroke-width=\"1\"/><text x=\"{mx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11\" font-weight=\"600\" fill=\"var(--muted-fg)\">",
1988                    my + 4.0
1989                );
1990                push_escaped_html(out, lbl);
1991                out.push_str(SVG_TEXT_CLOSE);
1992            }
1993        }
1994    }
1995    for (idx, node) in fc.get_nodes().iter().enumerate() {
1996        let (rx, ry, rw, rh): (f32, f32, f32, f32) = rects[idx];
1997        let cx: f32 = rx + rw * 0.5;
1998        let cy: f32 = ry + rh * 0.5;
1999        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2000        match node.get_shape() {
2001            MermaidNodeShape::StateStart => {
2002                let _: fmt::Result = write!(
2003                    out,
2004                    "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"9\" fill=\"var(--fg)\"/>"
2005                );
2006            }
2007            MermaidNodeShape::StateEnd => {
2008                let _: fmt::Result = write!(
2009                    out,
2010                    "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"10\" fill=\"none\" stroke=\"var(--fg)\" stroke-width=\"2\"/><circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"5.5\" fill=\"var(--fg)\"/>"
2011                );
2012            }
2013            MermaidNodeShape::Diamond => {
2014                let _: fmt::Result = write!(
2015                    out,
2016                    "<polygon points=\"{cx:.1},{ry:.1} {:.1},{cy:.1} {cx:.1},{:.1} {rx:.1},{cy:.1}\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.8\"/>",
2017                    rx + rw,
2018                    ry + rh
2019                );
2020            }
2021            MermaidNodeShape::Circle => {
2022                let r: f32 = rw.min(rh) * 0.5;
2023                let _: fmt::Result = write!(
2024                    out,
2025                    "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.8\"/>"
2026                );
2027            }
2028            MermaidNodeShape::Stadium => {
2029                let rad: f32 = rh * 0.5;
2030                let _: fmt::Result = write!(
2031                    out,
2032                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"{rad:.1}\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.8\"/>"
2033                );
2034            }
2035            MermaidNodeShape::Rounded => {
2036                let _: fmt::Result = write!(
2037                    out,
2038                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"10\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.8\"/>"
2039                );
2040            }
2041            MermaidNodeShape::Box => {
2042                let _: fmt::Result = write!(
2043                    out,
2044                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"5\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.8\"/>"
2045                );
2046            }
2047        }
2048        let lbl: &str = node.get_label().trim();
2049        if !lbl.is_empty() {
2050            let _: fmt::Result = write!(
2051                out,
2052                "<text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"600\" fill=\"var(--fg)\">",
2053                cy + 4.0
2054            );
2055            push_escaped_html(out, lbl);
2056            out.push_str(SVG_TEXT_CLOSE);
2057        }
2058    }
2059    out.push_str(MERMAID_SVG_CLOSE);
2060}
2061
2062/// Renders a Mermaid `sequenceDiagram` AST as a themed inline SVG.
2063///
2064/// # Arguments
2065///
2066/// - `&MermaidSequence` - Parsed sequence diagram.
2067/// - `&mut String` - Destination HTML/SVG buffer.
2068fn render_mermaid_sequence_svg(seq: &MermaidSequence, out: &mut String) {
2069    let p_count: usize = seq.get_participants().len();
2070    if p_count == 0 {
2071        return;
2072    }
2073    let col_w: f32 = 176.0;
2074    let pad: f32 = 24.0;
2075    let box_w: f32 = 132.0;
2076    let box_h: f32 = 34.0;
2077    let row_h: f32 = 44.0;
2078    let msg_count: usize = seq.get_messages().len();
2079    let svg_w: f32 = ((p_count as f32) * col_w + pad * 2.0).max(380.0);
2080    let top_y: f32 = pad;
2081    let life_top: f32 = top_y + box_h;
2082    let life_bot: f32 = life_top + 22.0 + (msg_count as f32) * row_h + 18.0;
2083    let svg_h: f32 = life_bot + box_h + pad;
2084    let _: fmt::Result = write!(
2085        out,
2086        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {svg_w:.1} {svg_h:.1}\" width=\"{svg_w:.0}\" height=\"{svg_h:.0}\" role=\"img\" aria-label=\"Mermaid sequence diagram\">"
2087    );
2088    out.push_str(MERMAID_SVG_ARROW_MARKER);
2089    let mut centers: Vec<f32> = Vec::with_capacity(p_count);
2090    for (idx, (_, label)) in seq.get_participants().iter().enumerate() {
2091        let cx: f32 = pad + (idx as f32) * col_w + col_w * 0.5;
2092        centers.push(cx);
2093        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2094        let _: fmt::Result = write!(
2095            out,
2096            "<line x1=\"{cx:.1}\" y1=\"{life_top:.1}\" x2=\"{cx:.1}\" y2=\"{life_bot:.1}\" stroke=\"var(--border)\" stroke-width=\"1.4\" stroke-dasharray=\"5 4\"/>"
2097        );
2098        for by in [top_y, life_bot].into_iter() {
2099            let bx: f32 = cx - box_w * 0.5;
2100            let _: fmt::Result = write!(
2101                out,
2102                "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{box_w:.1}\" height=\"{box_h:.1}\" rx=\"7\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.6\"/><text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"600\" fill=\"var(--fg)\">",
2103                by + 21.0
2104            );
2105            push_escaped_html(out, label);
2106            out.push_str(SVG_TEXT_CLOSE);
2107        }
2108    }
2109    for (idx, msg) in seq.get_messages().iter().enumerate() {
2110        let y: f32 = life_top + 28.0 + (idx as f32) * row_h;
2111        let x1: f32 = centers.get(msg.get_from_idx()).copied().unwrap_or(pad);
2112        let x2: f32 = centers.get(msg.get_to_idx()).copied().unwrap_or(pad);
2113        if msg.get_is_note() {
2114            let nx: f32 = x1.min(x2) - 48.0;
2115            let nw: f32 = (x2 - x1).abs().max(96.0) + 96.0;
2116            let _: fmt::Result = write!(
2117                out,
2118                "<rect x=\"{nx:.1}\" y=\"{:.1}\" width=\"{nw:.1}\" height=\"26\" rx=\"5\" fill=\"var(--muted)\" stroke=\"var(--warn)\" stroke-width=\"1.4\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11.5\" fill=\"var(--fg)\">",
2119                y - 13.0,
2120                nx + nw * 0.5,
2121                y + 4.0
2122            );
2123            push_escaped_html(out, msg.get_text());
2124            out.push_str(SVG_TEXT_CLOSE);
2125        } else {
2126            let dash: &str = match msg.get_style() {
2127                MermaidEdgeStyle::Dashed => MERMAID_SVG_DASH_ATTR,
2128                _ => "",
2129            };
2130            let _: fmt::Result = write!(
2131                out,
2132                "<line x1=\"{x1:.1}\" y1=\"{y:.1}\" x2=\"{x2:.1}\" y2=\"{y:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.6\"{dash} marker-end=\"url(#euv-m-arrow)\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11.5\" font-weight=\"500\" fill=\"var(--fg)\">",
2133                (x1 + x2) * 0.5,
2134                y - 7.0
2135            );
2136            push_escaped_html(out, msg.get_text());
2137            out.push_str(SVG_TEXT_CLOSE);
2138        }
2139    }
2140    out.push_str(MERMAID_SVG_CLOSE);
2141}
2142
2143/// Renders a Mermaid `classDiagram` AST as a themed inline SVG.
2144///
2145/// # Arguments
2146///
2147/// - `&MermaidClassDiagram` - Parsed class diagram.
2148/// - `&mut String` - Destination HTML/SVG buffer.
2149fn render_mermaid_class_svg(cls: &MermaidClassDiagram, out: &mut String) {
2150    let count: usize = cls.get_classes().len();
2151    if count == 0 {
2152        return;
2153    }
2154    let pad: f32 = 24.0;
2155    let gap: f32 = 28.0;
2156    let box_w: f32 = 180.0;
2157    let mut max_h: f32 = 64.0;
2158    for c in cls.get_classes().iter() {
2159        let h: f32 = 34.0 + (c.get_members().len() as f32) * 18.0 + 12.0;
2160        max_h = max_h.max(h);
2161    }
2162    let svg_w: f32 = pad * 2.0 + (count as f32) * box_w + (count.saturating_sub(1) as f32) * gap;
2163    let svg_h: f32 = pad * 2.0 + max_h + 24.0;
2164    let _: fmt::Result = write!(
2165        out,
2166        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {svg_w:.1} {svg_h:.1}\" width=\"{svg_w:.0}\" height=\"{svg_h:.0}\" role=\"img\" aria-label=\"Mermaid class diagram\">"
2167    );
2168    out.push_str(MERMAID_SVG_ARROW_MARKER);
2169    let mut pos_map: HashMap<&str, (f32, f32, f32)> = HashMap::with_capacity(count);
2170    for (idx, c) in cls.get_classes().iter().enumerate() {
2171        let x: f32 = pad + (idx as f32) * (box_w + gap);
2172        let h: f32 = 34.0 + (c.get_members().len() as f32) * 18.0 + 12.0;
2173        let _: Option<(f32, f32, f32)> = pos_map.insert(c.get_name().as_str(), (x, pad, h));
2174        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2175        let _: fmt::Result = write!(
2176            out,
2177            "<rect x=\"{x:.1}\" y=\"{pad:.1}\" width=\"{box_w:.1}\" height=\"{h:.1}\" rx=\"7\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.6\"/><line x1=\"{x:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" stroke=\"var(--border)\" stroke-width=\"1\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2178            pad + 30.0,
2179            x + box_w,
2180            pad + 30.0,
2181            x + box_w * 0.5,
2182            pad + 20.0
2183        );
2184        push_escaped_html(out, c.get_name());
2185        out.push_str(SVG_TEXT_CLOSE);
2186        for (mi, mem) in c.get_members().iter().enumerate() {
2187            let _: fmt::Result = write!(
2188                out,
2189                "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" fill=\"var(--muted-fg)\">",
2190                x + 10.0,
2191                pad + 48.0 + (mi as f32) * 18.0
2192            );
2193            push_escaped_html(out, mem);
2194            out.push_str(SVG_TEXT_CLOSE);
2195        }
2196    }
2197    for rel in cls.get_relations().iter() {
2198        if let (Some(&(x1, y1, h1)), Some(&(x2, y2, h2))) = (
2199            pos_map.get(rel.get_from().as_str()),
2200            pos_map.get(rel.get_to().as_str()),
2201        ) {
2202            let sx: f32 = if x2 >= x1 { x1 + box_w } else { x1 };
2203            let tx: f32 = if x2 >= x1 { x2 } else { x2 + box_w };
2204            let _: fmt::Result = write!(
2205                out,
2206                "<line x1=\"{sx:.1}\" y1=\"{:.1}\" x2=\"{tx:.1}\" y2=\"{:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\" marker-end=\"url(#euv-m-arrow)\"/>",
2207                y1 + h1 * 0.5,
2208                y2 + h2 * 0.5
2209            );
2210        }
2211    }
2212    out.push_str(MERMAID_SVG_CLOSE);
2213}
2214
2215/// Renders a Mermaid `erDiagram` AST as a themed inline SVG.
2216///
2217/// # Arguments
2218///
2219/// - `&MermaidErDiagram` - Parsed ER diagram.
2220/// - `&mut String` - Destination HTML/SVG buffer.
2221fn render_mermaid_er_svg(er: &MermaidErDiagram, out: &mut String) {
2222    let count: usize = er.get_entities().len();
2223    if count == 0 {
2224        return;
2225    }
2226    let pad: f32 = 24.0;
2227    let gap: f32 = 52.0;
2228    let box_w: f32 = 160.0;
2229    let mut max_h: f32 = 56.0;
2230    for ent in er.get_entities().iter() {
2231        let h: f32 = 34.0 + (ent.get_attributes().len() as f32) * 18.0 + 10.0;
2232        max_h = max_h.max(h);
2233    }
2234    let svg_w: f32 = pad * 2.0 + (count as f32) * box_w + (count.saturating_sub(1) as f32) * gap;
2235    let svg_h: f32 = pad * 2.0 + max_h + 16.0;
2236    let _: fmt::Result = write!(
2237        out,
2238        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {svg_w:.1} {svg_h:.1}\" width=\"{svg_w:.0}\" height=\"{svg_h:.0}\" role=\"img\" aria-label=\"Mermaid ER diagram\">"
2239    );
2240    let mut pos_map: HashMap<&str, (f32, f32, f32)> = HashMap::with_capacity(count);
2241    for (idx, ent) in er.get_entities().iter().enumerate() {
2242        let x: f32 = pad + (idx as f32) * (box_w + gap);
2243        let h: f32 = 34.0 + (ent.get_attributes().len() as f32) * 18.0 + 10.0;
2244        let _: Option<(f32, f32, f32)> = pos_map.insert(ent.get_name().as_str(), (x, pad, h));
2245        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2246        let _: fmt::Result = write!(
2247            out,
2248            "<rect x=\"{x:.1}\" y=\"{pad:.1}\" width=\"{box_w:.1}\" height=\"{h:.1}\" rx=\"6\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.6\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2249            x + box_w * 0.5,
2250            pad + 21.0
2251        );
2252        push_escaped_html(out, ent.get_name());
2253        out.push_str(SVG_TEXT_CLOSE);
2254        for (ai, attr) in ent.get_attributes().iter().enumerate() {
2255            let _: fmt::Result = write!(
2256                out,
2257                "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" fill=\"var(--muted-fg)\">",
2258                x + 10.0,
2259                pad + 44.0 + (ai as f32) * 18.0
2260            );
2261            push_escaped_html(out, attr);
2262            out.push_str(SVG_TEXT_CLOSE);
2263        }
2264    }
2265    for rel in er.get_relations().iter() {
2266        if let (Some(&(x1, y1, h1)), Some(&(x2, y2, h2))) = (
2267            pos_map.get(rel.get_left().as_str()),
2268            pos_map.get(rel.get_right().as_str()),
2269        ) {
2270            let sx: f32 = if x2 >= x1 { x1 + box_w } else { x1 };
2271            let tx: f32 = if x2 >= x1 { x2 } else { x2 + box_w };
2272            let sy: f32 = y1 + h1 * 0.5;
2273            let ty: f32 = y2 + h2 * 0.5;
2274            let _: fmt::Result = write!(
2275                out,
2276                "<line x1=\"{sx:.1}\" y1=\"{sy:.1}\" x2=\"{tx:.1}\" y2=\"{ty:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\"/>"
2277            );
2278            if !rel.get_label().is_empty() {
2279                let _: fmt::Result = write!(
2280                    out,
2281                    "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
2282                    (sx + tx) * 0.5,
2283                    (sy + ty) * 0.5 - 6.0
2284                );
2285                push_escaped_html(out, rel.get_label());
2286                out.push_str(SVG_TEXT_CLOSE);
2287            }
2288        }
2289    }
2290    out.push_str(MERMAID_SVG_CLOSE);
2291}
2292
2293/// Renders a Mermaid `pie` chart AST as a proportional inline SVG pie + legend.
2294///
2295/// # Arguments
2296///
2297/// - `&MermaidPieChart` - Parsed pie chart.
2298/// - `&mut String` - Destination HTML/SVG buffer.
2299fn render_mermaid_pie_svg(pie: &MermaidPieChart, out: &mut String) {
2300    let total: f32 = pie
2301        .get_slices()
2302        .iter()
2303        .map(|s: &MermaidPieSlice| s.get_value())
2304        .sum();
2305    if total <= 0.0 {
2306        return;
2307    }
2308    let has_title: bool = !pie.get_title().is_empty();
2309    let title_off: f32 = if has_title { 28.0 } else { 8.0 };
2310    let r: f32 = 76.0;
2311    let cx: f32 = 112.0;
2312    let cy: f32 = title_off + r + 14.0;
2313    let legend_x: f32 = cx + r + 36.0;
2314    let legend_h: f32 = (pie.get_slices().len() as f32) * 24.0;
2315    let svg_h: f32 = (cy + r + 20.0).max(title_off + legend_h + 36.0);
2316    let svg_w: f32 = 460.0;
2317    let _: fmt::Result = write!(
2318        out,
2319        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {svg_w:.1} {svg_h:.1}\" width=\"{svg_w:.0}\" height=\"{svg_h:.0}\" role=\"img\" aria-label=\"Mermaid pie chart\">"
2320    );
2321    if has_title {
2322        let _: fmt::Result = write!(
2323            out,
2324            "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2325            svg_w * 0.5
2326        );
2327        push_escaped_html(out, pie.get_title());
2328        out.push_str(SVG_TEXT_CLOSE);
2329    }
2330    let mut angle: f32 = -FRAC_PI_2;
2331    let legend_y0: f32 = cy - legend_h * 0.5 + 12.0;
2332    for (idx, slice) in pie.get_slices().iter().enumerate() {
2333        let color: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2334        let frac: f32 = slice.get_value() / total;
2335        let sweep: f32 = frac * TAU;
2336        if pie.get_slices().len() == 1 {
2337            let _: fmt::Result = write!(
2338                out,
2339                "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{color}\"/>"
2340            );
2341        } else {
2342            let x1: f32 = cx + r * angle.cos();
2343            let y1: f32 = cy + r * angle.sin();
2344            let end_a: f32 = angle + sweep;
2345            let x2: f32 = cx + r * end_a.cos();
2346            let y2: f32 = cy + r * end_a.sin();
2347            let large: u8 = if sweep > PI { 1 } else { 0 };
2348            let _: fmt::Result = write!(
2349                out,
2350                "<path d=\"M {cx:.1} {cy:.1} L {x1:.1} {y1:.1} A {r:.1} {r:.1} 0 {large} 1 {x2:.1} {y2:.1} Z\" fill=\"{color}\" stroke=\"var(--card)\" stroke-width=\"1.5\"/>"
2351            );
2352            angle = end_a;
2353        }
2354        let ly: f32 = legend_y0 + (idx as f32) * 24.0;
2355        let pct: f32 = frac * 100.0;
2356        let _: fmt::Result = write!(
2357            out,
2358            "<rect x=\"{legend_x:.1}\" y=\"{:.1}\" width=\"12\" height=\"12\" rx=\"3\" fill=\"{color}\"/><text x=\"{:.1}\" y=\"{ly:.1}\" font-size=\"12\" fill=\"var(--fg)\">",
2359            ly - 10.0,
2360            legend_x + 18.0
2361        );
2362        push_escaped_html(out, slice.get_label());
2363        let _: fmt::Result = write!(out, " ({pct:.0}%)</text>");
2364    }
2365    out.push_str(MERMAID_SVG_CLOSE);
2366}
2367
2368/// Renders a Mermaid `gantt` chart AST as a themed inline SVG timeline.
2369///
2370/// # Arguments
2371///
2372/// - `&MermaidGanttChart` - Parsed Gantt timeline.
2373/// - `&mut String` - Destination HTML/SVG buffer.
2374fn render_mermaid_gantt_svg(gantt: &MermaidGanttChart, out: &mut String) {
2375    let count: usize = gantt.get_tasks().len();
2376    if count == 0 {
2377        return;
2378    }
2379    let has_title: bool = !gantt.get_title().is_empty();
2380    let top: f32 = if has_title { 38.0 } else { 16.0 };
2381    let label_w: f32 = 148.0;
2382    let track_w: f32 = 340.0;
2383    let row_h: f32 = 30.0;
2384    let svg_w: f32 = label_w + track_w + 28.0;
2385    let svg_h: f32 = top + (count as f32) * row_h + 16.0;
2386    let max_end: f32 = gantt
2387        .get_tasks()
2388        .iter()
2389        .map(|t: &MermaidGanttTask| t.get_start_unit() + t.get_duration_unit())
2390        .fold(1.0_f32, f32::max);
2391    let _: fmt::Result = write!(
2392        out,
2393        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {svg_w:.1} {svg_h:.1}\" width=\"{svg_w:.0}\" height=\"{svg_h:.0}\" role=\"img\" aria-label=\"Mermaid Gantt chart\">"
2394    );
2395    if has_title {
2396        let _: fmt::Result = write!(
2397            out,
2398            "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2399            svg_w * 0.5
2400        );
2401        push_escaped_html(out, gantt.get_title());
2402        out.push_str(SVG_TEXT_CLOSE);
2403    }
2404    for (idx, task) in gantt.get_tasks().iter().enumerate() {
2405        let y: f32 = top + (idx as f32) * row_h;
2406        let bx: f32 = label_w + (task.get_start_unit() / max_end) * track_w;
2407        let bw: f32 = ((task.get_duration_unit() / max_end) * track_w).max(16.0);
2408        let fill: &str = match task.get_status() {
2409            MermaidGanttStatus::Done => MERMAID_SVG_VAR_TIP,
2410            MermaidGanttStatus::Active => MERMAID_SVG_VAR_LINK,
2411            MermaidGanttStatus::Critical => MERMAID_SVG_VAR_DANGER,
2412            MermaidGanttStatus::Normal => MERMAID_SVG_VAR_IMPORTANT,
2413        };
2414        let _: fmt::Result = write!(
2415            out,
2416            "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\" font-size=\"11.5\" fill=\"var(--fg)\">",
2417            label_w - 10.0,
2418            y + 15.0
2419        );
2420        push_escaped_html(out, task.get_label());
2421        let _: fmt::Result = write!(
2422            out,
2423            "</text><rect x=\"{bx:.1}\" y=\"{:.1}\" width=\"{bw:.1}\" height=\"18\" rx=\"5\" fill=\"{fill}\"/>",
2424            y + 2.0
2425        );
2426    }
2427    out.push_str(MERMAID_SVG_CLOSE);
2428}