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