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