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