Skip to main content

docs_compiler/
chrome.rs

1//! Site chrome (Wave 2d): the layout around page content — header, nav
2//! sidebar, table of contents, prev/next pagination, theme toggle, and
3//! the search island slot. Rust renders all of it statically; the only
4//! scripts are a five-line theme toggle and (optionally) the search
5//! island, which rides the same `<docs-island>` seam as every other
6//! interactive piece.
7//!
8//! The layout is deliberately restrained: a fixed sidebar built from the
9//! site's directory tree, the content column capped at a readable
10//! measure, a right-hand TOC on wide screens, and a dark theme by
11//! default with a persisted light alternative. No framework, no build
12//! step — one hand-written stylesheet.
13
14use crate::directives::html_escape;
15
16/// Prefix a site-relative URL with the chrome's base path. Paths may
17/// carry a leading slash; exactly one separator lands between the
18/// base path and the path either way.
19fn site_url(base_path: &str, path: &str) -> String {
20    let path = path.strip_prefix('/').unwrap_or(path);
21    if base_path.is_empty() {
22        return format!("/{path}");
23    }
24    format!("{base_path}/{path}")
25}
26
27/// The chrome stylesheet, embedded at compile time and emitted by the
28/// site builder as `/_assets/layout.css`.
29pub const LAYOUT_CSS: &str = include_str!("layout.css");
30
31/// One group in the sidebar nav tree (a top-level directory).
32#[derive(Debug, Clone, PartialEq)]
33pub struct NavGroup {
34    /// Group label (the directory's display name).
35    pub label: String,
36    /// Items in document order: (route, title).
37    pub items: Vec<(String, String)>,
38    /// Whether this group contains the active page.
39    pub active: bool,
40}
41
42/// One table-of-contents entry (h2/h3 with their anchor ids).
43#[derive(Debug, Clone, PartialEq)]
44pub struct TocEntry {
45    /// Heading level (2 or 3 — h1 is the page title).
46    pub level: u8,
47    /// Anchor id from docs-core's heading emission.
48    pub anchor: String,
49    /// Heading text.
50    pub text: String,
51}
52
53/// Everything the layout needs to wrap one page.
54#[derive(Debug, Clone, PartialEq)]
55pub struct Chrome {
56    /// Sidebar groups, in display order.
57    pub nav: Vec<NavGroup>,
58    /// This page's route (marks the active nav item).
59    pub active_route: String,
60    /// This page's TOC (h2/h3 with anchors), possibly empty.
61    pub toc: Vec<TocEntry>,
62    /// Previous page: (route, title).
63    pub prev: Option<(String, String)>,
64    /// Next page: (route, title).
65    pub next: Option<(String, String)>,
66    /// Search island chunk URL, when the site wires search. Emitted
67    /// verbatim (a site.toml author includes any base path).
68    pub search_island: Option<String>,
69    /// The search corpus URL handed to the island via props. Prefixed
70    /// with the base path like every other site-relative link.
71    pub search_index: Option<String>,
72    /// The docs_search.wasm reader module URL (site-relative; prefixed
73    /// like search_index). Empty = the island runs JSON-only scoring.
74    pub search_wasm: Option<String>,
75    /// The FST binary index URL (site-relative; prefixed).
76    pub search_bin: Option<String>,
77    /// Accent color override (`#rgb`/`#rrggbb`), from `site.toml`.
78    /// None = the default palette.
79    pub accent: Option<String>,
80}
81
82/// The theme-toggle inline script: toggles `data-theme` on `<html>` and
83/// persists the choice. The one sanctioned inline script in the chrome
84/// (everything else dynamic rides islands).
85const THEME_SCRIPT: &str = "<script>const h=document.documentElement;const t=document.getElementById('theme-toggle');if(t){t.addEventListener('click',()=>{const n=h.dataset.theme==='light'?'dark':'light';h.dataset.theme=n;try{localStorage.setItem('docs-theme',n)}catch(e){}});}try{const s=localStorage.getItem('docs-theme');if(s)h.dataset.theme=s}catch(e){}</script>";
86
87/// Parse `#rgb`/`#rrggbb` hex into (r, g, b); None on anything else.
88fn parse_hex_color(s: &str) -> Option<(u8, u8, u8)> {
89    let h = s.strip_prefix('#')?;
90    match h.len() {
91        3 => {
92            let mut c = [0u8; 3];
93            for (slot, ch) in c.iter_mut().zip(h.chars()) {
94                *slot = (ch.to_digit(16)? * 17) as u8;
95            }
96            Some((c[0], c[1], c[2]))
97        }
98        6 => {
99            let mut c = [0u8; 3];
100            let mut chars = h.chars();
101            for slot in &mut c {
102                let hi = chars.next()?.to_digit(16)?;
103                let lo = chars.next()?.to_digit(16)?;
104                *slot = ((hi << 4) | lo) as u8;
105            }
106            Some((c[0], c[1], c[2]))
107        }
108        _ => None,
109    }
110}
111
112/// CSS `<style>` overriding the palette accent for a `site.toml`
113/// `accent = "#hex"` line, emitted after `layout.css` so it wins the
114/// cascade. Both themes take the accent; light gets a darkened variant
115/// (x0.55 per channel) for contrast on the near-white bg, and the soft
116/// tints mirror the defaults (0.14 dark / 0.12 light alpha). Invalid
117/// hex = None (the default palette stands).
118pub fn accent_override(accent: &str) -> Option<String> {
119    let (r, g, b) = parse_hex_color(accent)?;
120    let dark = format!("#{r:02x}{g:02x}{b:02x}");
121    let shade = |c: u8| (f32::from(c) * 0.55) as u8;
122    let light = format!("#{0:02x}{1:02x}{2:02x}", shade(r), shade(g), shade(b));
123    Some(format!(
124        "<style>:root,html[data-theme=\"dark\"]{{--accent:{dark};--accent-soft:rgba({r},{g},{b},0.14)}}\
125html[data-theme=\"light\"]{{--accent:{light};--accent-soft:rgba({0},{1},{2},0.12)}}</style>",
126        shade(r),
127        shade(g),
128        shade(b),
129    ))
130}
131
132/// Wrap a rendered page document with the site chrome. `doc` is the
133/// full `<!doctype html>...<body>content</body></html>` document from
134/// `seo::document`; the body content is lifted into the layout
135/// (header + sidebar + main + TOC + pager) by exact-markup surgery on
136/// markup this crate itself emitted. `base_path` prefixes every
137/// site-relative URL the chrome emits (empty string = served at root).
138#[must_use]
139pub fn page(doc: &str, site_title: &str, chrome: &Chrome, base_path: &str) -> String {
140    let url = |path: &str| {
141        if base_path.is_empty() {
142            format!("/{path}")
143        } else {
144            format!("{base_path}/{path}")
145        }
146    };
147    let mut nav_markup = String::from("<a class=\"brand\" href=\"");
148    nav_markup.push_str(&url(""));
149    nav_markup.push_str("\">");
150    nav_markup.push_str(&html_escape(site_title));
151    nav_markup.push_str("</a>");
152    for group in &chrome.nav {
153        nav_markup.push_str(&format!(
154            "<details class=\"nav-group{}\"><summary>{}</summary>",
155            if group.active { " open active" } else { "" },
156            html_escape(&group.label),
157        ));
158        for (route, title) in &group.items {
159            let class = if *route == chrome.active_route {
160                " class=\"active\""
161            } else {
162                ""
163            };
164            nav_markup.push_str(&format!(
165                "<a href=\"{r}\"{c}>{t}</a>",
166                r = html_escape(&url(route)),
167                c = class,
168                t = html_escape(title),
169            ));
170        }
171        nav_markup.push_str("</details>");
172    }
173
174    let toc_markup = if chrome.toc.len() >= 2 {
175        let mut toc = String::from("<aside class=\"toc\"><p class=\"toc-title\">On this page</p>");
176        for entry in &chrome.toc {
177            toc.push_str(&format!(
178                "<a href=\"#{a}\" class=\"toc-l{lvl}\">{t}</a>",
179                a = html_escape(&entry.anchor),
180                lvl = entry.level,
181                t = html_escape(&entry.text),
182            ));
183        }
184        toc.push_str("</aside>");
185        toc
186    } else {
187        String::new()
188    };
189
190    let pager_markup = |link: &Option<(String, String)>,
191                        class: &'static str,
192                        label: &'static str| {
193        match link {
194            Some((route, title)) => format!(
195                "<a class=\"pager {class}\" href=\"{r}\"><span class=\"pager-label\">{l}</span><span class=\"pager-title\">{t}</span></a>",
196                r = html_escape(&url(route)),
197                l = label,
198                t = html_escape(title),
199            ),
200            None => String::new(),
201        }
202    };
203
204    let search_header = chrome.search_island.as_ref().map_or_else(String::new, |chunk| {
205        let index = chrome
206            .search_index
207            .clone()
208            .map(|i| site_url(base_path, &i))
209            .unwrap_or_else(|| url("search.json"));
210        let wasm_url = chrome
211            .search_wasm
212            .clone()
213            .map(|w| site_url(base_path, &w));
214        let bin_url = chrome
215            .search_bin
216            .clone()
217            .map(|b| site_url(base_path, &b));
218        let props = match (wasm_url, bin_url) {
219            (Some(w), Some(b)) => {
220                format!("{{\"index\":\"{i}\",\"wasm\":\"{w}\",\"bin\":\"{b}\"}}", i = html_escape(&index), w = html_escape(&w), b = html_escape(&b))
221            }
222            _ => format!("{{\"index\":\"{i}\"}}", i = html_escape(&index)),
223        };
224        format!(
225            "<docs-island component-url=\"{u}\" client=\"idle\"><script type=\"application/json\" data-island-props>{props}</script></docs-island>",
226            u = html_escape(chunk),
227        )
228    });
229
230    let css_link = url("_assets/layout.css");
231    let _ = &css_link;
232    let accent_style = chrome
233        .accent
234        .as_deref()
235        .and_then(accent_override)
236        .unwrap_or_default();
237
238    let doc = doc.replacen(
239        "</head>",
240        &format!(
241            "<link rel=\"stylesheet\" href=\"{}\">{accent_style}</head>",
242            html_escape(&css_link)
243        ),
244        1,
245    );
246    let doc = doc.replacen(
247        "<body>",
248        &format!(
249            "<body><header class=\"site-header\"><a class=\"brand\" href=\"{home}\">{b}</a>{search}<button id=\"theme-toggle\" aria-label=\"toggle theme\"></button></header>\
250<nav class=\"sidebar\">{nav}</nav>\
251<div class=\"page\"><main>",
252            home = html_escape(&url("")),
253            b = html_escape(site_title),
254            search = search_header,
255            nav = nav_markup,
256        ),
257        1,
258    );
259    doc.replacen(
260        "</body></html>",
261        &format!(
262            "<div class=\"pager\">{prev}{next}</div></main>{toc}</div>{THEME_SCRIPT}</body></html>",
263            prev = pager_markup(&chrome.prev, "prev", "Previous"),
264            next = pager_markup(&chrome.next, "next", "Next"),
265            toc = toc_markup,
266        ),
267        1,
268    )
269}
270
271/// Extract the TOC (h2/h3 with anchor ids) from a rendered body. h1 is
272/// the page title and stays out of the TOC; deeper levels rarely carry
273/// anchors worth listing.
274#[must_use]
275pub fn extract_toc(body: &str) -> Vec<TocEntry> {
276    let mut toc = Vec::new();
277    let mut rest = body;
278    loop {
279        let next_pos = match (rest.find("<h2 id=\""), rest.find("<h3 id=\"")) {
280            (Some(a), Some(b)) => Some(a.min(b)),
281            (Some(a), None) => Some(a),
282            (None, Some(b)) => Some(b),
283            (None, None) => None,
284        };
285        let Some(pos) = next_pos else { break };
286        let Some(window) = rest.get(pos..) else { break };
287        let level = if window.starts_with("<h2") { 2 } else { 3 };
288        let Some(id_rel) = window.find("id=\"").map(|p| p + 4) else {
289            break;
290        };
291        let Some(end_rel) = window.get(id_rel..).and_then(|s| s.find('"')) else {
292            break;
293        };
294        let id_end = id_rel + end_rel;
295        let Some(anchor) = window.get(id_rel..id_end).map(str::to_string) else {
296            break;
297        };
298        let Some(gt_rel) = window.get(id_end..).and_then(|s| s.find('>')) else {
299            break;
300        };
301        let text_start = id_end + gt_rel + 1;
302        let Some(lt_rel) = window.get(text_start..).and_then(|s| s.find('<')) else {
303            break;
304        };
305        let text_end = text_start + lt_rel;
306        let Some(text) = window
307            .get(text_start..text_end)
308            .map(|s| s.trim().to_string())
309        else {
310            break;
311        };
312        if !text.is_empty() {
313            toc.push(TocEntry {
314                level,
315                anchor,
316                text,
317            });
318        }
319        rest = match window.get(text_end..) {
320            Some(r) => r,
321            None => break,
322        };
323    }
324    toc
325}