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    #[cfg(not(target_arch = "wasm32"))]
64    let generated_at: String = Utc::now().to_rfc3339();
65    #[cfg(target_arch = "wasm32")]
66    let generated_at: String = String::new();
67    let entries: Vec<SearchIndexEntry> = site.search_entries();
68    let search_json_compact: String = match to_string(&entries) {
69        Ok(text) => text.replace(SCRIPT_ESC_CLOSE_FROM, SCRIPT_ESC_CLOSE_TO),
70        Err(err) => return Err(Error::other(err.to_string())),
71    };
72    let ordered_pages: Vec<&DocPage> = ordered_site_pages(site);
73    let base: &str = options.get_base_url().trim_end_matches('/');
74    let sidebar_entries: Vec<SidebarNavEntry<'_>> = build_sidebar_entries(&ordered_pages, base);
75    let site_title_escaped: String = escape_html(site.get_title());
76    let home_href: String = href_for_route(base, ROOT_ROUTE_STR);
77    let home_href_escaped: String = escape_html(&home_href);
78    let generated_at_escaped: String = escape_html(&generated_at);
79    let base_json: String = to_string(base).unwrap_or_else(|_| EMPTY_JSON_STRING.to_string());
80    for (idx, page) in ordered_pages.iter().enumerate() {
81        let prev_page: Option<&DocPage> = if idx > 0 {
82            ordered_pages.get(idx - 1).copied()
83        } else {
84            None
85        };
86        let next_page: Option<&DocPage> = ordered_pages.get(idx + 1).copied();
87        let ctx: PageRenderContext<'_> = PageRenderContext {
88            site,
89            sidebar_entries: sidebar_entries.as_slice(),
90            site_title_escaped: &site_title_escaped,
91            home_href_escaped: &home_href_escaped,
92            generated_at_escaped: &generated_at_escaped,
93            base_json: &base_json,
94            prev_page,
95            next_page,
96            search_json_compact: &search_json_compact,
97            options,
98        };
99        let html: String = render_page_html_with_context(page, &ctx);
100        let rel_file: PathBuf = html_path_for_route(out_dir, page.get_route());
101        if let Some(parent) = rel_file.parent() {
102            fs::create_dir_all(parent)?;
103        }
104        fs::write(&rel_file, &html)?;
105        if options.get_clean_urls() && page.get_route() != ROOT_ROUTE_STR {
106            let clean_file: PathBuf = clean_html_path_for_route(out_dir, page.get_route());
107            if let Some(parent) = clean_file.parent() {
108                fs::create_dir_all(parent)?;
109            }
110            fs::write(&clean_file, &html)?;
111        }
112    }
113    if let Some(first_page) = ordered_pages.first().copied()
114        && !out_dir.join(INDEX_HTML_NAME).exists()
115    {
116        let fallback_ctx: PageRenderContext<'_> = PageRenderContext {
117            site,
118            sidebar_entries: sidebar_entries.as_slice(),
119            site_title_escaped: &site_title_escaped,
120            home_href_escaped: &home_href_escaped,
121            generated_at_escaped: &generated_at_escaped,
122            base_json: &base_json,
123            prev_page: None,
124            next_page: ordered_pages.get(1).copied(),
125            search_json_compact: &search_json_compact,
126            options,
127        };
128        let fallback_html: String = render_page_html_with_context(first_page, &fallback_ctx);
129        fs::write(out_dir.join(INDEX_HTML_NAME), fallback_html)?;
130    }
131    let index_path: PathBuf = out_dir.join(INDEX_JSON_NAME);
132    let json: String = match to_string_pretty(&entries) {
133        Ok(text) => text,
134        Err(err) => return Err(Error::other(err.to_string())),
135    };
136    fs::write(&index_path, json)?;
137    let sitemap_xml: String = build_sitemap_xml(&ordered_pages, options.get_base_url());
138    fs::write(out_dir.join(SITEMAP_XML_NAME), sitemap_xml)?;
139    if let Some(assets_root) = options.try_get_assets_root() {
140        copy_static_assets(assets_root, out_dir)?;
141    }
142    Ok(GeneratedSiteReport::new(
143        site.get_pages().len(),
144        generated_at,
145        index_path.display().to_string(),
146    ))
147}
148
149/// Renders a single `DocPage` into a self-contained static HTML document using default build options.
150///
151/// # Arguments
152///
153/// - `&DocSite` - Parent site for navigation links.
154/// - `&DocPage` - Page to render.
155/// - `&str` - Build timestamp string.
156///
157/// # Returns
158///
159/// - `String` - Complete HTML document string.
160#[must_use]
161pub fn render_page_html(site: &DocSite, page: &DocPage, generated_at: &str) -> String {
162    let entries: Vec<SearchIndexEntry> = site.search_entries();
163    let compact: String = to_string(&entries)
164        .unwrap_or_else(|_| EMPTY_JSON_ARRAY.to_string())
165        .replace(SCRIPT_ESC_CLOSE_FROM, SCRIPT_ESC_CLOSE_TO);
166    let opts: DocsBuildOptions = DocsBuildOptions::default();
167    let base: &str = opts.get_base_url().trim_end_matches('/');
168    let ordered_pages: Vec<&DocPage> = ordered_site_pages(site);
169    let sidebar_entries: Vec<SidebarNavEntry<'_>> = build_sidebar_entries(&ordered_pages, base);
170    let site_title_escaped: String = escape_html(site.get_title());
171    let home_href: String = href_for_route(base, ROOT_ROUTE_STR);
172    let home_href_escaped: String = escape_html(&home_href);
173    let generated_at_escaped: String = escape_html(generated_at);
174    let base_json: String = to_string(base).unwrap_or_else(|_| EMPTY_JSON_STRING.to_string());
175    let ctx: PageRenderContext<'_> = PageRenderContext {
176        site,
177        sidebar_entries: sidebar_entries.as_slice(),
178        site_title_escaped: &site_title_escaped,
179        home_href_escaped: &home_href_escaped,
180        generated_at_escaped: &generated_at_escaped,
181        base_json: &base_json,
182        prev_page: None,
183        next_page: None,
184        search_json_compact: &compact,
185        options: &opts,
186    };
187    render_page_html_with_context(page, &ctx)
188}
189
190/// Precomputes sorted, pre-escaped sidebar navigation entries shared across every rendered page.
191///
192/// # Arguments
193///
194/// - `&[&'a DocPage]` - Site pages already sorted in canonical sidebar order.
195/// - `&str` - Normalized base URL without trailing slash.
196///
197/// # Returns
198///
199/// - `Vec<SidebarNavEntry<'a>>` - Pre-escaped sidebar entries ready for direct HTML emission.
200fn build_sidebar_entries<'a>(ordered: &[&'a DocPage], base: &str) -> Vec<SidebarNavEntry<'a>> {
201    let mut entries: Vec<SidebarNavEntry<'a>> = Vec::with_capacity(ordered.len());
202    let mut current_section: Option<&str> = None;
203    for &nav_page in ordered.iter() {
204        let sec: &str = nav_page.get_section().as_str();
205        let section_header_html: Option<String> = if current_section != Some(sec) {
206            current_section = Some(sec);
207            let mut sec_buf: String =
208                String::with_capacity(HTML_SEC_OPEN.len() + sec.len() + HTML_SEC_CLOSE.len());
209            sec_buf.push_str(HTML_SEC_OPEN);
210            push_escaped_html(&mut sec_buf, sec);
211            sec_buf.push_str(HTML_SEC_CLOSE);
212            Some(sec_buf)
213        } else {
214            None
215        };
216        let href: String = href_for_route(base, nav_page.get_route());
217        let title: &str = nav_page.get_title().as_str();
218        let mut tail: String = String::with_capacity(
219            href.len() + HTML_LINK_MID.len() + title.len() + HTML_LINK_CLOSE.len(),
220        );
221        push_escaped_html(&mut tail, &href);
222        tail.push_str(HTML_LINK_MID);
223        push_escaped_html(&mut tail, title);
224        tail.push_str(HTML_LINK_CLOSE);
225        entries.push(SidebarNavEntry {
226            route: nav_page.get_route().as_str(),
227            section_header_html,
228            link_tail_html: tail,
229        });
230    }
231    entries
232}
233
234/// Returns all site pages in canonical sidebar and pagination order.
235///
236/// # Arguments
237///
238/// - `&DocSite` - Loaded documentation site.
239///
240/// # Returns
241///
242/// - `Vec<&DocPage>` - Pages ordered by section rank, section label, page order, and route.
243fn ordered_site_pages(site: &DocSite) -> Vec<&DocPage> {
244    let mut ordered: Vec<&DocPage> = site.get_pages().iter().collect();
245    ordered.sort_by(|a: &&DocPage, b: &&DocPage| {
246        section_sort_rank(a.get_section())
247            .cmp(&section_sort_rank(b.get_section()))
248            .then_with(|| a.get_section().cmp(b.get_section()))
249            .then_with(|| a.get_order().cmp(&b.get_order()))
250            .then_with(|| a.get_route().cmp(b.get_route()))
251    });
252    ordered
253}
254
255/// Renders a full styled HTML page with sidebar sections, TOC, live search index, pagination, and optional HMR.
256///
257/// # Arguments
258///
259/// - `&DocPage` - Active page being rendered.
260/// - `&PageRenderContext<'_>` - Shared site, pagination, timestamp, search index, and build options context.
261///
262/// # Returns
263///
264/// - `String` - Complete HTML document string.
265fn render_page_html_with_context(page: &DocPage, ctx: &PageRenderContext<'_>) -> String {
266    let site: &DocSite = ctx.get_site();
267    let options: &DocsBuildOptions = ctx.get_options();
268    let base: &str = options.get_base_url().trim_end_matches('/');
269    let has_toc: bool = !page.get_toc().is_empty();
270    let brand_char: char = brand_monogram(site.get_title());
271    let mut out: String = String::with_capacity(
272        16384 + ctx.get_search_json_compact().len() + page.get_markdown_body().len() * 2,
273    );
274    out.push_str(HTML_DOCTYPE);
275    push_escaped_html(&mut out, page.get_title());
276    out.push_str(HTML_TITLE_SEP);
277    out.push_str(ctx.get_site_title_escaped());
278    out.push_str(HTML_STYLES_AND_HEAD_END);
279    out.push_str(HTML_TOPBAR_START);
280    out.push_str(ctx.get_home_href_escaped());
281    if starts_with_ascii_ignore_case(site.get_title().trim(), BRAND_PREFIX_EUV) {
282        out.push_str(HTML_TOPBAR_LOGO_IMG);
283    } else {
284        out.push_str(HTML_TOPBAR_MARK_OPEN);
285        out.push(brand_char);
286        out.push_str(HTML_TOPBAR_MARK_CLOSE);
287    }
288    out.push_str(ctx.get_site_title_escaped());
289    out.push_str(HTML_TOPBAR_END);
290    if has_toc {
291        out.push_str(HTML_SHELL_OPEN);
292    } else {
293        out.push_str(HTML_SHELL_NO_TOC_OPEN);
294    }
295    out.push_str(HTML_SIDEBAR_OPEN);
296    render_sidebar_nav(ctx.get_sidebar_entries(), page.get_route(), &mut out);
297    out.push_str(HTML_SIDEBAR_CLOSE);
298    out.push_str(HTML_BADGE_OPEN);
299    push_escaped_html(&mut out, page.get_section());
300    out.push_str(HTML_BADGE_CLOSE);
301    push_escaped_html(&mut out, page.get_title());
302    out.push_str(HTML_H1_CLOSE);
303    if should_render_lead(page) {
304        out.push_str(HTML_LEAD_OPEN);
305        push_escaped_html(&mut out, page.get_summary());
306        out.push_str(HTML_P_CLOSE);
307    }
308    if !page.get_markdown_body().is_empty() {
309        render_markdown_body_html(page, base, &mut out);
310    } else {
311        render_fallback_blocks_html(page, &mut out);
312    }
313    render_pager_nav(ctx.get_prev_page(), ctx.get_next_page(), base, &mut out);
314    out.push_str(HTML_FOOTER_PREFIX);
315    out.push_str(ctx.get_generated_at_escaped());
316    out.push_str(HTML_FOOTER_SUFFIX);
317    if has_toc {
318        out.push_str(HTML_TOC_OPEN);
319        for item in page.get_toc().iter() {
320            let cls: &str = match item.get_level() {
321                3 => TOC_LVL3_CLASS,
322                lvl if lvl >= 4 => TOC_LVL4_CLASS,
323                _ => "",
324            };
325            out.push_str(HTML_TOC_A_OPEN);
326            out.push_str(cls);
327            out.push_str(HTML_TOC_HREF_HASH);
328            push_escaped_html(&mut out, item.get_slug());
329            out.push_str(HTML_LINK_MID);
330            push_escaped_html(&mut out, item.get_title());
331            out.push_str(HTML_LINK_CLOSE);
332        }
333        out.push_str(HTML_TOC_CLOSE);
334    }
335    out.push_str(HTML_SHELL_CLOSE);
336    out.push_str(HTML_SCRIPT_PREFIX);
337    out.push_str(ctx.get_search_json_compact());
338    out.push_str(HTML_SCRIPT_BASE_PREFIX);
339    out.push_str(ctx.get_base_json());
340    out.push_str(HTML_SCRIPT_BODY);
341    if let Some(hmr_url) = options.try_get_hmr_endpoint() {
342        out.push_str(HTML_HMR_PREFIX);
343        push_escaped_html(&mut out, hmr_url);
344        out.push_str(HTML_HMR_SUFFIX);
345    }
346    out.push_str(HTML_BODY_END);
347    out
348}
349
350/// Renders the grouped section-ordered sidebar links from pre-escaped entries into `out`.
351///
352/// # Arguments
353///
354/// - `&[SidebarNavEntry<'_>]` - Pre-sorted and pre-escaped sidebar navigation entries.
355/// - `&str` - Canonical route of the currently active page.
356/// - `&mut String` - HTML output buffer.
357fn render_sidebar_nav(
358    sidebar_entries: &[SidebarNavEntry<'_>],
359    active_route: &str,
360    out: &mut String,
361) {
362    for entry in sidebar_entries.iter() {
363        if let Some(sec_html) = entry.try_get_section_header_html() {
364            out.push_str(sec_html);
365        }
366        if entry.get_route() == active_route {
367            out.push_str(HTML_NAV_LINK_ACTIVE_OPEN);
368        } else {
369            out.push_str(HTML_NAV_LINK_OPEN);
370        }
371        out.push_str(entry.get_link_tail_html());
372    }
373}
374
375/// Renders previous and next pagination cards when either neighbor exists.
376///
377/// # Arguments
378///
379/// - `Option<&DocPage>` - Previous page in reading order.
380/// - `Option<&DocPage>` - Next page in reading order.
381/// - `&str` - Normalized base URL without trailing slash.
382/// - `&mut String` - HTML output buffer.
383fn render_pager_nav(
384    prev_page: Option<&DocPage>,
385    next_page: Option<&DocPage>,
386    base: &str,
387    out: &mut String,
388) {
389    if prev_page.is_none() && next_page.is_none() {
390        return;
391    }
392    out.push_str(HTML_PAGER_OPEN);
393    if let Some(prev) = prev_page {
394        out.push_str(HTML_PAGER_PREV_OPEN);
395        let prev_href: String = href_for_route(base, prev.get_route());
396        push_escaped_html(out, &prev_href);
397        out.push_str(HTML_PAGER_PREV_LABEL);
398        push_escaped_html(out, prev.get_title());
399        out.push_str(HTML_PAGER_CARD_CLOSE);
400    } else {
401        out.push_str(HTML_PAGER_EMPTY);
402    }
403    if let Some(next) = next_page {
404        out.push_str(HTML_PAGER_NEXT_OPEN);
405        let next_href: String = href_for_route(base, next.get_route());
406        push_escaped_html(out, &next_href);
407        out.push_str(HTML_PAGER_NEXT_LABEL);
408        push_escaped_html(out, next.get_title());
409        out.push_str(HTML_PAGER_CARD_CLOSE);
410    } else {
411        out.push_str(HTML_PAGER_EMPTY);
412    }
413    out.push_str(HTML_PAGER_CLOSE);
414}
415
416/// Returns `true` when `page.summary` is non-empty and does not duplicate the first body paragraph.
417///
418/// # Arguments
419///
420/// - `&DocPage` - Candidate documentation page.
421///
422/// # Returns
423///
424/// - `bool` - Whether a separate `<p class="lead">` should be rendered.
425fn should_render_lead(page: &DocPage) -> bool {
426    let summary: &str = page.get_summary().trim();
427    if summary.is_empty() {
428        return false;
429    }
430    let first_prose: Option<&str> = page.get_blocks().iter().find_map(|b: &DocBlock| match b {
431        DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.trim()),
432        _ => None,
433    });
434    first_prose != Some(summary)
435}
436
437/// Computes the uppercase single-character brand monogram for the topbar badge.
438///
439/// # Arguments
440///
441/// - `&str` - Site brand title.
442///
443/// # Returns
444///
445/// - `char` - Uppercase alphanumeric initial or `'E'`.
446fn brand_monogram(title: &str) -> char {
447    title
448        .chars()
449        .find(|ch: &char| ch.is_alphanumeric())
450        .and_then(|ch: char| ch.to_uppercase().next())
451        .unwrap_or(DEFAULT_BRAND_MONOGRAM)
452}
453
454/// Renders full-fidelity Markdown HTML preserving inline formatting, links, images, lists, tables, code blocks, and custom containers.
455///
456/// # Arguments
457///
458/// - `&DocPage` - Parsed page carrying raw Markdown body text.
459/// - `&str` - Normalized base URL prefix.
460/// - `&mut String` - HTML output buffer.
461fn render_markdown_body_html(page: &DocPage, base: &str, out: &mut String) {
462    let body_raw: &str = page.get_markdown_body();
463    let mut state: MarkdownRenderState<'_> = MarkdownRenderState {
464        page,
465        base,
466        seen_slugs: BTreeMap::new(),
467        skipped_title_h1: false,
468        out,
469    };
470    if !body_raw.contains(CALLOUT_FENCE) {
471        render_markdown_chunk(body_raw, &mut state);
472        return;
473    }
474    let segments: Vec<BodySegment> = split_custom_containers(body_raw);
475    for seg in segments.into_iter() {
476        match seg {
477            BodySegment::Markdown(md) => {
478                render_markdown_chunk(&md, &mut state);
479            }
480            BodySegment::Callout { kind, title, body } => {
481                if kind == CALLOUT_KIND_DETAILS {
482                    state.out.push_str(HTML_CALLOUT_DETAILS_OPEN);
483                    push_escaped_html(state.out, &title);
484                    state.out.push_str(HTML_SUMMARY_CLOSE);
485                    render_markdown_chunk(&body, &mut state);
486                    state.out.push_str(HTML_DETAILS_CLOSE);
487                } else {
488                    state.out.push_str(HTML_CALLOUT_DIV_OPEN);
489                    push_escaped_html(state.out, &kind);
490                    state.out.push_str(HTML_CALLOUT_TITLE_MID);
491                    push_escaped_html(state.out, &title);
492                    state.out.push_str(HTML_DIV_CLOSE);
493                    render_markdown_chunk(&body, &mut state);
494                    state.out.push_str(HTML_DIV_CLOSE);
495                }
496            }
497        }
498    }
499}
500
501/// Splits VuePress-style `::: kind [title]` custom containers while ignoring fenced code blocks.
502///
503/// # Arguments
504///
505/// - `&str` - Raw Markdown document body.
506///
507/// # Returns
508///
509/// - `Vec<BodySegment>` - Ordered plain Markdown and callout segments.
510fn split_custom_containers(body: &str) -> Vec<BodySegment> {
511    let mut segments: Vec<BodySegment> = Vec::new();
512    let mut plain: String = String::new();
513    let mut active: Option<(String, String, String)> = None;
514    let mut in_fence: bool = false;
515    for line in body.lines() {
516        let trimmed: &str = line.trim();
517        if trimmed.starts_with(FENCE_BACKTICK) || trimmed.starts_with(FENCE_TILDE) {
518            in_fence = !in_fence;
519        }
520        if let Some((kind, title, inner)) = active.as_mut() {
521            if !in_fence && trimmed == CALLOUT_FENCE {
522                let done_kind: String = take(kind);
523                let done_title: String = take(title);
524                let done_body: String = take(inner);
525                active = None;
526                segments.push(BodySegment::Callout {
527                    kind: done_kind,
528                    title: done_title,
529                    body: done_body,
530                });
531                continue;
532            }
533            inner.push_str(line);
534            inner.push('\n');
535            continue;
536        }
537        if !in_fence && let Some(after) = trimmed.strip_prefix(CALLOUT_FENCE) {
538            let spec: &str = after.trim();
539            let (raw_kind, custom_title): (&str, &str) = match spec.find(char::is_whitespace) {
540                Some(pos) => (&spec[..pos], spec[pos..].trim()),
541                None => (spec, ""),
542            };
543            let normalized: Option<(&str, &str)> =
544                if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_TIP) {
545                    Some((CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP))
546                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_WARNING) {
547                    Some((CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING))
548                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_DANGER) {
549                    Some((CALLOUT_KIND_DANGER, CALLOUT_TITLE_DANGER))
550                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_INFO) {
551                    Some((CALLOUT_KIND_INFO, CALLOUT_TITLE_INFO))
552                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_NOTE) {
553                    Some((CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE))
554                } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_DETAILS) {
555                    Some((CALLOUT_KIND_DETAILS, CALLOUT_TITLE_DETAILS))
556                } else {
557                    None
558                };
559            if let Some((kind_str, default_title)) = normalized {
560                if !plain.is_empty() {
561                    segments.push(BodySegment::Markdown(take(&mut plain)));
562                }
563                let title: String = if custom_title.is_empty() {
564                    default_title.to_string()
565                } else {
566                    custom_title.to_string()
567                };
568                active = Some((kind_str.to_string(), title, String::new()));
569                continue;
570            }
571        }
572        plain.push_str(line);
573        plain.push('\n');
574    }
575    if let Some((kind, title, inner)) = active {
576        segments.push(BodySegment::Callout {
577            kind,
578            title,
579            body: inner,
580        });
581    }
582    if !plain.is_empty() {
583        segments.push(BodySegment::Markdown(plain));
584    }
585    segments
586}
587
588/// Renders a single Markdown chunk through `pulldown_cmark` into semantic, XSS-safe HTML.
589///
590/// # Arguments
591///
592/// - `&str` - Markdown chunk text.
593/// - `&mut MarkdownRenderState<'_>` - Mutable page rendering state and HTML output buffer.
594fn render_markdown_chunk(chunk: &str, state: &mut MarkdownRenderState<'_>) {
595    let parser: Parser<'_> = Parser::new_ext(chunk, Options::all());
596    let mut active_heading: Option<(u8, Option<String>, String, String)> = None;
597    let mut active_code: Option<(String, String)> = None;
598    let mut active_image: Option<(String, String, String)> = None;
599    let mut table_alignments: Vec<Alignment> = Vec::new();
600    let mut blockquote_alerts: Vec<bool> = Vec::new();
601    let mut in_table_head: bool = false;
602    let mut cell_index: usize = 0;
603    let mut pending_text: String = String::new();
604    for event in parser {
605        if let Some((_, _, ref mut heading_html, ref mut heading_plain)) = active_heading {
606            match event {
607                Event::End(TagEnd::Heading(_)) => {
608                    if let Some((level, custom_id, inner_html, plain)) = active_heading.take() {
609                        let trimmed_plain: &str = plain.trim();
610                        if !trimmed_plain.is_empty() {
611                            let raw_slug: String = custom_id
612                                .map(|s: String| slugify(&s))
613                                .filter(|s: &String| !s.is_empty())
614                                .unwrap_or_else(|| slugify(trimmed_plain));
615                            let slug: String = deduplicate_slug(raw_slug, &mut state.seen_slugs);
616                            if level <= 2
617                                && !state.skipped_title_h1
618                                && state.seen_slugs.len() == 1
619                                && trimmed_plain.eq_ignore_ascii_case(state.page.get_title().trim())
620                            {
621                                state.skipped_title_h1 = true;
622                            } else {
623                                let tag_lvl: u8 = level.clamp(2, 6);
624                                let _: fmt::Result =
625                                    write!(state.out, "<h{tag_lvl}{HTML_HEADING_ID_MID}");
626                                push_escaped_html(state.out, &slug);
627                                state.out.push_str(HTML_LINK_MID);
628                                state.out.push_str(&inner_html);
629                                state.out.push_str(HTML_ANCHOR_MID);
630                                push_escaped_html(state.out, &slug);
631                                state.out.push_str(HTML_ANCHOR_CLOSE);
632                                let _: fmt::Result = write!(state.out, "</h{tag_lvl}>");
633                            }
634                        }
635                    }
636                }
637                Event::Text(text) => {
638                    heading_plain.push_str(&text);
639                    push_escaped_html(heading_html, &text);
640                }
641                Event::Code(text) => {
642                    heading_plain.push_str(&text);
643                    heading_html.push_str(HTML_INLINE_CODE_OPEN);
644                    push_escaped_html(heading_html, &text);
645                    heading_html.push_str(HTML_INLINE_CODE_CLOSE);
646                }
647                Event::Start(Tag::Strong) => heading_html.push_str(HTML_STRONG_OPEN),
648                Event::End(TagEnd::Strong) => heading_html.push_str(HTML_STRONG_CLOSE),
649                Event::Start(Tag::Emphasis) => heading_html.push_str(HTML_EM_OPEN),
650                Event::End(TagEnd::Emphasis) => heading_html.push_str(HTML_EM_CLOSE),
651                Event::Start(Tag::Strikethrough) => heading_html.push_str(HTML_DEL_OPEN),
652                Event::End(TagEnd::Strikethrough) => heading_html.push_str(HTML_DEL_CLOSE),
653                Event::SoftBreak | Event::HardBreak => {
654                    heading_plain.push(' ');
655                    heading_html.push(' ');
656                }
657                _ => {}
658            }
659            continue;
660        }
661        if let Some((_, ref mut code_buf)) = active_code {
662            match event {
663                Event::End(TagEnd::CodeBlock) => {
664                    if let Some((info, code)) = active_code.take() {
665                        let trimmed: &str = code.trim_end_matches('\n');
666                        let (lang, title_opt, hl_lines): (String, Option<String>, Vec<usize>) =
667                            parse_code_fence_info(&info);
668                        if lang.eq_ignore_ascii_case(CODE_LANG_MERMAID) {
669                            render_mermaid_svg_html(trimmed, state.out);
670                        } else if lang.eq_ignore_ascii_case(CODE_LANG_ECHART)
671                            || lang.eq_ignore_ascii_case(CODE_LANG_ECHARTS)
672                        {
673                            render_echart_svg_html(trimmed, state.out);
674                        } else {
675                            render_highlighted_code_html_with_meta(
676                                &lang,
677                                title_opt.as_deref(),
678                                &hl_lines,
679                                trimmed,
680                                state.out,
681                            );
682                        }
683                    }
684                }
685                Event::Text(text) | Event::Code(text) => code_buf.push_str(&text),
686                Event::SoftBreak | Event::HardBreak => code_buf.push('\n'),
687                _ => {}
688            }
689            continue;
690        }
691        if let Some((_, _, ref mut alt_buf)) = active_image {
692            match event {
693                Event::End(TagEnd::Image) => {
694                    if let Some((src, title, alt)) = active_image.take()
695                        && let Some(resolved) =
696                            resolve_asset_src(state.base, state.page.get_route(), &src)
697                    {
698                        state.out.push_str(HTML_IMG_SRC_OPEN);
699                        push_escaped_html(state.out, &resolved);
700                        state.out.push_str(HTML_IMG_ALT_MID);
701                        push_escaped_html(state.out, alt.trim());
702                        if !title.is_empty() {
703                            state.out.push_str(HTML_IMG_TITLE_MID);
704                            push_escaped_html(state.out, &title);
705                        }
706                        state.out.push_str(HTML_IMG_LAZY_CLOSE);
707                    }
708                }
709                Event::Text(text) | Event::Code(text) => alt_buf.push_str(&text),
710                Event::SoftBreak | Event::HardBreak => alt_buf.push(' '),
711                _ => {}
712            }
713            continue;
714        }
715        if let Event::Text(text) = event {
716            pending_text.push_str(&text);
717            continue;
718        }
719        if !pending_text.is_empty() {
720            render_extended_inline_text_html(&pending_text, state.out);
721            pending_text.clear();
722        }
723        match event {
724            Event::Start(Tag::Heading { level, id, .. }) => {
725                active_heading = Some((
726                    heading_level_num(level),
727                    id.map(CowStr::into_string),
728                    String::new(),
729                    String::new(),
730                ));
731            }
732            Event::Start(Tag::Paragraph) => state.out.push_str(HTML_P_OPEN),
733            Event::End(TagEnd::Paragraph) => state.out.push_str(HTML_P_CLOSE),
734            Event::Start(Tag::BlockQuote(kind_opt)) => {
735                if let Some(kind) = kind_opt {
736                    let (cls, title): (&str, &str) = match kind {
737                        BlockQuoteKind::Note => (CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE),
738                        BlockQuoteKind::Tip => (CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP),
739                        BlockQuoteKind::Important => {
740                            (CALLOUT_KIND_IMPORTANT, CALLOUT_TITLE_IMPORTANT)
741                        }
742                        BlockQuoteKind::Warning => (CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING),
743                        BlockQuoteKind::Caution => (CALLOUT_KIND_CAUTION, CALLOUT_TITLE_CAUTION),
744                    };
745                    state.out.push_str(HTML_CALLOUT_DIV_OPEN);
746                    state.out.push_str(cls);
747                    state.out.push_str(HTML_CALLOUT_TITLE_MID);
748                    state.out.push_str(title);
749                    state.out.push_str(HTML_DIV_CLOSE);
750                    blockquote_alerts.push(true);
751                } else {
752                    state.out.push_str(HTML_QUOTE_OPEN);
753                    blockquote_alerts.push(false);
754                }
755            }
756            Event::End(TagEnd::BlockQuote(_)) => {
757                if blockquote_alerts.pop().unwrap_or(false) {
758                    state.out.push_str(HTML_DIV_CLOSE);
759                } else {
760                    state.out.push_str(HTML_QUOTE_CLOSE);
761                }
762            }
763            Event::Start(Tag::List(None)) => state.out.push_str(HTML_UL_OPEN),
764            Event::Start(Tag::List(Some(start))) => {
765                if start == 1 {
766                    state.out.push_str(HTML_OL_OPEN);
767                } else {
768                    state.out.push_str(HTML_OL_START_OPEN);
769                    let _: fmt::Result = write!(state.out, "{start}");
770                    state.out.push_str(HTML_LINK_MID);
771                }
772            }
773            Event::End(TagEnd::List(ordered)) => {
774                if ordered {
775                    state.out.push_str(HTML_OL_CLOSE);
776                } else {
777                    state.out.push_str(HTML_UL_CLOSE);
778                }
779            }
780            Event::Start(Tag::Item) => state.out.push_str(HTML_LI_OPEN),
781            Event::End(TagEnd::Item) => state.out.push_str(HTML_LI_CLOSE),
782            Event::Start(Tag::Strong) => state.out.push_str(HTML_STRONG_OPEN),
783            Event::End(TagEnd::Strong) => state.out.push_str(HTML_STRONG_CLOSE),
784            Event::Start(Tag::Emphasis) => state.out.push_str(HTML_EM_OPEN),
785            Event::End(TagEnd::Emphasis) => state.out.push_str(HTML_EM_CLOSE),
786            Event::Start(Tag::Strikethrough) => state.out.push_str(HTML_DEL_OPEN),
787            Event::End(TagEnd::Strikethrough) => state.out.push_str(HTML_DEL_CLOSE),
788            Event::Start(Tag::Superscript) => state.out.push_str(HTML_SUP_OPEN),
789            Event::End(TagEnd::Superscript) => state.out.push_str(HTML_SUP_CLOSE),
790            Event::Start(Tag::Subscript) => state.out.push_str(HTML_SUB_OPEN),
791            Event::End(TagEnd::Subscript) => state.out.push_str(HTML_SUB_CLOSE),
792            Event::Start(Tag::DefinitionList) => state.out.push_str(HTML_DL_OPEN),
793            Event::End(TagEnd::DefinitionList) => state.out.push_str(HTML_DL_CLOSE),
794            Event::Start(Tag::DefinitionListTitle) => state.out.push_str(HTML_DT_OPEN),
795            Event::End(TagEnd::DefinitionListTitle) => state.out.push_str(HTML_DT_CLOSE),
796            Event::Start(Tag::DefinitionListDefinition) => state.out.push_str(HTML_DD_OPEN),
797            Event::End(TagEnd::DefinitionListDefinition) => state.out.push_str(HTML_DD_CLOSE),
798            Event::Start(Tag::CodeBlock(kind)) => {
799                let info: String = match kind {
800                    CodeBlockKind::Fenced(tag) => {
801                        let t: &str = tag.trim();
802                        if t.is_empty() {
803                            DEFAULT_CODE_LABEL.to_string()
804                        } else {
805                            t.to_string()
806                        }
807                    }
808                    CodeBlockKind::Indented => DEFAULT_CODE_LABEL.to_string(),
809                };
810                active_code = Some((info, String::new()));
811            }
812            Event::Start(Tag::Link {
813                dest_url, title, ..
814            }) => {
815                let resolved: String =
816                    resolve_link_href(state.base, state.page.get_route(), &dest_url);
817                let external: bool = is_external_url(&resolved);
818                state.out.push_str(HTML_A_HREF_OPEN);
819                push_escaped_html(state.out, &resolved);
820                state.out.push('"');
821                if !title.is_empty() {
822                    state.out.push_str(HTML_TITLE_ATTR_OPEN);
823                    push_escaped_html(state.out, &title);
824                    state.out.push('"');
825                }
826                if external {
827                    state.out.push_str(HTML_EXTERNAL_LINK_ATTRS);
828                }
829                state.out.push('>');
830            }
831            Event::End(TagEnd::Link) => state.out.push_str(HTML_LINK_CLOSE),
832            Event::Start(Tag::Image {
833                dest_url, title, ..
834            }) => {
835                active_image = Some((dest_url.into_string(), title.into_string(), String::new()));
836            }
837            Event::Start(Tag::Table(aligns)) => {
838                table_alignments = aligns;
839                in_table_head = false;
840                state.out.push_str(HTML_TABLE_OPEN);
841            }
842            Event::End(TagEnd::Table) => {
843                table_alignments.clear();
844                state.out.push_str(HTML_TBODY_CLOSE);
845                state.out.push_str(HTML_TABLE_CLOSE);
846            }
847            Event::Start(Tag::TableHead) => {
848                in_table_head = true;
849                cell_index = 0;
850                state.out.push_str(HTML_THEAD_OPEN);
851            }
852            Event::End(TagEnd::TableHead) => {
853                in_table_head = false;
854                state.out.push_str(HTML_THEAD_CLOSE);
855                state.out.push_str(HTML_TBODY_OPEN);
856            }
857            Event::Start(Tag::TableRow) => {
858                cell_index = 0;
859                state.out.push_str(HTML_TR_OPEN);
860            }
861            Event::End(TagEnd::TableRow) => state.out.push_str(HTML_TR_CLOSE),
862            Event::Start(Tag::TableCell) => {
863                let align_attr: &str = match table_alignments.get(cell_index).copied() {
864                    Some(Alignment::Center) => HTML_ALIGN_CENTER,
865                    Some(Alignment::Right) => HTML_ALIGN_RIGHT,
866                    _ => "",
867                };
868                cell_index += 1;
869                if in_table_head {
870                    state.out.push_str(HTML_TH_PREFIX);
871                } else {
872                    state.out.push_str(HTML_TD_PREFIX);
873                }
874                state.out.push_str(align_attr);
875                state.out.push('>');
876            }
877            Event::End(TagEnd::TableCell) => {
878                if in_table_head {
879                    state.out.push_str(HTML_TH_CLOSE);
880                } else {
881                    state.out.push_str(HTML_TD_CLOSE);
882                }
883            }
884            Event::Start(Tag::FootnoteDefinition(label)) => {
885                let fn_slug: String = slugify(&label);
886                state.out.push_str(HTML_FOOTNOTE_DEF_OPEN);
887                push_escaped_html(state.out, &fn_slug);
888                state.out.push_str(HTML_FOOTNOTE_DEF_MID);
889                push_escaped_html(state.out, &label);
890                state.out.push_str(HTML_FOOTNOTE_DEF_CLOSE);
891            }
892            Event::End(TagEnd::FootnoteDefinition) => state.out.push_str(HTML_QUOTE_CLOSE),
893            Event::FootnoteReference(label) => {
894                let fn_slug: String = slugify(&label);
895                state.out.push_str(HTML_FOOTNOTE_REF_OPEN);
896                push_escaped_html(state.out, &fn_slug);
897                state.out.push_str(HTML_FOOTNOTE_REF_MID);
898                push_escaped_html(state.out, &label);
899                state.out.push_str(HTML_FOOTNOTE_REF_CLOSE);
900            }
901            Event::TaskListMarker(checked) => {
902                if checked {
903                    state.out.push_str(HTML_TASK_CHECKED);
904                } else {
905                    state.out.push_str(HTML_TASK_UNCHECKED);
906                }
907            }
908            Event::Rule => state.out.push_str(HTML_HR),
909            Event::Code(text) => {
910                state.out.push_str(HTML_INLINE_CODE_OPEN);
911                push_escaped_html(state.out, &text);
912                state.out.push_str(HTML_INLINE_CODE_CLOSE);
913            }
914            Event::SoftBreak => state.out.push(' '),
915            Event::HardBreak => state.out.push_str(HTML_BR),
916            Event::InlineMath(math) => {
917                let formatted: String = format_latex_math(&math);
918                state.out.push_str(HTML_MATH_INLINE_OPEN);
919                push_escaped_html(state.out, &formatted);
920                state.out.push_str(HTML_MATH_INLINE_CLOSE);
921            }
922            Event::DisplayMath(math) => {
923                let formatted: String = format_latex_math(&math);
924                state.out.push_str(HTML_MATH_DISPLAY_OPEN);
925                push_escaped_html(state.out, &formatted);
926                state.out.push_str(HTML_MATH_DISPLAY_CLOSE);
927            }
928            Event::Html(raw_html) | Event::InlineHtml(raw_html) => {
929                if is_safe_raw_html(&raw_html) {
930                    state.out.push_str(&raw_html);
931                } else {
932                    push_escaped_html(state.out, &raw_html);
933                }
934            }
935            _ => {}
936        }
937    }
938    if !pending_text.is_empty() {
939        render_extended_inline_text_html(&pending_text, state.out);
940    }
941}
942
943/// Renders structured `DocBlock` entries when a `DocPage` was constructed without raw Markdown text.
944///
945/// # Arguments
946///
947/// - `&DocPage` - Documentation page containing structured blocks.
948/// - `&mut String` - HTML output buffer.
949fn render_fallback_blocks_html(page: &DocPage, out: &mut String) {
950    let mut in_ul: bool = false;
951    for block in page.get_blocks().iter() {
952        let is_item: bool = matches!(block, DocBlock::ListItem(_));
953        if is_item && !in_ul {
954            out.push_str(HTML_UL_OPEN);
955            in_ul = true;
956        } else if !is_item && in_ul {
957            out.push_str(HTML_UL_CLOSE);
958            in_ul = false;
959        }
960        match block {
961            DocBlock::Heading { level, slug, text } => {
962                let tag_lvl: u8 = (*level).clamp(2, 6);
963                let _: fmt::Result = write!(out, "<h{tag_lvl}{HTML_HEADING_ID_MID}");
964                push_escaped_html(out, slug);
965                out.push_str(HTML_LINK_MID);
966                push_escaped_html(out, text);
967                let _: fmt::Result = write!(out, "</h{tag_lvl}>");
968            }
969            DocBlock::Paragraph(text) => {
970                out.push_str(HTML_P_OPEN);
971                push_escaped_html(out, text);
972                out.push_str(HTML_P_CLOSE);
973            }
974            DocBlock::ListItem(text) => {
975                out.push_str(HTML_LI_OPEN);
976                push_escaped_html(out, text);
977                out.push_str(HTML_LI_CLOSE);
978            }
979            DocBlock::BlockQuote(text) => {
980                out.push_str(HTML_QUOTE_OPEN);
981                push_escaped_html(out, text);
982                out.push_str(HTML_QUOTE_CLOSE);
983            }
984            DocBlock::Image { alt, src } => {
985                out.push_str(HTML_P_IMG_OPEN);
986                push_escaped_html(out, src);
987                out.push_str(HTML_IMG_ALT_MID);
988                push_escaped_html(out, alt);
989                out.push_str(HTML_P_IMG_CLOSE);
990            }
991            DocBlock::HorizontalRule => out.push_str(HTML_HR),
992            DocBlock::Code { language, code } => {
993                render_highlighted_code_html(language, code, out);
994            }
995            DocBlock::Table { headers, rows } => {
996                out.push_str(HTML_TABLE_OPEN);
997                if !headers.is_empty() {
998                    out.push_str(HTML_THEAD_OPEN);
999                    for h in headers.iter() {
1000                        out.push_str(HTML_TH_OPEN);
1001                        push_escaped_html(out, h);
1002                        out.push_str(HTML_TH_CLOSE);
1003                    }
1004                    out.push_str(HTML_THEAD_CLOSE);
1005                }
1006                out.push_str(HTML_TBODY_OPEN);
1007                for row in rows.iter() {
1008                    out.push_str(HTML_TR_OPEN);
1009                    for cell in row.iter() {
1010                        out.push_str(HTML_TD_OPEN);
1011                        push_escaped_html(out, cell);
1012                        out.push_str(HTML_TD_CLOSE);
1013                    }
1014                    out.push_str(HTML_TR_CLOSE);
1015                }
1016                out.push_str(HTML_TBODY_CLOSE);
1017                out.push_str(HTML_TABLE_CLOSE);
1018            }
1019        }
1020    }
1021    if in_ul {
1022        out.push_str(HTML_UL_CLOSE);
1023    }
1024}
1025
1026/// Returns `true` when `haystack` starts with `prefix` ignoring ASCII letter case without heap allocation.
1027///
1028/// # Arguments
1029///
1030/// - `&str` - Source UTF-8 string.
1031/// - `&str` - ASCII prefix to match.
1032///
1033/// # Returns
1034///
1035/// - `bool` - `true` when `haystack` begins with `prefix` ignoring ASCII case.
1036fn starts_with_ascii_ignore_case(haystack: &str, prefix: &str) -> bool {
1037    let h: &[u8] = haystack.as_bytes();
1038    let p: &[u8] = prefix.as_bytes();
1039    h.len() >= p.len() && h[..p.len()].eq_ignore_ascii_case(p)
1040}
1041
1042/// Returns `true` when `haystack` ends with `suffix` ignoring ASCII letter case without heap allocation.
1043///
1044/// # Arguments
1045///
1046/// - `&str` - Source UTF-8 string.
1047/// - `&str` - ASCII suffix to match.
1048///
1049/// # Returns
1050///
1051/// - `bool` - `true` when `haystack` ends with `suffix` ignoring ASCII case.
1052fn ends_with_ascii_ignore_case(haystack: &str, suffix: &str) -> bool {
1053    let h: &[u8] = haystack.as_bytes();
1054    let s: &[u8] = suffix.as_bytes();
1055    h.len() >= s.len() && h[h.len() - s.len()..].eq_ignore_ascii_case(s)
1056}
1057
1058/// Returns `true` when `haystack` contains lowercase ASCII `needle` ignoring ASCII letter case without heap allocation.
1059///
1060/// # Arguments
1061///
1062/// - `&str` - Source UTF-8 string.
1063/// - `&str` - Lowercase ASCII needle to search for.
1064///
1065/// # Returns
1066///
1067/// - `bool` - `true` when `needle` occurs inside `haystack` ignoring ASCII case.
1068fn contains_ascii_ignore_case(haystack: &str, needle: &str) -> bool {
1069    let h: &[u8] = haystack.as_bytes();
1070    let n: &[u8] = needle.as_bytes();
1071    let n_len: usize = n.len();
1072    if n_len == 0 {
1073        return true;
1074    }
1075    if n_len > h.len() {
1076        return false;
1077    }
1078    let first: u8 = n[0];
1079    let tail: &[u8] = &n[1..];
1080    let limit: usize = h.len() - n_len;
1081    let mut pos: usize = 0;
1082    while pos <= limit {
1083        if h[pos].to_ascii_lowercase() == first
1084            && h[pos + 1..pos + n_len].eq_ignore_ascii_case(tail)
1085        {
1086            return true;
1087        }
1088        pos += 1;
1089    }
1090    false
1091}
1092
1093/// Checks whether a raw Markdown HTML fragment is free of active script or event-handler vectors.
1094///
1095/// # Arguments
1096///
1097/// - `&str` - Raw HTML fragment emitted by `pulldown_cmark`.
1098///
1099/// # Returns
1100///
1101/// - `bool` - `true` when safe to pass through verbatim.
1102fn is_safe_raw_html(raw: &str) -> bool {
1103    if UNSAFE_HTML_TAGS
1104        .iter()
1105        .any(|tag: &&str| contains_ascii_ignore_case(raw, tag))
1106    {
1107        return false;
1108    }
1109    if contains_ascii_ignore_case(raw, SCHEME_JAVASCRIPT)
1110        || contains_ascii_ignore_case(raw, SCHEME_VBSCRIPT)
1111    {
1112        return false;
1113    }
1114    let bytes: &[u8] = raw.as_bytes();
1115    for i in 0..bytes.len().saturating_sub(3) {
1116        let before_ok: bool = i == 0 || bytes[i - 1].is_ascii_whitespace();
1117        if before_ok
1118            && bytes[i].to_ascii_lowercase() == BYTE_LOWER_O
1119            && bytes[i + 1].to_ascii_lowercase() == BYTE_LOWER_N
1120            && bytes[i + 2].is_ascii_alphabetic()
1121        {
1122            let rest: &str = &raw[i + 2..];
1123            let attr_len: usize = rest
1124                .bytes()
1125                .take_while(|b: &u8| b.is_ascii_alphabetic())
1126                .count();
1127            if rest[attr_len..].trim_start().starts_with('=') {
1128                return false;
1129            }
1130        }
1131    }
1132    true
1133}
1134
1135/// Resolves Markdown link targets, rewriting relative `.md` links to clean URLs and blocking unsafe schemes.
1136///
1137/// # Arguments
1138///
1139/// - `&str` - Normalized base URL prefix.
1140/// - `&str` - Current page canonical route.
1141/// - `&str` - Raw Markdown link destination.
1142///
1143/// # Returns
1144///
1145/// - `String` - Safe navigable HTML `href` attribute value.
1146fn resolve_link_href(base: &str, current_route: &str, raw_dest: &str) -> String {
1147    let dest: &str = raw_dest.trim();
1148    if starts_with_ascii_ignore_case(dest, SCHEME_JAVASCRIPT)
1149        || starts_with_ascii_ignore_case(dest, SCHEME_VBSCRIPT)
1150    {
1151        return "#".to_string();
1152    }
1153    if dest.starts_with('#')
1154        || starts_with_ascii_ignore_case(dest, SCHEME_HTTP)
1155        || starts_with_ascii_ignore_case(dest, SCHEME_HTTPS)
1156        || starts_with_ascii_ignore_case(dest, SCHEME_MAILTO)
1157    {
1158        return dest.to_string();
1159    }
1160    let (path_part, fragment): (&str, Option<&str>) = match dest.split_once('#') {
1161        Some((p, f)) => (p, Some(f)),
1162        None => (dest, None),
1163    };
1164    if ends_with_ascii_ignore_case(path_part, MARKDOWN_EXT_SUFFIX) {
1165        let joined: String = join_relative_route(current_route, path_part);
1166        let stripped: &str = joined
1167            .strip_suffix(MARKDOWN_EXT_SUFFIX)
1168            .or_else(|| joined.strip_suffix(MARKDOWN_EXT_UPPER))
1169            .unwrap_or(&joined);
1170        let mut segs: Vec<String> = stripped
1171            .split('/')
1172            .filter(|s: &&str| !s.is_empty())
1173            .map(|seg: &str| {
1174                let cleaned: String = slugify(seg);
1175                if cleaned.is_empty() {
1176                    seg.to_ascii_lowercase()
1177                } else {
1178                    cleaned
1179                }
1180            })
1181            .collect();
1182        if let Some(last) = segs.last()
1183            && (last.eq_ignore_ascii_case(STEM_README_LOWER)
1184                || last.eq_ignore_ascii_case(STEM_INDEX_LOWER))
1185        {
1186            let _: Option<String> = segs.pop();
1187        }
1188        let route: String = if segs.is_empty() {
1189            ROOT_ROUTE_STR.to_string()
1190        } else {
1191            format!("/{}", segs.join("/"))
1192        };
1193        let clean: String = href_for_route(base, &route);
1194        return match fragment {
1195            Some(frag) if !frag.is_empty() => format!("{clean}#{frag}"),
1196            _ => clean,
1197        };
1198    }
1199    if dest.starts_with('/') {
1200        if base.is_empty() {
1201            dest.to_string()
1202        } else {
1203            format!("{base}{dest}")
1204        }
1205    } else {
1206        dest.to_string()
1207    }
1208}
1209
1210/// Resolves Markdown image `src` attributes against `current_route` and `base`, blocking unsafe schemes.
1211///
1212/// # Arguments
1213///
1214/// - `&str` - Normalized base URL prefix.
1215/// - `&str` - Current page canonical route.
1216/// - `&str` - Raw Markdown image destination.
1217///
1218/// # Returns
1219///
1220/// - `Option<String>` - Safe `src` attribute value or `None` when blocked.
1221fn resolve_asset_src(base: &str, current_route: &str, raw_src: &str) -> Option<String> {
1222    let src: &str = raw_src.trim();
1223    if src.is_empty()
1224        || starts_with_ascii_ignore_case(src, SCHEME_JAVASCRIPT)
1225        || starts_with_ascii_ignore_case(src, SCHEME_VBSCRIPT)
1226    {
1227        return None;
1228    }
1229    if starts_with_ascii_ignore_case(src, SCHEME_HTTP)
1230        || starts_with_ascii_ignore_case(src, SCHEME_HTTPS)
1231        || starts_with_ascii_ignore_case(src, SCHEME_DATA)
1232    {
1233        return Some(src.to_string());
1234    }
1235    if src.starts_with('/') {
1236        return Some(if base.is_empty() {
1237            src.to_string()
1238        } else {
1239            format!("{base}{src}")
1240        });
1241    }
1242    let resolved: String = join_relative_route(current_route, src);
1243    Some(if base.is_empty() {
1244        resolved
1245    } else {
1246        format!("{base}{resolved}")
1247    })
1248}
1249
1250/// Resolves a relative link or asset path against a page's canonical directory route.
1251///
1252/// # Arguments
1253///
1254/// - `&str` - Canonical page route (for example `/guide/markdown`).
1255/// - `&str` - Relative path reference (for example `./getting-started.md` or `../img/logo.png`).
1256///
1257/// # Returns
1258///
1259/// - `String` - Normalized root-relative path beginning with `/`.
1260fn join_relative_route(current_route: &str, rel_path: &str) -> String {
1261    let mut stack: Vec<&str> = current_route
1262        .trim_matches('/')
1263        .split('/')
1264        .filter(|s: &&str| !s.is_empty())
1265        .collect();
1266    if !stack.is_empty() {
1267        let _: Option<&str> = stack.pop();
1268    }
1269    for seg in rel_path.split('/') {
1270        if seg.is_empty() || seg == "." {
1271            continue;
1272        }
1273        if seg == ".." {
1274            let _: Option<&str> = stack.pop();
1275        } else {
1276            stack.push(seg);
1277        }
1278    }
1279    if stack.is_empty() {
1280        ROOT_ROUTE_STR.to_string()
1281    } else {
1282        format!("/{}", stack.join("/"))
1283    }
1284}
1285
1286/// Returns `true` when `href` points to an external HTTP(S) origin.
1287///
1288/// # Arguments
1289///
1290/// - `&str` - Resolved href string.
1291///
1292/// # Returns
1293///
1294/// - `bool` - Whether the link should open in a new tab.
1295fn is_external_url(href: &str) -> bool {
1296    starts_with_ascii_ignore_case(href, SCHEME_HTTP)
1297        || starts_with_ascii_ignore_case(href, SCHEME_HTTPS)
1298}
1299
1300/// Builds a standard XML sitemap containing every generated page route in canonical order.
1301///
1302/// # Arguments
1303///
1304/// - `&[&DocPage]` - Ordered site pages.
1305/// - `&str` - Optional base URL prefix.
1306///
1307/// # Returns
1308///
1309/// - `String` - Complete `sitemap.xml` document.
1310fn build_sitemap_xml(pages: &[&DocPage], base_url: &str) -> String {
1311    let base: &str = base_url.trim_end_matches('/');
1312    let mut xml: String = String::with_capacity(SITEMAP_HEADER.len() + pages.len() * 64 + 16);
1313    xml.push_str(SITEMAP_HEADER);
1314    for page in pages.iter() {
1315        let loc: String = href_for_route(base, page.get_route());
1316        xml.push_str(SITEMAP_URL_OPEN);
1317        push_escaped_html(&mut xml, &loc);
1318        xml.push_str(SITEMAP_URL_CLOSE);
1319    }
1320    xml.push_str(SITEMAP_FOOTER);
1321    xml
1322}
1323
1324/// Copies recognized static asset directories and co-located media assets into `out_dir`.
1325///
1326/// # Arguments
1327///
1328/// - `&Path` - Source project or docs root directory.
1329/// - `&Path` - Output site directory.
1330///
1331/// # Returns
1332///
1333/// - `io::Result<()>` - Copy result.
1334fn copy_static_assets(src_root: &Path, out_dir: &Path) -> io::Result<()> {
1335    let canonical_out: PathBuf =
1336        fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
1337    for dir_name in ASSET_COPY_DIRS.iter() {
1338        let candidate: PathBuf = src_root.join(dir_name);
1339        if candidate.is_dir() {
1340            copy_dir_recursive(&candidate, &out_dir.join(dir_name), &canonical_out)?;
1341        }
1342    }
1343    copy_colocated_media(src_root, src_root, out_dir, &canonical_out)
1344}
1345
1346/// Recursively copies non-Markdown static asset files from `src` into `dst`.
1347///
1348/// # Arguments
1349///
1350/// - `&Path` - Source directory.
1351/// - `&Path` - Destination directory.
1352/// - `&Path` - Canonical output root skipped to avoid self-recursion.
1353///
1354/// # Returns
1355///
1356/// - `io::Result<()>` - Copy result.
1357fn copy_dir_recursive(src: &Path, dst: &Path, canonical_out: &Path) -> io::Result<()> {
1358    let src_canon: PathBuf = fs::canonicalize(src).unwrap_or_else(|_| src.to_path_buf());
1359    if src_canon == canonical_out || src_canon.starts_with(canonical_out) {
1360        return Ok(());
1361    }
1362    fs::create_dir_all(dst)?;
1363    for entry_res in fs::read_dir(src)? {
1364        let entry: DirEntry = entry_res?;
1365        let path: PathBuf = entry.path();
1366        let target: PathBuf = dst.join(entry.file_name());
1367        if path.is_dir() {
1368            copy_dir_recursive(&path, &target, canonical_out)?;
1369        } else if path
1370            .extension()
1371            .and_then(|s: &OsStr| s.to_str())
1372            .is_none_or(|ext: &str| !ext.eq_ignore_ascii_case(MARKDOWN_EXT_CHECK))
1373        {
1374            let _: u64 = fs::copy(&path, &target)?;
1375        }
1376    }
1377    Ok(())
1378}
1379
1380/// Recursively copies co-located media files alongside Markdown documents while skipping ignored dirs and `out_dir`.
1381///
1382/// # Arguments
1383///
1384/// - `&Path` - Original source root directory.
1385/// - `&Path` - Current directory being walked.
1386/// - `&Path` - Output site directory.
1387/// - `&Path` - Canonical output root skipped to avoid self-recursion.
1388///
1389/// # Returns
1390///
1391/// - `io::Result<()>` - Copy result.
1392fn copy_colocated_media(
1393    src_root: &Path,
1394    cur_dir: &Path,
1395    out_dir: &Path,
1396    canonical_out: &Path,
1397) -> io::Result<()> {
1398    for entry_res in fs::read_dir(cur_dir)? {
1399        let entry: DirEntry = entry_res?;
1400        let path: PathBuf = entry.path();
1401        if path.is_dir() {
1402            let name: String = entry.file_name().to_string_lossy().into_owned();
1403            if should_skip_dir(&name) {
1404                continue;
1405            }
1406            if cur_dir == src_root
1407                && ASSET_COPY_DIRS
1408                    .iter()
1409                    .any(|d: &&str| name.eq_ignore_ascii_case(d))
1410            {
1411                continue;
1412            }
1413            let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
1414            if canon == canonical_out || canon.starts_with(canonical_out) {
1415                continue;
1416            }
1417            copy_colocated_media(src_root, &path, out_dir, canonical_out)?;
1418        } else if path
1419            .extension()
1420            .and_then(|s: &OsStr| s.to_str())
1421            .is_some_and(|ext: &str| {
1422                CO_LOCATED_ASSET_EXTS
1423                    .iter()
1424                    .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
1425            })
1426            && let Ok(rel) = path.strip_prefix(src_root)
1427        {
1428            let target: PathBuf = out_dir.join(rel);
1429            if let Some(parent) = target.parent() {
1430                fs::create_dir_all(parent)?;
1431            }
1432            let _: u64 = fs::copy(&path, &target)?;
1433        }
1434    }
1435    Ok(())
1436}
1437
1438/// Formats a clean link href for `route` under `base`.
1439///
1440/// # Arguments
1441///
1442/// - `&str` - Normalized base URL without trailing slash.
1443/// - `&str` - Canonical route path.
1444///
1445/// # Returns
1446///
1447/// - `String` - Clean navigable href string.
1448fn href_for_route(base: &str, route: &str) -> String {
1449    let trimmed: &str = route.trim_matches('/');
1450    if trimmed.is_empty() {
1451        if base.is_empty() {
1452            ROOT_ROUTE_STR.to_string()
1453        } else {
1454            format!("{base}/")
1455        }
1456    } else if base.is_empty() {
1457        format!("/{trimmed}/")
1458    } else {
1459        format!("{base}/{trimmed}/")
1460    }
1461}
1462
1463/// Computes the filesystem output `.html` path for a canonical documentation route.
1464///
1465/// # Arguments
1466///
1467/// - `&Path` - Output root directory.
1468/// - `&str` - Canonical route path.
1469///
1470/// # Returns
1471///
1472/// - `PathBuf` - Destination `.html` file path.
1473fn 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(format!("{trimmed}{HTML_EXT}"))
1479    }
1480}
1481
1482/// Computes the clean directory-index `<route>/index.html` path for a canonical route.
1483///
1484/// # Arguments
1485///
1486/// - `&Path` - Output root directory.
1487/// - `&str` - Canonical route path.
1488///
1489/// # Returns
1490///
1491/// - `PathBuf` - Destination `<route>/index.html` path.
1492fn clean_html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1493    let trimmed: &str = route.trim_matches('/');
1494    if trimmed.is_empty() {
1495        out_dir.join(INDEX_HTML_NAME)
1496    } else {
1497        out_dir.join(trimmed).join(INDEX_HTML_NAME)
1498    }
1499}
1500
1501/// Renders a fenced code block with line numbers and exact VS Code Eva Light/Dark Bold syntax classes.
1502///
1503/// # Arguments
1504///
1505/// - `&str` - Language label from the fenced code info string.
1506/// - `&str` - Trimmed source code body.
1507/// - `&mut String` - HTML output buffer.
1508fn render_highlighted_code_html(language: &str, code: &str, out: &mut String) {
1509    render_highlighted_code_html_with_meta(language, None, &[], code, out);
1510}
1511
1512/// Renders a fenced code block with optional title/filename header, highlighted line tint, line numbers, and Eva Bold syntax classes.
1513///
1514/// # Arguments
1515///
1516/// - `&str` - Language label from the fenced code info string.
1517/// - `Option<&str>` - Optional title or filename displayed in the code header bar.
1518/// - `&[usize]` - Sorted 1-based highlighted line numbers.
1519/// - `&str` - Trimmed source code body.
1520/// - `&mut String` - HTML output buffer.
1521fn render_highlighted_code_html_with_meta(
1522    language: &str,
1523    title: Option<&str>,
1524    highlight_lines: &[usize],
1525    code: &str,
1526    out: &mut String,
1527) {
1528    let resolved_lang: CodeLang = CodeLang::from_name(language);
1529    out.push_str(HTML_CODE_WRAP_OPEN);
1530    if let Some(fname) = title {
1531        push_escaped_html(out, fname);
1532        out.push_str(" · ");
1533    }
1534    push_escaped_html(out, language);
1535    out.push_str(HTML_CODE_HEAD_MID);
1536    push_escaped_html(out, language);
1537    out.push_str(HTML_LINK_MID);
1538    for (idx, line) in code.split('\n').enumerate() {
1539        let line_no: usize = idx + 1;
1540        let is_hl: bool =
1541            !highlight_lines.is_empty() && highlight_lines.binary_search(&line_no).is_ok();
1542        if is_hl {
1543            out.push_str(HTML_CODE_LINE_HL_OPEN);
1544        } else {
1545            out.push_str(HTML_CODE_LINE_OPEN);
1546        }
1547        let _: fmt::Result = write!(out, "{line_no}");
1548        out.push_str(HTML_CODE_LINE_MID);
1549        let spans: Vec<CodeSpan> = tokenize_code_line_with_lang(line, resolved_lang);
1550        for span in spans.iter() {
1551            let class_opt: Option<&str> = match span.get_kind() {
1552                CodeTokenKind::Keyword => Some(TOK_CLASS_KW),
1553                CodeTokenKind::Control => Some(TOK_CLASS_CTRL),
1554                CodeTokenKind::Operator => Some(TOK_CLASS_OP),
1555                CodeTokenKind::Function => Some(TOK_CLASS_FN),
1556                CodeTokenKind::Type => Some(TOK_CLASS_TY),
1557                CodeTokenKind::PrimitiveType => Some(TOK_CLASS_PRIM),
1558                CodeTokenKind::String => Some(TOK_CLASS_STR),
1559                CodeTokenKind::Number => Some(TOK_CLASS_NUM),
1560                CodeTokenKind::Comment => Some(TOK_CLASS_CMT),
1561                CodeTokenKind::Macro => Some(TOK_CLASS_MAC),
1562                CodeTokenKind::Property => Some(TOK_CLASS_PROP),
1563                CodeTokenKind::Constant => Some(TOK_CLASS_CONST),
1564                CodeTokenKind::Punctuation => Some(TOK_CLASS_PUNC),
1565                CodeTokenKind::DiffAdd => Some(TOK_CLASS_ADD),
1566                CodeTokenKind::DiffDel => Some(TOK_CLASS_DEL),
1567                CodeTokenKind::Plain => None,
1568            };
1569            if let Some(cls) = class_opt {
1570                out.push_str(HTML_SPAN_CLASS_OPEN);
1571                out.push_str(cls);
1572                out.push_str(HTML_LINK_MID);
1573                push_escaped_html(out, span.get_text());
1574                out.push_str(HTML_SPAN_CLOSE);
1575            } else {
1576                push_escaped_html(out, span.get_text());
1577            }
1578        }
1579        out.push_str(HTML_CODE_LINE_CLOSE);
1580    }
1581    out.push_str(HTML_CODE_CLOSE);
1582}
1583
1584/// Renders an embedded `` ```echart `` / `` ```echarts `` Markdown fence into a themed zero-JS inline SVG chart card.
1585///
1586/// # Arguments
1587///
1588/// - `&str` - Raw chart JSON or key-value specification text.
1589/// - `&mut String` - Destination HTML output buffer.
1590fn render_echart_svg_html(source: &str, out: &mut String) {
1591    let opt: EuvChartOption = parse_markdown_echart_option(source);
1592    let title: &str = opt
1593        .title_opt()
1594        .map(|t: &EuvChartTitle| t.get_text().as_str())
1595        .filter(|s: &&str| !s.is_empty())
1596        .unwrap_or("Chart");
1597    out.push_str(ECHART_CARD_OPEN);
1598    push_escaped_html(out, title);
1599    out.push_str(MERMAID_CARD_MID);
1600    let labels: Vec<String> = opt
1601        .get_x_axes()
1602        .first()
1603        .map(|a: &EuvChartAxis| a.get_categories().clone())
1604        .unwrap_or_default();
1605    if let Some(first_ser) = opt.get_series().first()
1606        && let EuvChartSeriesData::Pie(pie) = first_ser.get_data()
1607    {
1608        let mut slices: Vec<MermaidPieSlice> = Vec::with_capacity(pie.get_slices().len());
1609        for s in pie.get_slices().iter() {
1610            slices.push(MermaidPieSlice::new(s.get_name().clone(), s.get_value()));
1611        }
1612        let mut chart: MermaidPieChart = MermaidPieChart::default();
1613        chart.set_title(title.to_string()).set_slices(slices);
1614        render_mermaid_pie_svg(&chart, out);
1615        out.push_str(MERMAID_CARD_CLOSE);
1616        return;
1617    }
1618    let mut xy: MermaidXyChart = MermaidXyChart::default();
1619    xy.set_title(title.to_string()).set_x_labels(labels);
1620    let mut series_vec: Vec<MermaidXySeries> = Vec::new();
1621    for ser in opt.get_series().iter() {
1622        match ser.get_data() {
1623            EuvChartSeriesData::Bar(bar) => {
1624                let vals: Vec<f32> = bar
1625                    .get_values()
1626                    .iter()
1627                    .map(|v: &Option<f32>| v.unwrap_or(0.0))
1628                    .collect();
1629                series_vec.push(MermaidXySeries::new(true, vals));
1630            }
1631            EuvChartSeriesData::Line(line) => {
1632                let vals: Vec<f32> = line
1633                    .get_values()
1634                    .iter()
1635                    .map(|v: &Option<f32>| v.unwrap_or(0.0))
1636                    .collect();
1637                series_vec.push(MermaidXySeries::new(false, vals));
1638            }
1639            _ => {}
1640        }
1641    }
1642    xy.set_series(series_vec);
1643    render_mermaid_xychart_svg(&xy, out);
1644    out.push_str(MERMAID_CARD_CLOSE);
1645}
1646
1647/// Appends HTML-escaped text directly into `out` via bulk slice copies with zero intermediate allocations.
1648///
1649/// # Arguments
1650///
1651/// - `&mut String` - Destination HTML buffer.
1652/// - `&str` - Raw UTF-8 input slice.
1653fn push_escaped_html(out: &mut String, input: &str) {
1654    let bytes: &[u8] = input.as_bytes();
1655    let mut start: usize = 0;
1656    for (idx, &byte) in bytes.iter().enumerate() {
1657        let esc: &str = match byte {
1658            BYTE_AMP => HTML_ESC_AMP,
1659            BYTE_LT => HTML_ESC_LT,
1660            BYTE_GT => HTML_ESC_GT,
1661            BYTE_DQUOTE => HTML_ESC_QUOT,
1662            _ => continue,
1663        };
1664        if start < idx {
1665            out.push_str(&input[start..idx]);
1666        }
1667        out.push_str(esc);
1668        start = idx + 1;
1669    }
1670    if start < bytes.len() {
1671        out.push_str(&input[start..]);
1672    }
1673}
1674
1675/// Escapes special HTML characters in text content.
1676///
1677/// # Arguments
1678///
1679/// - `&str` - Raw UTF-8 text.
1680///
1681/// # Returns
1682///
1683/// - `String` - Escaped HTML-safe string.
1684fn escape_html(input: &str) -> String {
1685    let mut out: String = String::with_capacity(input.len());
1686    push_escaped_html(&mut out, input);
1687    out
1688}
1689
1690/// Pushes a single HTML-escaped character into `out`.
1691///
1692/// # Arguments
1693///
1694/// - `char` - Source UTF-8 character.
1695/// - `&mut String` - Destination HTML buffer.
1696fn push_escaped_html_char(ch: char, out: &mut String) {
1697    match ch {
1698        '&' => out.push_str(HTML_ESC_AMP),
1699        '<' => out.push_str(HTML_ESC_LT),
1700        '>' => out.push_str(HTML_ESC_GT),
1701        '"' => out.push_str(HTML_ESC_QUOT),
1702        _ => out.push(ch),
1703    }
1704}
1705
1706/// Returns `true` when `bytes` contains any extended inline Markdown delimiter (`=`, `^`, `~`, `:`).
1707///
1708/// # Arguments
1709///
1710/// - `&[u8]` - Raw UTF-8 input bytes.
1711///
1712/// # Returns
1713///
1714/// - `bool` - `true` when extended inline parsing is required.
1715fn has_extended_inline_trigger(bytes: &[u8]) -> bool {
1716    for &byte in bytes.iter() {
1717        if byte == BYTE_EQ || byte == BYTE_CARET || byte == BYTE_TILDE || byte == BYTE_COLON {
1718            return true;
1719        }
1720    }
1721    false
1722}
1723
1724/// Renders extended inline Markdown syntax (`==mark==`, `^sup^`, `~sub~`, `:emoji:`) into XSS-safe HTML.
1725///
1726/// # Arguments
1727///
1728/// - `&str` - Raw inline Markdown text slice.
1729/// - `&mut String` - Destination HTML buffer.
1730fn render_extended_inline_text_html(raw: &str, out: &mut String) {
1731    let bytes: &[u8] = raw.as_bytes();
1732    if !has_extended_inline_trigger(bytes) {
1733        push_escaped_html(out, raw);
1734        return;
1735    }
1736    let len: usize = bytes.len();
1737    let mut i: usize = 0;
1738    while i < len {
1739        if i + 1 < len && bytes[i] == BYTE_EQ && bytes[i + 1] == BYTE_EQ {
1740            let rest: &str = &raw[i + 2..];
1741            if let Some(close_rel) = rest.find("==")
1742                && !rest[..close_rel].trim().is_empty()
1743            {
1744                out.push_str(HTML_MARK_OPEN);
1745                render_extended_inline_text_html(&rest[..close_rel], out);
1746                out.push_str(HTML_MARK_CLOSE);
1747                i += 2 + close_rel + 2;
1748                continue;
1749            }
1750        }
1751        if bytes[i] == BYTE_CARET {
1752            let rest: &str = &raw[i + 1..];
1753            if let Some(close_rel) = rest.find('^') {
1754                let inner: &str = &rest[..close_rel];
1755                if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
1756                    out.push_str(HTML_SUP_OPEN);
1757                    push_escaped_html(out, inner);
1758                    out.push_str(HTML_SUP_CLOSE);
1759                    i += 1 + close_rel + 1;
1760                    continue;
1761                }
1762            }
1763        }
1764        if bytes[i] == BYTE_TILDE && !(i + 1 < len && bytes[i + 1] == BYTE_TILDE) {
1765            let rest: &str = &raw[i + 1..];
1766            if let Some(close_rel) = rest.find('~') {
1767                let inner: &str = &rest[..close_rel];
1768                if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
1769                    out.push_str(HTML_SUB_OPEN);
1770                    push_escaped_html(out, inner);
1771                    out.push_str(HTML_SUB_CLOSE);
1772                    i += 1 + close_rel + 1;
1773                    continue;
1774                }
1775            }
1776        }
1777        if bytes[i] == BYTE_COLON {
1778            let rest: &str = &raw[i + 1..];
1779            if let Some(close_rel) = rest.find(':') {
1780                let code: &str = &rest[..close_rel];
1781                if !code.is_empty()
1782                    && code.len() <= 32
1783                    && code.bytes().all(|b: u8| {
1784                        b.is_ascii_alphanumeric() || b == BYTE_UNDERSCORE || b == BYTE_DASH
1785                    })
1786                    && let Some(emoji) = resolve_emoji_shortcode(code)
1787                {
1788                    out.push_str(emoji);
1789                    i += 1 + close_rel + 1;
1790                    continue;
1791                }
1792            }
1793        }
1794        if let Some(ch) = raw[i..].chars().next() {
1795            push_escaped_html_char(ch, out);
1796            i += ch.len_utf8();
1797        } else {
1798            break;
1799        }
1800    }
1801}
1802
1803/// Renders a fenced Mermaid diagram block into a zero-JS themed inline SVG card supporting all 11 Mermaid diagram families.
1804///
1805/// # Arguments
1806///
1807/// - `&str` - Raw Mermaid diagram source text.
1808/// - `&mut String` - Destination HTML output buffer.
1809fn render_mermaid_svg_html(source: &str, out: &mut String) {
1810    let diagram: MermaidDiagram = parse_mermaid_diagram(source);
1811    let badge: &str = match &diagram {
1812        MermaidDiagram::Flowchart(_) => MERMAID_BADGE_FLOWCHART,
1813        MermaidDiagram::Sequence(_) => MERMAID_BADGE_SEQUENCE,
1814        MermaidDiagram::State(_) => MERMAID_BADGE_STATE,
1815        MermaidDiagram::Class(_) => MERMAID_BADGE_CLASS,
1816        MermaidDiagram::Er(_) => MERMAID_BADGE_ER,
1817        MermaidDiagram::Pie(_) => MERMAID_BADGE_PIE,
1818        MermaidDiagram::Gantt(_) => MERMAID_BADGE_GANTT,
1819        MermaidDiagram::Timeline(_) => MERMAID_BADGE_TIMELINE,
1820        MermaidDiagram::Mindmap(_) => MERMAID_BADGE_MINDMAP,
1821        MermaidDiagram::XyChart(_) => MERMAID_BADGE_XYCHART,
1822        MermaidDiagram::GitGraph(_) => MERMAID_BADGE_GITGRAPH,
1823    };
1824    out.push_str(MERMAID_CARD_OPEN);
1825    out.push_str(badge);
1826    out.push_str(MERMAID_CARD_MID);
1827    match &diagram {
1828        MermaidDiagram::Flowchart(fc) | MermaidDiagram::State(fc) => {
1829            render_mermaid_flow_svg(fc, out);
1830        }
1831        MermaidDiagram::Sequence(seq) => {
1832            render_mermaid_sequence_svg(seq, out);
1833        }
1834        MermaidDiagram::Class(cls) => {
1835            render_mermaid_class_svg(cls, out);
1836        }
1837        MermaidDiagram::Er(er) => {
1838            render_mermaid_er_svg(er, out);
1839        }
1840        MermaidDiagram::Pie(pie) => {
1841            render_mermaid_pie_svg(pie, out);
1842        }
1843        MermaidDiagram::Gantt(gantt) => {
1844            render_mermaid_gantt_svg(gantt, out);
1845        }
1846        MermaidDiagram::Timeline(tl) => {
1847            render_mermaid_timeline_svg(tl, out);
1848        }
1849        MermaidDiagram::Mindmap(mm) => {
1850            render_mermaid_mindmap_svg(mm, out);
1851        }
1852        MermaidDiagram::XyChart(xy) => {
1853            render_mermaid_xychart_svg(xy, out);
1854        }
1855        MermaidDiagram::GitGraph(git) => {
1856            render_mermaid_gitgraph_svg(git, out);
1857        }
1858    }
1859    out.push_str(MERMAID_CARD_CLOSE);
1860}
1861
1862/// Runs 3-color DFS from `u` to collect acyclic forward edges for static Mermaid SVG layout.
1863///
1864/// # Arguments
1865///
1866/// - `usize` - Current node index.
1867/// - `&[Vec<usize>]` - Directed adjacency lists.
1868/// - `&mut [u8]` - Visitation state (`0` unvisited, `1` active stack, `2` done).
1869/// - `&mut Vec<(usize, usize)>` - Collected DAG edges.
1870fn dfs_svg_dag_edges(
1871    u: usize,
1872    adj: &[Vec<usize>],
1873    state: &mut [u8],
1874    dag_edges: &mut Vec<(usize, usize)>,
1875) {
1876    state[u] = 1;
1877    for &v in adj[u].iter() {
1878        if u == v || state[v] == 1 {
1879            continue;
1880        }
1881        dag_edges.push((u, v));
1882        if state[v] == 0 {
1883            dfs_svg_dag_edges(v, adj, state, dag_edges);
1884        }
1885    }
1886    state[u] = 2;
1887}
1888
1889/// Validates and escapes a Mermaid CSS color literal (`#hex` or safe alphanumeric name) for inline SVG attributes.
1890///
1891/// # Arguments
1892///
1893/// - `Option<&String>` - Optional CSS color string from `style` or `classDef`.
1894/// - `&str` - Fallback CSS color value.
1895///
1896/// # Returns
1897///
1898/// - `String` - Safe SVG fill/stroke/text color attribute string.
1899fn safe_svg_color(opt: Option<&String>, fallback: &str) -> String {
1900    if let Some(raw) = opt {
1901        let trimmed: &str = raw.trim();
1902        let valid: bool = !trimmed.is_empty()
1903            && trimmed.len() <= 32
1904            && trimmed
1905                .bytes()
1906                .all(|b: u8| b.is_ascii_alphanumeric() || b == BYTE_HASH || b == BYTE_DASH);
1907        if valid {
1908            return trimmed.to_string();
1909        }
1910    }
1911    fallback.to_string()
1912}
1913
1914/// Returns whether a Mermaid flowchart node belongs to subgraph `target_sg` directly or via ancestor subgraphs.
1915///
1916/// # Arguments
1917///
1918/// - `Option<usize>` - Node's direct enclosing subgraph index.
1919/// - `usize` - Candidate enclosing subgraph index.
1920/// - `&[MermaidSubgraph]` - All subgraphs in the flowchart.
1921///
1922/// # Returns
1923///
1924/// - `bool` - `true` when the node lies inside `target_sg`.
1925fn node_in_subgraph(
1926    mut cur: Option<usize>,
1927    target_sg: usize,
1928    subgraphs: &[MermaidSubgraph],
1929) -> bool {
1930    let mut hops: usize = 0;
1931    while let Some(idx) = cur {
1932        if idx == target_sg {
1933            return true;
1934        }
1935        hops += 1;
1936        if hops > subgraphs.len() {
1937            break;
1938        }
1939        cur = subgraphs
1940            .get(idx)
1941            .and_then(|sg: &MermaidSubgraph| sg.get_parent());
1942    }
1943    false
1944}
1945
1946/// Computes the nesting depth of a subgraph for layered padding and outer-to-inner rendering order.
1947///
1948/// # Arguments
1949///
1950/// - `usize` - Subgraph index.
1951/// - `&[MermaidSubgraph]` - All subgraphs in the flowchart.
1952///
1953/// # Returns
1954///
1955/// - `usize` - Nesting depth (`0` = top-level subgraph).
1956fn subgraph_depth(sg_idx: usize, subgraphs: &[MermaidSubgraph]) -> usize {
1957    let mut depth: usize = 0;
1958    let mut cur: Option<usize> = subgraphs
1959        .get(sg_idx)
1960        .and_then(|sg: &MermaidSubgraph| sg.get_parent());
1961    while let Some(parent_idx) = cur {
1962        depth += 1;
1963        if depth > subgraphs.len() {
1964            break;
1965        }
1966        cur = subgraphs
1967            .get(parent_idx)
1968            .and_then(|sg: &MermaidSubgraph| sg.get_parent());
1969    }
1970    depth
1971}
1972
1973/// Renders a Mermaid flowchart or state machine AST as a themed inline SVG supporting all 18 node shapes, nested subgraphs, custom styling, and all edge styles.
1974///
1975/// # Arguments
1976///
1977/// - `&MermaidFlowchart` - Parsed flowchart or state graph.
1978/// - `&mut String` - Destination HTML/SVG buffer.
1979fn render_mermaid_flow_svg(fc: &MermaidFlowchart, out: &mut String) {
1980    let n: usize = fc.get_nodes().len();
1981    if n == 0 {
1982        return;
1983    }
1984    let mut id_map: HashMap<&str, usize> = HashMap::with_capacity(n);
1985    for (idx, node) in fc.get_nodes().iter().enumerate() {
1986        let _: Option<usize> = id_map.insert(node.get_id().as_str(), idx);
1987    }
1988    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
1989    let mut in_deg: Vec<usize> = vec![0; n];
1990    for edge in fc.get_edges().iter() {
1991        if let (Some(&u), Some(&v)) = (
1992            id_map.get(edge.get_from().as_str()),
1993            id_map.get(edge.get_to().as_str()),
1994        ) && u != v
1995        {
1996            adj[u].push(v);
1997            in_deg[v] += 1;
1998        }
1999    }
2000    let mut visit_state: Vec<u8> = vec![0; n];
2001    let mut dag_edges: Vec<(usize, usize)> = Vec::with_capacity(fc.get_edges().len());
2002    for (idx, node) in fc.get_nodes().iter().enumerate() {
2003        if node.get_shape() == MermaidNodeShape::StateStart && visit_state[idx] == 0 {
2004            dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
2005        }
2006    }
2007    for (idx, node) in fc.get_nodes().iter().enumerate() {
2008        if in_deg[idx] == 0
2009            && node.get_shape() != MermaidNodeShape::StateEnd
2010            && visit_state[idx] == 0
2011        {
2012            dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
2013        }
2014    }
2015    for idx in 0..n {
2016        if visit_state[idx] == 0 {
2017            dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
2018        }
2019    }
2020    let mut layers: Vec<usize> = vec![0; n];
2021    for _ in 0..n {
2022        let mut changed: bool = false;
2023        for &(u, v) in dag_edges.iter() {
2024            if layers[v] <= layers[u] && layers[u] + 1 < n {
2025                layers[v] = layers[u] + 1;
2026                changed = true;
2027            }
2028        }
2029        if !changed {
2030            break;
2031        }
2032    }
2033    for edge in fc.get_edges().iter() {
2034        if let (Some(&u), Some(&v)) = (
2035            id_map.get(edge.get_from().as_str()),
2036            id_map.get(edge.get_to().as_str()),
2037        ) && u != v
2038            && fc.get_nodes()[v].get_shape() == MermaidNodeShape::StateEnd
2039            && layers[v] <= layers[u]
2040        {
2041            layers[v] = layers[u] + 1;
2042        }
2043    }
2044    let max_layer: usize = layers.iter().copied().max().unwrap_or(0);
2045    let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); max_layer + 1];
2046    for (idx, &lay) in layers.iter().enumerate() {
2047        buckets[lay].push(idx);
2048    }
2049    let horiz: bool = matches!(
2050        fc.get_direction(),
2051        MermaidFlowDirection::LeftRight | MermaidFlowDirection::RightLeft
2052    );
2053    let reversed: bool = matches!(
2054        fc.get_direction(),
2055        MermaidFlowDirection::RightLeft | MermaidFlowDirection::BottomTop
2056    );
2057    let node_sizes: Vec<(f32, f32)> = fc
2058        .get_nodes()
2059        .iter()
2060        .map(|node: &MermaidFlowNode| {
2061            let chars: f32 = node.get_label().chars().count() as f32;
2062            match node.get_shape() {
2063                MermaidNodeShape::StateStart | MermaidNodeShape::StateEnd => (24.0, 24.0),
2064                MermaidNodeShape::ForkJoin => {
2065                    if horiz {
2066                        (10.0, 64.0)
2067                    } else {
2068                        (88.0, 10.0)
2069                    }
2070                }
2071                MermaidNodeShape::Circle | MermaidNodeShape::DoubleCircle => {
2072                    let d: f32 = (chars * 7.6 + 28.0).clamp(54.0, 102.0);
2073                    (d, d)
2074                }
2075                MermaidNodeShape::Diamond => {
2076                    let w: f32 = (chars * 8.0 + 48.0).clamp(112.0, 204.0);
2077                    (w, 60.0)
2078                }
2079                MermaidNodeShape::Hexagon
2080                | MermaidNodeShape::Parallelogram
2081                | MermaidNodeShape::ParallelogramAlt
2082                | MermaidNodeShape::Trapezoid
2083                | MermaidNodeShape::TrapezoidAlt
2084                | MermaidNodeShape::Asymmetric => {
2085                    let w: f32 = (chars * 7.8 + 46.0).clamp(112.0, 224.0);
2086                    (w, 42.0)
2087                }
2088                MermaidNodeShape::Cylinder => {
2089                    let w: f32 = (chars * 7.6 + 38.0).clamp(104.0, 212.0);
2090                    (w, 48.0)
2091                }
2092                _ => {
2093                    let w: f32 = (chars * 7.6 + 36.0).clamp(96.0, 216.0);
2094                    (w, 40.0)
2095                }
2096            }
2097        })
2098        .collect();
2099    let has_sg: bool = !fc.get_subgraphs().is_empty();
2100    let pad: f32 = if has_sg { 44.0 } else { 28.0 };
2101    let main_gap: f32 = if horiz { 58.0 } else { 48.0 };
2102    let cross_gap: f32 = 28.0;
2103    let layer_count: usize = buckets.len();
2104    let mut layer_main: Vec<f32> = vec![0.0; layer_count];
2105    let mut layer_cross: Vec<f32> = vec![0.0; layer_count];
2106    for (li, items) in buckets.iter().enumerate() {
2107        let mut max_m: f32 = 0.0;
2108        let mut sum_c: f32 = 0.0;
2109        for (pos, &ni) in items.iter().enumerate() {
2110            let (nw, nh): (f32, f32) = node_sizes[ni];
2111            if horiz {
2112                max_m = max_m.max(nw);
2113                sum_c += nh;
2114            } else {
2115                max_m = max_m.max(nh);
2116                sum_c += nw;
2117            }
2118            if pos + 1 < items.len() {
2119                sum_c += cross_gap;
2120            }
2121        }
2122        layer_main[li] = max_m;
2123        layer_cross[li] = sum_c;
2124    }
2125    let total_main: f32 =
2126        layer_main.iter().sum::<f32>() + (layer_count.saturating_sub(1) as f32) * main_gap;
2127    let total_cross: f32 = layer_cross.iter().copied().fold(0.0_f32, f32::max);
2128    let mut rects: Vec<(f32, f32, f32, f32)> = vec![(0.0, 0.0, 0.0, 0.0); n];
2129    let mut main_cur: f32 = pad;
2130    let order: Vec<usize> = if reversed {
2131        (0..layer_count).rev().collect()
2132    } else {
2133        (0..layer_count).collect()
2134    };
2135    for li in order.into_iter() {
2136        let items: &[usize] = &buckets[li];
2137        let band_m: f32 = layer_main[li];
2138        let band_c: f32 = layer_cross[li];
2139        let mut cross_cur: f32 = pad + (total_cross - band_c) * 0.5;
2140        for &ni in items.iter() {
2141            let (nw, nh): (f32, f32) = node_sizes[ni];
2142            if horiz {
2143                rects[ni] = (main_cur + (band_m - nw) * 0.5, cross_cur, nw, nh);
2144                cross_cur += nh + cross_gap;
2145            } else {
2146                rects[ni] = (cross_cur, main_cur + (band_m - nh) * 0.5, nw, nh);
2147                cross_cur += nw + cross_gap;
2148            }
2149        }
2150        main_cur += band_m + main_gap;
2151    }
2152    let (svg_w, svg_h): (f32, f32) = if horiz {
2153        (
2154            (total_main + pad * 2.0).max(380.0),
2155            (total_cross + pad * 2.0).max(160.0),
2156        )
2157    } else {
2158        (
2159            (total_cross + pad * 2.0).max(380.0),
2160            (total_main + pad * 2.0).max(160.0),
2161        )
2162    };
2163    let _: fmt::Result = write!(
2164        out,
2165        "<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\">"
2166    );
2167    out.push_str(MERMAID_SVG_ARROW_MARKER);
2168    if has_sg {
2169        let mut sg_order: Vec<(usize, usize)> = (0..fc.get_subgraphs().len())
2170            .map(|i: usize| (subgraph_depth(i, fc.get_subgraphs()), i))
2171            .collect();
2172        sg_order.sort_by_key(|&(d, i): &(usize, usize)| (d, i));
2173        let max_depth: usize = sg_order
2174            .iter()
2175            .map(|&(d, _): &(usize, usize)| d)
2176            .max()
2177            .unwrap_or(0);
2178        for (depth, sg_idx) in sg_order.into_iter() {
2179            let mut min_x: f32 = f32::MAX;
2180            let mut min_y: f32 = f32::MAX;
2181            let mut max_x: f32 = f32::MIN;
2182            let mut max_y: f32 = f32::MIN;
2183            let mut found: bool = false;
2184            for (ni, node) in fc.get_nodes().iter().enumerate() {
2185                if node_in_subgraph(node.get_subgraph(), sg_idx, fc.get_subgraphs()) {
2186                    let (rx, ry, rw, rh): (f32, f32, f32, f32) = rects[ni];
2187                    min_x = min_x.min(rx);
2188                    min_y = min_y.min(ry);
2189                    max_x = max_x.max(rx + rw);
2190                    max_y = max_y.max(ry + rh);
2191                    found = true;
2192                }
2193            }
2194            if !found {
2195                continue;
2196            }
2197            let extra: f32 = ((max_depth - depth) as f32) * 10.0;
2198            let sx: f32 = (min_x - 14.0 - extra).max(4.0);
2199            let sy: f32 = (min_y - 26.0 - extra).max(4.0);
2200            let sw: f32 = (max_x - min_x + 28.0 + extra * 2.0).min(svg_w - sx - 4.0);
2201            let sh: f32 = (max_y - min_y + 40.0 + extra * 2.0).min(svg_h - sy - 4.0);
2202            let accent: &str = MERMAID_SVG_PALETTE[sg_idx % MERMAID_SVG_PALETTE.len()];
2203            let sg_title: &str = fc.get_subgraphs()[sg_idx].get_title().as_str();
2204            let _: fmt::Result = write!(
2205                out,
2206                "<rect x=\"{sx:.1}\" y=\"{sy:.1}\" width=\"{sw:.1}\" height=\"{sh:.1}\" rx=\"8\" fill=\"var(--muted)\" fill-opacity=\"0.42\" stroke=\"{accent}\" stroke-width=\"1.3\" stroke-dasharray=\"5 3\"/><text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" font-weight=\"700\" fill=\"{accent}\">",
2207                sx + 10.0,
2208                sy + 15.0
2209            );
2210            push_escaped_html(out, sg_title);
2211            out.push_str(SVG_TEXT_CLOSE);
2212        }
2213    }
2214    for edge in fc.get_edges().iter() {
2215        if let (Some(&u), Some(&v)) = (
2216            id_map.get(edge.get_from().as_str()),
2217            id_map.get(edge.get_to().as_str()),
2218        ) {
2219            let (ux, uy, uw, uh): (f32, f32, f32, f32) = rects[u];
2220            let (vx, vy, vw, vh): (f32, f32, f32, f32) = rects[v];
2221            let (x1, y1, x2, y2): (f32, f32, f32, f32) = if horiz {
2222                let sx: f32 = if vx >= ux { ux + uw } else { ux };
2223                let tx: f32 = if vx >= ux { vx } else { vx + vw };
2224                (sx, uy + uh * 0.5, tx, vy + vh * 0.5)
2225            } else {
2226                let sy: f32 = if vy >= uy { uy + uh } else { uy };
2227                let ty: f32 = if vy >= uy { vy } else { vy + vh };
2228                (ux + uw * 0.5, sy, vx + vw * 0.5, ty)
2229            };
2230            let style: MermaidEdgeStyle = edge.get_style();
2231            let dash: &str = match style {
2232                MermaidEdgeStyle::Dashed
2233                | MermaidEdgeStyle::DashedPlain
2234                | MermaidEdgeStyle::DashedBidir
2235                | MermaidEdgeStyle::DashedOpenArrow
2236                | MermaidEdgeStyle::DashedAsyncArrow
2237                | MermaidEdgeStyle::DashedCrossArrow => MERMAID_SVG_DASH_ATTR,
2238                _ => "",
2239            };
2240            let sw: f32 = match style {
2241                MermaidEdgeStyle::Thick
2242                | MermaidEdgeStyle::ThickPlain
2243                | MermaidEdgeStyle::ThickBidir => 2.6,
2244                _ => 1.6,
2245            };
2246            let marker_start: &str = match style {
2247                MermaidEdgeStyle::Bidir
2248                | MermaidEdgeStyle::DashedBidir
2249                | MermaidEdgeStyle::ThickBidir => MERMAID_SVG_MARKER_START_ATTR,
2250                MermaidEdgeStyle::CircleBoth => MERMAID_SVG_MARKER_CIRCLE_START,
2251                MermaidEdgeStyle::CrossBoth => MERMAID_SVG_MARKER_CROSS_START,
2252                _ => "",
2253            };
2254            let marker_end: &str = match style {
2255                MermaidEdgeStyle::Plain
2256                | MermaidEdgeStyle::DashedPlain
2257                | MermaidEdgeStyle::ThickPlain => "",
2258                MermaidEdgeStyle::CircleEnd | MermaidEdgeStyle::CircleBoth => {
2259                    MERMAID_SVG_MARKER_CIRCLE_END
2260                }
2261                MermaidEdgeStyle::CrossEnd
2262                | MermaidEdgeStyle::CrossBoth
2263                | MermaidEdgeStyle::CrossArrow
2264                | MermaidEdgeStyle::DashedCrossArrow => MERMAID_SVG_MARKER_CROSS_END,
2265                _ => MERMAID_SVG_MARKER_ATTR,
2266            };
2267            let _: fmt::Result = write!(
2268                out,
2269                "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"{sw:.1}\"{dash}{marker_start}{marker_end}/>"
2270            );
2271            let lbl: &str = edge.get_label().trim();
2272            if !lbl.is_empty() {
2273                let mx: f32 = (x1 + x2) * 0.5;
2274                let my: f32 = (y1 + y2) * 0.5;
2275                let bw: f32 = ((lbl.chars().count() as f32) * 6.8 + 12.0).max(28.0);
2276                let bx: f32 = mx - bw * 0.5;
2277                let by: f32 = my - 10.0;
2278                let _: fmt::Result = write!(
2279                    out,
2280                    "<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)\">",
2281                    my + 4.0
2282                );
2283                push_escaped_html(out, lbl);
2284                out.push_str(SVG_TEXT_CLOSE);
2285            }
2286        }
2287    }
2288    for (idx, node) in fc.get_nodes().iter().enumerate() {
2289        let (rx, ry, rw, rh): (f32, f32, f32, f32) = rects[idx];
2290        let cx: f32 = rx + rw * 0.5;
2291        let cy: f32 = ry + rh * 0.5;
2292        let default_accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2293        let fill: String = safe_svg_color(node.try_get_fill().as_ref(), MERMAID_SVG_VAR_MUTED);
2294        let stroke: String = safe_svg_color(node.try_get_stroke().as_ref(), default_accent);
2295        let text_col: String =
2296            safe_svg_color(node.try_get_text_color().as_ref(), MERMAID_SVG_VAR_FG);
2297        match node.get_shape() {
2298            MermaidNodeShape::StateStart => {
2299                let _: fmt::Result = write!(
2300                    out,
2301                    "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"9\" fill=\"var(--fg)\"/>"
2302                );
2303            }
2304            MermaidNodeShape::StateEnd => {
2305                let _: fmt::Result = write!(
2306                    out,
2307                    "<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)\"/>"
2308                );
2309            }
2310            MermaidNodeShape::ForkJoin => {
2311                let _: fmt::Result = write!(
2312                    out,
2313                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"4\" fill=\"var(--fg)\"/>"
2314                );
2315            }
2316            MermaidNodeShape::Diamond => {
2317                let _: fmt::Result = write!(
2318                    out,
2319                    "<polygon points=\"{cx:.1},{ry:.1} {:.1},{cy:.1} {cx:.1},{:.1} {rx:.1},{cy:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2320                    rx + rw,
2321                    ry + rh
2322                );
2323            }
2324            MermaidNodeShape::Hexagon => {
2325                let ins: f32 = 14.0;
2326                let _: fmt::Result = write!(
2327                    out,
2328                    "<polygon points=\"{:.1},{ry:.1} {:.1},{ry:.1} {:.1},{cy:.1} {:.1},{:.1} {:.1},{:.1} {rx:.1},{cy:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2329                    rx + ins,
2330                    rx + rw - ins,
2331                    rx + rw,
2332                    rx + rw - ins,
2333                    ry + rh,
2334                    rx + ins,
2335                    ry + rh
2336                );
2337            }
2338            MermaidNodeShape::Parallelogram => {
2339                let skew: f32 = 14.0;
2340                let _: fmt::Result = write!(
2341                    out,
2342                    "<polygon points=\"{:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {rx:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2343                    rx + skew,
2344                    rx + rw,
2345                    rx + rw - skew,
2346                    ry + rh,
2347                    ry + rh
2348                );
2349            }
2350            MermaidNodeShape::ParallelogramAlt => {
2351                let skew: f32 = 14.0;
2352                let _: fmt::Result = write!(
2353                    out,
2354                    "<polygon points=\"{rx:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2355                    rx + rw - skew,
2356                    rx + rw,
2357                    ry + rh,
2358                    rx + skew,
2359                    ry + rh
2360                );
2361            }
2362            MermaidNodeShape::Trapezoid => {
2363                let ins: f32 = 14.0;
2364                let _: fmt::Result = write!(
2365                    out,
2366                    "<polygon points=\"{:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {rx:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2367                    rx + ins,
2368                    rx + rw - ins,
2369                    rx + rw,
2370                    ry + rh,
2371                    ry + rh
2372                );
2373            }
2374            MermaidNodeShape::TrapezoidAlt => {
2375                let ins: f32 = 14.0;
2376                let _: fmt::Result = write!(
2377                    out,
2378                    "<polygon points=\"{rx:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2379                    rx + rw,
2380                    rx + rw - ins,
2381                    ry + rh,
2382                    rx + ins,
2383                    ry + rh
2384                );
2385            }
2386            MermaidNodeShape::Asymmetric => {
2387                let notch: f32 = 12.0;
2388                let _: fmt::Result = write!(
2389                    out,
2390                    "<polygon points=\"{rx:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {rx:.1},{:.1} {:.1},{cy:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2391                    rx + rw,
2392                    rx + rw,
2393                    ry + rh,
2394                    ry + rh,
2395                    rx + notch
2396                );
2397            }
2398            MermaidNodeShape::Circle => {
2399                let r: f32 = rw.min(rh) * 0.5;
2400                let _: fmt::Result = write!(
2401                    out,
2402                    "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2403                );
2404            }
2405            MermaidNodeShape::DoubleCircle => {
2406                let r: f32 = rw.min(rh) * 0.5;
2407                let r_in: f32 = (r - 4.5).max(4.0);
2408                let _: fmt::Result = write!(
2409                    out,
2410                    "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/><circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r_in:.1}\" fill=\"none\" stroke=\"{stroke}\" stroke-width=\"1.4\"/>"
2411                );
2412            }
2413            MermaidNodeShape::Subroutine => {
2414                let _: fmt::Result = write!(
2415                    out,
2416                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"4\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/><line x1=\"{:.1}\" y1=\"{ry:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" stroke=\"{stroke}\" stroke-width=\"1.4\"/><line x1=\"{:.1}\" y1=\"{ry:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" stroke=\"{stroke}\" stroke-width=\"1.4\"/>",
2417                    rx + 9.0,
2418                    rx + 9.0,
2419                    ry + rh,
2420                    rx + rw - 9.0,
2421                    rx + rw - 9.0,
2422                    ry + rh
2423                );
2424            }
2425            MermaidNodeShape::Cylinder => {
2426                let rx_e: f32 = rw * 0.5;
2427                let ry_e: f32 = 7.0;
2428                let body_y: f32 = ry + ry_e;
2429                let body_h: f32 = (rh - ry_e * 2.0).max(12.0);
2430                let bot_y: f32 = body_y + body_h;
2431                let _: fmt::Result = write!(
2432                    out,
2433                    "<path d=\"M {rx:.1} {body_y:.1} L {rx:.1} {bot_y:.1} A {rx_e:.1} {ry_e:.1} 0 0 0 {:.1} {bot_y:.1} L {:.1} {body_y:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/><ellipse cx=\"{cx:.1}\" cy=\"{body_y:.1}\" rx=\"{rx_e:.1}\" ry=\"{ry_e:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2434                    rx + rw,
2435                    rx + rw
2436                );
2437            }
2438            MermaidNodeShape::Stadium => {
2439                let rad: f32 = rh * 0.5;
2440                let _: fmt::Result = write!(
2441                    out,
2442                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"{rad:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2443                );
2444            }
2445            MermaidNodeShape::Rounded => {
2446                let _: fmt::Result = write!(
2447                    out,
2448                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"10\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2449                );
2450            }
2451            MermaidNodeShape::Note => {
2452                let _: fmt::Result = write!(
2453                    out,
2454                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"5\" fill=\"{fill}\" stroke=\"var(--warn)\" stroke-width=\"1.5\" stroke-dasharray=\"4 2\"/>"
2455                );
2456            }
2457            MermaidNodeShape::Box => {
2458                let _: fmt::Result = write!(
2459                    out,
2460                    "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"5\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2461                );
2462            }
2463        }
2464        let lbl: &str = node.get_label().trim();
2465        if !lbl.is_empty() && !matches!(node.get_shape(), MermaidNodeShape::ForkJoin) {
2466            let _: fmt::Result = write!(
2467                out,
2468                "<text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"600\" fill=\"{text_col}\">",
2469                cy + 4.0
2470            );
2471            push_escaped_html(out, lbl);
2472            out.push_str(SVG_TEXT_CLOSE);
2473        }
2474    }
2475    out.push_str(MERMAID_SVG_CLOSE);
2476}
2477
2478/// Renders a Mermaid `sequenceDiagram` AST as a themed inline SVG supporting actors, autonumbering, activations, notes, and nested control blocks.
2479///
2480/// # Arguments
2481///
2482/// - `&MermaidSequence` - Parsed sequence diagram.
2483/// - `&mut String` - Destination HTML/SVG buffer.
2484fn render_mermaid_sequence_svg(seq: &MermaidSequence, out: &mut String) {
2485    let p_count: usize = seq.get_participants().len();
2486    if p_count == 0 {
2487        return;
2488    }
2489    let col_w: f32 = 176.0;
2490    let pad: f32 = 28.0;
2491    let box_w: f32 = 132.0;
2492    let box_h: f32 = 38.0;
2493    let row_h: f32 = 44.0;
2494    let msg_count: usize = seq.get_messages().len();
2495    let svg_w: f32 = ((p_count as f32) * col_w + pad * 2.0).max(400.0);
2496    let top_y: f32 = pad;
2497    let life_top: f32 = top_y + box_h;
2498    let life_bot: f32 = life_top + 28.0 + (msg_count as f32) * row_h + 22.0;
2499    let svg_h: f32 = life_bot + box_h + pad;
2500    let _: fmt::Result = write!(
2501        out,
2502        "<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\">"
2503    );
2504    out.push_str(MERMAID_SVG_ARROW_MARKER);
2505    let mut centers: Vec<f32> = Vec::with_capacity(p_count);
2506    for (idx, (_, label)) in seq.get_participants().iter().enumerate() {
2507        let cx: f32 = pad + (idx as f32) * col_w + col_w * 0.5;
2508        centers.push(cx);
2509        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2510        let is_actor: bool = seq.get_actor_flags().get(idx).copied().unwrap_or(false);
2511        let _: fmt::Result = write!(
2512            out,
2513            "<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\"/>"
2514        );
2515        for by in [top_y, life_bot].into_iter() {
2516            if is_actor {
2517                let head_y: f32 = by + 8.0;
2518                let _: fmt::Result = write!(
2519                    out,
2520                    "<circle cx=\"{cx:.1}\" cy=\"{head_y:.1}\" r=\"5\" fill=\"none\" stroke=\"{accent}\" stroke-width=\"1.6\"/><path d=\"M {cx:.1} {:.1} L {cx:.1} {:.1} M {:.1} {:.1} L {:.1} {:.1} M {cx:.1} {:.1} L {:.1} {:.1} M {cx:.1} {:.1} L {:.1} {:.1}\" stroke=\"{accent}\" stroke-width=\"1.5\" fill=\"none\"/><text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11.5\" font-weight=\"600\" fill=\"var(--fg)\">",
2521                    head_y + 5.0,
2522                    head_y + 15.0,
2523                    cx - 8.0,
2524                    head_y + 9.0,
2525                    cx + 8.0,
2526                    head_y + 9.0,
2527                    head_y + 15.0,
2528                    cx - 6.0,
2529                    head_y + 22.0,
2530                    head_y + 15.0,
2531                    cx + 6.0,
2532                    head_y + 22.0,
2533                    by + 36.0
2534                );
2535                push_escaped_html(out, label);
2536                out.push_str(SVG_TEXT_CLOSE);
2537            } else {
2538                let bx: f32 = cx - box_w * 0.5;
2539                let _: fmt::Result = write!(
2540                    out,
2541                    "<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)\">",
2542                    by + 23.0
2543                );
2544                push_escaped_html(out, label);
2545                out.push_str(SVG_TEXT_CLOSE);
2546            }
2547        }
2548    }
2549    for blk in seq.get_blocks().iter() {
2550        let inset: f32 = 12.0 + (blk.get_depth() as f32) * 8.0;
2551        let bx: f32 = inset;
2552        let bw: f32 = (svg_w - inset * 2.0).max(80.0);
2553        let by: f32 = life_top + 12.0 + (blk.get_start_row() as f32) * row_h;
2554        let bh: f32 =
2555            ((blk.get_end_row().saturating_sub(blk.get_start_row()) + 1) as f32) * row_h + 16.0;
2556        let kw: &str = match blk.get_kind() {
2557            MermaidSeqBlockKind::Loop => "loop",
2558            MermaidSeqBlockKind::Alt => "alt",
2559            MermaidSeqBlockKind::Opt => "opt",
2560            MermaidSeqBlockKind::Par => "par",
2561            MermaidSeqBlockKind::Critical => "critical",
2562            MermaidSeqBlockKind::Break => "break",
2563            MermaidSeqBlockKind::Rect => "rect",
2564        };
2565        let _: fmt::Result = write!(
2566            out,
2567            "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{bw:.1}\" height=\"{bh:.1}\" rx=\"6\" fill=\"var(--muted)\" fill-opacity=\"0.28\" stroke=\"var(--important)\" stroke-width=\"1.2\" stroke-dasharray=\"4 3\"/><rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"58\" height=\"18\" rx=\"4\" fill=\"var(--important)\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10\" font-weight=\"700\" fill=\"#ffffff\">{kw}</text>",
2568            bx + 29.0,
2569            by + 12.5
2570        );
2571        if !blk.get_label().is_empty() {
2572            let _: fmt::Result = write!(
2573                out,
2574                "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"10.5\" font-weight=\"600\" fill=\"var(--muted-fg)\">[",
2575                bx + 66.0,
2576                by + 13.0
2577            );
2578            push_escaped_html(out, blk.get_label());
2579            out.push_str(SVG_BRACKET_TEXT_CLOSE);
2580        }
2581        for div in blk.get_dividers().iter() {
2582            let dy: f32 = life_top + 14.0 + (div.get_row_idx() as f32) * row_h;
2583            let _: fmt::Result = write!(
2584                out,
2585                "<line x1=\"{bx:.1}\" y1=\"{dy:.1}\" x2=\"{:.1}\" y2=\"{dy:.1}\" stroke=\"var(--important)\" stroke-width=\"1\" stroke-dasharray=\"4 3\"/>",
2586                bx + bw
2587            );
2588            if !div.get_label().is_empty() {
2589                let _: fmt::Result = write!(
2590                    out,
2591                    "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"10\" fill=\"var(--muted-fg)\">[",
2592                    bx + 10.0,
2593                    dy + 12.0
2594                );
2595                push_escaped_html(out, div.get_label());
2596                out.push_str(SVG_BRACKET_TEXT_CLOSE);
2597            }
2598        }
2599    }
2600    for act in seq.get_activations().iter() {
2601        if let Some(&cx) = centers.get(act.get_participant_idx()) {
2602            let ay: f32 = life_top + 24.0 + (act.get_start_row() as f32) * row_h;
2603            let ah: f32 =
2604                ((act.get_end_row().saturating_sub(act.get_start_row()) + 1) as f32) * row_h;
2605            let _: fmt::Result = write!(
2606                out,
2607                "<rect x=\"{:.1}\" y=\"{ay:.1}\" width=\"10\" height=\"{ah:.1}\" rx=\"2\" fill=\"var(--link)\" fill-opacity=\"0.35\" stroke=\"var(--link)\" stroke-width=\"1.2\"/>",
2608                cx - 5.0
2609            );
2610        }
2611    }
2612    let mut seq_num: usize = 0;
2613    for (idx, msg) in seq.get_messages().iter().enumerate() {
2614        let y: f32 = life_top + 32.0 + (idx as f32) * row_h;
2615        let x1: f32 = centers.get(msg.get_from_idx()).copied().unwrap_or(pad);
2616        let x2: f32 = centers.get(msg.get_to_idx()).copied().unwrap_or(pad);
2617        if msg.get_is_note() {
2618            let nw: f32 = ((msg.get_text().chars().count() as f32) * 7.2 + 28.0)
2619                .max((x2 - x1).abs() + 72.0)
2620                .clamp(112.0, svg_w - 24.0);
2621            let nx: f32 = match msg.get_note_placement() {
2622                MermaidSeqNotePlacement::LeftOf => (x1 - nw - 12.0).max(8.0),
2623                MermaidSeqNotePlacement::RightOf => (x1 + 12.0).min(svg_w - nw - 8.0),
2624                MermaidSeqNotePlacement::Over => {
2625                    ((x1 + x2) * 0.5 - nw * 0.5).clamp(8.0, svg_w - nw - 8.0)
2626                }
2627            };
2628            let _: fmt::Result = write!(
2629                out,
2630                "<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)\">",
2631                y - 13.0,
2632                nx + nw * 0.5,
2633                y + 4.0
2634            );
2635            push_escaped_html(out, msg.get_text());
2636            out.push_str(SVG_TEXT_CLOSE);
2637        } else {
2638            seq_num += 1;
2639            let style: MermaidEdgeStyle = msg.get_style();
2640            let dash: &str = match style {
2641                MermaidEdgeStyle::Dashed
2642                | MermaidEdgeStyle::DashedOpenArrow
2643                | MermaidEdgeStyle::DashedAsyncArrow
2644                | MermaidEdgeStyle::DashedCrossArrow => MERMAID_SVG_DASH_ATTR,
2645                _ => "",
2646            };
2647            let marker: &str = match style {
2648                MermaidEdgeStyle::CrossArrow | MermaidEdgeStyle::DashedCrossArrow => {
2649                    MERMAID_SVG_MARKER_CROSS_END
2650                }
2651                MermaidEdgeStyle::OpenArrow | MermaidEdgeStyle::DashedOpenArrow => "",
2652                _ => MERMAID_SVG_MARKER_ATTR,
2653            };
2654            if msg.get_from_idx() == msg.get_to_idx() {
2655                let loop_w: f32 = 34.0;
2656                let _: fmt::Result = write!(
2657                    out,
2658                    "<path d=\"M {x1:.1} {:.1} L {:.1} {:.1} L {:.1} {:.1} L {x1:.1} {:.1}\" fill=\"none\" stroke=\"var(--muted-fg)\" stroke-width=\"1.6\"{dash}{marker}/><text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11.5\" font-weight=\"500\" fill=\"var(--fg)\">",
2659                    y - 8.0,
2660                    x1 + loop_w,
2661                    y - 8.0,
2662                    x1 + loop_w,
2663                    y + 10.0,
2664                    y + 10.0,
2665                    x1 + loop_w + 6.0,
2666                    y + 3.0
2667                );
2668            } else {
2669                let _: fmt::Result = write!(
2670                    out,
2671                    "<line x1=\"{x1:.1}\" y1=\"{y:.1}\" x2=\"{x2:.1}\" y2=\"{y:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.6\"{dash}{marker}/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11.5\" font-weight=\"500\" fill=\"var(--fg)\">",
2672                    (x1 + x2) * 0.5,
2673                    y - 7.0
2674                );
2675            }
2676            if seq.get_autonumber() {
2677                let _: fmt::Result = write!(out, "{seq_num}. ");
2678            }
2679            push_escaped_html(out, msg.get_text());
2680            out.push_str(SVG_TEXT_CLOSE);
2681        }
2682    }
2683    out.push_str(MERMAID_SVG_CLOSE);
2684}
2685
2686/// Renders a Mermaid `classDiagram` AST as a themed inline SVG with stereotypes and UML relationship markers.
2687///
2688/// # Arguments
2689///
2690/// - `&MermaidClassDiagram` - Parsed class diagram.
2691/// - `&mut String` - Destination HTML/SVG buffer.
2692fn render_mermaid_class_svg(cls: &MermaidClassDiagram, out: &mut String) {
2693    let count: usize = cls.get_classes().len();
2694    if count == 0 {
2695        return;
2696    }
2697    let pad: f32 = 24.0;
2698    let gap: f32 = 44.0;
2699    let box_w: f32 = 188.0;
2700    let mut max_h: f32 = 68.0;
2701    for c in cls.get_classes().iter() {
2702        let extra: f32 = if c.get_stereotype().is_empty() {
2703            0.0
2704        } else {
2705            16.0
2706        };
2707        let h: f32 = 34.0 + extra + (c.get_members().len() as f32) * 18.0 + 12.0;
2708        max_h = max_h.max(h);
2709    }
2710    let svg_w: f32 = pad * 2.0 + (count as f32) * box_w + (count.saturating_sub(1) as f32) * gap;
2711    let svg_h: f32 = pad * 2.0 + max_h + 28.0;
2712    let _: fmt::Result = write!(
2713        out,
2714        "<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\">"
2715    );
2716    out.push_str(MERMAID_SVG_ARROW_MARKER);
2717    let mut pos_map: HashMap<&str, (f32, f32, f32)> = HashMap::with_capacity(count);
2718    for (idx, c) in cls.get_classes().iter().enumerate() {
2719        let x: f32 = pad + (idx as f32) * (box_w + gap);
2720        let has_stereo: bool = !c.get_stereotype().is_empty();
2721        let header_h: f32 = if has_stereo { 46.0 } else { 30.0 };
2722        let h: f32 = header_h + (c.get_members().len() as f32) * 18.0 + 16.0;
2723        let _: Option<(f32, f32, f32)> = pos_map.insert(c.get_name().as_str(), (x, pad, h));
2724        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2725        let _: fmt::Result = write!(
2726            out,
2727            "<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\"/>",
2728            pad + header_h,
2729            x + box_w,
2730            pad + header_h
2731        );
2732        if has_stereo {
2733            let _: fmt::Result = write!(
2734                out,
2735                "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10\" font-style=\"italic\" fill=\"{accent}\">&lt;&lt;",
2736                x + box_w * 0.5,
2737                pad + 15.0
2738            );
2739            push_escaped_html(out, c.get_stereotype());
2740            out.push_str("&gt;&gt;</text>");
2741        }
2742        let name_y: f32 = if has_stereo { pad + 34.0 } else { pad + 20.0 };
2743        let _: fmt::Result = write!(
2744            out,
2745            "<text x=\"{:.1}\" y=\"{name_y:.1}\" text-anchor=\"middle\" font-size=\"12.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2746            x + box_w * 0.5
2747        );
2748        push_escaped_html(out, c.get_name());
2749        out.push_str(SVG_TEXT_CLOSE);
2750        for (mi, mem) in c.get_members().iter().enumerate() {
2751            let _: fmt::Result = write!(
2752                out,
2753                "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" fill=\"var(--muted-fg)\">",
2754                x + 10.0,
2755                pad + header_h + 18.0 + (mi as f32) * 18.0
2756            );
2757            push_escaped_html(out, mem);
2758            out.push_str(SVG_TEXT_CLOSE);
2759        }
2760    }
2761    for rel in cls.get_relations().iter() {
2762        if let (Some(&(x1, y1, h1)), Some(&(x2, y2, h2))) = (
2763            pos_map.get(rel.get_from().as_str()),
2764            pos_map.get(rel.get_to().as_str()),
2765        ) {
2766            let sx: f32 = if x2 >= x1 { x1 + box_w } else { x1 };
2767            let tx: f32 = if x2 >= x1 { x2 } else { x2 + box_w };
2768            let sy: f32 = y1 + h1 * 0.5;
2769            let ty: f32 = y2 + h2 * 0.5;
2770            let dash: &str = match rel.get_style() {
2771                MermaidEdgeStyle::Dashed | MermaidEdgeStyle::DashedPlain => MERMAID_SVG_DASH_ATTR,
2772                _ => "",
2773            };
2774            let (m_start, m_end): (&str, &str) = match rel.get_rel_kind() {
2775                MermaidClassRelKind::Inheritance | MermaidClassRelKind::Realization => {
2776                    ("", MERMAID_SVG_MARKER_INHERIT_END)
2777                }
2778                MermaidClassRelKind::Composition => (MERMAID_SVG_MARKER_COMP_START, ""),
2779                MermaidClassRelKind::Aggregation => (MERMAID_SVG_MARKER_AGGR_START, ""),
2780                MermaidClassRelKind::Link => ("", ""),
2781                MermaidClassRelKind::Association | MermaidClassRelKind::Dependency => {
2782                    ("", MERMAID_SVG_MARKER_ATTR)
2783                }
2784            };
2785            let _: fmt::Result = write!(
2786                out,
2787                "<line x1=\"{sx:.1}\" y1=\"{sy:.1}\" x2=\"{tx:.1}\" y2=\"{ty:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\"{dash}{m_start}{m_end}/>"
2788            );
2789            if !rel.get_label().is_empty() {
2790                let _: fmt::Result = write!(
2791                    out,
2792                    "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
2793                    (sx + tx) * 0.5,
2794                    (sy + ty) * 0.5 - 6.0
2795                );
2796                push_escaped_html(out, rel.get_label());
2797                out.push_str(SVG_TEXT_CLOSE);
2798            }
2799        }
2800    }
2801    out.push_str(MERMAID_SVG_CLOSE);
2802}
2803
2804/// Renders an ER crow's-foot cardinality glyph at endpoint `(ex, ey)` pointing inward along `dir_x`.
2805///
2806/// # Arguments
2807///
2808/// - `&str` - Cardinality token (e.g. `"||"`, `"o{"`, `"|{"`, `"o|"`).
2809/// - `f32` - Endpoint X coordinate adjacent to the entity edge.
2810/// - `f32` - Endpoint Y coordinate.
2811/// - `f32` - Unit horizontal direction toward the middle of the connector (`1.0` or `-1.0`).
2812/// - `&mut String` - Destination SVG buffer.
2813fn render_er_card_svg(card: &str, ex: f32, ey: f32, dir_x: f32, out: &mut String) {
2814    let inner_x: f32 = ex + dir_x * 11.0;
2815    if card.contains('{') || card.contains('}') {
2816        let _: fmt::Result = write!(
2817            out,
2818            "<path d=\"M {inner_x:.1} {ey:.1} L {ex:.1} {:.1} M {inner_x:.1} {ey:.1} L {ex:.1} {:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.4\" fill=\"none\"/>",
2819            ey - 6.0,
2820            ey + 6.0
2821        );
2822    }
2823    if card.contains('o') {
2824        let _: fmt::Result = write!(
2825            out,
2826            "<circle cx=\"{:.1}\" cy=\"{ey:.1}\" r=\"3.5\" fill=\"var(--card)\" stroke=\"var(--muted-fg)\" stroke-width=\"1.4\"/>",
2827            ex + dir_x * 13.0
2828        );
2829    }
2830    if card.contains('|') {
2831        let bar_x: f32 = ex + dir_x * 6.0;
2832        let _: fmt::Result = write!(
2833            out,
2834            "<line x1=\"{bar_x:.1}\" y1=\"{:.1}\" x2=\"{bar_x:.1}\" y2=\"{:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\"/>",
2835            ey - 6.0,
2836            ey + 6.0
2837        );
2838    }
2839}
2840
2841/// Renders a Mermaid `erDiagram` AST as a themed inline SVG with typed entity fields and crow's-foot cardinality connectors.
2842///
2843/// # Arguments
2844///
2845/// - `&MermaidErDiagram` - Parsed ER diagram.
2846/// - `&mut String` - Destination HTML/SVG buffer.
2847fn render_mermaid_er_svg(er: &MermaidErDiagram, out: &mut String) {
2848    let count: usize = er.get_entities().len();
2849    if count == 0 {
2850        return;
2851    }
2852    let pad: f32 = 24.0;
2853    let gap: f32 = 72.0;
2854    let box_w: f32 = 176.0;
2855    let mut max_h: f32 = 56.0;
2856    for ent in er.get_entities().iter() {
2857        let h: f32 = 34.0 + (ent.get_attributes().len() as f32) * 18.0 + 12.0;
2858        max_h = max_h.max(h);
2859    }
2860    let svg_w: f32 = pad * 2.0 + (count as f32) * box_w + (count.saturating_sub(1) as f32) * gap;
2861    let svg_h: f32 = pad * 2.0 + max_h + 20.0;
2862    let _: fmt::Result = write!(
2863        out,
2864        "<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\">"
2865    );
2866    let mut pos_map: HashMap<&str, (f32, f32, f32)> = HashMap::with_capacity(count);
2867    for (idx, ent) in er.get_entities().iter().enumerate() {
2868        let x: f32 = pad + (idx as f32) * (box_w + gap);
2869        let h: f32 = 34.0 + (ent.get_attributes().len() as f32) * 18.0 + 12.0;
2870        let _: Option<(f32, f32, f32)> = pos_map.insert(ent.get_name().as_str(), (x, pad, h));
2871        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2872        let _: fmt::Result = write!(
2873            out,
2874            "<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\"/><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)\">",
2875            pad + 28.0,
2876            x + box_w,
2877            pad + 28.0,
2878            x + box_w * 0.5,
2879            pad + 19.0
2880        );
2881        push_escaped_html(out, ent.get_name());
2882        out.push_str(SVG_TEXT_CLOSE);
2883        for (ai, attr) in ent.get_attributes().iter().enumerate() {
2884            let is_key: bool = attr.contains(" PK") || attr.contains(" FK") || attr.contains(" UK");
2885            let col: &str = if is_key {
2886                MERMAID_SVG_VAR_FG
2887            } else {
2888                MERMAID_SVG_VAR_MUTED_FG
2889            };
2890            let fw: &str = if is_key { "600" } else { "400" };
2891            let _: fmt::Result = write!(
2892                out,
2893                "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" font-weight=\"{fw}\" fill=\"{col}\">",
2894                x + 10.0,
2895                pad + 46.0 + (ai as f32) * 18.0
2896            );
2897            push_escaped_html(out, attr);
2898            out.push_str(SVG_TEXT_CLOSE);
2899        }
2900    }
2901    for rel in er.get_relations().iter() {
2902        if let (Some(&(x1, y1, h1)), Some(&(x2, y2, h2))) = (
2903            pos_map.get(rel.get_left().as_str()),
2904            pos_map.get(rel.get_right().as_str()),
2905        ) {
2906            let ltr: bool = x2 >= x1;
2907            let sx: f32 = if ltr { x1 + box_w } else { x1 };
2908            let tx: f32 = if ltr { x2 } else { x2 + box_w };
2909            let sy: f32 = y1 + h1 * 0.5;
2910            let ty: f32 = y2 + h2 * 0.5;
2911            let dash: &str = if rel.get_dashed() {
2912                MERMAID_SVG_DASH_ATTR
2913            } else {
2914                ""
2915            };
2916            let _: fmt::Result = write!(
2917                out,
2918                "<line x1=\"{sx:.1}\" y1=\"{sy:.1}\" x2=\"{tx:.1}\" y2=\"{ty:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\"{dash}/>"
2919            );
2920            let dir_s: f32 = if ltr { 1.0 } else { -1.0 };
2921            render_er_card_svg(rel.get_left_card(), sx, sy, dir_s, out);
2922            render_er_card_svg(rel.get_right_card(), tx, ty, -dir_s, out);
2923            if !rel.get_label().is_empty() {
2924                let _: fmt::Result = write!(
2925                    out,
2926                    "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
2927                    (sx + tx) * 0.5,
2928                    (sy + ty) * 0.5 - 7.0
2929                );
2930                push_escaped_html(out, rel.get_label());
2931                out.push_str(SVG_TEXT_CLOSE);
2932            }
2933        }
2934    }
2935    out.push_str(MERMAID_SVG_CLOSE);
2936}
2937
2938/// Renders a Mermaid `pie` chart AST as a proportional inline SVG pie + legend.
2939///
2940/// # Arguments
2941///
2942/// - `&MermaidPieChart` - Parsed pie chart.
2943/// - `&mut String` - Destination HTML/SVG buffer.
2944fn render_mermaid_pie_svg(pie: &MermaidPieChart, out: &mut String) {
2945    let total: f32 = pie
2946        .get_slices()
2947        .iter()
2948        .map(|s: &MermaidPieSlice| s.get_value())
2949        .sum();
2950    if total <= 0.0 {
2951        return;
2952    }
2953    let has_title: bool = !pie.get_title().is_empty();
2954    let title_off: f32 = if has_title { 28.0 } else { 8.0 };
2955    let r: f32 = 76.0;
2956    let cx: f32 = 112.0;
2957    let cy: f32 = title_off + r + 14.0;
2958    let legend_x: f32 = cx + r + 36.0;
2959    let legend_h: f32 = (pie.get_slices().len() as f32) * 24.0;
2960    let svg_h: f32 = (cy + r + 20.0).max(title_off + legend_h + 36.0);
2961    let svg_w: f32 = 460.0;
2962    let _: fmt::Result = write!(
2963        out,
2964        "<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\">"
2965    );
2966    if has_title {
2967        let _: fmt::Result = write!(
2968            out,
2969            "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2970            svg_w * 0.5
2971        );
2972        push_escaped_html(out, pie.get_title());
2973        out.push_str(SVG_TEXT_CLOSE);
2974    }
2975    let mut angle: f32 = -FRAC_PI_2;
2976    let legend_y0: f32 = cy - legend_h * 0.5 + 12.0;
2977    for (idx, slice) in pie.get_slices().iter().enumerate() {
2978        let color: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2979        let frac: f32 = slice.get_value() / total;
2980        let sweep: f32 = frac * TAU;
2981        if pie.get_slices().len() == 1 {
2982            let _: fmt::Result = write!(
2983                out,
2984                "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{r:.1}\" fill=\"{color}\"/>"
2985            );
2986        } else {
2987            let x1: f32 = cx + r * angle.cos();
2988            let y1: f32 = cy + r * angle.sin();
2989            let end_a: f32 = angle + sweep;
2990            let x2: f32 = cx + r * end_a.cos();
2991            let y2: f32 = cy + r * end_a.sin();
2992            let large: u8 = if sweep > PI { 1 } else { 0 };
2993            let _: fmt::Result = write!(
2994                out,
2995                "<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\"/>"
2996            );
2997            angle = end_a;
2998        }
2999        let ly: f32 = legend_y0 + (idx as f32) * 24.0;
3000        let pct: f32 = frac * 100.0;
3001        let _: fmt::Result = write!(
3002            out,
3003            "<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)\">",
3004            ly - 10.0,
3005            legend_x + 18.0
3006        );
3007        push_escaped_html(out, slice.get_label());
3008        let _: fmt::Result = write!(out, " ({pct:.0}%)</text>");
3009    }
3010    out.push_str(MERMAID_SVG_CLOSE);
3011}
3012
3013/// Renders a Mermaid `gantt` chart AST as a themed inline SVG timeline including milestone diamonds.
3014///
3015/// # Arguments
3016///
3017/// - `&MermaidGanttChart` - Parsed Gantt timeline.
3018/// - `&mut String` - Destination HTML/SVG buffer.
3019fn render_mermaid_gantt_svg(gantt: &MermaidGanttChart, out: &mut String) {
3020    let count: usize = gantt.get_tasks().len();
3021    if count == 0 {
3022        return;
3023    }
3024    let has_title: bool = !gantt.get_title().is_empty();
3025    let top: f32 = if has_title { 38.0 } else { 16.0 };
3026    let label_w: f32 = 148.0;
3027    let track_w: f32 = 340.0;
3028    let row_h: f32 = 30.0;
3029    let svg_w: f32 = label_w + track_w + 28.0;
3030    let svg_h: f32 = top + (count as f32) * row_h + 16.0;
3031    let max_end: f32 = gantt
3032        .get_tasks()
3033        .iter()
3034        .map(|t: &MermaidGanttTask| t.get_start_unit() + t.get_duration_unit())
3035        .fold(1.0_f32, f32::max);
3036    let _: fmt::Result = write!(
3037        out,
3038        "<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\">"
3039    );
3040    if has_title {
3041        let _: fmt::Result = write!(
3042            out,
3043            "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
3044            svg_w * 0.5
3045        );
3046        push_escaped_html(out, gantt.get_title());
3047        out.push_str(SVG_TEXT_CLOSE);
3048    }
3049    for (idx, task) in gantt.get_tasks().iter().enumerate() {
3050        let y: f32 = top + (idx as f32) * row_h;
3051        let bx: f32 = label_w + (task.get_start_unit() / max_end) * track_w;
3052        let bw: f32 = ((task.get_duration_unit() / max_end) * track_w).max(16.0);
3053        let fill: &str = match task.get_status() {
3054            MermaidGanttStatus::Done => MERMAID_SVG_VAR_TIP,
3055            MermaidGanttStatus::Active => MERMAID_SVG_VAR_LINK,
3056            MermaidGanttStatus::Critical => MERMAID_SVG_VAR_DANGER,
3057            MermaidGanttStatus::Milestone => MERMAID_SVG_VAR_WARN,
3058            MermaidGanttStatus::Normal => MERMAID_SVG_VAR_IMPORTANT,
3059        };
3060        let _: fmt::Result = write!(
3061            out,
3062            "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\" font-size=\"11.5\" fill=\"var(--fg)\">",
3063            label_w - 10.0,
3064            y + 15.0
3065        );
3066        push_escaped_html(out, task.get_label());
3067        out.push_str(SVG_TEXT_CLOSE);
3068        if task.get_status() == MermaidGanttStatus::Milestone {
3069            let cy: f32 = y + 11.0;
3070            let _: fmt::Result = write!(
3071                out,
3072                "<polygon points=\"{bx:.1},{:.1} {:.1},{cy:.1} {bx:.1},{:.1} {:.1},{cy:.1}\" fill=\"{fill}\"/>",
3073                cy - 8.0,
3074                bx + 8.0,
3075                cy + 8.0,
3076                bx - 8.0
3077            );
3078        } else {
3079            let _: fmt::Result = write!(
3080                out,
3081                "<rect x=\"{bx:.1}\" y=\"{:.1}\" width=\"{bw:.1}\" height=\"18\" rx=\"5\" fill=\"{fill}\"/>",
3082                y + 2.0
3083            );
3084        }
3085    }
3086    out.push_str(MERMAID_SVG_CLOSE);
3087}
3088
3089/// Renders a Mermaid `timeline` diagram AST as a horizontal milestone inline SVG.
3090///
3091/// # Arguments
3092///
3093/// - `&MermaidTimeline` - Parsed timeline diagram.
3094/// - `&mut String` - Destination HTML/SVG buffer.
3095fn render_mermaid_timeline_svg(tl: &MermaidTimeline, out: &mut String) {
3096    let count: usize = tl.get_events().len();
3097    if count == 0 {
3098        return;
3099    }
3100    let has_title: bool = !tl.get_title().is_empty();
3101    let top: f32 = if has_title { 44.0 } else { 24.0 };
3102    let col_w: f32 = 154.0;
3103    let pad: f32 = 24.0;
3104    let max_items: usize = tl
3105        .get_events()
3106        .iter()
3107        .map(|ev: &MermaidTimelineEvent| ev.get_items().len())
3108        .max()
3109        .unwrap_or(1)
3110        .max(1);
3111    let svg_w: f32 = (pad * 2.0 + (count as f32) * col_w).max(380.0);
3112    let axis_y: f32 = top + 30.0;
3113    let svg_h: f32 = axis_y + 24.0 + (max_items as f32) * 32.0 + 20.0;
3114    let _: fmt::Result = write!(
3115        out,
3116        "<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 timeline\">"
3117    );
3118    if has_title {
3119        let _: fmt::Result = write!(
3120            out,
3121            "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
3122            svg_w * 0.5
3123        );
3124        push_escaped_html(out, tl.get_title());
3125        out.push_str(SVG_TEXT_CLOSE);
3126    }
3127    let _: fmt::Result = write!(
3128        out,
3129        "<line x1=\"{pad:.1}\" y1=\"{axis_y:.1}\" x2=\"{:.1}\" y2=\"{axis_y:.1}\" stroke=\"var(--border)\" stroke-width=\"2.5\"/>",
3130        svg_w - pad
3131    );
3132    for (idx, ev) in tl.get_events().iter().enumerate() {
3133        let cx: f32 = pad + (idx as f32) * col_w + col_w * 0.5;
3134        let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
3135        let _: fmt::Result = write!(
3136            out,
3137            "<circle cx=\"{cx:.1}\" cy=\"{axis_y:.1}\" r=\"6.5\" fill=\"{accent}\"/><text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"700\" fill=\"var(--fg)\">",
3138            axis_y - 12.0
3139        );
3140        push_escaped_html(out, ev.get_period());
3141        out.push_str(SVG_TEXT_CLOSE);
3142        for (ii, item) in ev.get_items().iter().enumerate() {
3143            let iy: f32 = axis_y + 18.0 + (ii as f32) * 32.0;
3144            let bw: f32 = col_w - 18.0;
3145            let bx: f32 = cx - bw * 0.5;
3146            let _: fmt::Result = write!(
3147                out,
3148                "<rect x=\"{bx:.1}\" y=\"{iy:.1}\" width=\"{bw:.1}\" height=\"24\" rx=\"5\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.2\"/><text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11\" fill=\"var(--fg)\">",
3149                iy + 16.0
3150            );
3151            push_escaped_html(out, item);
3152            out.push_str(SVG_TEXT_CLOSE);
3153        }
3154    }
3155    out.push_str(MERMAID_SVG_CLOSE);
3156}
3157
3158/// Renders a Mermaid `mindmap` AST as an indented horizontal tree inline SVG.
3159///
3160/// # Arguments
3161///
3162/// - `&MermaidMindmap` - Parsed mindmap hierarchy.
3163/// - `&mut String` - Destination HTML/SVG buffer.
3164fn render_mermaid_mindmap_svg(mm: &MermaidMindmap, out: &mut String) {
3165    let count: usize = mm.get_nodes().len();
3166    if count == 0 {
3167        return;
3168    }
3169    let pad: f32 = 22.0;
3170    let row_h: f32 = 34.0;
3171    let indent_w: f32 = 44.0;
3172    let max_depth: usize = mm
3173        .get_nodes()
3174        .iter()
3175        .map(|node: &MermaidMindmapNode| node.get_depth())
3176        .max()
3177        .unwrap_or(0);
3178    let svg_w: f32 = (pad * 2.0 + (max_depth as f32) * indent_w + 220.0).max(380.0);
3179    let svg_h: f32 = pad * 2.0 + (count as f32) * row_h;
3180    let _: fmt::Result = write!(
3181        out,
3182        "<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 mindmap\">"
3183    );
3184    let mut last_at_depth: Vec<Option<(f32, f32)>> = vec![None; max_depth + 2];
3185    for (idx, node) in mm.get_nodes().iter().enumerate() {
3186        let d: usize = node.get_depth();
3187        let nx: f32 = pad + (d as f32) * indent_w;
3188        let ny: f32 = pad + (idx as f32) * row_h;
3189        let nw: f32 = ((node.get_label().chars().count() as f32) * 7.4 + 28.0).clamp(84.0, 210.0);
3190        let nh: f32 = 26.0;
3191        let accent: &str = MERMAID_SVG_PALETTE[d % MERMAID_SVG_PALETTE.len()];
3192        if d > 0
3193            && let Some((px, py)) = last_at_depth[d - 1]
3194        {
3195            let _: fmt::Result = write!(
3196                out,
3197                "<path d=\"M {px:.1} {py:.1} L {px:.1} {:.1} L {nx:.1} {:.1}\" fill=\"none\" stroke=\"{accent}\" stroke-width=\"1.4\"/>",
3198                ny + nh * 0.5,
3199                ny + nh * 0.5
3200            );
3201        }
3202        let rad: f32 = match node.get_shape() {
3203            MermaidNodeShape::Circle
3204            | MermaidNodeShape::DoubleCircle
3205            | MermaidNodeShape::Stadium => nh * 0.5,
3206            MermaidNodeShape::Rounded => 8.0,
3207            _ => 4.0,
3208        };
3209        let _: fmt::Result = write!(
3210            out,
3211            "<rect x=\"{nx:.1}\" y=\"{ny:.1}\" width=\"{nw:.1}\" height=\"{nh:.1}\" rx=\"{rad:.1}\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.6\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"11.5\" font-weight=\"600\" fill=\"var(--fg)\">",
3212            nx + nw * 0.5,
3213            ny + 17.0
3214        );
3215        push_escaped_html(out, node.get_label());
3216        out.push_str(SVG_TEXT_CLOSE);
3217        last_at_depth[d] = Some((nx + 14.0, ny + nh));
3218    }
3219    out.push_str(MERMAID_SVG_CLOSE);
3220}
3221
3222/// Renders a Mermaid `xychart-beta` AST as a Cartesian bar/line inline SVG chart.
3223///
3224/// # Arguments
3225///
3226/// - `&MermaidXyChart` - Parsed XY chart.
3227/// - `&mut String` - Destination HTML/SVG buffer.
3228fn render_mermaid_xychart_svg(xy: &MermaidXyChart, out: &mut String) {
3229    let x_count: usize = xy.get_x_labels().len().max(
3230        xy.get_series()
3231            .iter()
3232            .map(|s: &MermaidXySeries| s.get_values().len())
3233            .max()
3234            .unwrap_or(0),
3235    );
3236    if x_count == 0 {
3237        return;
3238    }
3239    let has_title: bool = !xy.get_title().is_empty();
3240    let top: f32 = if has_title { 38.0 } else { 18.0 };
3241    let left: f32 = 54.0;
3242    let right: f32 = 22.0;
3243    let bottom: f32 = 34.0;
3244    let plot_w: f32 = ((x_count as f32) * 56.0).clamp(320.0, 620.0);
3245    let plot_h: f32 = 176.0;
3246    let svg_w: f32 = left + plot_w + right;
3247    let svg_h: f32 = top + plot_h + bottom;
3248    let mut y_min: f32 = xy.get_y_min();
3249    let mut y_max: f32 = xy.get_y_max();
3250    if (y_max - y_min).abs() < 1e-3 {
3251        y_min = 0.0;
3252        y_max = xy
3253            .get_series()
3254            .iter()
3255            .flat_map(|s: &MermaidXySeries| s.get_values().iter().copied())
3256            .fold(1.0_f32, f32::max);
3257    }
3258    let span: f32 = (y_max - y_min).max(1.0);
3259    let _: fmt::Result = write!(
3260        out,
3261        "<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 XY chart\">"
3262    );
3263    if has_title {
3264        let _: fmt::Result = write!(
3265            out,
3266            "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
3267            svg_w * 0.5
3268        );
3269        push_escaped_html(out, xy.get_title());
3270        out.push_str(SVG_TEXT_CLOSE);
3271    }
3272    for step in 0..=4 {
3273        let frac: f32 = (step as f32) / 4.0;
3274        let gy: f32 = top + plot_h * (1.0 - frac);
3275        let tick_val: f32 = y_min + span * frac;
3276        let _: fmt::Result = write!(
3277            out,
3278            "<line x1=\"{left:.1}\" y1=\"{gy:.1}\" x2=\"{:.1}\" y2=\"{gy:.1}\" stroke=\"var(--border)\" stroke-width=\"1\" stroke-dasharray=\"3 3\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\" font-size=\"10\" fill=\"var(--muted-fg)\">{tick_val:.0}</text>",
3279            left + plot_w,
3280            left - 8.0,
3281            gy + 3.5
3282        );
3283    }
3284    let slot_w: f32 = plot_w / (x_count as f32);
3285    for (si, ser) in xy.get_series().iter().enumerate() {
3286        let accent: &str = MERMAID_SVG_PALETTE[si % MERMAID_SVG_PALETTE.len()];
3287        if ser.get_is_bar() {
3288            let bw: f32 = (slot_w * 0.54).clamp(12.0, 38.0);
3289            for (vi, &v) in ser.get_values().iter().enumerate() {
3290                let norm: f32 = ((v - y_min) / span).clamp(0.0, 1.0);
3291                let bh: f32 = (norm * plot_h).max(2.0);
3292                let bx: f32 = left + (vi as f32) * slot_w + (slot_w - bw) * 0.5;
3293                let by: f32 = top + plot_h - bh;
3294                let _: fmt::Result = write!(
3295                    out,
3296                    "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{bw:.1}\" height=\"{bh:.1}\" rx=\"4\" fill=\"{accent}\" fill-opacity=\"0.85\"/>"
3297                );
3298            }
3299        } else {
3300            let mut pts: String = String::new();
3301            for (vi, &v) in ser.get_values().iter().enumerate() {
3302                let norm: f32 = ((v - y_min) / span).clamp(0.0, 1.0);
3303                let px: f32 = left + (vi as f32) * slot_w + slot_w * 0.5;
3304                let py: f32 = top + plot_h - norm * plot_h;
3305                if !pts.is_empty() {
3306                    pts.push(' ');
3307                }
3308                let _: fmt::Result = write!(pts, "{px:.1},{py:.1}");
3309            }
3310            if !pts.is_empty() {
3311                let _: fmt::Result = write!(
3312                    out,
3313                    "<polyline points=\"{pts}\" fill=\"none\" stroke=\"{accent}\" stroke-width=\"2.2\"/>"
3314                );
3315                for (vi, &v) in ser.get_values().iter().enumerate() {
3316                    let norm: f32 = ((v - y_min) / span).clamp(0.0, 1.0);
3317                    let px: f32 = left + (vi as f32) * slot_w + slot_w * 0.5;
3318                    let py: f32 = top + plot_h - norm * plot_h;
3319                    let _: fmt::Result = write!(
3320                        out,
3321                        "<circle cx=\"{px:.1}\" cy=\"{py:.1}\" r=\"3.5\" fill=\"{accent}\"/>"
3322                    );
3323                }
3324            }
3325        }
3326    }
3327    for idx in 0..x_count {
3328        let cx: f32 = left + (idx as f32) * slot_w + slot_w * 0.5;
3329        let lbl: &str = xy.get_x_labels().get(idx).map(String::as_str).unwrap_or("");
3330        let _: fmt::Result = write!(
3331            out,
3332            "<text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
3333            top + plot_h + 18.0
3334        );
3335        push_escaped_html(out, lbl);
3336        out.push_str(SVG_TEXT_CLOSE);
3337    }
3338    out.push_str(MERMAID_SVG_CLOSE);
3339}
3340
3341/// Renders a Mermaid `gitGraph` AST as a multi-lane commit & merge inline SVG.
3342///
3343/// # Arguments
3344///
3345/// - `&MermaidGitGraph` - Parsed Git commit graph.
3346/// - `&mut String` - Destination HTML/SVG buffer.
3347fn render_mermaid_gitgraph_svg(git: &MermaidGitGraph, out: &mut String) {
3348    let c_count: usize = git.get_commits().len();
3349    let b_count: usize = git.get_branches().len().max(1);
3350    if c_count == 0 {
3351        return;
3352    }
3353    let label_w: f32 = 104.0;
3354    let step_x: f32 = 64.0;
3355    let lane_h: f32 = 44.0;
3356    let top: f32 = 24.0;
3357    let svg_w: f32 = (label_w + (c_count as f32) * step_x + 40.0).max(380.0);
3358    let svg_h: f32 = top + (b_count as f32) * lane_h + 26.0;
3359    let _: fmt::Result = write!(
3360        out,
3361        "<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 gitGraph\">"
3362    );
3363    for (bi, bname) in git.get_branches().iter().enumerate() {
3364        let ly: f32 = top + (bi as f32) * lane_h + lane_h * 0.5;
3365        let accent: &str = MERMAID_SVG_PALETTE[bi % MERMAID_SVG_PALETTE.len()];
3366        let _: fmt::Result = write!(
3367            out,
3368            "<line x1=\"{label_w:.1}\" y1=\"{ly:.1}\" x2=\"{:.1}\" y2=\"{ly:.1}\" stroke=\"{accent}\" stroke-opacity=\"0.35\" stroke-width=\"2\"/><text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\" font-size=\"11.5\" font-weight=\"700\" fill=\"{accent}\">",
3369            svg_w - 20.0,
3370            label_w - 12.0,
3371            ly + 4.0
3372        );
3373        push_escaped_html(out, bname);
3374        out.push_str(SVG_TEXT_CLOSE);
3375    }
3376    let mut coords: Vec<(f32, f32)> = Vec::with_capacity(c_count);
3377    for (ci, commit) in git.get_commits().iter().enumerate() {
3378        let cx: f32 = label_w + 24.0 + (ci as f32) * step_x;
3379        let cy: f32 = top + (commit.get_lane() as f32) * lane_h + lane_h * 0.5;
3380        coords.push((cx, cy));
3381        let accent: &str = MERMAID_SVG_PALETTE[commit.get_lane() % MERMAID_SVG_PALETTE.len()];
3382        if let Some(p_idx) = commit.get_parent_idx()
3383            && let Some(&(px, py)) = coords.get(p_idx)
3384        {
3385            let _: fmt::Result = write!(
3386                out,
3387                "<line x1=\"{px:.1}\" y1=\"{py:.1}\" x2=\"{cx:.1}\" y2=\"{cy:.1}\" stroke=\"{accent}\" stroke-width=\"2\"/>"
3388            );
3389        }
3390        if let Some(m_lane) = commit.get_merge_from_lane() {
3391            let my: f32 = top + (m_lane as f32) * lane_h + lane_h * 0.5;
3392            let mx: f32 = (cx - step_x).max(label_w + 16.0);
3393            let m_acc: &str = MERMAID_SVG_PALETTE[m_lane % MERMAID_SVG_PALETTE.len()];
3394            let _: fmt::Result = write!(
3395                out,
3396                "<line x1=\"{mx:.1}\" y1=\"{my:.1}\" x2=\"{cx:.1}\" y2=\"{cy:.1}\" stroke=\"{m_acc}\" stroke-width=\"1.8\" stroke-dasharray=\"4 3\"/>"
3397            );
3398        }
3399        let _: fmt::Result = write!(
3400            out,
3401            "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"7\" fill=\"{accent}\" stroke=\"var(--card)\" stroke-width=\"2\"/><text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10\" fill=\"var(--muted-fg)\">",
3402            cy + 20.0
3403        );
3404        push_escaped_html(out, commit.get_id());
3405        out.push_str(SVG_TEXT_CLOSE);
3406        if !commit.get_tag().is_empty() {
3407            let _: fmt::Result = write!(
3408                out,
3409                "<rect x=\"{:.1}\" y=\"{:.1}\" width=\"46\" height=\"15\" rx=\"4\" fill=\"var(--warn)\"/><text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"9.5\" font-weight=\"700\" fill=\"#ffffff\">",
3410                cx - 23.0,
3411                cy - 24.0,
3412                cy - 13.0
3413            );
3414            push_escaped_html(out, commit.get_tag());
3415            out.push_str(SVG_TEXT_CLOSE);
3416        }
3417    }
3418    out.push_str(MERMAID_SVG_CLOSE);
3419}