Skip to main content

rto_render/
docs.rs

1//! The documentation-site renderer: ADR markdown → themed HTML pages, produced
2//! deterministically so CI diffs are meaningful. Replaces the shell
3//! `md2html.awk` stopgap with a real `CommonMark` parser (`pulldown-cmark`),
4//! fixing the whole class of hand-rolled-parser bugs (backtick runs, tables,
5//! heading edge cases) we hit before.
6//!
7//! Page chrome (theme, nav, back-link, footer) matches the previous site so the
8//! switch is drop-in. This module is pure string generation; the `roteiro`
9//! binary owns walking `docs/adr` and copying static assets.
10
11use std::collections::BTreeMap;
12use std::fmt::Write as _;
13
14use pulldown_cmark::{CowStr, Event, HeadingLevel, Options, Parser, Tag, TagEnd, html};
15
16/// A rendered ADR: its title (for the index) and the full themed HTML page.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RenderedAdr {
19    /// The ADR title (first `# ` heading, or the fallback passed to
20    /// [`render_adr`]).
21    pub title: String,
22    /// The complete HTML document.
23    pub html: String,
24}
25
26/// Where each source document is **actually published**: the file the site
27/// serves, keyed by the source markdown's file name.
28///
29/// [`rewrite_doc_link`] used to derive a link's target from the link's own
30/// spelling — `../BUILD_PLAN_V2.md` → `../BUILD_PLAN_V2.html` — which is correct
31/// only while every document is served under its own stem. Site pages ended
32/// that: a page is published as its declared `site-page:` slug, and a slug is
33/// URL-safe by construction (`[a-z0-9-]+`), so `docs/BUILD_PLAN_V2.md` is served
34/// as `build-plan-v2.html`. The rewrite then pointed four correct repository
35/// links at a page that is never emitted — issue #446, live on roteiro.dev.
36///
37/// So the served name is *looked up* rather than guessed. The renderer is handed
38/// the index of what the site emits, which is the only thing that knows the
39/// answer.
40///
41/// Keyed by file name rather than by full path because the site mirrors the
42/// repository's layout — `docs/*.md` at the root, `docs/adr/*.md` under `adr/` —
43/// so a link's directory hops are already correct and only the final segment can
44/// differ. A file name claimed by two published documents is recorded as
45/// **ambiguous** and left unrewritten: guessing which one a link meant is how a
46/// link silently points at the wrong page, which is worse than the 404 it
47/// replaces.
48#[derive(Debug, Default, Clone, PartialEq, Eq)]
49pub struct PublishedPages(BTreeMap<String, Option<String>>);
50
51impl PublishedPages {
52    /// An empty index: every `.md` link falls back to its own stem.
53    #[must_use]
54    pub fn new() -> Self {
55        Self::default()
56    }
57
58    /// Record that `source_file` (a markdown file name, e.g. `BUILD_PLAN_V2.md`)
59    /// is served as `served_as` (e.g. `build-plan-v2.html`).
60    ///
61    /// A second, differing claim on one file name makes it ambiguous; see the
62    /// type's documentation for why that is left unrewritten.
63    pub fn publish(&mut self, source_file: &str, served_as: &str) {
64        self.0
65            .entry(source_file.to_owned())
66            .and_modify(|slot| {
67                if slot.as_deref() != Some(served_as) {
68                    *slot = None;
69                }
70            })
71            .or_insert_with(|| Some(served_as.to_owned()));
72    }
73
74    /// The file `source_file` is served as, or `None` when it is unknown or
75    /// ambiguous.
76    fn served(&self, source_file: &str) -> Option<&str> {
77        self.0.get(source_file)?.as_deref()
78    }
79}
80
81/// Where a link that leaves the site points instead: the repository's own web
82/// view, at the commit the site was built from.
83///
84/// The Build Plan cites code as evidence for its claims — `[sync](../crates/…
85/// /sync.rs)` — which is correct in a checkout and dead on roteiro.dev, because
86/// `render docs` publishes documents and not source. Six such links were live on
87/// the site (issue #456). This is the answer chosen for them: keep the link's
88/// affordance and move its target to the one place the file is actually served.
89///
90/// # Pinned to a commit, not to a branch
91///
92/// `blob` carries a sha (`…/blob/<sha>`), not `…/blob/main`. GitHub serves a
93/// blob by sha forever, so the link keeps resolving after the file is renamed or
94/// deleted; a `main` link 404s on the next rename, and this is a *retired* plan
95/// whose citations describe the code as it stood, so drifting them onto today's
96/// `main` would be wrong even when it resolved. It is also the rule the vault
97/// renderer already ships (`source_blob_base` + `head_commit_id`), and one repo
98/// with two answers to "which commit does a source link mean" is its own defect.
99///
100/// The cost is stated rather than hidden: a site rendered from a commit that was
101/// never pushed yields links the host has never heard of. That is a local
102/// preview, not the published site — the Website workflow renders from a commit
103/// GitHub already has.
104///
105/// # No mappable origin
106///
107/// Construction goes through [`SourceBase::new`], which yields `None` when the
108/// caller has no blob base to offer — no `origin` remote, or a remote whose URL
109/// does not map to a web view. Links are then left exactly as they are: still
110/// correct in a checkout, still dead on the site. That is deliberate and is the
111/// least-bad of the three: refusing to render would break `render docs` in any
112/// repository without an `origin` (every test fixture, every fresh `git init`),
113/// and demoting the link to plain text would destroy information to hide a
114/// problem the reader can otherwise route around.
115///
116/// # Can the class recur?
117///
118/// Not while a base exists: the rule is structural, not a list of the six links
119/// that were found. *Any* link climbing above the site root is re-aimed, so a new
120/// citation added to any rendered document is handled the day it is written, and
121/// `a_link_out_of_the_site_goes_to_the_repository` is what fails if that stops.
122///
123/// It recurs silently in exactly one case — a site rendered where no base can be
124/// derived — and nothing catches that, because the output is the *authored* link
125/// and there is no rendered-site link gate (issue #459) to notice. That case is
126/// the one the deploy does not hit: the Website workflow checks out with an
127/// `origin` on `github.com`, and `without_an_origin_remote_a_source_link_is_left_as_authored`
128/// pins the behaviour rather than the absence of a gate.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct SourceBase {
131    /// Web blob base, no trailing slash — e.g.
132    /// `https://github.com/owner/repo/blob/<sha>`.
133    blob: String,
134    /// The rendered document's own directory, repository-relative and with no
135    /// trailing slash: `docs`, `docs/adr`, `website/pages`. A link is resolved
136    /// against this to get the path the repository serves.
137    dir: String,
138}
139
140impl SourceBase {
141    /// A source base for a document at repository-relative directory `dir`,
142    /// served from `blob`. `None` when `blob` is `None` — see the type's
143    /// documentation for why that leaves links alone rather than failing.
144    #[must_use]
145    pub fn new(blob: Option<&str>, dir: &str) -> Option<Self> {
146        Some(Self {
147            blob: blob?.trim_end_matches('/').to_owned(),
148            dir: dir.trim_matches('/').to_owned(),
149        })
150    }
151
152    /// The web URL for `path` — a link written relative to this document —
153    /// carrying `frag` through unchanged (`#L12` is a GitHub line anchor, and
154    /// the site has no better guess than the author's).
155    ///
156    /// `None` when `path` climbs out of the repository altogether, which no base
157    /// can name.
158    fn blob_url(&self, path: &str, frag: Option<&str>) -> Option<String> {
159        let joined = format!("{}/{}", self.dir, path);
160        let (up, segs) = resolve_relative(&joined);
161        if up > 0 || segs.is_empty() {
162            return None;
163        }
164        let repo_path = segs.join("/");
165        Some(match frag {
166            Some(frag) => format!("{}/{repo_path}#{frag}", self.blob),
167            None => format!("{}/{repo_path}", self.blob),
168        })
169    }
170}
171
172/// One page in the site navigation bar: where it goes and what it is called.
173///
174/// Built by the caller from the authored site pages (`rto_spec::site_nav` puts
175/// them in order), and passed to [`render_site_page`] whole so every page emits
176/// the *same* bar. A per-page bar assembled independently is a bar that can
177/// disagree with itself, which is how a page ends up unreachable from its
178/// neighbours.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct NavEntry {
181    /// Root-relative href (e.g. `modes.html`, or `./` for the landing page).
182    pub href: String,
183    /// Short label shown in the bar.
184    pub label: String,
185}
186
187/// An entry in the ADR/docs index page.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct IndexEntry {
190    /// Relative href (e.g. `0001-….html`).
191    pub href: String,
192    /// Display title.
193    pub title: String,
194}
195
196/// Convert `CommonMark` `md` to an HTML fragment (GitHub tables + strikethrough,
197/// and Roteiro `[[wiki-links]]` resolved). Resolves ADR links relative to the
198/// ADR directory; use [`render_doc`] for root-level pages.
199///
200/// A fragment renderer has no site to be a part of, so it carries neither
201/// [`PublishedPages`] nor [`SourceBase`]: a `.md` link is rewritten to its own
202/// stem, which is right for an ADR and a guess for anything published under a
203/// slug, and a link out of the site is left alone.
204#[must_use]
205pub fn markdown_to_html(md: &str) -> String {
206    render_markdown(md, "", &PublishedPages::new(), None, 0)
207}
208
209/// Render `md` to HTML: resolve `[[wiki-links]]` (ADR links use `adr_prefix` as
210/// their href prefix), rewrite ordinary `[…](*.md)` links to their rendered
211/// `.html` targets and links out of the site to `source`, then run `CommonMark`
212/// with GitHub tables/strikethrough. `depth` is the page's own depth below the
213/// site root; see [`rewrite_doc_link`].
214fn render_markdown(
215    md: &str,
216    adr_prefix: &str,
217    pages: &PublishedPages,
218    source: Option<&SourceBase>,
219    depth: usize,
220) -> String {
221    let pre = rewrite_wiki_links(md, adr_prefix);
222    let ids = heading_ids(&pre);
223    let mut next_id = 0usize;
224    // Rewrite link destinations pointing at local Markdown files to the HTML the
225    // site actually serves (e.g. `adr/0001-….md` → `adr/0001-….html`), and give
226    // every heading a stable `id` so it can be linked to.
227    let parser = Parser::new_ext(&pre, options()).map(|event| match event {
228        Event::Start(Tag::Link {
229            link_type,
230            dest_url,
231            title,
232            id,
233        }) => Event::Start(Tag::Link {
234            link_type,
235            dest_url: rewrite_doc_link(&dest_url, pages, source, depth)
236                .map_or(dest_url, CowStr::from),
237            title,
238            id,
239        }),
240        Event::Start(Tag::Heading {
241            level,
242            classes,
243            attrs,
244            ..
245        }) => {
246            let id = ids.get(next_id).cloned().map(CowStr::from);
247            next_id += 1;
248            Event::Start(Tag::Heading {
249                level,
250                id,
251                classes,
252                attrs,
253            })
254        }
255        other => other,
256    });
257    let mut out = String::new();
258    html::push_html(&mut out, parser);
259    out
260}
261
262/// The `CommonMark` dialect the whole site is parsed with — [`rto_graph`]'s, not
263/// a copy of it.
264///
265/// This used to build its own `Options` with the same three flags. It was the
266/// same set by agreement rather than by construction, which is the arrangement
267/// [`rto_graph::markdown_dialect`] exists to end: a different option set is a
268/// different language, and two parsers that disagree about it do not fail — they
269/// quietly disagree about where a heading's text ends, which is the defect #469
270/// was. That crate could not finish the consolidation while this file was held
271/// open by the work in #456/#457/#508; this is the remaining half.
272///
273/// What the dialect buys *this* renderer, and why the heading-attribute flag in
274/// particular is load-bearing here: **heading attributes are how a URL outlives a
275/// restructure.** A page split out of the old single-page site keeps the anchor
276/// the old page published — the heading declares `{#modes}` and lands at
277/// `#modes` — instead of silently becoming whatever the new heading text happens
278/// to slugify to. External links point at those anchors and cannot be updated, so
279/// the alternative is not a tidier URL; it is a dead one.
280fn options() -> Options {
281    // Keep this body a single delegation. It is the shape that invites a
282    // "just for rendering" flag, and the shape where adding one leaves nothing
283    // to notice it by — the duplicate that used to sit here is gone, so a
284    // divergence introduced now is invisible rather than merely unnoticed.
285    //
286    // A flag this renderer sets and `rto-graph`'s extractors do not is a flag
287    // that changes what a heading's text *is* on one surface and not the other.
288    // That is the #469 defect again, with the evidence removed.
289    //
290    // So a renderer-only flag belongs in `markdown_dialect` or nowhere, and "or
291    // nowhere" is not rhetoric: the claim that some future flag cannot reach
292    // heading text is an argument, not an observation, and an argument belongs
293    // in `rto-graph` beside the flag it licenses, where every surface reads it.
294    //
295    // `the_dialect_is_not_extended_here` fails if this body grows a flag.
296    rto_graph::markdown_dialect()
297}
298
299/// The `id` for every heading in `md`, in document order.
300///
301/// An explicit `{#anchor}` wins; otherwise the id is [`rto_graph::slugify`] of
302/// the heading text — the same function that builds the section's node key, so
303/// an authored link to `site:modes#offline-mode` lands on the heading the graph
304/// says it does. A heading whose text slugifies to nothing (`## ###`) falls back
305/// to its position, and a repeat gets a `-2`, `-3`, … suffix, because two
306/// elements sharing an `id` means one of them is unreachable.
307///
308/// Computed from a *first parse* rather than a line scan: heading text can be
309/// spread over several inline events, and `#` inside a fenced block is not a
310/// heading at all. Parsing twice costs a document-sized pass and cannot be wrong
311/// about what the renderer will see, because it is the same parser.
312///
313/// # This rule is not GitHub's, and deliberately stays that way
314///
315/// A document in `docs/` is read in two places under two slug rules: GitHub
316/// renders `**v0.10.x**` as `v010x` and this renders it as `v0-10-x`, so an
317/// anchor hand-written against one is dead in the other. That is real, and it is
318/// the *second* half of issue #457 — the six anchors that issue found were dead
319/// under **both** rules, because the heading text had changed under them.
320///
321/// It is not fixed by aligning this rule to GitHub's, and that is not a
322/// deferral. [`rto_graph::slugify`] is the *one* rule, shared on purpose:
323/// `rto_spec` builds every section node key with it (`adr:0001#design`,
324/// `site:modes#offline-mode`) and this builds the matching `id`, which is the
325/// only reason a `[[doc#section]]` wiki-link resolves through one and lands
326/// through the other. Re-keying it to GitHub's would re-key every section node in
327/// the graph and break every authored wiki-link `roteiro check` gates — to fix
328/// anchors in one retired document. rustdoc is a *third* rule already in play,
329/// so there is no single rule to converge on in any case.
330///
331/// Note what does **not** protect this: #397's guard (`doc_anchor_fragments.rs`)
332/// replicates rustdoc's rule in its own private `slugify` and never calls
333/// [`rto_graph::slugify`], so changing this rule would not have made it fail. It
334/// is not a guard on this code path, and treating it as one was the mistake worth
335/// recording here.
336///
337/// So the divergence is left, documented, and the affected anchors were given
338/// explicit ids that neither rule touches (see `docs/BUILD_PLAN.md`). **Nothing
339/// currently checks an intra-document anchor** in either rendering — not
340/// `roteiro check`, not this crate. Issue #459 is where that check belongs.
341fn heading_ids(md: &str) -> Vec<String> {
342    let mut ids: Vec<String> = Vec::new();
343    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
344    let mut current: Option<(Option<String>, String)> = None;
345    for event in Parser::new_ext(md, options()) {
346        match event {
347            Event::Start(Tag::Heading { id, .. }) => {
348                current = Some((id.map(|i| i.to_string()), String::new()));
349            }
350            Event::Text(t) | Event::Code(t) => {
351                if let Some((_, text)) = current.as_mut() {
352                    text.push_str(&t);
353                }
354            }
355            Event::End(TagEnd::Heading(_)) => {
356                let Some((explicit, text)) = current.take() else {
357                    continue;
358                };
359                let base = explicit
360                    .filter(|e| !e.is_empty())
361                    .unwrap_or_else(|| rto_graph::slugify(&text));
362                let base = if base.is_empty() {
363                    format!("section-{}", ids.len() + 1)
364                } else {
365                    base
366                };
367                let n = seen.entry(base.clone()).or_insert(0);
368                *n += 1;
369                ids.push(if *n == 1 { base } else { format!("{base}-{n}") });
370            }
371            _ => {}
372        }
373    }
374    ids
375}
376
377/// Split a relative path into the number of hops it takes **above** its own
378/// directory and the segments that remain, resolving `.` and `..` the way a
379/// browser and a filesystem both do.
380///
381/// `../crates/x.rs` is `(1, ["crates", "x.rs"])`; `adr/../guide.md` is
382/// `(0, ["guide.md"])`. The hop count is the whole escape test in
383/// [`rewrite_doc_link`]: a link that climbs further than the page sits below the
384/// site root is a link to something outside the site.
385fn resolve_relative(path: &str) -> (usize, Vec<&str>) {
386    let mut up = 0usize;
387    let mut segs: Vec<&str> = Vec::new();
388    for seg in path.split('/') {
389        match seg {
390            "" | "." => {}
391            ".." => {
392                if segs.pop().is_none() {
393                    up += 1;
394                }
395            }
396            s => segs.push(s),
397        }
398    }
399    (up, segs)
400}
401
402/// Rewrite a relative link so it points at what the **site** serves, preserving
403/// any `#fragment`. Returns `None` for external, protocol-relative, `mailto:`,
404/// pure-anchor and root-relative links, and for anything the site already serves
405/// under the spelling the link uses — all of which are left unchanged.
406///
407/// `depth` is how far below the site root the page being rendered sits: 0 for a
408/// root-level page, 1 for an ADR under `adr/`. It is supplied by the entry point
409/// rather than by the caller, because the entry point is the thing that knows.
410///
411/// Two rewrites live here, and the order between them is the interesting part:
412///
413/// * a `.md` link is aimed at the page the site publishes it as
414///   ([`PublishedPages`]) — checked **first**, so a document that happens to be
415///   reached by a path climbing out of its own directory still lands on its
416///   published page rather than being treated as unpublished (issue #446);
417/// * a link that climbs above the site root and is *not* published is aimed at
418///   the repository's web view ([`SourceBase`]) — issue #456.
419fn rewrite_doc_link(
420    dest: &str,
421    pages: &PublishedPages,
422    source: Option<&SourceBase>,
423    depth: usize,
424) -> Option<String> {
425    if dest.starts_with("http://")
426        || dest.starts_with("https://")
427        || dest.starts_with("//")
428        || dest.starts_with("mailto:")
429        || dest.starts_with('#')
430        || dest.starts_with('/')
431    {
432        return None;
433    }
434    let (path, frag) = dest
435        .split_once('#')
436        .map_or((dest, None), |(p, f)| (p, Some(f)));
437    // Only the final segment can differ between the repository and the site, so
438    // the link's own directory hops are kept verbatim; see [`PublishedPages`].
439    let (dir, file) = path.rsplit_once('/').map_or(("", path), |(d, f)| (d, f));
440    // `strip_suffix` rather than `ends_with`: the extension is matched exactly as
441    // it is written, which is the rule every document in this repository follows.
442    let is_markdown = path.strip_suffix(".md").is_some();
443    let sep = if dir.is_empty() { "" } else { "/" };
444
445    // A page the site publishes, under the name it publishes it as (issue #446).
446    // First, so a document reached by a path that climbs out of its own
447    // directory still lands on its page rather than being read as unpublished.
448    if let Some(served) = is_markdown.then(|| pages.served(file)).flatten() {
449        return Some(match frag {
450            Some(frag) => format!("{dir}{sep}{served}#{frag}"),
451            None => format!("{dir}{sep}{served}"),
452        });
453    }
454
455    // Not published, and climbing above the site root: no rewrite *within* the
456    // site can make this resolve, so hand it to the repository (issue #456).
457    // When there is no base to hand it to, fall through — everything below is
458    // the behaviour that predates this, unchanged, so a repository with no
459    // mappable `origin` renders exactly the site it rendered before.
460    if resolve_relative(path).0 > depth
461        && let Some(url) = source.and_then(|s| s.blob_url(path, frag))
462    {
463        return Some(url);
464    }
465
466    if !is_markdown {
467        return None;
468    }
469    // Unknown or ambiguous: fall back to the stem rewrite this has always done,
470    // which is right for every ADR (each is served under its own stem) and no
471    // worse than before for anything else.
472    let served = format!("{}.html", file.trim_end_matches(".md"));
473    Some(match frag {
474        Some(frag) => format!("{dir}{sep}{served}#{frag}"),
475        None => format!("{dir}{sep}{served}"),
476    })
477}
478
479/// Render one ADR markdown document to a themed HTML page. Leading YAML
480/// frontmatter is stripped; the title is the first `# ` heading, or `fallback`
481/// if there is none. ADR `[[…]]` links resolve to sibling ADR pages.
482///
483/// An ADR page is served one directory below the site root (`adr/`), which is
484/// the `1` below: a `../…` link from an ADR still lands inside the site, and only
485/// a second hop leaves it. See [`SourceBase`] for `source`.
486#[must_use]
487pub fn render_adr(
488    markdown: &str,
489    fallback_title: &str,
490    pages: &PublishedPages,
491    source: Option<&SourceBase>,
492) -> RenderedAdr {
493    let body = strip_frontmatter(markdown);
494    let title = first_heading(body).unwrap_or_else(|| fallback_title.to_owned());
495    let content = render_markdown(body, "", pages, source, 1);
496    let nav = "<p class=\"nav\"><a href=\"../\">← Roteiro home</a> · \
497               <a href=\"./\">All ADRs</a> · <a href=\"../build-plan.html\">Build Plan</a></p>";
498    let html = page(&format!("{title} — Roteiro"), "../", nav, &content);
499    RenderedAdr { title, html }
500}
501
502/// Render a root-level "lifetime doc" (e.g. the Build Plan) to a themed page.
503/// Its `[[docs/adr/…]]` links resolve into the `adr/` subdirectory.
504///
505/// The page is served *at* the site root — the `0` below — so any `../…` link
506/// leaves the site; see [`SourceBase`] for where those go.
507#[must_use]
508pub fn render_doc(
509    markdown: &str,
510    fallback_title: &str,
511    pages: &PublishedPages,
512    source: Option<&SourceBase>,
513) -> RenderedAdr {
514    let body = strip_frontmatter(markdown);
515    let title = first_heading(body).unwrap_or_else(|| fallback_title.to_owned());
516    let content = render_markdown(body, "adr/", pages, source, 0);
517    let nav = "<p class=\"nav\"><a href=\"./\">← Roteiro home</a> · \
518               <a href=\"adr/\">ADRs</a></p>";
519    let html = page(&format!("{title} — Roteiro"), "./", nav, &content);
520    RenderedAdr { title, html }
521}
522
523/// Render one **site page** — a document that declared itself published — to a
524/// themed root-level page carrying the site navigation bar.
525///
526/// `nav` is the whole bar, in order; `current_href` is this page's own entry,
527/// which is marked `aria-current="page"` and rendered unlinked so the reader can
528/// see where they are. A `current_href` that matches nothing in `nav` simply
529/// yields a bar with nothing marked, which is what a preview of an unlisted page
530/// should look like rather than an error.
531///
532/// The title is the first `# ` heading, or `fallback_title`. `[[docs/adr/…]]`
533/// links resolve into the `adr/` subdirectory, exactly as they do for the Build
534/// Plan: a site page is a root-level document.
535#[must_use]
536pub fn render_site_page(
537    markdown: &str,
538    fallback_title: &str,
539    nav: &[NavEntry],
540    current_href: &str,
541    pages: &PublishedPages,
542    source: Option<&SourceBase>,
543) -> RenderedAdr {
544    let body = strip_frontmatter(markdown);
545    let title = first_heading(body).unwrap_or_else(|| fallback_title.to_owned());
546    let content = render_markdown(body, "adr/", pages, source, 0);
547    let bar = render_nav(nav, current_href);
548    let html = page(&format!("{title} — Roteiro"), "./", &bar, &content);
549    RenderedAdr { title, html }
550}
551
552/// The site navigation bar: one link per page, the current one marked.
553///
554/// Plain anchors in a `<nav>`, styled by `website/public/style.css`. No script:
555/// the explorer is deliberately vendored with no build step (ADR-0010), and a
556/// navigation bar that needs JavaScript to be a navigation bar would be the
557/// first thing on this site that does.
558#[must_use]
559pub fn render_nav(nav: &[NavEntry], current_href: &str) -> String {
560    let mut out = String::from("<nav class=\"sitenav\">");
561    for entry in nav {
562        if entry.href == current_href {
563            let _ = write!(
564                out,
565                "<span aria-current=\"page\">{}</span>",
566                escape_html(&entry.label)
567            );
568        } else {
569            let _ = write!(
570                out,
571                "<a href=\"{}\">{}</a>",
572                escape_attr(&entry.href),
573                escape_html(&entry.label)
574            );
575        }
576    }
577    out.push_str("</nav>");
578    out
579}
580
581/// The marker whose contents [`replace_site_nav`] owns.
582const SITENAV_OPEN: &str = "<nav class=\"sitenav\">";
583
584/// Replace the `<nav class="sitenav">…</nav>` block in a **hand-written** page
585/// with the bar the renderer computes, returning `None` when the page carries no
586/// such block.
587///
588/// # Why this exists
589///
590/// `website/public/index.html` is the one page of roteiro.dev nothing renders —
591/// it is copied verbatim — and it used to carry a *hand-maintained copy* of the
592/// list the renderer derives from `site-order` (issue #508). Adding
593/// `docs/SERVING.md` appeared in every rendered page's bar automatically and had
594/// to be typed into the landing page by hand.
595///
596/// The failure that made it worth removing rather than remembering is silent and
597/// points the wrong way: a new page is published, reachable, and linked from
598/// every page **except the front one**. Nothing errors and `roteiro check`
599/// passes, because everything that is there resolves.
600///
601/// **That is also why no link auditor could have caught it, and why none will
602/// catch the next one of its shape.** The defect is a link that does *not*
603/// exist; auditing what is there cannot find what is missing. This removes the
604/// possibility instead — after this, the landing page has no independent list to
605/// disagree with. What still guards the seam is
606/// `the_landing_page_carries_the_bar_the_renderer_emits`, which now checks that
607/// the replacement *happened*: a landing page whose marker was renamed away
608/// keeps its stale bar silently, and that test is what fails.
609///
610/// # Why `None` rather than an error
611///
612/// A landing page with no `sitenav` is not claiming a bar, and a site is allowed
613/// not to have one — every `render docs` fixture writes a one-line `index.html`.
614/// The caller leaves such a page alone.
615#[must_use]
616pub fn replace_site_nav(html: &str, nav: &[NavEntry], current_href: &str) -> Option<String> {
617    let open = html.find(SITENAV_OPEN)?;
618    let close = html[open..].find("</nav>")? + open + "</nav>".len();
619    let mut out = String::with_capacity(html.len());
620    out.push_str(&html[..open]);
621    out.push_str(&render_nav(nav, current_href));
622    out.push_str(&html[close..]);
623    Some(out)
624}
625
626/// Render the docs index: any `lifetime` docs (Build Plan, …) then the ADRs.
627#[must_use]
628pub fn render_adr_index(lifetime: &[IndexEntry], entries: &[IndexEntry]) -> String {
629    let mut list = String::new();
630    if !lifetime.is_empty() {
631        list.push_str("<h1>Documentation</h1><ul>");
632        for e in lifetime {
633            let _ = write!(
634                list,
635                "<li><a href=\"{}\">{}</a></li>",
636                escape_attr(&e.href),
637                escape_html(&e.title)
638            );
639        }
640        list.push_str("</ul>");
641    }
642    list.push_str("<h1>Architecture Decision Records</h1><ul>");
643    for e in entries {
644        let _ = write!(
645            list,
646            "<li><a href=\"{}\">{}</a></li>",
647            escape_attr(&e.href),
648            escape_html(&e.title)
649        );
650    }
651    list.push_str("</ul>");
652    let nav = "<p class=\"nav\"><a href=\"../\">← Roteiro home</a></p>";
653    page("Documentation — Roteiro", "../", nav, &list)
654}
655
656/// Rewrite Roteiro `[[wiki-links]]` into Markdown, honouring code spans/fences:
657/// `[[docs/adr/<slug>.md]]` (optionally `#section`) becomes a link to that ADR
658/// page (`<adr_prefix><slug>.html`); any other `[[…]]` (code/file references,
659/// for which the site has no page) becomes inline code so it renders cleanly
660/// instead of leaking literal brackets.
661fn rewrite_wiki_links(md: &str, adr_prefix: &str) -> String {
662    let mut out = String::new();
663    let mut in_fence = false;
664    for line in md.lines() {
665        let trimmed = line.trim_start();
666        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
667            in_fence = !in_fence;
668            out.push_str(line);
669            out.push('\n');
670            continue;
671        }
672        if in_fence {
673            out.push_str(line);
674            out.push('\n');
675            continue;
676        }
677        rewrite_line_outside_code(line, adr_prefix, &mut out);
678        out.push('\n');
679    }
680    out
681}
682
683/// Rewrite wiki-links in one line, leaving `CommonMark` inline code spans
684/// untouched. A code span opens with a run of *n* backticks and closes with the
685/// next run of *exactly* *n* backticks; anything between (including `[[…]]`
686/// examples) is emitted verbatim. Backtick runs with no matching close are
687/// literal text and do not shield what follows.
688fn rewrite_line_outside_code(line: &str, adr_prefix: &str, out: &mut String) {
689    let bytes = line.as_bytes();
690    let mut text_start = 0;
691    let mut i = 0;
692    while i < bytes.len() {
693        if bytes[i] != b'`' {
694            i += 1;
695            continue;
696        }
697        let run_start = i;
698        while i < bytes.len() && bytes[i] == b'`' {
699            i += 1;
700        }
701        let run = i - run_start;
702        if let Some(rel) = find_closing_run(&bytes[i..], run) {
703            // Text before the opening delimiter is ordinary prose.
704            rewrite_wiki_in(&line[text_start..run_start], adr_prefix, out);
705            let code_end = i + rel + run;
706            out.push_str(&line[run_start..code_end]); // span, delimiters included
707            i = code_end;
708            text_start = i;
709        }
710        // No close → treat the run as literal text; keep it in the pending
711        // buffer (rewrite_wiki_in leaves backticks alone) and keep scanning.
712    }
713    rewrite_wiki_in(&line[text_start..], adr_prefix, out);
714}
715
716/// Byte offset (within `bytes`) of the next backtick run of *exactly* `run`
717/// backticks, or `None`. Longer or shorter runs are skipped, per `CommonMark`.
718fn find_closing_run(bytes: &[u8], run: usize) -> Option<usize> {
719    let mut i = 0;
720    while i < bytes.len() {
721        if bytes[i] != b'`' {
722            i += 1;
723            continue;
724        }
725        let start = i;
726        while i < bytes.len() && bytes[i] == b'`' {
727            i += 1;
728        }
729        if i - start == run {
730            return Some(start);
731        }
732    }
733    None
734}
735
736/// Rewrite every `[[…]]` in one non-code text segment.
737fn rewrite_wiki_in(seg: &str, adr_prefix: &str, out: &mut String) {
738    let mut rest = seg;
739    while let Some(open) = rest.find("[[") {
740        out.push_str(&rest[..open]);
741        let after = &rest[open + 2..];
742        if let Some(close) = after.find("]]") {
743            out.push_str(&wiki_target(&after[..close], adr_prefix));
744            rest = &after[close + 2..];
745        } else {
746            out.push_str("[[");
747            rest = after;
748        }
749    }
750    out.push_str(rest);
751}
752
753/// Resolve one wiki-link's inner text to Markdown.
754fn wiki_target(inner: &str, adr_prefix: &str) -> String {
755    let inner = inner.trim();
756    let path = inner.split_once('#').map_or(inner, |(p, _)| p.trim());
757    if let Some(rest) = path.strip_prefix("docs/adr/")
758        && let Some(stem) = rest.strip_suffix(".md")
759    {
760        return format!("[{}]({adr_prefix}{stem}.html)", adr_label(stem));
761    }
762    // Code/file reference — the site has no page for it; show it as code.
763    format!("`{inner}`")
764}
765
766/// A display label for an ADR filename stem: `0001-build-…` → `ADR-0001`.
767fn adr_label(stem: &str) -> String {
768    let digits: String = stem.chars().take_while(char::is_ascii_digit).collect();
769    if digits.is_empty() {
770        stem.to_owned()
771    } else {
772        format!("ADR-{digits}")
773    }
774}
775
776/// Wrap body HTML in the themed page chrome. `root` is the relative path to the
777/// site root (e.g. `"../"` for pages under `adr/`).
778fn page(title: &str, root: &str, nav: &str, body: &str) -> String {
779    format!(
780        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
781         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
782         <link rel=\"icon\" href=\"{root}favicon.svg\" type=\"image/svg+xml\">\
783         <link rel=\"icon\" href=\"{root}favicon.ico\" type=\"image/x-icon\" sizes=\"16x16 32x32 48x48\">\
784         <link rel=\"apple-touch-icon\" href=\"{root}apple-touch-icon.png\">\
785         <link rel=\"stylesheet\" href=\"{root}style.css\">\
786         <title>{title}</title></head><body>\
787         {nav}{body}\
788         <p class=\"backlink\"><a href=\"{root}\">← Back to roteiro.dev</a></p>\
789         <footer>Dual-licensed MIT OR Apache-2.0 · The Roteiro Project Team</footer>\
790         </body></html>",
791        title = escape_html(title),
792    )
793}
794
795/// Strip a leading `---`-delimited YAML frontmatter block.
796fn strip_frontmatter(text: &str) -> &str {
797    let Some(rest) = text.strip_prefix("---\n") else {
798        return text;
799    };
800    match rest.find("\n---\n") {
801        Some(end) => &rest[end + 5..],
802        None => rest.strip_suffix("\n---").unwrap_or(text),
803    }
804}
805
806/// The visible text of the document's first level-1 heading — what the reader
807/// sees in the rendered `<h1>` — or `None` when the document has none.
808///
809/// Read from a **parse**, for the same reason [`heading_ids`] is: the heading's
810/// raw line is source, not text. A line scan cannot tell `{#modes}` (a heading
811/// attribute this renderer deliberately enables, see [`options`]) from the words
812/// of the heading, so it read `# The five ways to run it {#modes}` back as a
813/// title and put the markup in the `<title>` element of every page moved by the
814/// site split — issue #460, live on roteiro.dev. The `<h1>` on the same page was
815/// already right, because that side went through the parser.
816///
817/// The fix is *not* a second place that knows how to strip `{#…}`. A rule
818/// spelled out twice is a rule that can disagree with itself, and this one
819/// already disagrees once: the anchor is markup to the parser and text to the
820/// scanner. Asking the parser removes the second opinion rather than aligning
821/// it, and carries the rest of the dialect along for free — a fenced `# …` is
822/// not a title, a setext underline is one, and inline markup (`` `code` ``,
823/// emphasis, a link label) contributes its text and not its punctuation.
824///
825/// The parse stops at the first `</h1>`; nothing walks the rest of the document.
826fn first_heading(body: &str) -> Option<String> {
827    let mut text: Option<String> = None;
828    for event in Parser::new_ext(body, options()) {
829        match event {
830            Event::Start(Tag::Heading {
831                level: HeadingLevel::H1,
832                ..
833            }) => text = Some(String::new()),
834            // Only accumulates once an H1 has opened; a code span is part of the
835            // heading's text, exactly as it is for the heading's id.
836            Event::Text(t) | Event::Code(t) => {
837                if let Some(text) = text.as_mut() {
838                    text.push_str(&t);
839                }
840            }
841            Event::End(TagEnd::Heading(HeadingLevel::H1)) => break,
842            _ => {}
843        }
844    }
845    // An empty `#` heading names nothing, so it defers to the caller's fallback
846    // rather than rendering `<title> — Roteiro</title>`.
847    text.map(|t| t.trim().to_owned()).filter(|t| !t.is_empty())
848}
849
850fn escape_html(s: &str) -> String {
851    s.replace('&', "&amp;")
852        .replace('<', "&lt;")
853        .replace('>', "&gt;")
854}
855
856fn escape_attr(s: &str) -> String {
857    escape_html(s).replace('"', "&quot;")
858}
859
860#[cfg(test)]
861mod tests {
862    use super::{
863        IndexEntry, NavEntry, PublishedPages, SourceBase, escape_html, markdown_to_html, options,
864        render_adr, render_adr_index, render_doc, render_markdown, render_nav, render_site_page,
865        replace_site_nav,
866    };
867
868    /// The site index most tests do not exercise: with it empty, a `.md` link
869    /// falls back to its own stem, which is what every assertion below predates.
870    fn no_pages() -> PublishedPages {
871        PublishedPages::new()
872    }
873
874    fn nav() -> Vec<NavEntry> {
875        vec![
876            NavEntry {
877                href: "./".into(),
878                label: "Home".into(),
879            },
880            NavEntry {
881                href: "modes.html".into(),
882                label: "Modes & Co".into(),
883            },
884        ]
885    }
886
887    #[test]
888    fn markdown_renders_headings_and_tables() {
889        let html = markdown_to_html("# Title\n\n| a | b |\n|---|---|\n| 1 | 2 |\n");
890        assert!(html.contains("<h1 id=\"title\">Title</h1>"), "{html}");
891        assert!(html.contains("<table>"));
892        assert!(html.contains("<td>1</td>"));
893    }
894
895    #[test]
896    fn adr_wiki_links_become_sibling_page_links() {
897        // An ADR-to-ADR wiki link resolves to the sibling .html; a code/file
898        // reference becomes inline code; both stop leaking literal `[[ ]]`.
899        let md = "See [[docs/adr/0001-build-roteiro.md]] and \
900                  [[crates/rto-graph/src/store.rs#Store]] here.\n";
901        let html = markdown_to_html(md);
902        assert!(
903            html.contains("<a href=\"0001-build-roteiro.html\">ADR-0001</a>"),
904            "ADR wiki-link → sibling page: {html}"
905        );
906        assert!(
907            html.contains("<code>crates/rto-graph/src/store.rs#Store</code>"),
908            "code reference → inline code: {html}"
909        );
910        assert!(
911            !html.contains("[["),
912            "no literal wiki brackets leak: {html}"
913        );
914    }
915
916    #[test]
917    fn wiki_links_inside_code_are_left_literal() {
918        // A documented example of the syntax, in backticks or a fence, must not
919        // be rewritten.
920        let inline = markdown_to_html("use `[[docs/adr/0001-x.md]]` in prose\n");
921        assert!(
922            inline.contains("<code>[[docs/adr/0001-x.md]]</code>"),
923            "{inline}"
924        );
925        let fenced = markdown_to_html("```\n[[docs/adr/0001-x.md]]\n```\n");
926        assert!(
927            fenced.contains("[[docs/adr/0001-x.md]]"),
928            "fence literal: {fenced}"
929        );
930    }
931
932    #[test]
933    fn multi_backtick_code_spans_are_honoured() {
934        // A tight double-backtick span (`` ``…`` ``) and the Build Plan's
935        // nested-backtick example must both survive verbatim — the previous
936        // single-backtick split rewrote the wiki-link inside them.
937        let tight = markdown_to_html("say ``[[docs/adr/0001-x.md]]`` please\n");
938        assert!(
939            tight.contains("<code>[[docs/adr/0001-x.md]]</code>"),
940            "{tight}"
941        );
942        assert!(!tight.contains("<a "), "no link inside code span: {tight}");
943
944        let nested = markdown_to_html("its `` `[[path#Symbol]]` `` example\n");
945        assert!(
946            nested.contains("<code>`[[path#Symbol]]`</code>"),
947            "{nested}"
948        );
949        assert!(
950            !nested.contains("<a "),
951            "no link inside nested span: {nested}"
952        );
953
954        // An unterminated run is literal and does not shield a later real link.
955        let stray = markdown_to_html("a ` stray tick then [[docs/adr/0001-x.md]]\n");
956        assert!(
957            stray.contains("<a href=\"0001-x.html\">ADR-0001</a>"),
958            "unterminated backtick must not shield: {stray}"
959        );
960    }
961
962    #[test]
963    fn markdown_md_links_are_rewritten_to_html() {
964        // Ordinary `[text](path.md)` links must point at the rendered `.html`,
965        // preserving fragments; external and anchor links are left alone.
966        let html = markdown_to_html(
967            "See [ADR-1](adr/0001-x.md) and [§2](adr/0001-x.md#context) and \
968             [home](https://x.dev) and [top](#intro).\n",
969        );
970        assert!(html.contains("href=\"adr/0001-x.html\""), "{html}");
971        assert!(html.contains("href=\"adr/0001-x.html#context\""), "{html}");
972        assert!(
973            html.contains("href=\"https://x.dev\""),
974            "external unchanged: {html}"
975        );
976        assert!(html.contains("href=\"#intro\""), "anchor unchanged: {html}");
977        assert!(!html.contains(".md\""), "no raw .md hrefs remain: {html}");
978    }
979
980    #[test]
981    fn render_doc_links_adrs_into_subdir() {
982        // A root-level lifetime doc (Build Plan) resolves ADR links into `adr/`.
983        let r = render_doc(
984            "# Build Plan\n\nGoverned by [[docs/adr/0001-x.md]].\n",
985            "Build Plan",
986            &no_pages(),
987            None,
988        );
989        assert_eq!(r.title, "Build Plan");
990        assert!(
991            r.html.contains("<a href=\"adr/0001-x.html\">ADR-0001</a>"),
992            "root doc → adr/ prefix: {}",
993            r.html
994        );
995        // Root-level chrome: assets/back-link relative to site root.
996        assert!(r.html.contains("href=\"./style.css\""));
997        // Full favicon set — root-relative from the site root.
998        assert!(r.html.contains("href=\"./favicon.svg\""));
999        assert!(r.html.contains("href=\"./favicon.ico\""));
1000        assert!(
1001            r.html
1002                .contains("rel=\"apple-touch-icon\" href=\"./apple-touch-icon.png\"")
1003        );
1004    }
1005
1006    const ADR: &str = "---\nadr-id: \"0001\"\nstatus: Accepted\n---\n\n# ADR-0001: Example\n\n## Context\n\nSome `code` and a [link](https://x).\n";
1007
1008    #[test]
1009    fn render_adr_strips_frontmatter_and_themes() {
1010        let r = render_adr(ADR, "fallback", &no_pages(), None);
1011        assert_eq!(r.title, "ADR-0001: Example");
1012        // Frontmatter is gone; heading + section rendered.
1013        assert!(!r.html.contains("adr-id"));
1014        assert!(
1015            r.html
1016                .contains("<h1 id=\"adr-0001-example\">ADR-0001: Example</h1>")
1017        );
1018        // The section anchor matches the section's node key (`adr:0001#context`),
1019        // so a link through the graph lands on the heading in the browser.
1020        assert!(r.html.contains("<h2 id=\"context\">Context</h2>"));
1021        assert!(r.html.contains("<code>code</code>"));
1022        // Themed chrome present.
1023        assert!(
1024            r.html
1025                .contains("<link rel=\"stylesheet\" href=\"../style.css\">")
1026        );
1027        // Full favicon set (SVG + `.ico` fallback for browsers without SVG-favicon
1028        // support, e.g. Safari) — root-relative from a sub-page.
1029        assert!(r.html.contains("href=\"../favicon.svg\""));
1030        assert!(r.html.contains("href=\"../favicon.ico\""));
1031        assert!(
1032            r.html
1033                .contains("rel=\"apple-touch-icon\" href=\"../apple-touch-icon.png\"")
1034        );
1035        assert!(r.html.contains("← Roteiro home"));
1036        assert!(r.html.contains("← Back to roteiro.dev"));
1037        assert!(r.html.starts_with("<!doctype html>"));
1038    }
1039
1040    #[test]
1041    fn render_adr_falls_back_without_h1() {
1042        let r = render_adr(
1043            "no frontmatter, no heading\n",
1044            "slug-name",
1045            &no_pages(),
1046            None,
1047        );
1048        assert_eq!(r.title, "slug-name");
1049    }
1050
1051    #[test]
1052    fn index_lists_entries_and_escapes() {
1053        let entries = [
1054            IndexEntry {
1055                href: "0001-x.html".into(),
1056                title: "First & <best>".into(),
1057            },
1058            IndexEntry {
1059                href: "0002-y.html".into(),
1060                title: "Second".into(),
1061            },
1062        ];
1063        let lifetime = [IndexEntry {
1064            href: "../build-plan.html".into(),
1065            title: "Build Plan".into(),
1066        }];
1067        let html = render_adr_index(&lifetime, &entries);
1068        assert!(html.contains("<a href=\"../build-plan.html\">Build Plan</a>"));
1069        assert!(html.contains("<a href=\"0001-x.html\">First &amp; &lt;best&gt;</a>"));
1070        assert!(html.contains("<a href=\"0002-y.html\">Second</a>"));
1071        // First entry precedes second (order preserved).
1072        assert!(html.find("0001-x").unwrap() < html.find("0002-y").unwrap());
1073        // Lifetime docs listed before the ADRs.
1074        assert!(html.find("build-plan").unwrap() < html.find("0001-x").unwrap());
1075    }
1076
1077    #[test]
1078    fn an_explicit_anchor_survives_the_split_that_moved_its_section() {
1079        // The hazard this mechanism exists for. The old single-page site
1080        // published `#modes`, `#crossrepo`, `#remote-tier` — short, hand-chosen
1081        // ids that no heading text slugifies to. External links point at them and
1082        // cannot be updated, so a page that inherits a section must be able to
1083        // inherit its anchor verbatim.
1084        let html = markdown_to_html(
1085            "## The five ways to run it {#modes}\n\n## Cross-repo: a hub and its spokes {#crossrepo}\n",
1086        );
1087        assert!(
1088            html.contains("<h2 id=\"modes\">The five ways to run it</h2>"),
1089            "{html}"
1090        );
1091        assert!(
1092            html.contains("<h2 id=\"crossrepo\">Cross-repo: a hub and its spokes</h2>"),
1093            "{html}"
1094        );
1095        // The attribute is markup, not part of the heading's text.
1096        assert!(!html.contains("{#"), "no literal attribute leaks: {html}");
1097    }
1098
1099    #[test]
1100    fn generated_anchors_match_the_graph_s_section_keys_and_stay_unique() {
1101        // `rto_spec` builds `<doc>#<slugify(heading)>` section keys from the same
1102        // function, so a link that resolves in the graph lands on the heading.
1103        let html = markdown_to_html("## Install & build\n\n## Install & build\n\n## ###\n");
1104        assert!(html.contains("id=\"install-build\""), "{html}");
1105        // A repeat is suffixed rather than duplicated: two elements sharing an
1106        // `id` makes one of them unreachable.
1107        assert!(html.contains("id=\"install-build-2\""), "{html}");
1108        // A heading that slugifies to nothing still gets a usable anchor.
1109        assert!(html.contains("id=\"section-3\""), "{html}");
1110    }
1111
1112    #[test]
1113    fn inline_code_counts_as_heading_text() {
1114        // The old page's headings look like `What <code>init</code> sets up`.
1115        // Dropping the code span would slugify only the prose around it and give
1116        // the section an anchor nobody would guess.
1117        let html = markdown_to_html("### What `init` sets up\n");
1118        assert!(
1119            html.contains("<h3 id=\"what-init-sets-up\">"),
1120            "code span is part of the heading's text: {html}"
1121        );
1122    }
1123
1124    #[test]
1125    fn a_hash_inside_a_fence_is_not_a_heading() {
1126        // The id list is computed from a real parse, so fenced content cannot
1127        // shift every subsequent heading's anchor by one.
1128        let html = markdown_to_html("```\n## Not a heading\n```\n\n## Real\n");
1129        assert!(html.contains("<h2 id=\"real\">Real</h2>"), "{html}");
1130    }
1131
1132    #[test]
1133    fn a_heading_s_anchor_never_reaches_the_title() {
1134        // Issue #460, live on roteiro.dev: every page the site split moved
1135        // carries `{#…}` on its H1, and the title was read off the raw line.
1136        let r = render_site_page(
1137            "---\nsite-page: modes\n---\n\n# The five ways to run it {#modes}\n\nBody.\n",
1138            "fallback",
1139            &nav(),
1140            "modes.html",
1141            &no_pages(),
1142            None,
1143        );
1144        // The heading was always right; the title is the side that was wrong.
1145        assert!(
1146            r.html
1147                .contains("<h1 id=\"modes\">The five ways to run it</h1>"),
1148            "{}",
1149            r.html
1150        );
1151        assert_eq!(r.title, "The five ways to run it");
1152        assert!(
1153            r.html
1154                .contains("<title>The five ways to run it — Roteiro</title>"),
1155            "{}",
1156            r.html
1157        );
1158        // The most-seen string a page has: the tab, the bookmark, the search
1159        // result, the social preview. Nothing of the attribute survives anywhere.
1160        assert!(
1161            !r.html.contains("{#"),
1162            "no literal attribute leaks: {}",
1163            r.html
1164        );
1165    }
1166
1167    #[test]
1168    fn the_same_holds_for_an_adr_and_for_a_root_level_doc() {
1169        // One extractor serves all three renderers, so all three are checked:
1170        // a fix that reached only the page the issue named would leave the ADR
1171        // index quoting `{#…}` back at the reader.
1172        let adr = render_adr("# ADR-0001: Example {#adr1}\n", "slug", &no_pages(), None);
1173        assert_eq!(adr.title, "ADR-0001: Example");
1174        assert!(
1175            adr.html
1176                .contains("<title>ADR-0001: Example — Roteiro</title>"),
1177            "{}",
1178            adr.html
1179        );
1180        let doc = render_doc(
1181            "# Roteiro — Build Plan {#plan}\n",
1182            "Build Plan",
1183            &no_pages(),
1184            None,
1185        );
1186        assert_eq!(doc.title, "Roteiro — Build Plan");
1187        assert!(!doc.html.contains("{#"), "{}", doc.html);
1188    }
1189
1190    #[test]
1191    fn a_title_that_legitimately_spells_the_anchor_syntax_keeps_it() {
1192        // The other half of the rule, and the reason the fix is a parse and not
1193        // a strip: `{#…}` is an attribute only where the dialect says it is, and
1194        // a rule spelled out by hand does not know where that is. Inside a code
1195        // span it is prose, and a stripper blind to code spans mangles a page
1196        // whose subject *is* this syntax — which is most of the pages that
1197        // document it.
1198        let coded = render_doc(
1199            "# Why `{#anchor}` outlives a restructure\n",
1200            "fallback",
1201            &no_pages(),
1202            None,
1203        );
1204        assert_eq!(coded.title, "Why {#anchor} outlives a restructure");
1205        assert!(
1206            coded
1207                .html
1208                .contains("<title>Why {#anchor} outlives a restructure — Roteiro</title>"),
1209            "{}",
1210            coded.html
1211        );
1212        // Mid-heading and uncoded, it is still prose: an attribute block is
1213        // trailing or it is nothing.
1214        let mid = render_doc(
1215            "# Anchors are written {#id}, in prose\n",
1216            "fallback",
1217            &no_pages(),
1218            None,
1219        );
1220        assert_eq!(mid.title, "Anchors are written {#id}, in prose");
1221    }
1222
1223    #[test]
1224    fn the_title_and_the_heading_never_disagree() {
1225        // The invariant underneath #460, stated directly. Where the attribute
1226        // block ends is the dialect's call, not this module's — braces the
1227        // parser eats are gone from *both* surfaces, braces it keeps are on
1228        // both. Reading the title from the same parse is what makes that true by
1229        // construction rather than by two rules that happen to match today.
1230        for md in [
1231            "# The five ways to run it {#modes}\n",
1232            "# Why `{#anchor}` outlives a restructure\n",
1233            "# Anchors are written {#id}, in prose\n",
1234            "# Install & build {#build}\n",
1235            "# What `init` sets up\n",
1236            "# Sets like {#1, #2}\n",
1237        ] {
1238            let r = render_doc(md, "fallback", &no_pages(), None);
1239            let inner = r
1240                .html
1241                .split_once("<h1")
1242                .and_then(|(_, rest)| rest.split_once('>'))
1243                .and_then(|(_, rest)| rest.split_once("</h1>"))
1244                .map(|(text, _)| text.to_owned())
1245                .unwrap_or_default();
1246            // The heading carries inline markup (`<code>`, emphasis); the title
1247            // is the words inside it. Dropping the tags — and nothing else, so
1248            // entities still have to match — is what makes them comparable.
1249            let mut heading = String::new();
1250            let mut depth = 0usize;
1251            for c in inner.chars() {
1252                match c {
1253                    '<' => depth += 1,
1254                    '>' => depth = depth.saturating_sub(1),
1255                    _ if depth == 0 => heading.push(c),
1256                    _ => {}
1257                }
1258            }
1259            assert_eq!(
1260                heading,
1261                escape_html(&r.title),
1262                "title and heading disagree for {md:?}: {}",
1263                r.html
1264            );
1265        }
1266    }
1267
1268    #[test]
1269    fn the_title_is_the_heading_the_reader_sees() {
1270        // Inline markup contributes its text, not its punctuation — the same
1271        // rule the heading's own id already follows.
1272        let code = render_doc("# What `init` sets up\n", "fallback", &no_pages(), None);
1273        assert_eq!(code.title, "What init sets up");
1274        // A line scan called this document's title `Not a title`; the parser
1275        // knows a fenced hash is not a heading at all.
1276        let fenced = render_doc(
1277            "```\n# Not a title\n```\n\n# The real one\n",
1278            "fallback",
1279            &no_pages(),
1280            None,
1281        );
1282        assert_eq!(fenced.title, "The real one");
1283        // And a heading spelled the other way is still a heading: the page shows
1284        // an `<h1>`, so the tab has to show its words rather than the file stem.
1285        let setext = render_doc("Underlined\n==========\n", "fallback", &no_pages(), None);
1286        assert!(
1287            setext.html.contains("<h1 id=\"underlined\">"),
1288            "{}",
1289            setext.html
1290        );
1291        assert_eq!(setext.title, "Underlined");
1292    }
1293
1294    #[test]
1295    fn a_document_with_no_h1_falls_back_and_the_fallback_is_used_verbatim() {
1296        // The fallback is the caller's string, not markdown: it is never parsed,
1297        // so it cannot be stripped and cannot leak markup it does not contain.
1298        // Callers pass a file stem or a declared slug.
1299        let none = render_site_page(
1300            "---\nsite-page: modes\n---\n\nNo heading at all.\n",
1301            "The five ways to run it",
1302            &nav(),
1303            "modes.html",
1304            &no_pages(),
1305            None,
1306        );
1307        assert_eq!(none.title, "The five ways to run it");
1308        assert!(
1309            none.html
1310                .contains("<title>The five ways to run it — Roteiro</title>"),
1311            "{}",
1312            none.html
1313        );
1314        // An H1 with nothing in it names nothing, so it defers to the fallback
1315        // rather than emitting `<title> — Roteiro</title>`.
1316        let empty = render_doc("#\n\nBody.\n", "build-plan", &no_pages(), None);
1317        assert_eq!(empty.title, "build-plan");
1318        // A lower heading is not the document's title.
1319        let sub = render_doc("## Only a section {#s}\n", "build-plan", &no_pages(), None);
1320        assert_eq!(sub.title, "build-plan");
1321    }
1322
1323    #[test]
1324    fn a_site_page_carries_the_bar_with_itself_marked() {
1325        let r = render_site_page(
1326            "---\nsite-page: modes\n---\n\n# The five ways to run it\n\nSee [[docs/adr/0019-remote.md]].\n",
1327            "fallback",
1328            &nav(),
1329            "modes.html",
1330            &no_pages(),
1331            None,
1332        );
1333        assert_eq!(r.title, "The five ways to run it");
1334        // Frontmatter is chrome for the graph, not content for the reader.
1335        assert!(!r.html.contains("site-page"), "{}", r.html);
1336        // The current page is unlinked and marked; its neighbour is a link.
1337        assert!(
1338            r.html
1339                .contains("<span aria-current=\"page\">Modes &amp; Co</span>"),
1340            "{}",
1341            r.html
1342        );
1343        assert!(r.html.contains("<a href=\"./\">Home</a>"), "{}", r.html);
1344        // A root-level page: assets and ADR links resolve from the site root.
1345        assert!(r.html.contains("href=\"./style.css\""), "{}", r.html);
1346        assert!(
1347            r.html
1348                .contains("<a href=\"adr/0019-remote.html\">ADR-0019</a>"),
1349            "{}",
1350            r.html
1351        );
1352    }
1353
1354    #[test]
1355    fn the_bar_is_plain_anchors_and_escapes_its_labels() {
1356        let bar = render_nav(&nav(), "nothing.html");
1357        assert!(bar.starts_with("<nav class=\"sitenav\">"), "{bar}");
1358        // Nothing marked when the current page is not in the bar — a preview of
1359        // an unlisted page, not an error.
1360        assert!(!bar.contains("aria-current"), "{bar}");
1361        assert!(bar.contains("Modes &amp; Co"), "escaped label: {bar}");
1362        // No script: the site has no build step and this must not introduce one.
1363        assert!(!bar.contains("<script"), "{bar}");
1364    }
1365
1366    #[test]
1367    fn a_link_resolves_to_the_page_the_site_actually_serves() {
1368        // Issue #446: four ADRs link `../BUILD_PLAN_V2.md`, which is correct in
1369        // the repository. Published under a `site-page:` slug, that document is
1370        // served as `build-plan-v2.html` — so rewriting the link to its own stem
1371        // aims it at a page that is never emitted.
1372        let mut pages = PublishedPages::new();
1373        pages.publish("BUILD_PLAN_V2.md", "build-plan-v2.html");
1374        let html = render_markdown("See [V2](../BUILD_PLAN_V2.md).\n", "", &pages, None, 0);
1375        assert!(
1376            html.contains("href=\"../build-plan-v2.html\""),
1377            "served name, and the link's own hop kept: {html}"
1378        );
1379        // A fragment survives the substitution.
1380        let frag = render_markdown("[s](../BUILD_PLAN_V2.md#stage-21)\n", "", &pages, None, 0);
1381        assert!(
1382            frag.contains("href=\"../build-plan-v2.html#stage-21\""),
1383            "{frag}"
1384        );
1385        // An unpublished document still falls back to its stem, unchanged.
1386        let other = render_markdown("[x](../REVIEW_CHECKLIST.md)\n", "", &pages, None, 0);
1387        assert!(
1388            other.contains("href=\"../REVIEW_CHECKLIST.html\""),
1389            "{other}"
1390        );
1391    }
1392
1393    #[test]
1394    fn a_file_name_two_documents_claim_is_left_alone() {
1395        // Guessing which one a link meant would silently point it at the wrong
1396        // page — worse than the 404 the lookup exists to remove.
1397        let mut pages = PublishedPages::new();
1398        pages.publish("GUIDE.md", "guide.html");
1399        pages.publish("GUIDE.md", "other-guide.html");
1400        let html = render_markdown("[g](GUIDE.md)\n", "", &pages, None, 0);
1401        assert!(html.contains("href=\"GUIDE.html\""), "unrewritten: {html}");
1402        // Re-publishing the *same* target is not a conflict.
1403        let mut same = PublishedPages::new();
1404        same.publish("GUIDE.md", "guide.html");
1405        same.publish("GUIDE.md", "guide.html");
1406        let html = render_markdown("[g](GUIDE.md)\n", "", &same, None, 0);
1407        assert!(html.contains("href=\"guide.html\""), "{html}");
1408    }
1409
1410    #[test]
1411    fn the_dialect_is_not_extended_here() {
1412        // `options` exists to hold renderer-specific rationale, not to add
1413        // flags. This reads as a tautology against the body as written, and that
1414        // is exactly its job: it has no failure mode until someone gives the
1415        // body one, and that single edit is the only thing the comment beside it
1416        // can ask against rather than prevent.
1417        //
1418        // Note what it pins — the *dialect*, not the shape of the body. A
1419        // rewrite that still yields this option set is harmless and keeps
1420        // passing; every divergence that would change what a heading's text is
1421        // fails. That is the invariant worth holding, and it is a wider one than
1422        // "stay a single delegation".
1423        assert_eq!(options(), rto_graph::markdown_dialect());
1424    }
1425
1426    /// A source base for a document in `dir`, at a fixed sha.
1427    fn source(dir: &str) -> SourceBase {
1428        SourceBase::new(Some("https://github.com/o/r/blob/abc123"), dir).expect("base")
1429    }
1430
1431    #[test]
1432    fn a_link_out_of_the_site_goes_to_the_repository() {
1433        // Issue #456: the Build Plan cites code as evidence — correct in a
1434        // checkout, dead on the site, which publishes documents and not source.
1435        let base = source("docs");
1436        let html = render_markdown(
1437            "[sync](../crates/rto-graph/src/sync.rs) and [wf](../.github/workflows/website.yml)\n",
1438            "adr/",
1439            &no_pages(),
1440            Some(&base),
1441            0,
1442        );
1443        assert!(
1444            html.contains(
1445                "href=\"https://github.com/o/r/blob/abc123/crates/rto-graph/src/sync.rs\""
1446            ),
1447            "resolved against the document's own directory: {html}"
1448        );
1449        assert!(
1450            html.contains(
1451                "href=\"https://github.com/o/r/blob/abc123/.github/workflows/website.yml\""
1452            ),
1453            "a dotted directory is a directory, not a `.` segment: {html}"
1454        );
1455        // A line anchor is the author's, and travels.
1456        let frag = render_markdown(
1457            "[l](../crates/roteiro/src/init.rs#L12)\n",
1458            "adr/",
1459            &no_pages(),
1460            Some(&base),
1461            0,
1462        );
1463        assert!(
1464            frag.contains("blob/abc123/crates/roteiro/src/init.rs#L12\""),
1465            "{frag}"
1466        );
1467    }
1468
1469    #[test]
1470    fn a_link_that_stays_inside_the_site_is_left_alone() {
1471        // The whole discrimination is the hop count: `ask.html` and `adr/` are
1472        // written *for* the site and are correct there, so rewriting them to the
1473        // repository would break links that work today.
1474        let base = source("docs");
1475        let html = render_markdown(
1476            "[a](ask.html), [d](adr/), [s](./style.css) and [r](/abs.html)\n",
1477            "adr/",
1478            &no_pages(),
1479            Some(&base),
1480            0,
1481        );
1482        assert!(!html.contains("github.com"), "none rewritten: {html}");
1483        for href in [
1484            "\"ask.html\"",
1485            "\"adr/\"",
1486            "\"./style.css\"",
1487            "\"/abs.html\"",
1488        ] {
1489            assert!(html.contains(href), "{href} kept verbatim: {html}");
1490        }
1491    }
1492
1493    #[test]
1494    fn an_adr_may_climb_one_level_and_still_be_inside_the_site() {
1495        // An ADR page is served at `adr/<slug>.html`, so `../x` lands at the site
1496        // root. Treating that as an escape would send every ADR's back-link to
1497        // GitHub. The second hop does leave.
1498        let base = source("docs/adr");
1499        let inside = render_markdown("[b](../build-plan.html)\n", "", &no_pages(), Some(&base), 1);
1500        assert!(!inside.contains("github.com"), "{inside}");
1501        let outside = render_markdown("[c](../../Cargo.toml)\n", "", &no_pages(), Some(&base), 1);
1502        assert!(
1503            outside.contains("href=\"https://github.com/o/r/blob/abc123/Cargo.toml\""),
1504            "{outside}"
1505        );
1506    }
1507
1508    #[test]
1509    fn a_published_page_beats_the_escape_rule() {
1510        // Order matters: #446's lookup runs first, so a document reached by a
1511        // path that climbs out of its own directory still lands on the page the
1512        // site publishes it as, rather than being handed to the repository.
1513        let mut pages = PublishedPages::new();
1514        pages.publish("BUILD_PLAN_V2.md", "build-plan-v2.html");
1515        let base = source("website/pages");
1516        let html = render_markdown(
1517            "[v2](../../docs/BUILD_PLAN_V2.md)\n",
1518            "adr/",
1519            &pages,
1520            Some(&base),
1521            0,
1522        );
1523        assert!(
1524            html.contains("href=\"../../docs/build-plan-v2.html\""),
1525            "still the site's page: {html}"
1526        );
1527        assert!(!html.contains("github.com"), "{html}");
1528    }
1529
1530    #[test]
1531    fn without_a_source_base_the_link_is_left_as_authored() {
1532        // No `origin`, or one that maps to no web view. Leaving the link is the
1533        // deliberate choice: it stays correct in a checkout, and a rewrite that
1534        // silently produced a broken URL would be worse than the link it replaced.
1535        assert_eq!(SourceBase::new(None, "docs"), None);
1536        let html = render_markdown(
1537            "[s](../crates/rto-graph/src/sync.rs)\n",
1538            "adr/",
1539            &no_pages(),
1540            None,
1541            0,
1542        );
1543        assert!(
1544            html.contains("href=\"../crates/rto-graph/src/sync.rs\""),
1545            "{html}"
1546        );
1547    }
1548
1549    #[test]
1550    fn the_landing_pages_bar_is_replaced_rather_than_maintained() {
1551        // Issue #508. The stale copy is overwritten wholesale, so there is no
1552        // second list left to drift out of `site-order`.
1553        let stale = "<h1>Roteiro</h1>\n<nav class=\"sitenav\">\n<a href=\"old.html\">Old</a>\n\
1554                     </nav>\n<p>after</p>\n";
1555        let out = replace_site_nav(stale, &nav(), "./").expect("marker found");
1556        assert!(
1557            !out.contains("old.html"),
1558            "the hand-written list is gone: {out}"
1559        );
1560        assert!(
1561            out.contains("<a href=\"modes.html\">Modes &amp; Co</a>"),
1562            "the computed bar took its place: {out}"
1563        );
1564        assert!(
1565            out.starts_with("<h1>Roteiro</h1>\n") && out.ends_with("<p>after</p>\n"),
1566            "only the bar is touched: {out}"
1567        );
1568        // A page that claims no bar is left alone rather than failing: every
1569        // `render docs` fixture writes a one-line landing page.
1570        assert_eq!(replace_site_nav("<h1>Home</h1>\n", &nav(), "./"), None);
1571    }
1572
1573    #[test]
1574    fn site_pages_render_deterministically() {
1575        let md = "---\nsite-page: a\n---\n\n# A\n\n## S\n";
1576        assert_eq!(
1577            render_site_page(md, "f", &nav(), "a.html", &no_pages(), None),
1578            render_site_page(md, "f", &nav(), "a.html", &no_pages(), None)
1579        );
1580    }
1581
1582    #[test]
1583    fn rendering_is_deterministic() {
1584        assert_eq!(
1585            render_adr(ADR, "f", &no_pages(), None),
1586            render_adr(ADR, "f", &no_pages(), None)
1587        );
1588    }
1589}