1use super::*;
2
3pub 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
31pub 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
46pub 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#[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
190fn 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
234fn ordered_site_pages(site: &DocSite) -> Vec<&DocPage> {
244 let mut ordered: Vec<&DocPage> = site.get_pages().iter().collect();
245 ordered.sort_by(|alpha_val: &&DocPage, blue_val: &&DocPage| {
246 section_sort_rank(alpha_val.get_section())
247 .cmp(§ion_sort_rank(blue_val.get_section()))
248 .then_with(|| alpha_val.get_section().cmp(blue_val.get_section()))
249 .then_with(|| alpha_val.get_order().cmp(&blue_val.get_order()))
250 .then_with(|| alpha_val.get_route().cmp(blue_val.get_route()))
251 });
252 ordered
253}
254
255fn 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
350fn 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
375fn 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
416fn 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> =
431 page.get_blocks()
432 .iter()
433 .find_map(|blue_val: &DocBlock| match blue_val {
434 DocBlock::Paragraph(point_val) | DocBlock::BlockQuote(point_val) => {
435 Some(point_val.trim())
436 }
437 _ => None,
438 });
439 first_prose != Some(summary)
440}
441
442fn brand_monogram(title: &str) -> char {
452 title
453 .chars()
454 .find(|ch: &char| ch.is_alphanumeric())
455 .and_then(|ch: char| ch.to_uppercase().next())
456 .unwrap_or(DEFAULT_BRAND_MONOGRAM)
457}
458
459fn render_markdown_body_html(page: &DocPage, base: &str, out: &mut String) {
467 let body_raw: &str = page.get_markdown_body();
468 let mut state: MarkdownRenderState<'_> = MarkdownRenderState {
469 page,
470 base,
471 seen_slugs: BTreeMap::new(),
472 skipped_title_h1: false,
473 out,
474 };
475 if !body_raw.contains(CALLOUT_FENCE) {
476 render_markdown_chunk(body_raw, &mut state);
477 return;
478 }
479 let segments: Vec<BodySegment> = split_custom_containers(body_raw);
480 for seg in segments.into_iter() {
481 match seg {
482 BodySegment::Markdown(md) => {
483 render_markdown_chunk(&md, &mut state);
484 }
485 BodySegment::Callout { kind, title, body } => {
486 if kind == CALLOUT_KIND_DETAILS {
487 state.out.push_str(HTML_CALLOUT_DETAILS_OPEN);
488 push_escaped_html(state.out, &title);
489 state.out.push_str(HTML_SUMMARY_CLOSE);
490 render_markdown_chunk(&body, &mut state);
491 state.out.push_str(HTML_DETAILS_CLOSE);
492 } else {
493 state.out.push_str(HTML_CALLOUT_DIV_OPEN);
494 push_escaped_html(state.out, &kind);
495 state.out.push_str(HTML_CALLOUT_TITLE_MID);
496 push_escaped_html(state.out, &title);
497 state.out.push_str(HTML_DIV_CLOSE);
498 render_markdown_chunk(&body, &mut state);
499 state.out.push_str(HTML_DIV_CLOSE);
500 }
501 }
502 }
503 }
504}
505
506fn split_custom_containers(body: &str) -> Vec<BodySegment> {
516 let mut segments: Vec<BodySegment> = Vec::new();
517 let mut plain: String = String::new();
518 let mut active: Option<(String, String, String)> = None;
519 let mut in_fence: bool = false;
520 for line in body.lines() {
521 let trimmed: &str = line.trim();
522 if trimmed.starts_with(FENCE_BACKTICK) || trimmed.starts_with(FENCE_TILDE) {
523 in_fence = !in_fence;
524 }
525 if let Some((kind, title, inner)) = active.as_mut() {
526 if !in_fence && trimmed == CALLOUT_FENCE {
527 let done_kind: String = take(kind);
528 let done_title: String = take(title);
529 let done_body: String = take(inner);
530 active = None;
531 segments.push(BodySegment::Callout {
532 kind: done_kind,
533 title: done_title,
534 body: done_body,
535 });
536 continue;
537 }
538 inner.push_str(line);
539 inner.push('\n');
540 continue;
541 }
542 if !in_fence && let Some(after) = trimmed.strip_prefix(CALLOUT_FENCE) {
543 let spec: &str = after.trim();
544 let (raw_kind, custom_title): (&str, &str) = match spec.find(char::is_whitespace) {
545 Some(pos) => (&spec[..pos], spec[pos..].trim()),
546 None => (spec, ""),
547 };
548 let normalized: Option<(&str, &str)> =
549 if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_TIP) {
550 Some((CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP))
551 } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_WARNING) {
552 Some((CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING))
553 } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_DANGER) {
554 Some((CALLOUT_KIND_DANGER, CALLOUT_TITLE_DANGER))
555 } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_INFO) {
556 Some((CALLOUT_KIND_INFO, CALLOUT_TITLE_INFO))
557 } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_NOTE) {
558 Some((CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE))
559 } else if raw_kind.eq_ignore_ascii_case(CALLOUT_KIND_DETAILS) {
560 Some((CALLOUT_KIND_DETAILS, CALLOUT_TITLE_DETAILS))
561 } else {
562 None
563 };
564 if let Some((kind_str, default_title)) = normalized {
565 if !plain.is_empty() {
566 segments.push(BodySegment::Markdown(take(&mut plain)));
567 }
568 let title: String = if custom_title.is_empty() {
569 default_title.to_string()
570 } else {
571 custom_title.to_string()
572 };
573 active = Some((kind_str.to_string(), title, String::new()));
574 continue;
575 }
576 }
577 plain.push_str(line);
578 plain.push('\n');
579 }
580 if let Some((kind, title, inner)) = active {
581 segments.push(BodySegment::Callout {
582 kind,
583 title,
584 body: inner,
585 });
586 }
587 if !plain.is_empty() {
588 segments.push(BodySegment::Markdown(plain));
589 }
590 segments
591}
592
593fn render_markdown_chunk(chunk: &str, state: &mut MarkdownRenderState<'_>) {
600 let parser: Parser<'_> = Parser::new_ext(chunk, Options::all());
601 let mut active_heading: Option<(u8, Option<String>, String, String)> = None;
602 let mut active_code: Option<(String, String)> = None;
603 let mut active_image: Option<(String, String, String)> = None;
604 let mut table_alignments: Vec<Alignment> = Vec::new();
605 let mut blockquote_alerts: Vec<bool> = Vec::new();
606 let mut in_table_head: bool = false;
607 let mut cell_index: usize = 0;
608 let mut pending_text: String = String::new();
609 for event in parser {
610 if let Some((_, _, ref mut heading_html, ref mut heading_plain)) = active_heading {
611 match event {
612 Event::End(TagEnd::Heading(_)) => {
613 if let Some((level, custom_id, inner_html, plain)) = active_heading.take() {
614 let trimmed_plain: &str = plain.trim();
615 if !trimmed_plain.is_empty() {
616 let raw_slug: String = custom_id
617 .map(|text_value: String| slugify(&text_value))
618 .filter(|label_str: &String| !label_str.is_empty())
619 .unwrap_or_else(|| slugify(trimmed_plain));
620 let slug: String = deduplicate_slug(raw_slug, &mut state.seen_slugs);
621 if level <= 2
622 && !state.skipped_title_h1
623 && state.seen_slugs.len() == 1
624 && trimmed_plain.eq_ignore_ascii_case(state.page.get_title().trim())
625 {
626 state.skipped_title_h1 = true;
627 } else {
628 let tag_lvl: u8 = level.clamp(2, 6);
629 let _: fmt::Result =
630 write!(state.out, "<h{tag_lvl}{HTML_HEADING_ID_MID}");
631 push_escaped_html(state.out, &slug);
632 state.out.push_str(HTML_LINK_MID);
633 state.out.push_str(&inner_html);
634 state.out.push_str(HTML_ANCHOR_MID);
635 push_escaped_html(state.out, &slug);
636 state.out.push_str(HTML_ANCHOR_CLOSE);
637 let _: fmt::Result = write!(state.out, "</h{tag_lvl}>");
638 }
639 }
640 }
641 }
642 Event::Text(text) => {
643 heading_plain.push_str(&text);
644 push_escaped_html(heading_html, &text);
645 }
646 Event::Code(text) => {
647 heading_plain.push_str(&text);
648 heading_html.push_str(HTML_INLINE_CODE_OPEN);
649 push_escaped_html(heading_html, &text);
650 heading_html.push_str(HTML_INLINE_CODE_CLOSE);
651 }
652 Event::Start(Tag::Strong) => heading_html.push_str(HTML_STRONG_OPEN),
653 Event::End(TagEnd::Strong) => heading_html.push_str(HTML_STRONG_CLOSE),
654 Event::Start(Tag::Emphasis) => heading_html.push_str(HTML_EM_OPEN),
655 Event::End(TagEnd::Emphasis) => heading_html.push_str(HTML_EM_CLOSE),
656 Event::Start(Tag::Strikethrough) => heading_html.push_str(HTML_DEL_OPEN),
657 Event::End(TagEnd::Strikethrough) => heading_html.push_str(HTML_DEL_CLOSE),
658 Event::SoftBreak | Event::HardBreak => {
659 heading_plain.push(' ');
660 heading_html.push(' ');
661 }
662 _ => {}
663 }
664 continue;
665 }
666 if let Some((_, ref mut code_buf)) = active_code {
667 match event {
668 Event::End(TagEnd::CodeBlock) => {
669 if let Some((info, code)) = active_code.take() {
670 let trimmed: &str = code.trim_end_matches('\n');
671 let (lang, title_opt, hl_lines): (String, Option<String>, Vec<usize>) =
672 parse_code_fence_info(&info);
673 if lang.eq_ignore_ascii_case(CODE_LANG_MERMAID) {
674 render_mermaid_svg_html(trimmed, state.out);
675 } else if lang.eq_ignore_ascii_case(CODE_LANG_ECHART)
676 || lang.eq_ignore_ascii_case(CODE_LANG_ECHARTS)
677 {
678 render_echart_svg_html(trimmed, state.out);
679 } else {
680 render_highlighted_code_html_with_meta(
681 &lang,
682 title_opt.as_deref(),
683 &hl_lines,
684 trimmed,
685 state.out,
686 );
687 }
688 }
689 }
690 Event::Text(text) | Event::Code(text) => code_buf.push_str(&text),
691 Event::SoftBreak | Event::HardBreak => code_buf.push('\n'),
692 _ => {}
693 }
694 continue;
695 }
696 if let Some((_, _, ref mut alt_buf)) = active_image {
697 match event {
698 Event::End(TagEnd::Image) => {
699 if let Some((src, title, alt)) = active_image.take()
700 && let Some(resolved) =
701 resolve_asset_src(state.base, state.page.get_route(), &src)
702 {
703 state.out.push_str(HTML_IMG_SRC_OPEN);
704 push_escaped_html(state.out, &resolved);
705 state.out.push_str(HTML_IMG_ALT_MID);
706 push_escaped_html(state.out, alt.trim());
707 if !title.is_empty() {
708 state.out.push_str(HTML_IMG_TITLE_MID);
709 push_escaped_html(state.out, &title);
710 }
711 state.out.push_str(HTML_IMG_LAZY_CLOSE);
712 }
713 }
714 Event::Text(text) | Event::Code(text) => alt_buf.push_str(&text),
715 Event::SoftBreak | Event::HardBreak => alt_buf.push(' '),
716 _ => {}
717 }
718 continue;
719 }
720 if let Event::Text(text) = event {
721 pending_text.push_str(&text);
722 continue;
723 }
724 if !pending_text.is_empty() {
725 render_extended_inline_text_html(&pending_text, state.out);
726 pending_text.clear();
727 }
728 match event {
729 Event::Start(Tag::Heading { level, id, .. }) => {
730 active_heading = Some((
731 heading_level_num(level),
732 id.map(CowStr::into_string),
733 String::new(),
734 String::new(),
735 ));
736 }
737 Event::Start(Tag::Paragraph) => state.out.push_str(HTML_P_OPEN),
738 Event::End(TagEnd::Paragraph) => state.out.push_str(HTML_P_CLOSE),
739 Event::Start(Tag::BlockQuote(kind_opt)) => {
740 if let Some(kind) = kind_opt {
741 let (cls, title): (&str, &str) = match kind {
742 BlockQuoteKind::Note => (CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE),
743 BlockQuoteKind::Tip => (CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP),
744 BlockQuoteKind::Important => {
745 (CALLOUT_KIND_IMPORTANT, CALLOUT_TITLE_IMPORTANT)
746 }
747 BlockQuoteKind::Warning => (CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING),
748 BlockQuoteKind::Caution => (CALLOUT_KIND_CAUTION, CALLOUT_TITLE_CAUTION),
749 };
750 state.out.push_str(HTML_CALLOUT_DIV_OPEN);
751 state.out.push_str(cls);
752 state.out.push_str(HTML_CALLOUT_TITLE_MID);
753 state.out.push_str(title);
754 state.out.push_str(HTML_DIV_CLOSE);
755 blockquote_alerts.push(true);
756 } else {
757 state.out.push_str(HTML_QUOTE_OPEN);
758 blockquote_alerts.push(false);
759 }
760 }
761 Event::End(TagEnd::BlockQuote(_)) => {
762 if blockquote_alerts.pop().unwrap_or(false) {
763 state.out.push_str(HTML_DIV_CLOSE);
764 } else {
765 state.out.push_str(HTML_QUOTE_CLOSE);
766 }
767 }
768 Event::Start(Tag::List(None)) => state.out.push_str(HTML_UL_OPEN),
769 Event::Start(Tag::List(Some(start))) => {
770 if start == 1 {
771 state.out.push_str(HTML_OL_OPEN);
772 } else {
773 state.out.push_str(HTML_OL_START_OPEN);
774 let _: fmt::Result = write!(state.out, "{start}");
775 state.out.push_str(HTML_LINK_MID);
776 }
777 }
778 Event::End(TagEnd::List(ordered)) => {
779 if ordered {
780 state.out.push_str(HTML_OL_CLOSE);
781 } else {
782 state.out.push_str(HTML_UL_CLOSE);
783 }
784 }
785 Event::Start(Tag::Item) => state.out.push_str(HTML_LI_OPEN),
786 Event::End(TagEnd::Item) => state.out.push_str(HTML_LI_CLOSE),
787 Event::Start(Tag::Strong) => state.out.push_str(HTML_STRONG_OPEN),
788 Event::End(TagEnd::Strong) => state.out.push_str(HTML_STRONG_CLOSE),
789 Event::Start(Tag::Emphasis) => state.out.push_str(HTML_EM_OPEN),
790 Event::End(TagEnd::Emphasis) => state.out.push_str(HTML_EM_CLOSE),
791 Event::Start(Tag::Strikethrough) => state.out.push_str(HTML_DEL_OPEN),
792 Event::End(TagEnd::Strikethrough) => state.out.push_str(HTML_DEL_CLOSE),
793 Event::Start(Tag::Superscript) => state.out.push_str(HTML_SUP_OPEN),
794 Event::End(TagEnd::Superscript) => state.out.push_str(HTML_SUP_CLOSE),
795 Event::Start(Tag::Subscript) => state.out.push_str(HTML_SUB_OPEN),
796 Event::End(TagEnd::Subscript) => state.out.push_str(HTML_SUB_CLOSE),
797 Event::Start(Tag::DefinitionList) => state.out.push_str(HTML_DL_OPEN),
798 Event::End(TagEnd::DefinitionList) => state.out.push_str(HTML_DL_CLOSE),
799 Event::Start(Tag::DefinitionListTitle) => state.out.push_str(HTML_DT_OPEN),
800 Event::End(TagEnd::DefinitionListTitle) => state.out.push_str(HTML_DT_CLOSE),
801 Event::Start(Tag::DefinitionListDefinition) => state.out.push_str(HTML_DD_OPEN),
802 Event::End(TagEnd::DefinitionListDefinition) => state.out.push_str(HTML_DD_CLOSE),
803 Event::Start(Tag::CodeBlock(kind)) => {
804 let info: String = match kind {
805 CodeBlockKind::Fenced(tag) => {
806 let content_text: &str = tag.trim();
807 if content_text.is_empty() {
808 DEFAULT_CODE_LABEL.to_string()
809 } else {
810 content_text.to_string()
811 }
812 }
813 CodeBlockKind::Indented => DEFAULT_CODE_LABEL.to_string(),
814 };
815 active_code = Some((info, String::new()));
816 }
817 Event::Start(Tag::Link {
818 dest_url, title, ..
819 }) => {
820 let resolved: String =
821 resolve_link_href(state.base, state.page.get_route(), &dest_url);
822 let external: bool = is_external_url(&resolved);
823 state.out.push_str(HTML_A_HREF_OPEN);
824 push_escaped_html(state.out, &resolved);
825 state.out.push('"');
826 if !title.is_empty() {
827 state.out.push_str(HTML_TITLE_ATTR_OPEN);
828 push_escaped_html(state.out, &title);
829 state.out.push('"');
830 }
831 if external {
832 state.out.push_str(HTML_EXTERNAL_LINK_ATTRS);
833 }
834 state.out.push('>');
835 }
836 Event::End(TagEnd::Link) => state.out.push_str(HTML_LINK_CLOSE),
837 Event::Start(Tag::Image {
838 dest_url, title, ..
839 }) => {
840 active_image = Some((dest_url.into_string(), title.into_string(), String::new()));
841 }
842 Event::Start(Tag::Table(aligns)) => {
843 table_alignments = aligns;
844 in_table_head = false;
845 state.out.push_str(HTML_TABLE_OPEN);
846 }
847 Event::End(TagEnd::Table) => {
848 table_alignments.clear();
849 state.out.push_str(HTML_TBODY_CLOSE);
850 state.out.push_str(HTML_TABLE_CLOSE);
851 }
852 Event::Start(Tag::TableHead) => {
853 in_table_head = true;
854 cell_index = 0;
855 state.out.push_str(HTML_THEAD_OPEN);
856 }
857 Event::End(TagEnd::TableHead) => {
858 in_table_head = false;
859 state.out.push_str(HTML_THEAD_CLOSE);
860 state.out.push_str(HTML_TBODY_OPEN);
861 }
862 Event::Start(Tag::TableRow) => {
863 cell_index = 0;
864 state.out.push_str(HTML_TR_OPEN);
865 }
866 Event::End(TagEnd::TableRow) => state.out.push_str(HTML_TR_CLOSE),
867 Event::Start(Tag::TableCell) => {
868 let align_attr: &str = match table_alignments.get(cell_index).copied() {
869 Some(Alignment::Center) => HTML_ALIGN_CENTER,
870 Some(Alignment::Right) => HTML_ALIGN_RIGHT,
871 _ => "",
872 };
873 cell_index += 1;
874 if in_table_head {
875 state.out.push_str(HTML_TH_PREFIX);
876 } else {
877 state.out.push_str(HTML_TD_PREFIX);
878 }
879 state.out.push_str(align_attr);
880 state.out.push('>');
881 }
882 Event::End(TagEnd::TableCell) => {
883 if in_table_head {
884 state.out.push_str(HTML_TH_CLOSE);
885 } else {
886 state.out.push_str(HTML_TD_CLOSE);
887 }
888 }
889 Event::Start(Tag::FootnoteDefinition(label)) => {
890 let fn_slug: String = slugify(&label);
891 state.out.push_str(HTML_FOOTNOTE_DEF_OPEN);
892 push_escaped_html(state.out, &fn_slug);
893 state.out.push_str(HTML_FOOTNOTE_DEF_MID);
894 push_escaped_html(state.out, &label);
895 state.out.push_str(HTML_FOOTNOTE_DEF_CLOSE);
896 }
897 Event::End(TagEnd::FootnoteDefinition) => state.out.push_str(HTML_QUOTE_CLOSE),
898 Event::FootnoteReference(label) => {
899 let fn_slug: String = slugify(&label);
900 state.out.push_str(HTML_FOOTNOTE_REF_OPEN);
901 push_escaped_html(state.out, &fn_slug);
902 state.out.push_str(HTML_FOOTNOTE_REF_MID);
903 push_escaped_html(state.out, &label);
904 state.out.push_str(HTML_FOOTNOTE_REF_CLOSE);
905 }
906 Event::TaskListMarker(checked) => {
907 if checked {
908 state.out.push_str(HTML_TASK_CHECKED);
909 } else {
910 state.out.push_str(HTML_TASK_UNCHECKED);
911 }
912 }
913 Event::Rule => state.out.push_str(HTML_HR),
914 Event::Code(text) => {
915 state.out.push_str(HTML_INLINE_CODE_OPEN);
916 push_escaped_html(state.out, &text);
917 state.out.push_str(HTML_INLINE_CODE_CLOSE);
918 }
919 Event::SoftBreak => state.out.push(' '),
920 Event::HardBreak => state.out.push_str(HTML_BR),
921 Event::InlineMath(math) => {
922 let formatted: String = format_latex_math(&math);
923 state.out.push_str(HTML_MATH_INLINE_OPEN);
924 push_escaped_html(state.out, &formatted);
925 state.out.push_str(HTML_MATH_INLINE_CLOSE);
926 }
927 Event::DisplayMath(math) => {
928 let formatted: String = format_latex_math(&math);
929 state.out.push_str(HTML_MATH_DISPLAY_OPEN);
930 push_escaped_html(state.out, &formatted);
931 state.out.push_str(HTML_MATH_DISPLAY_CLOSE);
932 }
933 Event::Html(raw_html) | Event::InlineHtml(raw_html) => {
934 if is_safe_raw_html(&raw_html) {
935 state.out.push_str(&raw_html);
936 } else {
937 push_escaped_html(state.out, &raw_html);
938 }
939 }
940 _ => {}
941 }
942 }
943 if !pending_text.is_empty() {
944 render_extended_inline_text_html(&pending_text, state.out);
945 }
946}
947
948fn render_fallback_blocks_html(page: &DocPage, out: &mut String) {
955 let mut in_ul: bool = false;
956 for block in page.get_blocks().iter() {
957 let is_item: bool = matches!(block, DocBlock::ListItem(_));
958 if is_item && !in_ul {
959 out.push_str(HTML_UL_OPEN);
960 in_ul = true;
961 } else if !is_item && in_ul {
962 out.push_str(HTML_UL_CLOSE);
963 in_ul = false;
964 }
965 match block {
966 DocBlock::Heading { level, slug, text } => {
967 let tag_lvl: u8 = (*level).clamp(2, 6);
968 let _: fmt::Result = write!(out, "<h{tag_lvl}{HTML_HEADING_ID_MID}");
969 push_escaped_html(out, slug);
970 out.push_str(HTML_LINK_MID);
971 push_escaped_html(out, text);
972 let _: fmt::Result = write!(out, "</h{tag_lvl}>");
973 }
974 DocBlock::Paragraph(text) => {
975 out.push_str(HTML_P_OPEN);
976 push_escaped_html(out, text);
977 out.push_str(HTML_P_CLOSE);
978 }
979 DocBlock::ListItem(text) => {
980 out.push_str(HTML_LI_OPEN);
981 push_escaped_html(out, text);
982 out.push_str(HTML_LI_CLOSE);
983 }
984 DocBlock::BlockQuote(text) => {
985 out.push_str(HTML_QUOTE_OPEN);
986 push_escaped_html(out, text);
987 out.push_str(HTML_QUOTE_CLOSE);
988 }
989 DocBlock::Image { alt, src } => {
990 out.push_str(HTML_P_IMG_OPEN);
991 push_escaped_html(out, src);
992 out.push_str(HTML_IMG_ALT_MID);
993 push_escaped_html(out, alt);
994 out.push_str(HTML_P_IMG_CLOSE);
995 }
996 DocBlock::HorizontalRule => out.push_str(HTML_HR),
997 DocBlock::Code { language, code } => {
998 render_highlighted_code_html(language, code, out);
999 }
1000 DocBlock::Table { headers, rows } => {
1001 out.push_str(HTML_TABLE_OPEN);
1002 if !headers.is_empty() {
1003 out.push_str(HTML_THEAD_OPEN);
1004 for height_val in headers.iter() {
1005 out.push_str(HTML_TH_OPEN);
1006 push_escaped_html(out, height_val);
1007 out.push_str(HTML_TH_CLOSE);
1008 }
1009 out.push_str(HTML_THEAD_CLOSE);
1010 }
1011 out.push_str(HTML_TBODY_OPEN);
1012 for row in rows.iter() {
1013 out.push_str(HTML_TR_OPEN);
1014 for cell in row.iter() {
1015 out.push_str(HTML_TD_OPEN);
1016 push_escaped_html(out, cell);
1017 out.push_str(HTML_TD_CLOSE);
1018 }
1019 out.push_str(HTML_TR_CLOSE);
1020 }
1021 out.push_str(HTML_TBODY_CLOSE);
1022 out.push_str(HTML_TABLE_CLOSE);
1023 }
1024 }
1025 }
1026 if in_ul {
1027 out.push_str(HTML_UL_CLOSE);
1028 }
1029}
1030
1031fn starts_with_ascii_ignore_case(haystack: &str, prefix: &str) -> bool {
1042 let height_val: &[u8] = haystack.as_bytes();
1043 let point_val: &[u8] = prefix.as_bytes();
1044 height_val.len() >= point_val.len()
1045 && height_val[..point_val.len()].eq_ignore_ascii_case(point_val)
1046}
1047
1048fn ends_with_ascii_ignore_case(haystack: &str, suffix: &str) -> bool {
1059 let height_val: &[u8] = haystack.as_bytes();
1060 let source_val: &[u8] = suffix.as_bytes();
1061 height_val.len() >= source_val.len()
1062 && height_val[height_val.len() - source_val.len()..].eq_ignore_ascii_case(source_val)
1063}
1064
1065fn contains_ascii_ignore_case(haystack: &str, needle: &str) -> bool {
1076 let height_val: &[u8] = haystack.as_bytes();
1077 let item_count: &[u8] = needle.as_bytes();
1078 let n_len: usize = item_count.len();
1079 if n_len == 0 {
1080 return true;
1081 }
1082 if n_len > height_val.len() {
1083 return false;
1084 }
1085 let first: u8 = item_count[0];
1086 let tail: &[u8] = &item_count[1..];
1087 let limit: usize = height_val.len() - n_len;
1088 let mut pos: usize = 0;
1089 while pos <= limit {
1090 if height_val[pos].to_ascii_lowercase() == first
1091 && height_val[pos + 1..pos + n_len].eq_ignore_ascii_case(tail)
1092 {
1093 return true;
1094 }
1095 pos += 1;
1096 }
1097 false
1098}
1099
1100fn is_safe_raw_html(raw: &str) -> bool {
1110 if UNSAFE_HTML_TAGS
1111 .iter()
1112 .any(|tag: &&str| contains_ascii_ignore_case(raw, tag))
1113 {
1114 return false;
1115 }
1116 if contains_ascii_ignore_case(raw, SCHEME_JAVASCRIPT)
1117 || contains_ascii_ignore_case(raw, SCHEME_VBSCRIPT)
1118 {
1119 return false;
1120 }
1121 let bytes: &[u8] = raw.as_bytes();
1122 for item_index in 0..bytes.len().saturating_sub(3) {
1123 let before_ok: bool = item_index == 0 || bytes[item_index - 1].is_ascii_whitespace();
1124 if before_ok
1125 && bytes[item_index].to_ascii_lowercase() == BYTE_LOWER_O
1126 && bytes[item_index + 1].to_ascii_lowercase() == BYTE_LOWER_N
1127 && bytes[item_index + 2].is_ascii_alphabetic()
1128 {
1129 let rest: &str = &raw[item_index + 2..];
1130 let attr_len: usize = rest
1131 .bytes()
1132 .take_while(|blue_val: &u8| blue_val.is_ascii_alphabetic())
1133 .count();
1134 if rest[attr_len..].trim_start().starts_with('=') {
1135 return false;
1136 }
1137 }
1138 }
1139 true
1140}
1141
1142fn resolve_link_href(base: &str, current_route: &str, raw_dest: &str) -> String {
1154 let dest: &str = raw_dest.trim();
1155 if starts_with_ascii_ignore_case(dest, SCHEME_JAVASCRIPT)
1156 || starts_with_ascii_ignore_case(dest, SCHEME_VBSCRIPT)
1157 {
1158 return "#".to_string();
1159 }
1160 if dest.starts_with('#')
1161 || starts_with_ascii_ignore_case(dest, SCHEME_HTTP)
1162 || starts_with_ascii_ignore_case(dest, SCHEME_HTTPS)
1163 || starts_with_ascii_ignore_case(dest, SCHEME_MAILTO)
1164 {
1165 return dest.to_string();
1166 }
1167 let (path_part, fragment): (&str, Option<&str>) = match dest.split_once('#') {
1168 Some((point_val, factor_val)) => (point_val, Some(factor_val)),
1169 None => (dest, None),
1170 };
1171 if ends_with_ascii_ignore_case(path_part, MARKDOWN_EXT_SUFFIX) {
1172 let joined: String = join_relative_route(current_route, path_part);
1173 let stripped: &str = joined
1174 .strip_suffix(MARKDOWN_EXT_SUFFIX)
1175 .or_else(|| joined.strip_suffix(MARKDOWN_EXT_UPPER))
1176 .unwrap_or(&joined);
1177 let mut segs: Vec<String> = stripped
1178 .split('/')
1179 .filter(|source_val: &&str| !source_val.is_empty())
1180 .map(|seg: &str| {
1181 let cleaned: String = slugify(seg);
1182 if cleaned.is_empty() {
1183 seg.to_ascii_lowercase()
1184 } else {
1185 cleaned
1186 }
1187 })
1188 .collect();
1189 if let Some(last) = segs.last()
1190 && (last.eq_ignore_ascii_case(STEM_README_LOWER)
1191 || last.eq_ignore_ascii_case(STEM_INDEX_LOWER))
1192 {
1193 let _: Option<String> = segs.pop();
1194 }
1195 let route: String = if segs.is_empty() {
1196 ROOT_ROUTE_STR.to_string()
1197 } else {
1198 format!("/{}", segs.join("/"))
1199 };
1200 let clean: String = href_for_route(base, &route);
1201 return match fragment {
1202 Some(frag) if !frag.is_empty() => format!("{clean}#{frag}"),
1203 _ => clean,
1204 };
1205 }
1206 if dest.starts_with('/') {
1207 if base.is_empty() {
1208 dest.to_string()
1209 } else {
1210 format!("{base}{dest}")
1211 }
1212 } else {
1213 dest.to_string()
1214 }
1215}
1216
1217fn resolve_asset_src(base: &str, current_route: &str, raw_src: &str) -> Option<String> {
1229 let src: &str = raw_src.trim();
1230 if src.is_empty()
1231 || starts_with_ascii_ignore_case(src, SCHEME_JAVASCRIPT)
1232 || starts_with_ascii_ignore_case(src, SCHEME_VBSCRIPT)
1233 {
1234 return None;
1235 }
1236 if starts_with_ascii_ignore_case(src, SCHEME_HTTP)
1237 || starts_with_ascii_ignore_case(src, SCHEME_HTTPS)
1238 || starts_with_ascii_ignore_case(src, SCHEME_DATA)
1239 {
1240 return Some(src.to_string());
1241 }
1242 if src.starts_with('/') {
1243 return Some(if base.is_empty() {
1244 src.to_string()
1245 } else {
1246 format!("{base}{src}")
1247 });
1248 }
1249 let resolved: String = join_relative_route(current_route, src);
1250 Some(if base.is_empty() {
1251 resolved
1252 } else {
1253 format!("{base}{resolved}")
1254 })
1255}
1256
1257fn join_relative_route(current_route: &str, rel_path: &str) -> String {
1268 let mut stack: Vec<&str> = current_route
1269 .trim_matches('/')
1270 .split('/')
1271 .filter(|source_val: &&str| !source_val.is_empty())
1272 .collect();
1273 if !stack.is_empty() {
1274 let _: Option<&str> = stack.pop();
1275 }
1276 for seg in rel_path.split('/') {
1277 if seg.is_empty() || seg == "." {
1278 continue;
1279 }
1280 if seg == ".." {
1281 let _: Option<&str> = stack.pop();
1282 } else {
1283 stack.push(seg);
1284 }
1285 }
1286 if stack.is_empty() {
1287 ROOT_ROUTE_STR.to_string()
1288 } else {
1289 format!("/{}", stack.join("/"))
1290 }
1291}
1292
1293fn is_external_url(href: &str) -> bool {
1303 starts_with_ascii_ignore_case(href, SCHEME_HTTP)
1304 || starts_with_ascii_ignore_case(href, SCHEME_HTTPS)
1305}
1306
1307fn build_sitemap_xml(pages: &[&DocPage], base_url: &str) -> String {
1318 let base: &str = base_url.trim_end_matches('/');
1319 let mut xml: String = String::with_capacity(SITEMAP_HEADER.len() + pages.len() * 64 + 16);
1320 xml.push_str(SITEMAP_HEADER);
1321 for page in pages.iter() {
1322 let loc: String = href_for_route(base, page.get_route());
1323 xml.push_str(SITEMAP_URL_OPEN);
1324 push_escaped_html(&mut xml, &loc);
1325 xml.push_str(SITEMAP_URL_CLOSE);
1326 }
1327 xml.push_str(SITEMAP_FOOTER);
1328 xml
1329}
1330
1331fn copy_static_assets(src_root: &Path, out_dir: &Path) -> io::Result<()> {
1342 let canonical_out: PathBuf =
1343 fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
1344 for dir_name in ASSET_COPY_DIRS.iter() {
1345 let candidate: PathBuf = src_root.join(dir_name);
1346 if candidate.is_dir() {
1347 copy_dir_recursive(&candidate, &out_dir.join(dir_name), &canonical_out)?;
1348 }
1349 }
1350 copy_colocated_media(src_root, src_root, out_dir, &canonical_out)
1351}
1352
1353fn copy_dir_recursive(src: &Path, dst: &Path, canonical_out: &Path) -> io::Result<()> {
1365 let src_canon: PathBuf = fs::canonicalize(src).unwrap_or_else(|_| src.to_path_buf());
1366 if src_canon == canonical_out || src_canon.starts_with(canonical_out) {
1367 return Ok(());
1368 }
1369 fs::create_dir_all(dst)?;
1370 for entry_res in fs::read_dir(src)? {
1371 let entry: DirEntry = entry_res?;
1372 let path: PathBuf = entry.path();
1373 let target: PathBuf = dst.join(entry.file_name());
1374 if path.is_dir() {
1375 copy_dir_recursive(&path, &target, canonical_out)?;
1376 } else if path
1377 .extension()
1378 .and_then(|source_val: &OsStr| source_val.to_str())
1379 .is_none_or(|ext: &str| !ext.eq_ignore_ascii_case(MARKDOWN_EXT_CHECK))
1380 {
1381 let _: u64 = fs::copy(&path, &target)?;
1382 }
1383 }
1384 Ok(())
1385}
1386
1387fn copy_colocated_media(
1400 src_root: &Path,
1401 cur_dir: &Path,
1402 out_dir: &Path,
1403 canonical_out: &Path,
1404) -> io::Result<()> {
1405 for entry_res in fs::read_dir(cur_dir)? {
1406 let entry: DirEntry = entry_res?;
1407 let path: PathBuf = entry.path();
1408 if path.is_dir() {
1409 let name: String = entry.file_name().to_string_lossy().into_owned();
1410 if should_skip_dir(&name) {
1411 continue;
1412 }
1413 if cur_dir == src_root
1414 && ASSET_COPY_DIRS
1415 .iter()
1416 .any(|delta_val: &&str| name.eq_ignore_ascii_case(delta_val))
1417 {
1418 continue;
1419 }
1420 let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
1421 if canon == canonical_out || canon.starts_with(canonical_out) {
1422 continue;
1423 }
1424 copy_colocated_media(src_root, &path, out_dir, canonical_out)?;
1425 } else if path
1426 .extension()
1427 .and_then(|source_val: &OsStr| source_val.to_str())
1428 .is_some_and(|ext: &str| {
1429 CO_LOCATED_ASSET_EXTS
1430 .iter()
1431 .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
1432 })
1433 && let Ok(rel) = path.strip_prefix(src_root)
1434 {
1435 let target: PathBuf = out_dir.join(rel);
1436 if let Some(parent) = target.parent() {
1437 fs::create_dir_all(parent)?;
1438 }
1439 let _: u64 = fs::copy(&path, &target)?;
1440 }
1441 }
1442 Ok(())
1443}
1444
1445fn href_for_route(base: &str, route: &str) -> String {
1456 let trimmed: &str = route.trim_matches('/');
1457 if trimmed.is_empty() {
1458 if base.is_empty() {
1459 ROOT_ROUTE_STR.to_string()
1460 } else {
1461 format!("{base}/")
1462 }
1463 } else if base.is_empty() {
1464 format!("/{trimmed}/")
1465 } else {
1466 format!("{base}/{trimmed}/")
1467 }
1468}
1469
1470fn html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1481 let trimmed: &str = route.trim_matches('/');
1482 if trimmed.is_empty() {
1483 out_dir.join(INDEX_HTML_NAME)
1484 } else {
1485 out_dir.join(format!("{trimmed}{HTML_EXT}"))
1486 }
1487}
1488
1489fn clean_html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1500 let trimmed: &str = route.trim_matches('/');
1501 if trimmed.is_empty() {
1502 out_dir.join(INDEX_HTML_NAME)
1503 } else {
1504 out_dir.join(trimmed).join(INDEX_HTML_NAME)
1505 }
1506}
1507
1508fn render_highlighted_code_html(language: &str, code: &str, out: &mut String) {
1516 render_highlighted_code_html_with_meta(language, None, &[], code, out);
1517}
1518
1519fn render_highlighted_code_html_with_meta(
1529 language: &str,
1530 title: Option<&str>,
1531 highlight_lines: &[usize],
1532 code: &str,
1533 out: &mut String,
1534) {
1535 let resolved_lang: CodeLang = CodeLang::from_name(language);
1536 out.push_str(HTML_CODE_WRAP_OPEN);
1537 if let Some(fname) = title {
1538 push_escaped_html(out, fname);
1539 out.push_str(" · ");
1540 }
1541 push_escaped_html(out, language);
1542 out.push_str(HTML_CODE_HEAD_MID);
1543 push_escaped_html(out, language);
1544 out.push_str(HTML_LINK_MID);
1545 for (idx, line) in code.split('\n').enumerate() {
1546 let line_no: usize = idx + 1;
1547 let is_hl: bool =
1548 !highlight_lines.is_empty() && highlight_lines.binary_search(&line_no).is_ok();
1549 if is_hl {
1550 out.push_str(HTML_CODE_LINE_HL_OPEN);
1551 } else {
1552 out.push_str(HTML_CODE_LINE_OPEN);
1553 }
1554 let _: fmt::Result = write!(out, "{line_no}");
1555 out.push_str(HTML_CODE_LINE_MID);
1556 let spans: Vec<CodeSpan> = tokenize_code_line_with_lang(line, resolved_lang);
1557 for span in spans.iter() {
1558 let class_opt: Option<&str> = match span.get_kind() {
1559 CodeTokenKind::Keyword => Some(TOK_CLASS_KW),
1560 CodeTokenKind::Control => Some(TOK_CLASS_CTRL),
1561 CodeTokenKind::Operator => Some(TOK_CLASS_OP),
1562 CodeTokenKind::Function => Some(TOK_CLASS_FN),
1563 CodeTokenKind::Type => Some(TOK_CLASS_TY),
1564 CodeTokenKind::PrimitiveType => Some(TOK_CLASS_PRIM),
1565 CodeTokenKind::String => Some(TOK_CLASS_STR),
1566 CodeTokenKind::Number => Some(TOK_CLASS_NUM),
1567 CodeTokenKind::Comment => Some(TOK_CLASS_CMT),
1568 CodeTokenKind::Macro => Some(TOK_CLASS_MAC),
1569 CodeTokenKind::Property => Some(TOK_CLASS_PROP),
1570 CodeTokenKind::Constant => Some(TOK_CLASS_CONST),
1571 CodeTokenKind::Punctuation => Some(TOK_CLASS_PUNC),
1572 CodeTokenKind::DiffAdd => Some(TOK_CLASS_ADD),
1573 CodeTokenKind::DiffDel => Some(TOK_CLASS_DEL),
1574 CodeTokenKind::Plain => None,
1575 };
1576 if let Some(cls) = class_opt {
1577 out.push_str(HTML_SPAN_CLASS_OPEN);
1578 out.push_str(cls);
1579 out.push_str(HTML_LINK_MID);
1580 push_escaped_html(out, span.get_text());
1581 out.push_str(HTML_SPAN_CLOSE);
1582 } else {
1583 push_escaped_html(out, span.get_text());
1584 }
1585 }
1586 out.push_str(HTML_CODE_LINE_CLOSE);
1587 }
1588 out.push_str(HTML_CODE_CLOSE);
1589}
1590
1591fn render_echart_svg_html(source: &str, out: &mut String) {
1598 let opt: EuvChartOption = parse_markdown_echart_option(source);
1599 let title: &str = opt
1600 .title_opt()
1601 .map(|blend_factor: &EuvChartTitle| blend_factor.get_text().as_str())
1602 .filter(|source_val: &&str| !source_val.is_empty())
1603 .unwrap_or("Chart");
1604 out.push_str(ECHART_CARD_OPEN);
1605 push_escaped_html(out, title);
1606 out.push_str(MERMAID_CARD_MID);
1607 let labels: Vec<String> = opt
1608 .get_x_axes()
1609 .first()
1610 .map(|alpha_val: &EuvChartAxis| alpha_val.get_categories().clone())
1611 .unwrap_or_default();
1612 if let Some(first_ser) = opt.get_series().first()
1613 && let EuvChartSeriesData::Pie(pie) = first_ser.get_data()
1614 {
1615 let mut slices: Vec<MermaidPieSlice> = Vec::with_capacity(pie.get_slices().len());
1616 for scale_val in pie.get_slices().iter() {
1617 slices.push(MermaidPieSlice::new(
1618 scale_val.get_name().clone(),
1619 scale_val.get_value(),
1620 ));
1621 }
1622 let mut chart: MermaidPieChart = MermaidPieChart::default();
1623 chart.set_title(title.to_string()).set_slices(slices);
1624 render_mermaid_pie_svg(&chart, out);
1625 out.push_str(MERMAID_CARD_CLOSE);
1626 return;
1627 }
1628 let mut xy: MermaidXyChart = MermaidXyChart::default();
1629 xy.set_title(title.to_string()).set_x_labels(labels);
1630 let mut series_vec: Vec<MermaidXySeries> = Vec::new();
1631 for ser in opt.get_series().iter() {
1632 match ser.get_data() {
1633 EuvChartSeriesData::Bar(bar) => {
1634 let vals: Vec<f32> = bar
1635 .get_values()
1636 .iter()
1637 .map(|item_val: &Option<f32>| item_val.unwrap_or(0.0))
1638 .collect();
1639 series_vec.push(MermaidXySeries::new(true, vals));
1640 }
1641 EuvChartSeriesData::Line(line) => {
1642 let vals: Vec<f32> = line
1643 .get_values()
1644 .iter()
1645 .map(|tex_v: &Option<f32>| tex_v.unwrap_or(0.0))
1646 .collect();
1647 series_vec.push(MermaidXySeries::new(false, vals));
1648 }
1649 _ => {}
1650 }
1651 }
1652 xy.set_series(series_vec);
1653 render_mermaid_xychart_svg(&xy, out);
1654 out.push_str(MERMAID_CARD_CLOSE);
1655}
1656
1657fn push_escaped_html(out: &mut String, input: &str) {
1664 let bytes: &[u8] = input.as_bytes();
1665 let mut start: usize = 0;
1666 for (idx, &byte) in bytes.iter().enumerate() {
1667 let esc: &str = match byte {
1668 BYTE_AMP => HTML_ESC_AMP,
1669 BYTE_LT => HTML_ESC_LT,
1670 BYTE_GT => HTML_ESC_GT,
1671 BYTE_DQUOTE => HTML_ESC_QUOT,
1672 _ => continue,
1673 };
1674 if start < idx {
1675 out.push_str(&input[start..idx]);
1676 }
1677 out.push_str(esc);
1678 start = idx + 1;
1679 }
1680 if start < bytes.len() {
1681 out.push_str(&input[start..]);
1682 }
1683}
1684
1685fn escape_html(input: &str) -> String {
1695 let mut out: String = String::with_capacity(input.len());
1696 push_escaped_html(&mut out, input);
1697 out
1698}
1699
1700fn push_escaped_html_char(ch: char, out: &mut String) {
1707 match ch {
1708 '&' => out.push_str(HTML_ESC_AMP),
1709 '<' => out.push_str(HTML_ESC_LT),
1710 '>' => out.push_str(HTML_ESC_GT),
1711 '"' => out.push_str(HTML_ESC_QUOT),
1712 _ => out.push(ch),
1713 }
1714}
1715
1716fn has_extended_inline_trigger(bytes: &[u8]) -> bool {
1726 for &byte in bytes.iter() {
1727 if byte == BYTE_EQ || byte == BYTE_CARET || byte == BYTE_TILDE || byte == BYTE_COLON {
1728 return true;
1729 }
1730 }
1731 false
1732}
1733
1734fn render_extended_inline_text_html(raw: &str, out: &mut String) {
1741 let bytes: &[u8] = raw.as_bytes();
1742 if !has_extended_inline_trigger(bytes) {
1743 push_escaped_html(out, raw);
1744 return;
1745 }
1746 let len: usize = bytes.len();
1747 let mut item_index: usize = 0;
1748 while item_index < len {
1749 if item_index + 1 < len && bytes[item_index] == BYTE_EQ && bytes[item_index + 1] == BYTE_EQ
1750 {
1751 let rest: &str = &raw[item_index + 2..];
1752 if let Some(close_rel) = rest.find("==")
1753 && !rest[..close_rel].trim().is_empty()
1754 {
1755 out.push_str(HTML_MARK_OPEN);
1756 render_extended_inline_text_html(&rest[..close_rel], out);
1757 out.push_str(HTML_MARK_CLOSE);
1758 item_index += 2 + close_rel + 2;
1759 continue;
1760 }
1761 }
1762 if bytes[item_index] == BYTE_CARET {
1763 let rest: &str = &raw[item_index + 1..];
1764 if let Some(close_rel) = rest.find('^') {
1765 let inner: &str = &rest[..close_rel];
1766 if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
1767 out.push_str(HTML_SUP_OPEN);
1768 push_escaped_html(out, inner);
1769 out.push_str(HTML_SUP_CLOSE);
1770 item_index += 1 + close_rel + 1;
1771 continue;
1772 }
1773 }
1774 }
1775 if bytes[item_index] == BYTE_TILDE
1776 && !(item_index + 1 < len && bytes[item_index + 1] == BYTE_TILDE)
1777 {
1778 let rest: &str = &raw[item_index + 1..];
1779 if let Some(close_rel) = rest.find('~') {
1780 let inner: &str = &rest[..close_rel];
1781 if !inner.is_empty() && !inner.chars().any(char::is_whitespace) {
1782 out.push_str(HTML_SUB_OPEN);
1783 push_escaped_html(out, inner);
1784 out.push_str(HTML_SUB_CLOSE);
1785 item_index += 1 + close_rel + 1;
1786 continue;
1787 }
1788 }
1789 }
1790 if bytes[item_index] == BYTE_COLON {
1791 let rest: &str = &raw[item_index + 1..];
1792 if let Some(close_rel) = rest.find(':') {
1793 let code: &str = &rest[..close_rel];
1794 if !code.is_empty()
1795 && code.len() <= 32
1796 && code.bytes().all(|blue_val: u8| {
1797 blue_val.is_ascii_alphanumeric()
1798 || blue_val == BYTE_UNDERSCORE
1799 || blue_val == BYTE_DASH
1800 })
1801 && let Some(emoji) = resolve_emoji_shortcode(code)
1802 {
1803 out.push_str(emoji);
1804 item_index += 1 + close_rel + 1;
1805 continue;
1806 }
1807 }
1808 }
1809 if let Some(ch) = raw[item_index..].chars().next() {
1810 push_escaped_html_char(ch, out);
1811 item_index += ch.len_utf8();
1812 } else {
1813 break;
1814 }
1815 }
1816}
1817
1818fn render_mermaid_svg_html(source: &str, out: &mut String) {
1825 let diagram: MermaidDiagram = parse_mermaid_diagram(source);
1826 let badge: &str = match &diagram {
1827 MermaidDiagram::Flowchart(_) => MERMAID_BADGE_FLOWCHART,
1828 MermaidDiagram::Sequence(_) => MERMAID_BADGE_SEQUENCE,
1829 MermaidDiagram::State(_) => MERMAID_BADGE_STATE,
1830 MermaidDiagram::Class(_) => MERMAID_BADGE_CLASS,
1831 MermaidDiagram::Er(_) => MERMAID_BADGE_ER,
1832 MermaidDiagram::Pie(_) => MERMAID_BADGE_PIE,
1833 MermaidDiagram::Gantt(_) => MERMAID_BADGE_GANTT,
1834 MermaidDiagram::Timeline(_) => MERMAID_BADGE_TIMELINE,
1835 MermaidDiagram::Mindmap(_) => MERMAID_BADGE_MINDMAP,
1836 MermaidDiagram::XyChart(_) => MERMAID_BADGE_XYCHART,
1837 MermaidDiagram::GitGraph(_) => MERMAID_BADGE_GITGRAPH,
1838 };
1839 out.push_str(MERMAID_CARD_OPEN);
1840 out.push_str(badge);
1841 out.push_str(MERMAID_CARD_MID);
1842 match &diagram {
1843 MermaidDiagram::Flowchart(fc) | MermaidDiagram::State(fc) => {
1844 render_mermaid_flow_svg(fc, out);
1845 }
1846 MermaidDiagram::Sequence(seq) => {
1847 render_mermaid_sequence_svg(seq, out);
1848 }
1849 MermaidDiagram::Class(cls) => {
1850 render_mermaid_class_svg(cls, out);
1851 }
1852 MermaidDiagram::Er(er) => {
1853 render_mermaid_er_svg(er, out);
1854 }
1855 MermaidDiagram::Pie(pie) => {
1856 render_mermaid_pie_svg(pie, out);
1857 }
1858 MermaidDiagram::Gantt(gantt) => {
1859 render_mermaid_gantt_svg(gantt, out);
1860 }
1861 MermaidDiagram::Timeline(tl) => {
1862 render_mermaid_timeline_svg(tl, out);
1863 }
1864 MermaidDiagram::Mindmap(mm) => {
1865 render_mermaid_mindmap_svg(mm, out);
1866 }
1867 MermaidDiagram::XyChart(xy) => {
1868 render_mermaid_xychart_svg(xy, out);
1869 }
1870 MermaidDiagram::GitGraph(git) => {
1871 render_mermaid_gitgraph_svg(git, out);
1872 }
1873 }
1874 out.push_str(MERMAID_CARD_CLOSE);
1875}
1876
1877fn dfs_svg_dag_edges(
1886 tex_u: usize,
1887 adj: &[Vec<usize>],
1888 state: &mut [u8],
1889 dag_edges: &mut Vec<(usize, usize)>,
1890) {
1891 state[tex_u] = 1;
1892 for &item_val in adj[tex_u].iter() {
1893 if tex_u == item_val || state[item_val] == 1 {
1894 continue;
1895 }
1896 dag_edges.push((tex_u, item_val));
1897 if state[item_val] == 0 {
1898 dfs_svg_dag_edges(item_val, adj, state, dag_edges);
1899 }
1900 }
1901 state[tex_u] = 2;
1902}
1903
1904fn safe_svg_color(opt: Option<&String>, fallback: &str) -> String {
1915 if let Some(raw) = opt {
1916 let trimmed: &str = raw.trim();
1917 let valid: bool = !trimmed.is_empty()
1918 && trimmed.len() <= 32
1919 && trimmed.bytes().all(|blue_val: u8| {
1920 blue_val.is_ascii_alphanumeric() || blue_val == BYTE_HASH || blue_val == BYTE_DASH
1921 });
1922 if valid {
1923 return trimmed.to_string();
1924 }
1925 }
1926 fallback.to_string()
1927}
1928
1929fn node_in_subgraph(
1941 mut cur: Option<usize>,
1942 target_sg: usize,
1943 subgraphs: &[MermaidSubgraph],
1944) -> bool {
1945 let mut hops: usize = 0;
1946 while let Some(idx) = cur {
1947 if idx == target_sg {
1948 return true;
1949 }
1950 hops += 1;
1951 if hops > subgraphs.len() {
1952 break;
1953 }
1954 cur = subgraphs
1955 .get(idx)
1956 .and_then(|sg: &MermaidSubgraph| sg.get_parent());
1957 }
1958 false
1959}
1960
1961fn subgraph_depth(sg_idx: usize, subgraphs: &[MermaidSubgraph]) -> usize {
1972 let mut depth: usize = 0;
1973 let mut cur: Option<usize> = subgraphs
1974 .get(sg_idx)
1975 .and_then(|sg: &MermaidSubgraph| sg.get_parent());
1976 while let Some(parent_idx) = cur {
1977 depth += 1;
1978 if depth > subgraphs.len() {
1979 break;
1980 }
1981 cur = subgraphs
1982 .get(parent_idx)
1983 .and_then(|sg: &MermaidSubgraph| sg.get_parent());
1984 }
1985 depth
1986}
1987
1988fn render_mermaid_flow_svg(fc: &MermaidFlowchart, out: &mut String) {
1995 let item_count: usize = fc.get_nodes().len();
1996 if item_count == 0 {
1997 return;
1998 }
1999 let mut id_map: HashMap<&str, usize> = HashMap::with_capacity(item_count);
2000 for (idx, node) in fc.get_nodes().iter().enumerate() {
2001 let _: Option<usize> = id_map.insert(node.get_id().as_str(), idx);
2002 }
2003 let mut adj: Vec<Vec<usize>> = vec![Vec::new(); item_count];
2004 let mut in_deg: Vec<usize> = vec![0; item_count];
2005 for edge in fc.get_edges().iter() {
2006 if let (Some(&tex_u), Some(&item_val)) = (
2007 id_map.get(edge.get_from().as_str()),
2008 id_map.get(edge.get_to().as_str()),
2009 ) && tex_u != item_val
2010 {
2011 adj[tex_u].push(item_val);
2012 in_deg[item_val] += 1;
2013 }
2014 }
2015 let mut visit_state: Vec<u8> = vec![0; item_count];
2016 let mut dag_edges: Vec<(usize, usize)> = Vec::with_capacity(fc.get_edges().len());
2017 for (idx, node) in fc.get_nodes().iter().enumerate() {
2018 if node.get_shape() == MermaidNodeShape::StateStart && visit_state[idx] == 0 {
2019 dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
2020 }
2021 }
2022 for (idx, node) in fc.get_nodes().iter().enumerate() {
2023 if in_deg[idx] == 0
2024 && node.get_shape() != MermaidNodeShape::StateEnd
2025 && visit_state[idx] == 0
2026 {
2027 dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
2028 }
2029 }
2030 for idx in 0..item_count {
2031 if visit_state[idx] == 0 {
2032 dfs_svg_dag_edges(idx, &adj, &mut visit_state, &mut dag_edges);
2033 }
2034 }
2035 let mut layers: Vec<usize> = vec![0; item_count];
2036 for _ in 0..item_count {
2037 let mut changed: bool = false;
2038 for &(bary_u, tex_v) in dag_edges.iter() {
2039 if layers[tex_v] <= layers[bary_u] && layers[bary_u] + 1 < item_count {
2040 layers[tex_v] = layers[bary_u] + 1;
2041 changed = true;
2042 }
2043 }
2044 if !changed {
2045 break;
2046 }
2047 }
2048 for edge in fc.get_edges().iter() {
2049 if let (Some(&unit_u), Some(&bary_v)) = (
2050 id_map.get(edge.get_from().as_str()),
2051 id_map.get(edge.get_to().as_str()),
2052 ) && unit_u != bary_v
2053 && fc.get_nodes()[bary_v].get_shape() == MermaidNodeShape::StateEnd
2054 && layers[bary_v] <= layers[unit_u]
2055 {
2056 layers[bary_v] = layers[unit_u] + 1;
2057 }
2058 }
2059 let max_layer: usize = layers.iter().copied().max().unwrap_or(0);
2060 let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); max_layer + 1];
2061 for (idx, &lay) in layers.iter().enumerate() {
2062 buckets[lay].push(idx);
2063 }
2064 let horiz: bool = matches!(
2065 fc.get_direction(),
2066 MermaidFlowDirection::LeftRight | MermaidFlowDirection::RightLeft
2067 );
2068 let reversed: bool = matches!(
2069 fc.get_direction(),
2070 MermaidFlowDirection::RightLeft | MermaidFlowDirection::BottomTop
2071 );
2072 let node_sizes: Vec<(f32, f32)> = fc
2073 .get_nodes()
2074 .iter()
2075 .map(|node: &MermaidFlowNode| {
2076 let chars: f32 = node.get_label().chars().count() as f32;
2077 match node.get_shape() {
2078 MermaidNodeShape::StateStart | MermaidNodeShape::StateEnd => (24.0, 24.0),
2079 MermaidNodeShape::ForkJoin => {
2080 if horiz {
2081 (10.0, 64.0)
2082 } else {
2083 (88.0, 10.0)
2084 }
2085 }
2086 MermaidNodeShape::Circle | MermaidNodeShape::DoubleCircle => {
2087 let delta_val: f32 = (chars * 7.6 + 28.0).clamp(54.0, 102.0);
2088 (delta_val, delta_val)
2089 }
2090 MermaidNodeShape::Diamond => {
2091 let width_val: f32 = (chars * 8.0 + 48.0).clamp(112.0, 204.0);
2092 (width_val, 60.0)
2093 }
2094 MermaidNodeShape::Hexagon
2095 | MermaidNodeShape::Parallelogram
2096 | MermaidNodeShape::ParallelogramAlt
2097 | MermaidNodeShape::Trapezoid
2098 | MermaidNodeShape::TrapezoidAlt
2099 | MermaidNodeShape::Asymmetric => {
2100 let span_width: f32 = (chars * 7.8 + 46.0).clamp(112.0, 224.0);
2101 (span_width, 42.0)
2102 }
2103 MermaidNodeShape::Cylinder => {
2104 let weight_val: f32 = (chars * 7.6 + 38.0).clamp(104.0, 212.0);
2105 (weight_val, 48.0)
2106 }
2107 _ => {
2108 let width_val_primary: f32 = (chars * 7.6 + 36.0).clamp(96.0, 216.0);
2109 (width_val_primary, 40.0)
2110 }
2111 }
2112 })
2113 .collect();
2114 let has_sg: bool = !fc.get_subgraphs().is_empty();
2115 let pad: f32 = if has_sg { 44.0 } else { 28.0 };
2116 let main_gap: f32 = if horiz { 58.0 } else { 48.0 };
2117 let cross_gap: f32 = 28.0;
2118 let layer_count: usize = buckets.len();
2119 let mut layer_main: Vec<f32> = vec![0.0; layer_count];
2120 let mut layer_cross: Vec<f32> = vec![0.0; layer_count];
2121 for (li, items) in buckets.iter().enumerate() {
2122 let mut max_m: f32 = 0.0;
2123 let mut sum_c: f32 = 0.0;
2124 for (pos, &ni) in items.iter().enumerate() {
2125 let (nw, nh): (f32, f32) = node_sizes[ni];
2126 if horiz {
2127 max_m = max_m.max(nw);
2128 sum_c += nh;
2129 } else {
2130 max_m = max_m.max(nh);
2131 sum_c += nw;
2132 }
2133 if pos + 1 < items.len() {
2134 sum_c += cross_gap;
2135 }
2136 }
2137 layer_main[li] = max_m;
2138 layer_cross[li] = sum_c;
2139 }
2140 let total_main: f32 =
2141 layer_main.iter().sum::<f32>() + (layer_count.saturating_sub(1) as f32) * main_gap;
2142 let total_cross: f32 = layer_cross.iter().copied().fold(0.0_f32, f32::max);
2143 let mut rects: Vec<(f32, f32, f32, f32)> = vec![(0.0, 0.0, 0.0, 0.0); item_count];
2144 let mut main_cur: f32 = pad;
2145 let order: Vec<usize> = if reversed {
2146 (0..layer_count).rev().collect()
2147 } else {
2148 (0..layer_count).collect()
2149 };
2150 for li in order.into_iter() {
2151 let items: &[usize] = &buckets[li];
2152 let band_m: f32 = layer_main[li];
2153 let band_c: f32 = layer_cross[li];
2154 let mut cross_cur: f32 = pad + (total_cross - band_c) * 0.5;
2155 for &ni in items.iter() {
2156 let (nw, nh): (f32, f32) = node_sizes[ni];
2157 if horiz {
2158 rects[ni] = (main_cur + (band_m - nw) * 0.5, cross_cur, nw, nh);
2159 cross_cur += nh + cross_gap;
2160 } else {
2161 rects[ni] = (cross_cur, main_cur + (band_m - nh) * 0.5, nw, nh);
2162 cross_cur += nw + cross_gap;
2163 }
2164 }
2165 main_cur += band_m + main_gap;
2166 }
2167 let (svg_w, svg_h): (f32, f32) = if horiz {
2168 (
2169 (total_main + pad * 2.0).max(380.0),
2170 (total_cross + pad * 2.0).max(160.0),
2171 )
2172 } else {
2173 (
2174 (total_cross + pad * 2.0).max(380.0),
2175 (total_main + pad * 2.0).max(160.0),
2176 )
2177 };
2178 let _: fmt::Result = write!(
2179 out,
2180 "<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\">"
2181 );
2182 out.push_str(MERMAID_SVG_ARROW_MARKER);
2183 if has_sg {
2184 let mut sg_order: Vec<(usize, usize)> = (0..fc.get_subgraphs().len())
2185 .map(|item_index: usize| (subgraph_depth(item_index, fc.get_subgraphs()), item_index))
2186 .collect();
2187 sg_order.sort_by_key(|&(distance_val, outer_index): &(usize, usize)| {
2188 (distance_val, outer_index)
2189 });
2190 let max_depth: usize = sg_order
2191 .iter()
2192 .map(|&(depth_val, _): &(usize, usize)| depth_val)
2193 .max()
2194 .unwrap_or(0);
2195 for (depth, sg_idx) in sg_order.into_iter() {
2196 let mut min_x: f32 = f32::MAX;
2197 let mut min_y: f32 = f32::MAX;
2198 let mut max_x: f32 = f32::MIN;
2199 let mut max_y: f32 = f32::MIN;
2200 let mut found: bool = false;
2201 for (ni, node) in fc.get_nodes().iter().enumerate() {
2202 if node_in_subgraph(node.get_subgraph(), sg_idx, fc.get_subgraphs()) {
2203 let (rx, ry, rw, rh): (f32, f32, f32, f32) = rects[ni];
2204 min_x = min_x.min(rx);
2205 min_y = min_y.min(ry);
2206 max_x = max_x.max(rx + rw);
2207 max_y = max_y.max(ry + rh);
2208 found = true;
2209 }
2210 }
2211 if !found {
2212 continue;
2213 }
2214 let extra: f32 = ((max_depth - depth) as f32) * 10.0;
2215 let sx: f32 = (min_x - 14.0 - extra).max(4.0);
2216 let sy: f32 = (min_y - 26.0 - extra).max(4.0);
2217 let stroke_width: f32 = (max_x - min_x + 28.0 + extra * 2.0).min(svg_w - sx - 4.0);
2218 let sh: f32 = (max_y - min_y + 40.0 + extra * 2.0).min(svg_h - sy - 4.0);
2219 let accent: &str = MERMAID_SVG_PALETTE[sg_idx % MERMAID_SVG_PALETTE.len()];
2220 let sg_title: &str = fc.get_subgraphs()[sg_idx].get_title().as_str();
2221 let _: fmt::Result = write!(
2222 out,
2223 "<rect x=\"{sx:.1}\" y=\"{sy:.1}\" width=\"{stroke_width:.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}\">",
2224 sx + 10.0,
2225 sy + 15.0
2226 );
2227 push_escaped_html(out, sg_title);
2228 out.push_str(SVG_TEXT_CLOSE);
2229 }
2230 }
2231 for edge in fc.get_edges().iter() {
2232 if let (Some(&upper_val), Some(&sample_val)) = (
2233 id_map.get(edge.get_from().as_str()),
2234 id_map.get(edge.get_to().as_str()),
2235 ) {
2236 let (ux, uy, uw, uh): (f32, f32, f32, f32) = rects[upper_val];
2237 let (vx, vy, vw, vh): (f32, f32, f32, f32) = rects[sample_val];
2238 let (x1, y1, x2, y2): (f32, f32, f32, f32) = if horiz {
2239 let sx: f32 = if vx >= ux { ux + uw } else { ux };
2240 let tx: f32 = if vx >= ux { vx } else { vx + vw };
2241 (sx, uy + uh * 0.5, tx, vy + vh * 0.5)
2242 } else {
2243 let sy: f32 = if vy >= uy { uy + uh } else { uy };
2244 let ty: f32 = if vy >= uy { vy } else { vy + vh };
2245 (ux + uw * 0.5, sy, vx + vw * 0.5, ty)
2246 };
2247 let style: MermaidEdgeStyle = edge.get_style();
2248 let dash: &str = match style {
2249 MermaidEdgeStyle::Dashed
2250 | MermaidEdgeStyle::DashedPlain
2251 | MermaidEdgeStyle::DashedBidir
2252 | MermaidEdgeStyle::DashedOpenArrow
2253 | MermaidEdgeStyle::DashedAsyncArrow
2254 | MermaidEdgeStyle::DashedCrossArrow => MERMAID_SVG_DASH_ATTR,
2255 _ => "",
2256 };
2257 let source_width: f32 = match style {
2258 MermaidEdgeStyle::Thick
2259 | MermaidEdgeStyle::ThickPlain
2260 | MermaidEdgeStyle::ThickBidir => 2.6,
2261 _ => 1.6,
2262 };
2263 let marker_start: &str = match style {
2264 MermaidEdgeStyle::Bidir
2265 | MermaidEdgeStyle::DashedBidir
2266 | MermaidEdgeStyle::ThickBidir => MERMAID_SVG_MARKER_START_ATTR,
2267 MermaidEdgeStyle::CircleBoth => MERMAID_SVG_MARKER_CIRCLE_START,
2268 MermaidEdgeStyle::CrossBoth => MERMAID_SVG_MARKER_CROSS_START,
2269 _ => "",
2270 };
2271 let marker_end: &str = match style {
2272 MermaidEdgeStyle::Plain
2273 | MermaidEdgeStyle::DashedPlain
2274 | MermaidEdgeStyle::ThickPlain => "",
2275 MermaidEdgeStyle::CircleEnd | MermaidEdgeStyle::CircleBoth => {
2276 MERMAID_SVG_MARKER_CIRCLE_END
2277 }
2278 MermaidEdgeStyle::CrossEnd
2279 | MermaidEdgeStyle::CrossBoth
2280 | MermaidEdgeStyle::CrossArrow
2281 | MermaidEdgeStyle::DashedCrossArrow => MERMAID_SVG_MARKER_CROSS_END,
2282 _ => MERMAID_SVG_MARKER_ATTR,
2283 };
2284 let _: fmt::Result = write!(
2285 out,
2286 "<line x1=\"{x1:.1}\" y1=\"{y1:.1}\" x2=\"{x2:.1}\" y2=\"{y2:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"{source_width:.1}\"{dash}{marker_start}{marker_end}/>"
2287 );
2288 let text_value: &str = edge.get_label().trim();
2289 if !text_value.is_empty() {
2290 let mx: f32 = (x1 + x2) * 0.5;
2291 let my: f32 = (y1 + y2) * 0.5;
2292 let border_width: f32 =
2293 ((text_value.chars().count() as f32) * 6.8 + 12.0).max(28.0);
2294 let bx: f32 = mx - border_width * 0.5;
2295 let by: f32 = my - 10.0;
2296 let _: fmt::Result = write!(
2297 out,
2298 "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{border_width:.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)\">",
2299 my + 4.0
2300 );
2301 push_escaped_html(out, text_value);
2302 out.push_str(SVG_TEXT_CLOSE);
2303 }
2304 }
2305 }
2306 for (idx, node) in fc.get_nodes().iter().enumerate() {
2307 let (rx, ry, rw, rh): (f32, f32, f32, f32) = rects[idx];
2308 let cx: f32 = rx + rw * 0.5;
2309 let cy: f32 = ry + rh * 0.5;
2310 let default_accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2311 let fill: String = safe_svg_color(node.try_get_fill().as_ref(), MERMAID_SVG_VAR_MUTED);
2312 let stroke: String = safe_svg_color(node.try_get_stroke().as_ref(), default_accent);
2313 let text_col: String =
2314 safe_svg_color(node.try_get_text_color().as_ref(), MERMAID_SVG_VAR_FG);
2315 match node.get_shape() {
2316 MermaidNodeShape::StateStart => {
2317 let _: fmt::Result = write!(
2318 out,
2319 "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"9\" fill=\"var(--fg)\"/>"
2320 );
2321 }
2322 MermaidNodeShape::StateEnd => {
2323 let _: fmt::Result = write!(
2324 out,
2325 "<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)\"/>"
2326 );
2327 }
2328 MermaidNodeShape::ForkJoin => {
2329 let _: fmt::Result = write!(
2330 out,
2331 "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"4\" fill=\"var(--fg)\"/>"
2332 );
2333 }
2334 MermaidNodeShape::Diamond => {
2335 let _: fmt::Result = write!(
2336 out,
2337 "<polygon points=\"{cx:.1},{ry:.1} {:.1},{cy:.1} {cx:.1},{:.1} {rx:.1},{cy:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2338 rx + rw,
2339 ry + rh
2340 );
2341 }
2342 MermaidNodeShape::Hexagon => {
2343 let ins: f32 = 14.0;
2344 let _: fmt::Result = write!(
2345 out,
2346 "<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\"/>",
2347 rx + ins,
2348 rx + rw - ins,
2349 rx + rw,
2350 rx + rw - ins,
2351 ry + rh,
2352 rx + ins,
2353 ry + rh
2354 );
2355 }
2356 MermaidNodeShape::Parallelogram => {
2357 let skew: f32 = 14.0;
2358 let _: fmt::Result = write!(
2359 out,
2360 "<polygon points=\"{:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {rx:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2361 rx + skew,
2362 rx + rw,
2363 rx + rw - skew,
2364 ry + rh,
2365 ry + rh
2366 );
2367 }
2368 MermaidNodeShape::ParallelogramAlt => {
2369 let skew: f32 = 14.0;
2370 let _: fmt::Result = write!(
2371 out,
2372 "<polygon points=\"{rx:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2373 rx + rw - skew,
2374 rx + rw,
2375 ry + rh,
2376 rx + skew,
2377 ry + rh
2378 );
2379 }
2380 MermaidNodeShape::Trapezoid => {
2381 let ins: f32 = 14.0;
2382 let _: fmt::Result = write!(
2383 out,
2384 "<polygon points=\"{:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {rx:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2385 rx + ins,
2386 rx + rw - ins,
2387 rx + rw,
2388 ry + rh,
2389 ry + rh
2390 );
2391 }
2392 MermaidNodeShape::TrapezoidAlt => {
2393 let ins: f32 = 14.0;
2394 let _: fmt::Result = write!(
2395 out,
2396 "<polygon points=\"{rx:.1},{ry:.1} {:.1},{ry:.1} {:.1},{:.1} {:.1},{:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>",
2397 rx + rw,
2398 rx + rw - ins,
2399 ry + rh,
2400 rx + ins,
2401 ry + rh
2402 );
2403 }
2404 MermaidNodeShape::Asymmetric => {
2405 let notch: f32 = 12.0;
2406 let _: fmt::Result = write!(
2407 out,
2408 "<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\"/>",
2409 rx + rw,
2410 rx + rw,
2411 ry + rh,
2412 ry + rh,
2413 rx + notch
2414 );
2415 }
2416 MermaidNodeShape::Circle => {
2417 let red_val: f32 = rw.min(rh) * 0.5;
2418 let _: fmt::Result = write!(
2419 out,
2420 "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{red_val:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2421 );
2422 }
2423 MermaidNodeShape::DoubleCircle => {
2424 let radius_val: f32 = rw.min(rh) * 0.5;
2425 let r_in: f32 = (radius_val - 4.5).max(4.0);
2426 let _: fmt::Result = write!(
2427 out,
2428 "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{radius_val:.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\"/>"
2429 );
2430 }
2431 MermaidNodeShape::Subroutine => {
2432 let _: fmt::Result = write!(
2433 out,
2434 "<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\"/>",
2435 rx + 9.0,
2436 rx + 9.0,
2437 ry + rh,
2438 rx + rw - 9.0,
2439 rx + rw - 9.0,
2440 ry + rh
2441 );
2442 }
2443 MermaidNodeShape::Cylinder => {
2444 let rx_e: f32 = rw * 0.5;
2445 let ry_e: f32 = 7.0;
2446 let body_y: f32 = ry + ry_e;
2447 let body_h: f32 = (rh - ry_e * 2.0).max(12.0);
2448 let bot_y: f32 = body_y + body_h;
2449 let _: fmt::Result = write!(
2450 out,
2451 "<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\"/>",
2452 rx + rw,
2453 rx + rw
2454 );
2455 }
2456 MermaidNodeShape::Stadium => {
2457 let rad: f32 = rh * 0.5;
2458 let _: fmt::Result = write!(
2459 out,
2460 "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"{rad:.1}\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2461 );
2462 }
2463 MermaidNodeShape::Rounded => {
2464 let _: fmt::Result = write!(
2465 out,
2466 "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"10\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2467 );
2468 }
2469 MermaidNodeShape::Note => {
2470 let _: fmt::Result = write!(
2471 out,
2472 "<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\"/>"
2473 );
2474 }
2475 MermaidNodeShape::Box => {
2476 let _: fmt::Result = write!(
2477 out,
2478 "<rect x=\"{rx:.1}\" y=\"{ry:.1}\" width=\"{rw:.1}\" height=\"{rh:.1}\" rx=\"5\" fill=\"{fill}\" stroke=\"{stroke}\" stroke-width=\"1.8\"/>"
2479 );
2480 }
2481 }
2482 let label_str: &str = node.get_label().trim();
2483 if !label_str.is_empty() && !matches!(node.get_shape(), MermaidNodeShape::ForkJoin) {
2484 let _: fmt::Result = write!(
2485 out,
2486 "<text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"12\" font-weight=\"600\" fill=\"{text_col}\">",
2487 cy + 4.0
2488 );
2489 push_escaped_html(out, label_str);
2490 out.push_str(SVG_TEXT_CLOSE);
2491 }
2492 }
2493 out.push_str(MERMAID_SVG_CLOSE);
2494}
2495
2496fn render_mermaid_sequence_svg(seq: &MermaidSequence, out: &mut String) {
2503 let p_count: usize = seq.get_participants().len();
2504 if p_count == 0 {
2505 return;
2506 }
2507 let col_w: f32 = 176.0;
2508 let pad: f32 = 28.0;
2509 let box_w: f32 = 132.0;
2510 let box_h: f32 = 38.0;
2511 let row_h: f32 = 44.0;
2512 let msg_count: usize = seq.get_messages().len();
2513 let svg_w: f32 = ((p_count as f32) * col_w + pad * 2.0).max(400.0);
2514 let top_y: f32 = pad;
2515 let life_top: f32 = top_y + box_h;
2516 let life_bot: f32 = life_top + 28.0 + (msg_count as f32) * row_h + 22.0;
2517 let svg_h: f32 = life_bot + box_h + pad;
2518 let _: fmt::Result = write!(
2519 out,
2520 "<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\">"
2521 );
2522 out.push_str(MERMAID_SVG_ARROW_MARKER);
2523 let mut centers: Vec<f32> = Vec::with_capacity(p_count);
2524 for (idx, (_, label)) in seq.get_participants().iter().enumerate() {
2525 let cx: f32 = pad + (idx as f32) * col_w + col_w * 0.5;
2526 centers.push(cx);
2527 let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2528 let is_actor: bool = seq.get_actor_flags().get(idx).copied().unwrap_or(false);
2529 let _: fmt::Result = write!(
2530 out,
2531 "<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\"/>"
2532 );
2533 for by in [top_y, life_bot].into_iter() {
2534 if is_actor {
2535 let head_y: f32 = by + 8.0;
2536 let _: fmt::Result = write!(
2537 out,
2538 "<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)\">",
2539 head_y + 5.0,
2540 head_y + 15.0,
2541 cx - 8.0,
2542 head_y + 9.0,
2543 cx + 8.0,
2544 head_y + 9.0,
2545 head_y + 15.0,
2546 cx - 6.0,
2547 head_y + 22.0,
2548 head_y + 15.0,
2549 cx + 6.0,
2550 head_y + 22.0,
2551 by + 36.0
2552 );
2553 push_escaped_html(out, label);
2554 out.push_str(SVG_TEXT_CLOSE);
2555 } else {
2556 let bx: f32 = cx - box_w * 0.5;
2557 let _: fmt::Result = write!(
2558 out,
2559 "<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)\">",
2560 by + 23.0
2561 );
2562 push_escaped_html(out, label);
2563 out.push_str(SVG_TEXT_CLOSE);
2564 }
2565 }
2566 }
2567 for blk in seq.get_blocks().iter() {
2568 let inset: f32 = 12.0 + (blk.get_depth() as f32) * 8.0;
2569 let bx: f32 = inset;
2570 let border_width: f32 = (svg_w - inset * 2.0).max(80.0);
2571 let by: f32 = life_top + 12.0 + (blk.get_start_row() as f32) * row_h;
2572 let bh: f32 =
2573 ((blk.get_end_row().saturating_sub(blk.get_start_row()) + 1) as f32) * row_h + 16.0;
2574 let kw: &str = match blk.get_kind() {
2575 MermaidSeqBlockKind::Loop => "loop",
2576 MermaidSeqBlockKind::Alt => "alt",
2577 MermaidSeqBlockKind::Opt => "opt",
2578 MermaidSeqBlockKind::Par => "par",
2579 MermaidSeqBlockKind::Critical => "critical",
2580 MermaidSeqBlockKind::Break => "break",
2581 MermaidSeqBlockKind::Rect => "rect",
2582 };
2583 let _: fmt::Result = write!(
2584 out,
2585 "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{border_width:.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>",
2586 bx + 29.0,
2587 by + 12.5
2588 );
2589 if !blk.get_label().is_empty() {
2590 let _: fmt::Result = write!(
2591 out,
2592 "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"10.5\" font-weight=\"600\" fill=\"var(--muted-fg)\">[",
2593 bx + 66.0,
2594 by + 13.0
2595 );
2596 push_escaped_html(out, blk.get_label());
2597 out.push_str(SVG_BRACKET_TEXT_CLOSE);
2598 }
2599 for div in blk.get_dividers().iter() {
2600 let dy: f32 = life_top + 14.0 + (div.get_row_idx() as f32) * row_h;
2601 let _: fmt::Result = write!(
2602 out,
2603 "<line x1=\"{bx:.1}\" y1=\"{dy:.1}\" x2=\"{:.1}\" y2=\"{dy:.1}\" stroke=\"var(--important)\" stroke-width=\"1\" stroke-dasharray=\"4 3\"/>",
2604 bx + border_width
2605 );
2606 if !div.get_label().is_empty() {
2607 let _: fmt::Result = write!(
2608 out,
2609 "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"10\" fill=\"var(--muted-fg)\">[",
2610 bx + 10.0,
2611 dy + 12.0
2612 );
2613 push_escaped_html(out, div.get_label());
2614 out.push_str(SVG_BRACKET_TEXT_CLOSE);
2615 }
2616 }
2617 }
2618 for act in seq.get_activations().iter() {
2619 if let Some(&cx) = centers.get(act.get_participant_idx()) {
2620 let ay: f32 = life_top + 24.0 + (act.get_start_row() as f32) * row_h;
2621 let ah: f32 =
2622 ((act.get_end_row().saturating_sub(act.get_start_row()) + 1) as f32) * row_h;
2623 let _: fmt::Result = write!(
2624 out,
2625 "<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\"/>",
2626 cx - 5.0
2627 );
2628 }
2629 }
2630 let mut seq_num: usize = 0;
2631 for (idx, msg) in seq.get_messages().iter().enumerate() {
2632 let pos_y: f32 = life_top + 32.0 + (idx as f32) * row_h;
2633 let x1: f32 = centers.get(msg.get_from_idx()).copied().unwrap_or(pad);
2634 let x2: f32 = centers.get(msg.get_to_idx()).copied().unwrap_or(pad);
2635 if msg.get_is_note() {
2636 let nw: f32 = ((msg.get_text().chars().count() as f32) * 7.2 + 28.0)
2637 .max((x2 - x1).abs() + 72.0)
2638 .clamp(112.0, svg_w - 24.0);
2639 let nx: f32 = match msg.get_note_placement() {
2640 MermaidSeqNotePlacement::LeftOf => (x1 - nw - 12.0).max(8.0),
2641 MermaidSeqNotePlacement::RightOf => (x1 + 12.0).min(svg_w - nw - 8.0),
2642 MermaidSeqNotePlacement::Over => {
2643 ((x1 + x2) * 0.5 - nw * 0.5).clamp(8.0, svg_w - nw - 8.0)
2644 }
2645 };
2646 let _: fmt::Result = write!(
2647 out,
2648 "<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)\">",
2649 pos_y - 13.0,
2650 nx + nw * 0.5,
2651 pos_y + 4.0
2652 );
2653 push_escaped_html(out, msg.get_text());
2654 out.push_str(SVG_TEXT_CLOSE);
2655 } else {
2656 seq_num += 1;
2657 let style: MermaidEdgeStyle = msg.get_style();
2658 let dash: &str = match style {
2659 MermaidEdgeStyle::Dashed
2660 | MermaidEdgeStyle::DashedOpenArrow
2661 | MermaidEdgeStyle::DashedAsyncArrow
2662 | MermaidEdgeStyle::DashedCrossArrow => MERMAID_SVG_DASH_ATTR,
2663 _ => "",
2664 };
2665 let marker: &str = match style {
2666 MermaidEdgeStyle::CrossArrow | MermaidEdgeStyle::DashedCrossArrow => {
2667 MERMAID_SVG_MARKER_CROSS_END
2668 }
2669 MermaidEdgeStyle::OpenArrow | MermaidEdgeStyle::DashedOpenArrow => "",
2670 _ => MERMAID_SVG_MARKER_ATTR,
2671 };
2672 if msg.get_from_idx() == msg.get_to_idx() {
2673 let loop_w: f32 = 34.0;
2674 let _: fmt::Result = write!(
2675 out,
2676 "<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)\">",
2677 pos_y - 8.0,
2678 x1 + loop_w,
2679 pos_y - 8.0,
2680 x1 + loop_w,
2681 pos_y + 10.0,
2682 pos_y + 10.0,
2683 x1 + loop_w + 6.0,
2684 pos_y + 3.0
2685 );
2686 } else {
2687 let _: fmt::Result = write!(
2688 out,
2689 "<line x1=\"{x1:.1}\" y1=\"{pos_y:.1}\" x2=\"{x2:.1}\" y2=\"{pos_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)\">",
2690 (x1 + x2) * 0.5,
2691 pos_y - 7.0
2692 );
2693 }
2694 if seq.get_autonumber() {
2695 let _: fmt::Result = write!(out, "{seq_num}. ");
2696 }
2697 push_escaped_html(out, msg.get_text());
2698 out.push_str(SVG_TEXT_CLOSE);
2699 }
2700 }
2701 out.push_str(MERMAID_SVG_CLOSE);
2702}
2703
2704fn render_mermaid_class_svg(cls: &MermaidClassDiagram, out: &mut String) {
2711 let count: usize = cls.get_classes().len();
2712 if count == 0 {
2713 return;
2714 }
2715 let pad: f32 = 24.0;
2716 let gap: f32 = 44.0;
2717 let box_w: f32 = 188.0;
2718 let mut max_h: f32 = 68.0;
2719 for char_item in cls.get_classes().iter() {
2720 let extra: f32 = if char_item.get_stereotype().is_empty() {
2721 0.0
2722 } else {
2723 16.0
2724 };
2725 let height_val: f32 = 34.0 + extra + (char_item.get_members().len() as f32) * 18.0 + 12.0;
2726 max_h = max_h.max(height_val);
2727 }
2728 let svg_w: f32 = pad * 2.0 + (count as f32) * box_w + (count.saturating_sub(1) as f32) * gap;
2729 let svg_h: f32 = pad * 2.0 + max_h + 28.0;
2730 let _: fmt::Result = write!(
2731 out,
2732 "<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\">"
2733 );
2734 out.push_str(MERMAID_SVG_ARROW_MARKER);
2735 let mut pos_map: HashMap<&str, (f32, f32, f32)> = HashMap::with_capacity(count);
2736 for (idx, color_item) in cls.get_classes().iter().enumerate() {
2737 let pos_x: f32 = pad + (idx as f32) * (box_w + gap);
2738 let has_stereo: bool = !color_item.get_stereotype().is_empty();
2739 let header_h: f32 = if has_stereo { 46.0 } else { 30.0 };
2740 let span_height: f32 = header_h + (color_item.get_members().len() as f32) * 18.0 + 16.0;
2741 let _: Option<(f32, f32, f32)> =
2742 pos_map.insert(color_item.get_name().as_str(), (pos_x, pad, span_height));
2743 let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2744 let _: fmt::Result = write!(
2745 out,
2746 "<rect x=\"{pos_x:.1}\" y=\"{pad:.1}\" width=\"{box_w:.1}\" height=\"{span_height:.1}\" rx=\"7\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.6\"/><line x1=\"{pos_x:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" stroke=\"var(--border)\" stroke-width=\"1\"/>",
2747 pad + header_h,
2748 pos_x + box_w,
2749 pad + header_h
2750 );
2751 if has_stereo {
2752 let _: fmt::Result = write!(
2753 out,
2754 "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10\" font-style=\"italic\" fill=\"{accent}\"><<",
2755 pos_x + box_w * 0.5,
2756 pad + 15.0
2757 );
2758 push_escaped_html(out, color_item.get_stereotype());
2759 out.push_str(">></text>");
2760 }
2761 let name_y: f32 = if has_stereo { pad + 34.0 } else { pad + 20.0 };
2762 let _: fmt::Result = write!(
2763 out,
2764 "<text x=\"{:.1}\" y=\"{name_y:.1}\" text-anchor=\"middle\" font-size=\"12.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2765 pos_x + box_w * 0.5
2766 );
2767 push_escaped_html(out, color_item.get_name());
2768 out.push_str(SVG_TEXT_CLOSE);
2769 for (mi, mem) in color_item.get_members().iter().enumerate() {
2770 let _: fmt::Result = write!(
2771 out,
2772 "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" fill=\"var(--muted-fg)\">",
2773 pos_x + 10.0,
2774 pad + header_h + 18.0 + (mi as f32) * 18.0
2775 );
2776 push_escaped_html(out, mem);
2777 out.push_str(SVG_TEXT_CLOSE);
2778 }
2779 }
2780 for rel in cls.get_relations().iter() {
2781 if let (Some(&(x1, y1, h1)), Some(&(x2, y2, h2))) = (
2782 pos_map.get(rel.get_from().as_str()),
2783 pos_map.get(rel.get_to().as_str()),
2784 ) {
2785 let sx: f32 = if x2 >= x1 { x1 + box_w } else { x1 };
2786 let tx: f32 = if x2 >= x1 { x2 } else { x2 + box_w };
2787 let sy: f32 = y1 + h1 * 0.5;
2788 let ty: f32 = y2 + h2 * 0.5;
2789 let dash: &str = match rel.get_style() {
2790 MermaidEdgeStyle::Dashed | MermaidEdgeStyle::DashedPlain => MERMAID_SVG_DASH_ATTR,
2791 _ => "",
2792 };
2793 let (m_start, m_end): (&str, &str) = match rel.get_rel_kind() {
2794 MermaidClassRelKind::Inheritance | MermaidClassRelKind::Realization => {
2795 ("", MERMAID_SVG_MARKER_INHERIT_END)
2796 }
2797 MermaidClassRelKind::Composition => (MERMAID_SVG_MARKER_COMP_START, ""),
2798 MermaidClassRelKind::Aggregation => (MERMAID_SVG_MARKER_AGGR_START, ""),
2799 MermaidClassRelKind::Link => ("", ""),
2800 MermaidClassRelKind::Association | MermaidClassRelKind::Dependency => {
2801 ("", MERMAID_SVG_MARKER_ATTR)
2802 }
2803 };
2804 let _: fmt::Result = write!(
2805 out,
2806 "<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}/>"
2807 );
2808 if !rel.get_label().is_empty() {
2809 let _: fmt::Result = write!(
2810 out,
2811 "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
2812 (sx + tx) * 0.5,
2813 (sy + ty) * 0.5 - 6.0
2814 );
2815 push_escaped_html(out, rel.get_label());
2816 out.push_str(SVG_TEXT_CLOSE);
2817 }
2818 }
2819 }
2820 out.push_str(MERMAID_SVG_CLOSE);
2821}
2822
2823fn render_er_card_svg(card: &str, ex: f32, ey: f32, dir_x: f32, out: &mut String) {
2833 let inner_x: f32 = ex + dir_x * 11.0;
2834 if card.contains('{') || card.contains('}') {
2835 let _: fmt::Result = write!(
2836 out,
2837 "<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\"/>",
2838 ey - 6.0,
2839 ey + 6.0
2840 );
2841 }
2842 if card.contains('o') {
2843 let _: fmt::Result = write!(
2844 out,
2845 "<circle cx=\"{:.1}\" cy=\"{ey:.1}\" r=\"3.5\" fill=\"var(--card)\" stroke=\"var(--muted-fg)\" stroke-width=\"1.4\"/>",
2846 ex + dir_x * 13.0
2847 );
2848 }
2849 if card.contains('|') {
2850 let bar_x: f32 = ex + dir_x * 6.0;
2851 let _: fmt::Result = write!(
2852 out,
2853 "<line x1=\"{bar_x:.1}\" y1=\"{:.1}\" x2=\"{bar_x:.1}\" y2=\"{:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\"/>",
2854 ey - 6.0,
2855 ey + 6.0
2856 );
2857 }
2858}
2859
2860fn render_mermaid_er_svg(er: &MermaidErDiagram, out: &mut String) {
2867 let count: usize = er.get_entities().len();
2868 if count == 0 {
2869 return;
2870 }
2871 let pad: f32 = 24.0;
2872 let gap: f32 = 72.0;
2873 let box_w: f32 = 176.0;
2874 let mut max_h: f32 = 56.0;
2875 for ent in er.get_entities().iter() {
2876 let height_val: f32 = 34.0 + (ent.get_attributes().len() as f32) * 18.0 + 12.0;
2877 max_h = max_h.max(height_val);
2878 }
2879 let svg_w: f32 = pad * 2.0 + (count as f32) * box_w + (count.saturating_sub(1) as f32) * gap;
2880 let svg_h: f32 = pad * 2.0 + max_h + 20.0;
2881 let _: fmt::Result = write!(
2882 out,
2883 "<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\">"
2884 );
2885 let mut pos_map: HashMap<&str, (f32, f32, f32)> = HashMap::with_capacity(count);
2886 for (idx, ent) in er.get_entities().iter().enumerate() {
2887 let pos_x: f32 = pad + (idx as f32) * (box_w + gap);
2888 let span_height: f32 = 34.0 + (ent.get_attributes().len() as f32) * 18.0 + 12.0;
2889 let _: Option<(f32, f32, f32)> =
2890 pos_map.insert(ent.get_name().as_str(), (pos_x, pad, span_height));
2891 let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2892 let _: fmt::Result = write!(
2893 out,
2894 "<rect x=\"{pos_x:.1}\" y=\"{pad:.1}\" width=\"{box_w:.1}\" height=\"{span_height:.1}\" rx=\"6\" fill=\"var(--muted)\" stroke=\"{accent}\" stroke-width=\"1.6\"/><line x1=\"{pos_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)\">",
2895 pad + 28.0,
2896 pos_x + box_w,
2897 pad + 28.0,
2898 pos_x + box_w * 0.5,
2899 pad + 19.0
2900 );
2901 push_escaped_html(out, ent.get_name());
2902 out.push_str(SVG_TEXT_CLOSE);
2903 for (align_items_mode, attr) in ent.get_attributes().iter().enumerate() {
2904 let is_key: bool = attr.contains(" PK") || attr.contains(" FK") || attr.contains(" UK");
2905 let col: &str = if is_key {
2906 MERMAID_SVG_VAR_FG
2907 } else {
2908 MERMAID_SVG_VAR_MUTED_FG
2909 };
2910 let fw: &str = if is_key { "600" } else { "400" };
2911 let _: fmt::Result = write!(
2912 out,
2913 "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"11\" font-weight=\"{fw}\" fill=\"{col}\">",
2914 pos_x + 10.0,
2915 pad + 46.0 + (align_items_mode as f32) * 18.0
2916 );
2917 push_escaped_html(out, attr);
2918 out.push_str(SVG_TEXT_CLOSE);
2919 }
2920 }
2921 for rel in er.get_relations().iter() {
2922 if let (Some(&(x1, y1, h1)), Some(&(x2, y2, h2))) = (
2923 pos_map.get(rel.get_left().as_str()),
2924 pos_map.get(rel.get_right().as_str()),
2925 ) {
2926 let ltr: bool = x2 >= x1;
2927 let sx: f32 = if ltr { x1 + box_w } else { x1 };
2928 let tx: f32 = if ltr { x2 } else { x2 + box_w };
2929 let sy: f32 = y1 + h1 * 0.5;
2930 let ty: f32 = y2 + h2 * 0.5;
2931 let dash: &str = if rel.get_dashed() {
2932 MERMAID_SVG_DASH_ATTR
2933 } else {
2934 ""
2935 };
2936 let _: fmt::Result = write!(
2937 out,
2938 "<line x1=\"{sx:.1}\" y1=\"{sy:.1}\" x2=\"{tx:.1}\" y2=\"{ty:.1}\" stroke=\"var(--muted-fg)\" stroke-width=\"1.5\"{dash}/>"
2939 );
2940 let dir_s: f32 = if ltr { 1.0 } else { -1.0 };
2941 render_er_card_svg(rel.get_left_card(), sx, sy, dir_s, out);
2942 render_er_card_svg(rel.get_right_card(), tx, ty, -dir_s, out);
2943 if !rel.get_label().is_empty() {
2944 let _: fmt::Result = write!(
2945 out,
2946 "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
2947 (sx + tx) * 0.5,
2948 (sy + ty) * 0.5 - 7.0
2949 );
2950 push_escaped_html(out, rel.get_label());
2951 out.push_str(SVG_TEXT_CLOSE);
2952 }
2953 }
2954 }
2955 out.push_str(MERMAID_SVG_CLOSE);
2956}
2957
2958fn render_mermaid_pie_svg(pie: &MermaidPieChart, out: &mut String) {
2965 let total: f32 = pie
2966 .get_slices()
2967 .iter()
2968 .map(|source_val: &MermaidPieSlice| source_val.get_value())
2969 .sum();
2970 if total <= 0.0 {
2971 return;
2972 }
2973 let has_title: bool = !pie.get_title().is_empty();
2974 let title_off: f32 = if has_title { 28.0 } else { 8.0 };
2975 let red_val: f32 = 76.0;
2976 let cx: f32 = 112.0;
2977 let cy: f32 = title_off + red_val + 14.0;
2978 let legend_x: f32 = cx + red_val + 36.0;
2979 let legend_h: f32 = (pie.get_slices().len() as f32) * 24.0;
2980 let svg_h: f32 = (cy + red_val + 20.0).max(title_off + legend_h + 36.0);
2981 let svg_w: f32 = 460.0;
2982 let _: fmt::Result = write!(
2983 out,
2984 "<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\">"
2985 );
2986 if has_title {
2987 let _: fmt::Result = write!(
2988 out,
2989 "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
2990 svg_w * 0.5
2991 );
2992 push_escaped_html(out, pie.get_title());
2993 out.push_str(SVG_TEXT_CLOSE);
2994 }
2995 let mut angle: f32 = -FRAC_PI_2;
2996 let legend_y0: f32 = cy - legend_h * 0.5 + 12.0;
2997 for (idx, slice) in pie.get_slices().iter().enumerate() {
2998 let color: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
2999 let frac: f32 = slice.get_value() / total;
3000 let sweep: f32 = frac * TAU;
3001 if pie.get_slices().len() == 1 {
3002 let _: fmt::Result = write!(
3003 out,
3004 "<circle cx=\"{cx:.1}\" cy=\"{cy:.1}\" r=\"{red_val:.1}\" fill=\"{color}\"/>"
3005 );
3006 } else {
3007 let x1: f32 = cx + red_val * angle.cos();
3008 let y1: f32 = cy + red_val * angle.sin();
3009 let end_a: f32 = angle + sweep;
3010 let x2: f32 = cx + red_val * end_a.cos();
3011 let y2: f32 = cy + red_val * end_a.sin();
3012 let large: u8 = if sweep > PI { 1 } else { 0 };
3013 let _: fmt::Result = write!(
3014 out,
3015 "<path d=\"M {cx:.1} {cy:.1} L {x1:.1} {y1:.1} A {red_val:.1} {red_val:.1} 0 {large} 1 {x2:.1} {y2:.1} Z\" fill=\"{color}\" stroke=\"var(--card)\" stroke-width=\"1.5\"/>"
3016 );
3017 angle = end_a;
3018 }
3019 let ly: f32 = legend_y0 + (idx as f32) * 24.0;
3020 let pct: f32 = frac * 100.0;
3021 let _: fmt::Result = write!(
3022 out,
3023 "<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)\">",
3024 ly - 10.0,
3025 legend_x + 18.0
3026 );
3027 push_escaped_html(out, slice.get_label());
3028 let _: fmt::Result = write!(out, " ({pct:.0}%)</text>");
3029 }
3030 out.push_str(MERMAID_SVG_CLOSE);
3031}
3032
3033fn render_mermaid_gantt_svg(gantt: &MermaidGanttChart, out: &mut String) {
3040 let count: usize = gantt.get_tasks().len();
3041 if count == 0 {
3042 return;
3043 }
3044 let has_title: bool = !gantt.get_title().is_empty();
3045 let top: f32 = if has_title { 38.0 } else { 16.0 };
3046 let label_w: f32 = 148.0;
3047 let track_w: f32 = 340.0;
3048 let row_h: f32 = 30.0;
3049 let svg_w: f32 = label_w + track_w + 28.0;
3050 let svg_h: f32 = top + (count as f32) * row_h + 16.0;
3051 let max_end: f32 = gantt
3052 .get_tasks()
3053 .iter()
3054 .map(|blend_factor: &MermaidGanttTask| {
3055 blend_factor.get_start_unit() + blend_factor.get_duration_unit()
3056 })
3057 .fold(1.0_f32, f32::max);
3058 let _: fmt::Result = write!(
3059 out,
3060 "<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\">"
3061 );
3062 if has_title {
3063 let _: fmt::Result = write!(
3064 out,
3065 "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
3066 svg_w * 0.5
3067 );
3068 push_escaped_html(out, gantt.get_title());
3069 out.push_str(SVG_TEXT_CLOSE);
3070 }
3071 for (idx, task) in gantt.get_tasks().iter().enumerate() {
3072 let pos_y: f32 = top + (idx as f32) * row_h;
3073 let bx: f32 = label_w + (task.get_start_unit() / max_end) * track_w;
3074 let border_width: f32 = ((task.get_duration_unit() / max_end) * track_w).max(16.0);
3075 let fill: &str = match task.get_status() {
3076 MermaidGanttStatus::Done => MERMAID_SVG_VAR_TIP,
3077 MermaidGanttStatus::Active => MERMAID_SVG_VAR_LINK,
3078 MermaidGanttStatus::Critical => MERMAID_SVG_VAR_DANGER,
3079 MermaidGanttStatus::Milestone => MERMAID_SVG_VAR_WARN,
3080 MermaidGanttStatus::Normal => MERMAID_SVG_VAR_IMPORTANT,
3081 };
3082 let _: fmt::Result = write!(
3083 out,
3084 "<text x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\" font-size=\"11.5\" fill=\"var(--fg)\">",
3085 label_w - 10.0,
3086 pos_y + 15.0
3087 );
3088 push_escaped_html(out, task.get_label());
3089 out.push_str(SVG_TEXT_CLOSE);
3090 if task.get_status() == MermaidGanttStatus::Milestone {
3091 let cy: f32 = pos_y + 11.0;
3092 let _: fmt::Result = write!(
3093 out,
3094 "<polygon points=\"{bx:.1},{:.1} {:.1},{cy:.1} {bx:.1},{:.1} {:.1},{cy:.1}\" fill=\"{fill}\"/>",
3095 cy - 8.0,
3096 bx + 8.0,
3097 cy + 8.0,
3098 bx - 8.0
3099 );
3100 } else {
3101 let _: fmt::Result = write!(
3102 out,
3103 "<rect x=\"{bx:.1}\" y=\"{:.1}\" width=\"{border_width:.1}\" height=\"18\" rx=\"5\" fill=\"{fill}\"/>",
3104 pos_y + 2.0
3105 );
3106 }
3107 }
3108 out.push_str(MERMAID_SVG_CLOSE);
3109}
3110
3111fn render_mermaid_timeline_svg(tl: &MermaidTimeline, out: &mut String) {
3118 let count: usize = tl.get_events().len();
3119 if count == 0 {
3120 return;
3121 }
3122 let has_title: bool = !tl.get_title().is_empty();
3123 let top: f32 = if has_title { 44.0 } else { 24.0 };
3124 let col_w: f32 = 154.0;
3125 let pad: f32 = 24.0;
3126 let max_items: usize = tl
3127 .get_events()
3128 .iter()
3129 .map(|ui_event: &MermaidTimelineEvent| ui_event.get_items().len())
3130 .max()
3131 .unwrap_or(1)
3132 .max(1);
3133 let svg_w: f32 = (pad * 2.0 + (count as f32) * col_w).max(380.0);
3134 let axis_y: f32 = top + 30.0;
3135 let svg_h: f32 = axis_y + 24.0 + (max_items as f32) * 32.0 + 20.0;
3136 let _: fmt::Result = write!(
3137 out,
3138 "<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\">"
3139 );
3140 if has_title {
3141 let _: fmt::Result = write!(
3142 out,
3143 "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
3144 svg_w * 0.5
3145 );
3146 push_escaped_html(out, tl.get_title());
3147 out.push_str(SVG_TEXT_CLOSE);
3148 }
3149 let _: fmt::Result = write!(
3150 out,
3151 "<line x1=\"{pad:.1}\" y1=\"{axis_y:.1}\" x2=\"{:.1}\" y2=\"{axis_y:.1}\" stroke=\"var(--border)\" stroke-width=\"2.5\"/>",
3152 svg_w - pad
3153 );
3154 for (idx, dispatched_event) in tl.get_events().iter().enumerate() {
3155 let cx: f32 = pad + (idx as f32) * col_w + col_w * 0.5;
3156 let accent: &str = MERMAID_SVG_PALETTE[idx % MERMAID_SVG_PALETTE.len()];
3157 let _: fmt::Result = write!(
3158 out,
3159 "<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)\">",
3160 axis_y - 12.0
3161 );
3162 push_escaped_html(out, dispatched_event.get_period());
3163 out.push_str(SVG_TEXT_CLOSE);
3164 for (ii, item) in dispatched_event.get_items().iter().enumerate() {
3165 let iy: f32 = axis_y + 18.0 + (ii as f32) * 32.0;
3166 let border_width: f32 = col_w - 18.0;
3167 let bx: f32 = cx - border_width * 0.5;
3168 let _: fmt::Result = write!(
3169 out,
3170 "<rect x=\"{bx:.1}\" y=\"{iy:.1}\" width=\"{border_width:.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)\">",
3171 iy + 16.0
3172 );
3173 push_escaped_html(out, item);
3174 out.push_str(SVG_TEXT_CLOSE);
3175 }
3176 }
3177 out.push_str(MERMAID_SVG_CLOSE);
3178}
3179
3180fn render_mermaid_mindmap_svg(mm: &MermaidMindmap, out: &mut String) {
3187 let count: usize = mm.get_nodes().len();
3188 if count == 0 {
3189 return;
3190 }
3191 let pad: f32 = 22.0;
3192 let row_h: f32 = 34.0;
3193 let indent_w: f32 = 44.0;
3194 let max_depth: usize = mm
3195 .get_nodes()
3196 .iter()
3197 .map(|node: &MermaidMindmapNode| node.get_depth())
3198 .max()
3199 .unwrap_or(0);
3200 let svg_w: f32 = (pad * 2.0 + (max_depth as f32) * indent_w + 220.0).max(380.0);
3201 let svg_h: f32 = pad * 2.0 + (count as f32) * row_h;
3202 let _: fmt::Result = write!(
3203 out,
3204 "<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\">"
3205 );
3206 let mut last_at_depth: Vec<Option<(f32, f32)>> = vec![None; max_depth + 2];
3207 for (idx, node) in mm.get_nodes().iter().enumerate() {
3208 let delta_val: usize = node.get_depth();
3209 let nx: f32 = pad + (delta_val as f32) * indent_w;
3210 let ny: f32 = pad + (idx as f32) * row_h;
3211 let nw: f32 = ((node.get_label().chars().count() as f32) * 7.4 + 28.0).clamp(84.0, 210.0);
3212 let nh: f32 = 26.0;
3213 let accent: &str = MERMAID_SVG_PALETTE[delta_val % MERMAID_SVG_PALETTE.len()];
3214 if delta_val > 0
3215 && let Some((px, py)) = last_at_depth[delta_val - 1]
3216 {
3217 let _: fmt::Result = write!(
3218 out,
3219 "<path d=\"M {px:.1} {py:.1} L {px:.1} {:.1} L {nx:.1} {:.1}\" fill=\"none\" stroke=\"{accent}\" stroke-width=\"1.4\"/>",
3220 ny + nh * 0.5,
3221 ny + nh * 0.5
3222 );
3223 }
3224 let rad: f32 = match node.get_shape() {
3225 MermaidNodeShape::Circle
3226 | MermaidNodeShape::DoubleCircle
3227 | MermaidNodeShape::Stadium => nh * 0.5,
3228 MermaidNodeShape::Rounded => 8.0,
3229 _ => 4.0,
3230 };
3231 let _: fmt::Result = write!(
3232 out,
3233 "<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)\">",
3234 nx + nw * 0.5,
3235 ny + 17.0
3236 );
3237 push_escaped_html(out, node.get_label());
3238 out.push_str(SVG_TEXT_CLOSE);
3239 last_at_depth[delta_val] = Some((nx + 14.0, ny + nh));
3240 }
3241 out.push_str(MERMAID_SVG_CLOSE);
3242}
3243
3244fn render_mermaid_xychart_svg(xy: &MermaidXyChart, out: &mut String) {
3251 let x_count: usize = xy.get_x_labels().len().max(
3252 xy.get_series()
3253 .iter()
3254 .map(|source_val: &MermaidXySeries| source_val.get_values().len())
3255 .max()
3256 .unwrap_or(0),
3257 );
3258 if x_count == 0 {
3259 return;
3260 }
3261 let has_title: bool = !xy.get_title().is_empty();
3262 let top: f32 = if has_title { 38.0 } else { 18.0 };
3263 let left: f32 = 54.0;
3264 let right: f32 = 22.0;
3265 let bottom: f32 = 34.0;
3266 let plot_w: f32 = ((x_count as f32) * 56.0).clamp(320.0, 620.0);
3267 let plot_h: f32 = 176.0;
3268 let svg_w: f32 = left + plot_w + right;
3269 let svg_h: f32 = top + plot_h + bottom;
3270 let mut y_min: f32 = xy.get_y_min();
3271 let mut y_max: f32 = xy.get_y_max();
3272 if (y_max - y_min).abs() < 1e-3 {
3273 y_min = 0.0;
3274 y_max = xy
3275 .get_series()
3276 .iter()
3277 .flat_map(|scale_val: &MermaidXySeries| scale_val.get_values().iter().copied())
3278 .fold(1.0_f32, f32::max);
3279 }
3280 let span: f32 = (y_max - y_min).max(1.0);
3281 let _: fmt::Result = write!(
3282 out,
3283 "<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\">"
3284 );
3285 if has_title {
3286 let _: fmt::Result = write!(
3287 out,
3288 "<text x=\"{:.1}\" y=\"22\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"700\" fill=\"var(--fg)\">",
3289 svg_w * 0.5
3290 );
3291 push_escaped_html(out, xy.get_title());
3292 out.push_str(SVG_TEXT_CLOSE);
3293 }
3294 for step in 0..=4 {
3295 let frac: f32 = (step as f32) / 4.0;
3296 let gy: f32 = top + plot_h * (1.0 - frac);
3297 let tick_val: f32 = y_min + span * frac;
3298 let _: fmt::Result = write!(
3299 out,
3300 "<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>",
3301 left + plot_w,
3302 left - 8.0,
3303 gy + 3.5
3304 );
3305 }
3306 let slot_w: f32 = plot_w / (x_count as f32);
3307 for (si, ser) in xy.get_series().iter().enumerate() {
3308 let accent: &str = MERMAID_SVG_PALETTE[si % MERMAID_SVG_PALETTE.len()];
3309 if ser.get_is_bar() {
3310 let border_width: f32 = (slot_w * 0.54).clamp(12.0, 38.0);
3311 for (vi, &item_val) in ser.get_values().iter().enumerate() {
3312 let norm: f32 = ((item_val - y_min) / span).clamp(0.0, 1.0);
3313 let bh: f32 = (norm * plot_h).max(2.0);
3314 let bx: f32 = left + (vi as f32) * slot_w + (slot_w - border_width) * 0.5;
3315 let by: f32 = top + plot_h - bh;
3316 let _: fmt::Result = write!(
3317 out,
3318 "<rect x=\"{bx:.1}\" y=\"{by:.1}\" width=\"{border_width:.1}\" height=\"{bh:.1}\" rx=\"4\" fill=\"{accent}\" fill-opacity=\"0.85\"/>"
3319 );
3320 }
3321 } else {
3322 let mut pts: String = String::new();
3323 for (vi, &tex_v) in ser.get_values().iter().enumerate() {
3324 let norm: f32 = ((tex_v - y_min) / span).clamp(0.0, 1.0);
3325 let px: f32 = left + (vi as f32) * slot_w + slot_w * 0.5;
3326 let py: f32 = top + plot_h - norm * plot_h;
3327 if !pts.is_empty() {
3328 pts.push(' ');
3329 }
3330 let _: fmt::Result = write!(pts, "{px:.1},{py:.1}");
3331 }
3332 if !pts.is_empty() {
3333 let _: fmt::Result = write!(
3334 out,
3335 "<polyline points=\"{pts}\" fill=\"none\" stroke=\"{accent}\" stroke-width=\"2.2\"/>"
3336 );
3337 for (vi, &bary_v) in ser.get_values().iter().enumerate() {
3338 let norm: f32 = ((bary_v - y_min) / span).clamp(0.0, 1.0);
3339 let px: f32 = left + (vi as f32) * slot_w + slot_w * 0.5;
3340 let py: f32 = top + plot_h - norm * plot_h;
3341 let _: fmt::Result = write!(
3342 out,
3343 "<circle cx=\"{px:.1}\" cy=\"{py:.1}\" r=\"3.5\" fill=\"{accent}\"/>"
3344 );
3345 }
3346 }
3347 }
3348 }
3349 for idx in 0..x_count {
3350 let cx: f32 = left + (idx as f32) * slot_w + slot_w * 0.5;
3351 let text_value: &str = xy.get_x_labels().get(idx).map(String::as_str).unwrap_or("");
3352 let _: fmt::Result = write!(
3353 out,
3354 "<text x=\"{cx:.1}\" y=\"{:.1}\" text-anchor=\"middle\" font-size=\"10.5\" fill=\"var(--muted-fg)\">",
3355 top + plot_h + 18.0
3356 );
3357 push_escaped_html(out, text_value);
3358 out.push_str(SVG_TEXT_CLOSE);
3359 }
3360 out.push_str(MERMAID_SVG_CLOSE);
3361}
3362
3363fn render_mermaid_gitgraph_svg(git: &MermaidGitGraph, out: &mut String) {
3370 let c_count: usize = git.get_commits().len();
3371 let b_count: usize = git.get_branches().len().max(1);
3372 if c_count == 0 {
3373 return;
3374 }
3375 let label_w: f32 = 104.0;
3376 let step_x: f32 = 64.0;
3377 let lane_h: f32 = 44.0;
3378 let top: f32 = 24.0;
3379 let svg_w: f32 = (label_w + (c_count as f32) * step_x + 40.0).max(380.0);
3380 let svg_h: f32 = top + (b_count as f32) * lane_h + 26.0;
3381 let _: fmt::Result = write!(
3382 out,
3383 "<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\">"
3384 );
3385 for (bi, bname) in git.get_branches().iter().enumerate() {
3386 let ly: f32 = top + (bi as f32) * lane_h + lane_h * 0.5;
3387 let accent: &str = MERMAID_SVG_PALETTE[bi % MERMAID_SVG_PALETTE.len()];
3388 let _: fmt::Result = write!(
3389 out,
3390 "<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}\">",
3391 svg_w - 20.0,
3392 label_w - 12.0,
3393 ly + 4.0
3394 );
3395 push_escaped_html(out, bname);
3396 out.push_str(SVG_TEXT_CLOSE);
3397 }
3398 let mut coords: Vec<(f32, f32)> = Vec::with_capacity(c_count);
3399 for (ci, commit) in git.get_commits().iter().enumerate() {
3400 let cx: f32 = label_w + 24.0 + (ci as f32) * step_x;
3401 let cy: f32 = top + (commit.get_lane() as f32) * lane_h + lane_h * 0.5;
3402 coords.push((cx, cy));
3403 let accent: &str = MERMAID_SVG_PALETTE[commit.get_lane() % MERMAID_SVG_PALETTE.len()];
3404 if let Some(p_idx) = commit.get_parent_idx()
3405 && let Some(&(px, py)) = coords.get(p_idx)
3406 {
3407 let _: fmt::Result = write!(
3408 out,
3409 "<line x1=\"{px:.1}\" y1=\"{py:.1}\" x2=\"{cx:.1}\" y2=\"{cy:.1}\" stroke=\"{accent}\" stroke-width=\"2\"/>"
3410 );
3411 }
3412 if let Some(m_lane) = commit.get_merge_from_lane() {
3413 let my: f32 = top + (m_lane as f32) * lane_h + lane_h * 0.5;
3414 let mx: f32 = (cx - step_x).max(label_w + 16.0);
3415 let m_acc: &str = MERMAID_SVG_PALETTE[m_lane % MERMAID_SVG_PALETTE.len()];
3416 let _: fmt::Result = write!(
3417 out,
3418 "<line x1=\"{mx:.1}\" y1=\"{my:.1}\" x2=\"{cx:.1}\" y2=\"{cy:.1}\" stroke=\"{m_acc}\" stroke-width=\"1.8\" stroke-dasharray=\"4 3\"/>"
3419 );
3420 }
3421 let _: fmt::Result = write!(
3422 out,
3423 "<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)\">",
3424 cy + 20.0
3425 );
3426 push_escaped_html(out, commit.get_id());
3427 out.push_str(SVG_TEXT_CLOSE);
3428 if !commit.get_tag().is_empty() {
3429 let _: fmt::Result = write!(
3430 out,
3431 "<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\">",
3432 cx - 23.0,
3433 cy - 24.0,
3434 cy - 13.0
3435 );
3436 push_escaped_html(out, commit.get_tag());
3437 out.push_str(SVG_TEXT_CLOSE);
3438 }
3439 }
3440 out.push_str(MERMAID_SVG_CLOSE);
3441}