Skip to main content

euv_docs/generator/
fn.rs

1use super::*;
2
3/// Loads all Markdown files beneath `src_dir` (excluding `out_dir`) and builds a complete static docs site.
4///
5/// # Arguments
6///
7/// - `&Path` - Source project or Markdown directory.
8/// - `&Path` - Output static site directory.
9/// - `&DocsBuildOptions` - Site title, base URL, clean URL, asset copy, and optional dev HMR configuration.
10///
11/// # Returns
12///
13/// - `io::Result<GeneratedSiteReport>` - Summary of generated artifacts or I/O error.
14pub fn build_docs_bundle(
15    src_dir: &Path,
16    out_dir: &Path,
17    options: &DocsBuildOptions,
18) -> io::Result<GeneratedSiteReport> {
19    let site: DocSite =
20        load_doc_site_excluding(src_dir, options.try_get_title().as_deref(), Some(out_dir))?;
21    if site.get_pages().is_empty() {
22        return Err(Error::new(ErrorKind::NotFound, ERR_NO_MARKDOWN_FOUND));
23    }
24    let mut resolved: DocsBuildOptions = options.clone();
25    if resolved.try_get_assets_root().is_none() {
26        resolved.set_assets_root(Some(src_dir.to_path_buf()));
27    }
28    generate_static_docs_with_options(&site, out_dir, &resolved)
29}
30
31/// Generates static HTML pages, search index, and sitemap for `site` into `out_dir` using default options.
32///
33/// # Arguments
34///
35/// - `&DocSite` - Loaded documentation site.
36/// - `&Path` - Destination output directory.
37///
38/// # Returns
39///
40/// - `io::Result<GeneratedSiteReport>` - Summary of written artifacts or I/O error.
41pub fn generate_static_docs(site: &DocSite, out_dir: &Path) -> io::Result<GeneratedSiteReport> {
42    let opts: DocsBuildOptions = DocsBuildOptions::default();
43    generate_static_docs_with_options(site, out_dir, &opts)
44}
45
46/// Generates a complete static documentation site with clean URLs, instant search, TOC, asset copying, and optional dev HMR.
47///
48/// # Arguments
49///
50/// - `&DocSite` - Loaded documentation site.
51/// - `&Path` - Destination output directory.
52/// - `&DocsBuildOptions` - Build options controlling base URL, asset copying, clean URLs, and dev HMR.
53///
54/// # Returns
55///
56/// - `io::Result<GeneratedSiteReport>` - Summary of written artifacts or I/O error.
57pub fn generate_static_docs_with_options(
58    site: &DocSite,
59    out_dir: &Path,
60    options: &DocsBuildOptions,
61) -> io::Result<GeneratedSiteReport> {
62    fs::create_dir_all(out_dir)?;
63    let generated_at: String = Utc::now().to_rfc3339();
64    let entries: Vec<SearchIndexEntry> = site.search_entries();
65    let search_json_compact: String = match to_string(&entries) {
66        Ok(text) => text.replace(SCRIPT_ESC_CLOSE_FROM, SCRIPT_ESC_CLOSE_TO),
67        Err(err) => return Err(Error::other(err.to_string())),
68    };
69    let ordered_pages: Vec<&DocPage> = ordered_site_pages(site);
70    for (idx, page) in ordered_pages.iter().enumerate() {
71        let prev_page: Option<&DocPage> = if idx > 0 {
72            ordered_pages.get(idx - 1).copied()
73        } else {
74            None
75        };
76        let next_page: Option<&DocPage> = ordered_pages.get(idx + 1).copied();
77        let ctx: PageRenderContext<'_> = PageRenderContext {
78            site,
79            prev_page,
80            next_page,
81            generated_at: &generated_at,
82            search_json_compact: &search_json_compact,
83            options,
84        };
85        let html: String = render_page_html_with_context(page, &ctx);
86        let rel_file: PathBuf = html_path_for_route(out_dir, page.get_route());
87        if let Some(parent) = rel_file.parent() {
88            fs::create_dir_all(parent)?;
89        }
90        fs::write(&rel_file, &html)?;
91        if options.get_clean_urls() && page.get_route() != ROOT_ROUTE_STR {
92            let clean_file: PathBuf = clean_html_path_for_route(out_dir, page.get_route());
93            if let Some(parent) = clean_file.parent() {
94                fs::create_dir_all(parent)?;
95            }
96            fs::write(&clean_file, &html)?;
97        }
98    }
99    if let Some(first_page) = ordered_pages.first().copied()
100        && !out_dir.join(INDEX_HTML_NAME).exists()
101    {
102        let fallback_ctx: PageRenderContext<'_> = PageRenderContext {
103            site,
104            prev_page: None,
105            next_page: ordered_pages.get(1).copied(),
106            generated_at: &generated_at,
107            search_json_compact: &search_json_compact,
108            options,
109        };
110        let fallback_html: String = render_page_html_with_context(first_page, &fallback_ctx);
111        fs::write(out_dir.join(INDEX_HTML_NAME), fallback_html)?;
112    }
113    let index_path: PathBuf = out_dir.join(INDEX_JSON_NAME);
114    let json: String = match to_string_pretty(&entries) {
115        Ok(text) => text,
116        Err(err) => return Err(Error::other(err.to_string())),
117    };
118    fs::write(&index_path, json)?;
119    let sitemap_xml: String = build_sitemap_xml(&ordered_pages, options.get_base_url());
120    fs::write(out_dir.join(SITEMAP_XML_NAME), sitemap_xml)?;
121    if let Some(assets_root) = options.try_get_assets_root() {
122        copy_static_assets(assets_root, out_dir)?;
123    }
124    Ok(GeneratedSiteReport::new(
125        site.get_pages().len(),
126        generated_at,
127        index_path.display().to_string(),
128    ))
129}
130
131/// Renders a single `DocPage` into a self-contained static HTML document using default build options.
132///
133/// # Arguments
134///
135/// - `&DocSite` - Parent site for navigation links.
136/// - `&DocPage` - Page to render.
137/// - `&str` - Build timestamp string.
138///
139/// # Returns
140///
141/// - `String` - Complete HTML document string.
142#[must_use]
143pub fn render_page_html(site: &DocSite, page: &DocPage, generated_at: &str) -> String {
144    let entries: Vec<SearchIndexEntry> = site.search_entries();
145    let compact: String = to_string(&entries)
146        .unwrap_or_else(|_| EMPTY_JSON_ARRAY.to_string())
147        .replace(SCRIPT_ESC_CLOSE_FROM, SCRIPT_ESC_CLOSE_TO);
148    let opts: DocsBuildOptions = DocsBuildOptions::default();
149    let ctx: PageRenderContext<'_> = PageRenderContext {
150        site,
151        prev_page: None,
152        next_page: None,
153        generated_at,
154        search_json_compact: &compact,
155        options: &opts,
156    };
157    render_page_html_with_context(page, &ctx)
158}
159
160/// Returns all site pages in canonical sidebar and pagination order.
161///
162/// # Arguments
163///
164/// - `&DocSite` - Loaded documentation site.
165///
166/// # Returns
167///
168/// - `Vec<&DocPage>` - Pages ordered by section rank, section label, page order, and route.
169fn ordered_site_pages(site: &DocSite) -> Vec<&DocPage> {
170    let mut ordered: Vec<&DocPage> = site.get_pages().iter().collect();
171    ordered.sort_by(|a: &&DocPage, b: &&DocPage| {
172        section_sort_rank(a.get_section())
173            .cmp(&section_sort_rank(b.get_section()))
174            .then_with(|| a.get_section().cmp(b.get_section()))
175            .then_with(|| a.get_order().cmp(&b.get_order()))
176            .then_with(|| a.get_route().cmp(b.get_route()))
177    });
178    ordered
179}
180
181/// Renders a full styled HTML page with sidebar sections, TOC, live search index, pagination, and optional HMR.
182///
183/// # Arguments
184///
185/// - `&DocPage` - Active page being rendered.
186/// - `&PageRenderContext<'_>` - Shared site, pagination, timestamp, search index, and build options context.
187///
188/// # Returns
189///
190/// - `String` - Complete HTML document string.
191fn render_page_html_with_context(page: &DocPage, ctx: &PageRenderContext<'_>) -> String {
192    let site: &DocSite = ctx.get_site();
193    let options: &DocsBuildOptions = ctx.get_options();
194    let base: &str = options.get_base_url().trim_end_matches('/');
195    let home_href: String = href_for_route(base, ROOT_ROUTE_STR);
196    let has_toc: bool = !page.get_toc().is_empty();
197    let brand_char: char = brand_monogram(site.get_title());
198    let mut out: String = String::with_capacity(12288);
199    out.push_str(HTML_DOCTYPE);
200    out.push_str(&escape_html(page.get_title()));
201    out.push_str(HTML_TITLE_SEP);
202    out.push_str(&escape_html(site.get_title()));
203    out.push_str(HTML_STYLES_AND_HEAD_END);
204    out.push_str(HTML_TOPBAR_START);
205    out.push_str(&escape_html(&home_href));
206    out.push_str(HTML_TOPBAR_MARK_OPEN);
207    out.push(brand_char);
208    out.push_str(HTML_TOPBAR_MARK_CLOSE);
209    out.push_str(&escape_html(site.get_title()));
210    out.push_str(HTML_TOPBAR_END);
211    if has_toc {
212        out.push_str(HTML_SHELL_OPEN);
213    } else {
214        out.push_str(HTML_SHELL_NO_TOC_OPEN);
215    }
216    out.push_str(HTML_SIDEBAR_OPEN);
217    render_sidebar_nav(site, page, base, &mut out);
218    out.push_str(HTML_SIDEBAR_CLOSE);
219    out.push_str(HTML_BADGE_OPEN);
220    out.push_str(&escape_html(page.get_section()));
221    out.push_str(HTML_BADGE_CLOSE);
222    out.push_str(&escape_html(page.get_title()));
223    out.push_str(HTML_H1_CLOSE);
224    if should_render_lead(page) {
225        out.push_str(HTML_LEAD_OPEN);
226        out.push_str(&escape_html(page.get_summary()));
227        out.push_str(HTML_P_CLOSE);
228    }
229    if !page.get_markdown_body().is_empty() {
230        render_markdown_body_html(page, base, &mut out);
231    } else {
232        render_fallback_blocks_html(page, &mut out);
233    }
234    render_pager_nav(ctx.get_prev_page(), ctx.get_next_page(), base, &mut out);
235    out.push_str(HTML_FOOTER_PREFIX);
236    out.push_str(&escape_html(ctx.get_generated_at()));
237    out.push_str(HTML_FOOTER_SUFFIX);
238    if has_toc {
239        out.push_str(HTML_TOC_OPEN);
240        for item in page.get_toc().iter() {
241            let cls: &str = match item.get_level() {
242                3 => TOC_LVL3_CLASS,
243                lvl if lvl >= 4 => TOC_LVL4_CLASS,
244                _ => "",
245            };
246            out.push_str(&format!(
247                "<a class=\"{cls}\" href=\"#{}\">{}</a>",
248                escape_html(item.get_slug()),
249                escape_html(item.get_title())
250            ));
251        }
252        out.push_str(HTML_TOC_CLOSE);
253    }
254    out.push_str(HTML_SHELL_CLOSE);
255    let base_json: String = to_string(base).unwrap_or_else(|_| EMPTY_JSON_STRING.to_string());
256    out.push_str(HTML_SCRIPT_PREFIX);
257    out.push_str(ctx.get_search_json_compact());
258    out.push_str(HTML_SCRIPT_BASE_PREFIX);
259    out.push_str(&base_json);
260    out.push_str(HTML_SCRIPT_BODY);
261    if let Some(hmr_url) = options.try_get_hmr_endpoint() {
262        out.push_str(HTML_HMR_PREFIX);
263        out.push_str(&escape_html(hmr_url));
264        out.push_str(HTML_HMR_SUFFIX);
265    }
266    out.push_str(HTML_BODY_END);
267    out
268}
269
270/// Renders the grouped section-ordered sidebar links into `out`.
271///
272/// # Arguments
273///
274/// - `&DocSite` - Documentation site.
275/// - `&DocPage` - Currently active page.
276/// - `&str` - Normalized base URL without trailing slash.
277/// - `&mut String` - HTML output buffer.
278fn render_sidebar_nav(site: &DocSite, active_page: &DocPage, base: &str, out: &mut String) {
279    let ordered: Vec<&DocPage> = ordered_site_pages(site);
280    let mut current_section: Option<&str> = None;
281    for nav_page in ordered.into_iter() {
282        let sec: &str = nav_page.get_section().as_str();
283        if current_section != Some(sec) {
284            current_section = Some(sec);
285            out.push_str(HTML_SEC_OPEN);
286            out.push_str(&escape_html(sec));
287            out.push_str(HTML_SEC_CLOSE);
288        }
289        let href: String = href_for_route(base, nav_page.get_route());
290        if nav_page.get_route() == active_page.get_route() {
291            out.push_str(HTML_NAV_LINK_ACTIVE_OPEN);
292        } else {
293            out.push_str(HTML_NAV_LINK_OPEN);
294        }
295        out.push_str(&escape_html(&href));
296        out.push_str(HTML_LINK_MID);
297        out.push_str(&escape_html(nav_page.get_title()));
298        out.push_str(HTML_LINK_CLOSE);
299    }
300}
301
302/// Renders previous and next pagination cards when either neighbor exists.
303///
304/// # Arguments
305///
306/// - `Option<&DocPage>` - Previous page in reading order.
307/// - `Option<&DocPage>` - Next page in reading order.
308/// - `&str` - Normalized base URL without trailing slash.
309/// - `&mut String` - HTML output buffer.
310fn render_pager_nav(
311    prev_page: Option<&DocPage>,
312    next_page: Option<&DocPage>,
313    base: &str,
314    out: &mut String,
315) {
316    if prev_page.is_none() && next_page.is_none() {
317        return;
318    }
319    out.push_str(HTML_PAGER_OPEN);
320    if let Some(prev) = prev_page {
321        out.push_str(HTML_PAGER_PREV_OPEN);
322        out.push_str(&escape_html(&href_for_route(base, prev.get_route())));
323        out.push_str(HTML_PAGER_PREV_LABEL);
324        out.push_str(&escape_html(prev.get_title()));
325        out.push_str(HTML_PAGER_CARD_CLOSE);
326    } else {
327        out.push_str(HTML_PAGER_EMPTY);
328    }
329    if let Some(next) = next_page {
330        out.push_str(HTML_PAGER_NEXT_OPEN);
331        out.push_str(&escape_html(&href_for_route(base, next.get_route())));
332        out.push_str(HTML_PAGER_NEXT_LABEL);
333        out.push_str(&escape_html(next.get_title()));
334        out.push_str(HTML_PAGER_CARD_CLOSE);
335    } else {
336        out.push_str(HTML_PAGER_EMPTY);
337    }
338    out.push_str(HTML_PAGER_CLOSE);
339}
340
341/// Returns `true` when `page.summary` is non-empty and does not duplicate the first body paragraph.
342///
343/// # Arguments
344///
345/// - `&DocPage` - Candidate documentation page.
346///
347/// # Returns
348///
349/// - `bool` - Whether a separate `<p class="lead">` should be rendered.
350fn should_render_lead(page: &DocPage) -> bool {
351    let summary: &str = page.get_summary().trim();
352    if summary.is_empty() {
353        return false;
354    }
355    let first_prose: Option<&str> = page.get_blocks().iter().find_map(|b: &DocBlock| match b {
356        DocBlock::Paragraph(p) | DocBlock::BlockQuote(p) => Some(p.trim()),
357        _ => None,
358    });
359    first_prose != Some(summary)
360}
361
362/// Computes the uppercase single-character brand monogram for the topbar badge.
363///
364/// # Arguments
365///
366/// - `&str` - Site brand title.
367///
368/// # Returns
369///
370/// - `char` - Uppercase alphanumeric initial or `'E'`.
371fn brand_monogram(title: &str) -> char {
372    title
373        .chars()
374        .find(|ch: &char| ch.is_alphanumeric())
375        .and_then(|ch: char| ch.to_uppercase().next())
376        .unwrap_or(DEFAULT_BRAND_MONOGRAM)
377}
378
379/// Renders full-fidelity Markdown HTML preserving inline formatting, links, images, lists, tables, code blocks, and custom containers.
380///
381/// # Arguments
382///
383/// - `&DocPage` - Parsed page carrying raw Markdown body text.
384/// - `&str` - Normalized base URL prefix.
385/// - `&mut String` - HTML output buffer.
386fn render_markdown_body_html(page: &DocPage, base: &str, out: &mut String) {
387    let segments: Vec<BodySegment> = split_custom_containers(page.get_markdown_body());
388    let mut state: MarkdownRenderState<'_> = MarkdownRenderState {
389        page,
390        base,
391        seen_slugs: BTreeMap::new(),
392        skipped_title_h1: false,
393        out,
394    };
395    for seg in segments.into_iter() {
396        match seg {
397            BodySegment::Markdown(md) => {
398                render_markdown_chunk(&md, &mut state);
399            }
400            BodySegment::Callout { kind, title, body } => {
401                if kind == CALLOUT_KIND_DETAILS {
402                    state.out.push_str(&format!(
403                        "<details class=\"callout callout-details\"><summary>{}</summary>",
404                        escape_html(&title)
405                    ));
406                    render_markdown_chunk(&body, &mut state);
407                    state.out.push_str(HTML_DETAILS_CLOSE);
408                } else {
409                    state.out.push_str(&format!(
410                        "<div class=\"callout callout-{}\"><div class=\"callout-title\">{}</div>",
411                        escape_html(&kind),
412                        escape_html(&title)
413                    ));
414                    render_markdown_chunk(&body, &mut state);
415                    state.out.push_str(HTML_DIV_CLOSE);
416                }
417            }
418        }
419    }
420}
421
422/// Splits VuePress-style `::: kind [title]` custom containers while ignoring fenced code blocks.
423///
424/// # Arguments
425///
426/// - `&str` - Raw Markdown document body.
427///
428/// # Returns
429///
430/// - `Vec<BodySegment>` - Ordered plain Markdown and callout segments.
431fn split_custom_containers(body: &str) -> Vec<BodySegment> {
432    let mut segments: Vec<BodySegment> = Vec::new();
433    let mut plain: String = String::new();
434    let mut active: Option<(String, String, String)> = None;
435    let mut in_fence: bool = false;
436    for line in body.lines() {
437        let trimmed: &str = line.trim();
438        if trimmed.starts_with(FENCE_BACKTICK) || trimmed.starts_with(FENCE_TILDE) {
439            in_fence = !in_fence;
440        }
441        if let Some((kind, title, inner)) = active.as_mut() {
442            if !in_fence && trimmed == CALLOUT_FENCE {
443                let done_kind: String = take(kind);
444                let done_title: String = take(title);
445                let done_body: String = take(inner);
446                active = None;
447                segments.push(BodySegment::Callout {
448                    kind: done_kind,
449                    title: done_title,
450                    body: done_body,
451                });
452                continue;
453            }
454            inner.push_str(line);
455            inner.push('\n');
456            continue;
457        }
458        if !in_fence && let Some(after) = trimmed.strip_prefix(CALLOUT_FENCE) {
459            let spec: &str = after.trim();
460            let (raw_kind, custom_title): (&str, &str) = match spec.find(char::is_whitespace) {
461                Some(pos) => (&spec[..pos], spec[pos..].trim()),
462                None => (spec, ""),
463            };
464            let normalized: Option<(&str, &str)> = match raw_kind.to_ascii_lowercase().as_str() {
465                CALLOUT_KIND_TIP => Some((CALLOUT_KIND_TIP, CALLOUT_TITLE_TIP)),
466                CALLOUT_KIND_WARNING => Some((CALLOUT_KIND_WARNING, CALLOUT_TITLE_WARNING)),
467                CALLOUT_KIND_DANGER => Some((CALLOUT_KIND_DANGER, CALLOUT_TITLE_DANGER)),
468                CALLOUT_KIND_INFO => Some((CALLOUT_KIND_INFO, CALLOUT_TITLE_INFO)),
469                CALLOUT_KIND_NOTE => Some((CALLOUT_KIND_NOTE, CALLOUT_TITLE_NOTE)),
470                CALLOUT_KIND_DETAILS => Some((CALLOUT_KIND_DETAILS, CALLOUT_TITLE_DETAILS)),
471                _ => None,
472            };
473            if let Some((kind_str, default_title)) = normalized {
474                if !plain.is_empty() {
475                    segments.push(BodySegment::Markdown(take(&mut plain)));
476                }
477                let title: String = if custom_title.is_empty() {
478                    default_title.to_string()
479                } else {
480                    custom_title.to_string()
481                };
482                active = Some((kind_str.to_string(), title, String::new()));
483                continue;
484            }
485        }
486        plain.push_str(line);
487        plain.push('\n');
488    }
489    if let Some((kind, title, inner)) = active {
490        segments.push(BodySegment::Callout {
491            kind,
492            title,
493            body: inner,
494        });
495    }
496    if !plain.is_empty() {
497        segments.push(BodySegment::Markdown(plain));
498    }
499    segments
500}
501
502/// Renders a single Markdown chunk through `pulldown_cmark` into semantic, XSS-safe HTML.
503///
504/// # Arguments
505///
506/// - `&str` - Markdown chunk text.
507/// - `&mut MarkdownRenderState<'_>` - Mutable page rendering state and HTML output buffer.
508fn render_markdown_chunk(chunk: &str, state: &mut MarkdownRenderState<'_>) {
509    let parser: Parser<'_> = Parser::new_ext(chunk, Options::all());
510    let mut active_heading: Option<(u8, Option<String>, String, String)> = None;
511    let mut active_code: Option<(String, String)> = None;
512    let mut active_image: Option<(String, String, String)> = None;
513    let mut table_alignments: Vec<Alignment> = Vec::new();
514    let mut in_table_head: bool = false;
515    let mut cell_index: usize = 0;
516    for event in parser {
517        if let Some((_, _, ref mut heading_html, ref mut heading_plain)) = active_heading {
518            match event {
519                Event::End(TagEnd::Heading(_)) => {
520                    if let Some((level, custom_id, inner_html, plain)) = active_heading.take() {
521                        let trimmed_plain: &str = plain.trim();
522                        if !trimmed_plain.is_empty() {
523                            let raw_slug: String = custom_id
524                                .map(|s: String| slugify(&s))
525                                .filter(|s: &String| !s.is_empty())
526                                .unwrap_or_else(|| slugify(trimmed_plain));
527                            let slug: String = deduplicate_slug(raw_slug, &mut state.seen_slugs);
528                            if level <= 2
529                                && !state.skipped_title_h1
530                                && state.seen_slugs.len() == 1
531                                && trimmed_plain.eq_ignore_ascii_case(state.page.get_title().trim())
532                            {
533                                state.skipped_title_h1 = true;
534                            } else {
535                                let tag_lvl: u8 = level.clamp(2, 6);
536                                let esc_slug: String = escape_html(&slug);
537                                state.out.push_str(&format!(
538                                    "<h{tag_lvl} id=\"{esc_slug}\">{inner_html}<a class=\"anchor\" href=\"#{esc_slug}\" aria-label=\"Anchor\">#</a></h{tag_lvl}>"
539                                ));
540                            }
541                        }
542                    }
543                }
544                Event::Text(text) => {
545                    heading_plain.push_str(&text);
546                    heading_html.push_str(&escape_html(&text));
547                }
548                Event::Code(text) => {
549                    heading_plain.push_str(&text);
550                    heading_html.push_str(HTML_INLINE_CODE_OPEN);
551                    heading_html.push_str(&escape_html(&text));
552                    heading_html.push_str(HTML_INLINE_CODE_CLOSE);
553                }
554                Event::Start(Tag::Strong) => heading_html.push_str(HTML_STRONG_OPEN),
555                Event::End(TagEnd::Strong) => heading_html.push_str(HTML_STRONG_CLOSE),
556                Event::Start(Tag::Emphasis) => heading_html.push_str(HTML_EM_OPEN),
557                Event::End(TagEnd::Emphasis) => heading_html.push_str(HTML_EM_CLOSE),
558                Event::Start(Tag::Strikethrough) => heading_html.push_str(HTML_DEL_OPEN),
559                Event::End(TagEnd::Strikethrough) => heading_html.push_str(HTML_DEL_CLOSE),
560                Event::SoftBreak | Event::HardBreak => {
561                    heading_plain.push(' ');
562                    heading_html.push(' ');
563                }
564                _ => {}
565            }
566            continue;
567        }
568        if let Some((_, ref mut code_buf)) = active_code {
569            match event {
570                Event::End(TagEnd::CodeBlock) => {
571                    if let Some((lang, code)) = active_code.take() {
572                        let trimmed: &str = code.trim_end_matches('\n');
573                        state.out.push_str(HTML_CODE_WRAP_OPEN);
574                        state.out.push_str(&escape_html(&lang));
575                        state.out.push_str(HTML_CODE_HEAD_MID);
576                        state.out.push_str(&escape_html(&lang));
577                        state.out.push_str(HTML_LINK_MID);
578                        state.out.push_str(&escape_html(trimmed));
579                        state.out.push_str(HTML_CODE_CLOSE);
580                    }
581                }
582                Event::Text(text) | Event::Code(text) => code_buf.push_str(&text),
583                Event::SoftBreak | Event::HardBreak => code_buf.push('\n'),
584                _ => {}
585            }
586            continue;
587        }
588        if let Some((_, _, ref mut alt_buf)) = active_image {
589            match event {
590                Event::End(TagEnd::Image) => {
591                    if let Some((src, title, alt)) = active_image.take()
592                        && let Some(resolved) =
593                            resolve_asset_src(state.base, state.page.get_route(), &src)
594                    {
595                        if title.is_empty() {
596                            state.out.push_str(&format!(
597                                "<img src=\"{}\" alt=\"{}\" loading=\"lazy\">",
598                                escape_html(&resolved),
599                                escape_html(alt.trim())
600                            ));
601                        } else {
602                            state.out.push_str(&format!(
603                                "<img src=\"{}\" alt=\"{}\" title=\"{}\" loading=\"lazy\">",
604                                escape_html(&resolved),
605                                escape_html(alt.trim()),
606                                escape_html(&title)
607                            ));
608                        }
609                    }
610                }
611                Event::Text(text) | Event::Code(text) => alt_buf.push_str(&text),
612                Event::SoftBreak | Event::HardBreak => alt_buf.push(' '),
613                _ => {}
614            }
615            continue;
616        }
617        match event {
618            Event::Start(Tag::Heading { level, id, .. }) => {
619                active_heading = Some((
620                    heading_level_num(level),
621                    id.map(CowStr::into_string),
622                    String::new(),
623                    String::new(),
624                ));
625            }
626            Event::Start(Tag::Paragraph) => state.out.push_str(HTML_P_OPEN),
627            Event::End(TagEnd::Paragraph) => state.out.push_str(HTML_P_CLOSE),
628            Event::Start(Tag::BlockQuote(_)) => state.out.push_str(HTML_QUOTE_OPEN),
629            Event::End(TagEnd::BlockQuote(_)) => state.out.push_str(HTML_QUOTE_CLOSE),
630            Event::Start(Tag::List(None)) => state.out.push_str(HTML_UL_OPEN),
631            Event::Start(Tag::List(Some(start))) => {
632                if start == 1 {
633                    state.out.push_str(HTML_OL_OPEN);
634                } else {
635                    state.out.push_str(&format!("<ol start=\"{start}\">"));
636                }
637            }
638            Event::End(TagEnd::List(ordered)) => {
639                if ordered {
640                    state.out.push_str(HTML_OL_CLOSE);
641                } else {
642                    state.out.push_str(HTML_UL_CLOSE);
643                }
644            }
645            Event::Start(Tag::Item) => state.out.push_str(HTML_LI_OPEN),
646            Event::End(TagEnd::Item) => state.out.push_str(HTML_LI_CLOSE),
647            Event::Start(Tag::Strong) => state.out.push_str(HTML_STRONG_OPEN),
648            Event::End(TagEnd::Strong) => state.out.push_str(HTML_STRONG_CLOSE),
649            Event::Start(Tag::Emphasis) => state.out.push_str(HTML_EM_OPEN),
650            Event::End(TagEnd::Emphasis) => state.out.push_str(HTML_EM_CLOSE),
651            Event::Start(Tag::Strikethrough) => state.out.push_str(HTML_DEL_OPEN),
652            Event::End(TagEnd::Strikethrough) => state.out.push_str(HTML_DEL_CLOSE),
653            Event::Start(Tag::CodeBlock(kind)) => {
654                let lang: String = match kind {
655                    CodeBlockKind::Fenced(tag) => {
656                        let first: &str = tag.split_whitespace().next().unwrap_or("");
657                        if first.is_empty() {
658                            DEFAULT_CODE_LABEL.to_string()
659                        } else {
660                            first.to_string()
661                        }
662                    }
663                    CodeBlockKind::Indented => DEFAULT_CODE_LABEL.to_string(),
664                };
665                active_code = Some((lang, String::new()));
666            }
667            Event::Start(Tag::Link {
668                dest_url, title, ..
669            }) => {
670                let resolved: String =
671                    resolve_link_href(state.base, state.page.get_route(), &dest_url);
672                let external: bool = is_external_url(&resolved);
673                state.out.push_str(HTML_A_HREF_OPEN);
674                state.out.push_str(&escape_html(&resolved));
675                state.out.push('"');
676                if !title.is_empty() {
677                    state.out.push_str(HTML_TITLE_ATTR_OPEN);
678                    state.out.push_str(&escape_html(&title));
679                    state.out.push('"');
680                }
681                if external {
682                    state.out.push_str(HTML_EXTERNAL_LINK_ATTRS);
683                }
684                state.out.push('>');
685            }
686            Event::End(TagEnd::Link) => state.out.push_str(HTML_LINK_CLOSE),
687            Event::Start(Tag::Image {
688                dest_url, title, ..
689            }) => {
690                active_image = Some((dest_url.into_string(), title.into_string(), String::new()));
691            }
692            Event::Start(Tag::Table(aligns)) => {
693                table_alignments = aligns;
694                in_table_head = false;
695                state.out.push_str(HTML_TABLE_OPEN);
696            }
697            Event::End(TagEnd::Table) => {
698                table_alignments.clear();
699                state.out.push_str(HTML_TBODY_CLOSE);
700                state.out.push_str(HTML_TABLE_CLOSE);
701            }
702            Event::Start(Tag::TableHead) => {
703                in_table_head = true;
704                cell_index = 0;
705                state.out.push_str(HTML_THEAD_OPEN);
706            }
707            Event::End(TagEnd::TableHead) => {
708                in_table_head = false;
709                state.out.push_str(HTML_THEAD_CLOSE);
710                state.out.push_str(HTML_TBODY_OPEN);
711            }
712            Event::Start(Tag::TableRow) => {
713                cell_index = 0;
714                state.out.push_str(HTML_TR_OPEN);
715            }
716            Event::End(TagEnd::TableRow) => state.out.push_str(HTML_TR_CLOSE),
717            Event::Start(Tag::TableCell) => {
718                let align_attr: &str = match table_alignments.get(cell_index).copied() {
719                    Some(Alignment::Center) => HTML_ALIGN_CENTER,
720                    Some(Alignment::Right) => HTML_ALIGN_RIGHT,
721                    _ => "",
722                };
723                cell_index += 1;
724                if in_table_head {
725                    state.out.push_str(&format!("<th{align_attr}>"));
726                } else {
727                    state.out.push_str(&format!("<td{align_attr}>"));
728                }
729            }
730            Event::End(TagEnd::TableCell) => {
731                if in_table_head {
732                    state.out.push_str(HTML_TH_CLOSE);
733                } else {
734                    state.out.push_str(HTML_TD_CLOSE);
735                }
736            }
737            Event::Start(Tag::FootnoteDefinition(label)) => {
738                state.out.push_str(&format!(
739                    "<blockquote class=\"footnote\" id=\"fn-{}\"><strong>[^{}]</strong> ",
740                    escape_html(&slugify(&label)),
741                    escape_html(&label)
742                ));
743            }
744            Event::End(TagEnd::FootnoteDefinition) => state.out.push_str(HTML_QUOTE_CLOSE),
745            Event::FootnoteReference(label) => {
746                state.out.push_str(&format!(
747                    "<sup><a href=\"#fn-{}\">[^{}]</a></sup>",
748                    escape_html(&slugify(&label)),
749                    escape_html(&label)
750                ));
751            }
752            Event::TaskListMarker(checked) => {
753                if checked {
754                    state.out.push_str(HTML_TASK_CHECKED);
755                } else {
756                    state.out.push_str(HTML_TASK_UNCHECKED);
757                }
758            }
759            Event::Rule => state.out.push_str(HTML_HR),
760            Event::Text(text) => state.out.push_str(&escape_html(&text)),
761            Event::Code(text) => {
762                state.out.push_str(HTML_INLINE_CODE_OPEN);
763                state.out.push_str(&escape_html(&text));
764                state.out.push_str(HTML_INLINE_CODE_CLOSE);
765            }
766            Event::SoftBreak => state.out.push(' '),
767            Event::HardBreak => state.out.push_str(HTML_BR),
768            Event::Html(raw_html) | Event::InlineHtml(raw_html) => {
769                if is_safe_raw_html(&raw_html) {
770                    state.out.push_str(&raw_html);
771                } else {
772                    state.out.push_str(&escape_html(&raw_html));
773                }
774            }
775            _ => {}
776        }
777    }
778}
779
780/// Renders structured `DocBlock` entries when a `DocPage` was constructed without raw Markdown text.
781///
782/// # Arguments
783///
784/// - `&DocPage` - Documentation page containing structured blocks.
785/// - `&mut String` - HTML output buffer.
786fn render_fallback_blocks_html(page: &DocPage, out: &mut String) {
787    let mut in_ul: bool = false;
788    for block in page.get_blocks().iter() {
789        let is_item: bool = matches!(block, DocBlock::ListItem(_));
790        if is_item && !in_ul {
791            out.push_str(HTML_UL_OPEN);
792            in_ul = true;
793        } else if !is_item && in_ul {
794            out.push_str(HTML_UL_CLOSE);
795            in_ul = false;
796        }
797        match block {
798            DocBlock::Heading { level, slug, text } => {
799                let tag_lvl: u8 = (*level).clamp(2, 6);
800                out.push_str(&format!(
801                    "<h{tag_lvl} id=\"{}\">{}</h{tag_lvl}>",
802                    escape_html(slug),
803                    escape_html(text)
804                ));
805            }
806            DocBlock::Paragraph(text) => {
807                out.push_str(HTML_P_OPEN);
808                out.push_str(&escape_html(text));
809                out.push_str(HTML_P_CLOSE);
810            }
811            DocBlock::ListItem(text) => {
812                out.push_str(HTML_LI_OPEN);
813                out.push_str(&escape_html(text));
814                out.push_str(HTML_LI_CLOSE);
815            }
816            DocBlock::BlockQuote(text) => {
817                out.push_str(HTML_QUOTE_OPEN);
818                out.push_str(&escape_html(text));
819                out.push_str(HTML_QUOTE_CLOSE);
820            }
821            DocBlock::Image { alt, src } => {
822                out.push_str(&format!(
823                    "<p><img src=\"{}\" alt=\"{}\" loading=\"lazy\"></p>",
824                    escape_html(src),
825                    escape_html(alt)
826                ));
827            }
828            DocBlock::HorizontalRule => out.push_str(HTML_HR),
829            DocBlock::Code { language, code } => {
830                out.push_str(HTML_CODE_WRAP_OPEN);
831                out.push_str(&escape_html(language));
832                out.push_str(HTML_CODE_HEAD_MID);
833                out.push_str(&escape_html(language));
834                out.push_str(HTML_LINK_MID);
835                out.push_str(&escape_html(code));
836                out.push_str(HTML_CODE_CLOSE);
837            }
838            DocBlock::Table { headers, rows } => {
839                out.push_str(HTML_TABLE_OPEN);
840                if !headers.is_empty() {
841                    out.push_str(HTML_THEAD_OPEN);
842                    for h in headers.iter() {
843                        out.push_str(HTML_TH_OPEN);
844                        out.push_str(&escape_html(h));
845                        out.push_str(HTML_TH_CLOSE);
846                    }
847                    out.push_str(HTML_THEAD_CLOSE);
848                }
849                out.push_str(HTML_TBODY_OPEN);
850                for row in rows.iter() {
851                    out.push_str(HTML_TR_OPEN);
852                    for cell in row.iter() {
853                        out.push_str(HTML_TD_OPEN);
854                        out.push_str(&escape_html(cell));
855                        out.push_str(HTML_TD_CLOSE);
856                    }
857                    out.push_str(HTML_TR_CLOSE);
858                }
859                out.push_str(HTML_TBODY_CLOSE);
860                out.push_str(HTML_TABLE_CLOSE);
861            }
862        }
863    }
864    if in_ul {
865        out.push_str(HTML_UL_CLOSE);
866    }
867}
868
869/// Checks whether a raw Markdown HTML fragment is free of active script or event-handler vectors.
870///
871/// # Arguments
872///
873/// - `&str` - Raw HTML fragment emitted by `pulldown_cmark`.
874///
875/// # Returns
876///
877/// - `bool` - `true` when safe to pass through verbatim.
878fn is_safe_raw_html(raw: &str) -> bool {
879    let low: String = raw.to_ascii_lowercase();
880    if UNSAFE_HTML_TAGS.iter().any(|tag: &&str| low.contains(tag)) {
881        return false;
882    }
883    if low.contains(SCHEME_JAVASCRIPT) || low.contains(SCHEME_VBSCRIPT) {
884        return false;
885    }
886    let bytes: &[u8] = low.as_bytes();
887    for i in 0..bytes.len().saturating_sub(3) {
888        let before_ok: bool = i == 0 || bytes[i - 1].is_ascii_whitespace();
889        if before_ok
890            && bytes[i] == b'o'
891            && bytes[i + 1] == b'n'
892            && bytes[i + 2].is_ascii_alphabetic()
893        {
894            let rest: &str = &low[i + 2..];
895            let attr_len: usize = rest
896                .bytes()
897                .take_while(|b: &u8| b.is_ascii_alphabetic())
898                .count();
899            if rest[attr_len..].trim_start().starts_with('=') {
900                return false;
901            }
902        }
903    }
904    true
905}
906
907/// Resolves Markdown link targets, rewriting relative `.md` links to clean URLs and blocking unsafe schemes.
908///
909/// # Arguments
910///
911/// - `&str` - Normalized base URL prefix.
912/// - `&str` - Current page canonical route.
913/// - `&str` - Raw Markdown link destination.
914///
915/// # Returns
916///
917/// - `String` - Safe navigable HTML `href` attribute value.
918fn resolve_link_href(base: &str, current_route: &str, raw_dest: &str) -> String {
919    let dest: &str = raw_dest.trim();
920    let low: String = dest.to_ascii_lowercase();
921    if low.starts_with(SCHEME_JAVASCRIPT) || low.starts_with(SCHEME_VBSCRIPT) {
922        return "#".to_string();
923    }
924    if dest.starts_with('#')
925        || low.starts_with(SCHEME_HTTP)
926        || low.starts_with(SCHEME_HTTPS)
927        || low.starts_with(SCHEME_MAILTO)
928    {
929        return dest.to_string();
930    }
931    let (path_part, fragment): (&str, Option<&str>) = match dest.split_once('#') {
932        Some((p, f)) => (p, Some(f)),
933        None => (dest, None),
934    };
935    let path_low: String = path_part.to_ascii_lowercase();
936    if path_low.ends_with(MARKDOWN_EXT_SUFFIX) {
937        let joined: String = join_relative_route(current_route, path_part);
938        let stripped: &str = joined
939            .strip_suffix(MARKDOWN_EXT_SUFFIX)
940            .or_else(|| joined.strip_suffix(MARKDOWN_EXT_UPPER))
941            .unwrap_or(&joined);
942        let mut segs: Vec<String> = stripped
943            .split('/')
944            .filter(|s: &&str| !s.is_empty())
945            .map(|seg: &str| {
946                let cleaned: String = slugify(seg);
947                if cleaned.is_empty() {
948                    seg.to_ascii_lowercase()
949                } else {
950                    cleaned
951                }
952            })
953            .collect();
954        if let Some(last) = segs.last()
955            && (last.eq_ignore_ascii_case(STEM_README_LOWER)
956                || last.eq_ignore_ascii_case(STEM_INDEX_LOWER))
957        {
958            let _: Option<String> = segs.pop();
959        }
960        let route: String = if segs.is_empty() {
961            ROOT_ROUTE_STR.to_string()
962        } else {
963            format!("/{}", segs.join("/"))
964        };
965        let clean: String = href_for_route(base, &route);
966        return match fragment {
967            Some(frag) if !frag.is_empty() => format!("{clean}#{frag}"),
968            _ => clean,
969        };
970    }
971    if dest.starts_with('/') {
972        if base.is_empty() {
973            dest.to_string()
974        } else {
975            format!("{base}{dest}")
976        }
977    } else {
978        dest.to_string()
979    }
980}
981
982/// Resolves Markdown image `src` attributes against `current_route` and `base`, blocking unsafe schemes.
983///
984/// # Arguments
985///
986/// - `&str` - Normalized base URL prefix.
987/// - `&str` - Current page canonical route.
988/// - `&str` - Raw Markdown image destination.
989///
990/// # Returns
991///
992/// - `Option<String>` - Safe `src` attribute value or `None` when blocked.
993fn resolve_asset_src(base: &str, current_route: &str, raw_src: &str) -> Option<String> {
994    let src: &str = raw_src.trim();
995    let low: String = src.to_ascii_lowercase();
996    if src.is_empty() || low.starts_with(SCHEME_JAVASCRIPT) || low.starts_with(SCHEME_VBSCRIPT) {
997        return None;
998    }
999    if low.starts_with(SCHEME_HTTP) || low.starts_with(SCHEME_HTTPS) || low.starts_with(SCHEME_DATA)
1000    {
1001        return Some(src.to_string());
1002    }
1003    if src.starts_with('/') {
1004        return Some(if base.is_empty() {
1005            src.to_string()
1006        } else {
1007            format!("{base}{src}")
1008        });
1009    }
1010    let resolved: String = join_relative_route(current_route, src);
1011    Some(if base.is_empty() {
1012        resolved
1013    } else {
1014        format!("{base}{resolved}")
1015    })
1016}
1017
1018/// Resolves a relative link or asset path against a page's canonical directory route.
1019///
1020/// # Arguments
1021///
1022/// - `&str` - Canonical page route (for example `/guide/markdown`).
1023/// - `&str` - Relative path reference (for example `./getting-started.md` or `../img/logo.png`).
1024///
1025/// # Returns
1026///
1027/// - `String` - Normalized root-relative path beginning with `/`.
1028fn join_relative_route(current_route: &str, rel_path: &str) -> String {
1029    let mut stack: Vec<String> = current_route
1030        .trim_matches('/')
1031        .split('/')
1032        .filter(|s: &&str| !s.is_empty())
1033        .map(str::to_string)
1034        .collect();
1035    if !stack.is_empty() {
1036        let _: Option<String> = stack.pop();
1037    }
1038    for seg in rel_path.split('/') {
1039        if seg.is_empty() || seg == "." {
1040            continue;
1041        }
1042        if seg == ".." {
1043            let _: Option<String> = stack.pop();
1044        } else {
1045            stack.push(seg.to_string());
1046        }
1047    }
1048    if stack.is_empty() {
1049        ROOT_ROUTE_STR.to_string()
1050    } else {
1051        format!("/{}", stack.join("/"))
1052    }
1053}
1054
1055/// Returns `true` when `href` points to an external HTTP(S) origin.
1056///
1057/// # Arguments
1058///
1059/// - `&str` - Resolved href string.
1060///
1061/// # Returns
1062///
1063/// - `bool` - Whether the link should open in a new tab.
1064fn is_external_url(href: &str) -> bool {
1065    let low: String = href.to_ascii_lowercase();
1066    low.starts_with(SCHEME_HTTP) || low.starts_with(SCHEME_HTTPS)
1067}
1068
1069/// Builds a standard XML sitemap containing every generated page route in canonical order.
1070///
1071/// # Arguments
1072///
1073/// - `&[&DocPage]` - Ordered site pages.
1074/// - `&str` - Optional base URL prefix.
1075///
1076/// # Returns
1077///
1078/// - `String` - Complete `sitemap.xml` document.
1079fn build_sitemap_xml(pages: &[&DocPage], base_url: &str) -> String {
1080    let base: &str = base_url.trim_end_matches('/');
1081    let mut xml: String = String::from(SITEMAP_HEADER);
1082    for page in pages.iter() {
1083        let loc: String = href_for_route(base, page.get_route());
1084        xml.push_str(SITEMAP_URL_OPEN);
1085        xml.push_str(&escape_html(&loc));
1086        xml.push_str(SITEMAP_URL_CLOSE);
1087    }
1088    xml.push_str(SITEMAP_FOOTER);
1089    xml
1090}
1091
1092/// Copies recognized static asset directories and co-located media assets into `out_dir`.
1093///
1094/// # Arguments
1095///
1096/// - `&Path` - Source project or docs root directory.
1097/// - `&Path` - Output site directory.
1098///
1099/// # Returns
1100///
1101/// - `io::Result<()>` - Copy result.
1102fn copy_static_assets(src_root: &Path, out_dir: &Path) -> io::Result<()> {
1103    let canonical_out: PathBuf =
1104        fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
1105    for dir_name in ASSET_COPY_DIRS.iter() {
1106        let candidate: PathBuf = src_root.join(dir_name);
1107        if candidate.is_dir() {
1108            copy_dir_recursive(&candidate, &out_dir.join(dir_name), &canonical_out)?;
1109        }
1110    }
1111    copy_colocated_media(src_root, src_root, out_dir, &canonical_out)
1112}
1113
1114/// Recursively copies non-Markdown static asset files from `src` into `dst`.
1115///
1116/// # Arguments
1117///
1118/// - `&Path` - Source directory.
1119/// - `&Path` - Destination directory.
1120/// - `&Path` - Canonical output root skipped to avoid self-recursion.
1121///
1122/// # Returns
1123///
1124/// - `io::Result<()>` - Copy result.
1125fn copy_dir_recursive(src: &Path, dst: &Path, canonical_out: &Path) -> io::Result<()> {
1126    let src_canon: PathBuf = fs::canonicalize(src).unwrap_or_else(|_| src.to_path_buf());
1127    if src_canon == canonical_out || src_canon.starts_with(canonical_out) {
1128        return Ok(());
1129    }
1130    fs::create_dir_all(dst)?;
1131    for entry_res in fs::read_dir(src)? {
1132        let entry: DirEntry = entry_res?;
1133        let path: PathBuf = entry.path();
1134        let target: PathBuf = dst.join(entry.file_name());
1135        if path.is_dir() {
1136            copy_dir_recursive(&path, &target, canonical_out)?;
1137        } else if path
1138            .extension()
1139            .and_then(|s: &OsStr| s.to_str())
1140            .is_none_or(|ext: &str| !ext.eq_ignore_ascii_case(MARKDOWN_EXT_CHECK))
1141        {
1142            let _: u64 = fs::copy(&path, &target)?;
1143        }
1144    }
1145    Ok(())
1146}
1147
1148/// Recursively copies co-located media files alongside Markdown documents while skipping ignored dirs and `out_dir`.
1149///
1150/// # Arguments
1151///
1152/// - `&Path` - Original source root directory.
1153/// - `&Path` - Current directory being walked.
1154/// - `&Path` - Output site directory.
1155/// - `&Path` - Canonical output root skipped to avoid self-recursion.
1156///
1157/// # Returns
1158///
1159/// - `io::Result<()>` - Copy result.
1160fn copy_colocated_media(
1161    src_root: &Path,
1162    cur_dir: &Path,
1163    out_dir: &Path,
1164    canonical_out: &Path,
1165) -> io::Result<()> {
1166    for entry_res in fs::read_dir(cur_dir)? {
1167        let entry: DirEntry = entry_res?;
1168        let path: PathBuf = entry.path();
1169        if path.is_dir() {
1170            let name: String = entry.file_name().to_string_lossy().into_owned();
1171            if should_skip_dir(&name) {
1172                continue;
1173            }
1174            if cur_dir == src_root
1175                && ASSET_COPY_DIRS
1176                    .iter()
1177                    .any(|d: &&str| name.eq_ignore_ascii_case(d))
1178            {
1179                continue;
1180            }
1181            let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
1182            if canon == canonical_out || canon.starts_with(canonical_out) {
1183                continue;
1184            }
1185            copy_colocated_media(src_root, &path, out_dir, canonical_out)?;
1186        } else if path
1187            .extension()
1188            .and_then(|s: &OsStr| s.to_str())
1189            .is_some_and(|ext: &str| {
1190                CO_LOCATED_ASSET_EXTS
1191                    .iter()
1192                    .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
1193            })
1194            && let Ok(rel) = path.strip_prefix(src_root)
1195        {
1196            let target: PathBuf = out_dir.join(rel);
1197            if let Some(parent) = target.parent() {
1198                fs::create_dir_all(parent)?;
1199            }
1200            let _: u64 = fs::copy(&path, &target)?;
1201        }
1202    }
1203    Ok(())
1204}
1205
1206/// Formats a clean link href for `route` under `base`.
1207///
1208/// # Arguments
1209///
1210/// - `&str` - Normalized base URL without trailing slash.
1211/// - `&str` - Canonical route path.
1212///
1213/// # Returns
1214///
1215/// - `String` - Clean navigable href string.
1216fn href_for_route(base: &str, route: &str) -> String {
1217    let trimmed: &str = route.trim_matches('/');
1218    if trimmed.is_empty() {
1219        if base.is_empty() {
1220            ROOT_ROUTE_STR.to_string()
1221        } else {
1222            format!("{base}/")
1223        }
1224    } else if base.is_empty() {
1225        format!("/{trimmed}/")
1226    } else {
1227        format!("{base}/{trimmed}/")
1228    }
1229}
1230
1231/// Computes the filesystem output `.html` path for a canonical documentation route.
1232///
1233/// # Arguments
1234///
1235/// - `&Path` - Output root directory.
1236/// - `&str` - Canonical route path.
1237///
1238/// # Returns
1239///
1240/// - `PathBuf` - Destination `.html` file path.
1241fn html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1242    let trimmed: &str = route.trim_matches('/');
1243    if trimmed.is_empty() {
1244        out_dir.join(INDEX_HTML_NAME)
1245    } else {
1246        out_dir.join(format!("{trimmed}{HTML_EXT}"))
1247    }
1248}
1249
1250/// Computes the clean directory-index `<route>/index.html` path for a canonical route.
1251///
1252/// # Arguments
1253///
1254/// - `&Path` - Output root directory.
1255/// - `&str` - Canonical route path.
1256///
1257/// # Returns
1258///
1259/// - `PathBuf` - Destination `<route>/index.html` path.
1260fn clean_html_path_for_route(out_dir: &Path, route: &str) -> PathBuf {
1261    let trimmed: &str = route.trim_matches('/');
1262    if trimmed.is_empty() {
1263        out_dir.join(INDEX_HTML_NAME)
1264    } else {
1265        out_dir.join(trimmed).join(INDEX_HTML_NAME)
1266    }
1267}
1268
1269/// Escapes special HTML characters in text content.
1270///
1271/// # Arguments
1272///
1273/// - `&str` - Raw UTF-8 text.
1274///
1275/// # Returns
1276///
1277/// - `String` - Escaped HTML-safe string.
1278fn escape_html(input: &str) -> String {
1279    let mut out: String = String::with_capacity(input.len());
1280    for ch in input.chars() {
1281        match ch {
1282            '&' => out.push_str(HTML_ESC_AMP),
1283            '<' => out.push_str(HTML_ESC_LT),
1284            '>' => out.push_str(HTML_ESC_GT),
1285            '"' => out.push_str(HTML_ESC_QUOT),
1286            _ => out.push(ch),
1287        }
1288    }
1289    out
1290}