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}
76
77/// The theme-toggle inline script: toggles `data-theme` on `<html>` and
78/// persists the choice. The one sanctioned inline script in the chrome
79/// (everything else dynamic rides islands).
80const 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>";
81
82/// Wrap a rendered page document with the site chrome. `doc` is the
83/// full `<!doctype html>...<body>content</body></html>` document from
84/// `seo::document`; the body content is lifted into the layout
85/// (header + sidebar + main + TOC + pager) by exact-markup surgery on
86/// markup this crate itself emitted. `base_path` prefixes every
87/// site-relative URL the chrome emits (empty string = served at root).
88#[must_use]
89pub fn page(doc: &str, site_title: &str, chrome: &Chrome, base_path: &str) -> String {
90    // Site-relative URL builder under the (possibly empty) base path.
91    let url = |path: &str| {
92        if base_path.is_empty() {
93            format!("/{path}")
94        } else {
95            format!("{base_path}/{path}")
96        }
97    };
98    let mut nav_markup = String::from("<a class=\"brand\" href=\"");
99    nav_markup.push_str(&url(""));
100    nav_markup.push_str("\">");
101    nav_markup.push_str(&html_escape(site_title));
102    nav_markup.push_str("</a>");
103    for group in &chrome.nav {
104        nav_markup.push_str(&format!(
105            "<details class=\"nav-group{}\"><summary>{}</summary>",
106            if group.active { " open active" } else { "" },
107            html_escape(&group.label),
108        ));
109        for (route, title) in &group.items {
110            let class = if *route == chrome.active_route {
111                " class=\"active\""
112            } else {
113                ""
114            };
115            nav_markup.push_str(&format!(
116                "<a href=\"{r}\"{c}>{t}</a>",
117                r = html_escape(&url(route)),
118                c = class,
119                t = html_escape(title),
120            ));
121        }
122        nav_markup.push_str("</details>");
123    }
124
125    let toc_markup = if chrome.toc.len() >= 2 {
126        let mut toc = String::from("<aside class=\"toc\"><p class=\"toc-title\">On this page</p>");
127        for entry in &chrome.toc {
128            toc.push_str(&format!(
129                "<a href=\"#{a}\" class=\"toc-l{lvl}\">{t}</a>",
130                a = html_escape(&entry.anchor),
131                lvl = entry.level,
132                t = html_escape(&entry.text),
133            ));
134        }
135        toc.push_str("</aside>");
136        toc
137    } else {
138        String::new()
139    };
140
141    let pager_markup = |link: &Option<(String, String)>,
142                        class: &'static str,
143                        label: &'static str| {
144        match link {
145            Some((route, title)) => format!(
146                "<a class=\"pager {class}\" href=\"{r}\"><span class=\"pager-label\">{l}</span><span class=\"pager-title\">{t}</span></a>",
147                r = html_escape(&url(route)),
148                l = label,
149                t = html_escape(title),
150            ),
151            None => String::new(),
152        }
153    };
154
155    let search_header = chrome.search_island.as_ref().map_or_else(String::new, |chunk| {
156        let index = chrome
157            .search_index
158            .clone()
159            .map(|i| site_url(base_path, &i))
160            .unwrap_or_else(|| url("search.json"));
161        let wasm_url = chrome
162            .search_wasm
163            .clone()
164            .map(|w| site_url(base_path, &w));
165        let bin_url = chrome
166            .search_bin
167            .clone()
168            .map(|b| site_url(base_path, &b));
169        let props = match (wasm_url, bin_url) {
170            (Some(w), Some(b)) => {
171                format!("{{\"index\":\"{i}\",\"wasm\":\"{w}\",\"bin\":\"{b}\"}}", i = html_escape(&index), w = html_escape(&w), b = html_escape(&b))
172            }
173            _ => format!("{{\"index\":\"{i}\"}}", i = html_escape(&index)),
174        };
175        format!(
176            "<docs-island component-url=\"{u}\" client=\"idle\"><script type=\"application/json\" data-island-props>{props}</script></docs-island>",
177            u = html_escape(chunk),
178        )
179    });
180
181    let css_link = url("_assets/layout.css");
182    let _ = &css_link;
183
184    let doc = doc.replacen(
185        "</head>",
186        &format!(
187            "<link rel=\"stylesheet\" href=\"{}\"></head>",
188            html_escape(&css_link)
189        ),
190        1,
191    );
192    let doc = doc.replacen(
193        "<body>",
194        &format!(
195            "<body><header class=\"site-header\"><a class=\"brand\" href=\"{home}\">{b}</a>{search}<button id=\"theme-toggle\" aria-label=\"toggle theme\"></button></header>\
196<nav class=\"sidebar\">{nav}</nav>\
197<div class=\"page\"><main>",
198            home = html_escape(&url("")),
199            b = html_escape(site_title),
200            search = search_header,
201            nav = nav_markup,
202        ),
203        1,
204    );
205    doc.replacen(
206        "</body></html>",
207        &format!(
208            "<div class=\"pager\">{prev}{next}</div></main>{toc}</div>{THEME_SCRIPT}</body></html>",
209            prev = pager_markup(&chrome.prev, "prev", "Previous"),
210            next = pager_markup(&chrome.next, "next", "Next"),
211            toc = toc_markup,
212        ),
213        1,
214    )
215}
216
217/// Extract the TOC (h2/h3 with anchor ids) from a rendered body. h1 is
218/// the page title and stays out of the TOC; deeper levels rarely carry
219/// anchors worth listing.
220#[must_use]
221pub fn extract_toc(body: &str) -> Vec<TocEntry> {
222    let mut toc = Vec::new();
223    let mut rest = body;
224    loop {
225        let next_pos = match (rest.find("<h2 id=\""), rest.find("<h3 id=\"")) {
226            (Some(a), Some(b)) => Some(a.min(b)),
227            (Some(a), None) => Some(a),
228            (None, Some(b)) => Some(b),
229            (None, None) => None,
230        };
231        let Some(pos) = next_pos else { break };
232        let Some(window) = rest.get(pos..) else { break };
233        let level = if window.starts_with("<h2") { 2 } else { 3 };
234        let Some(id_rel) = window.find("id=\"").map(|p| p + 4) else {
235            break;
236        };
237        let Some(end_rel) = window.get(id_rel..).and_then(|s| s.find('"')) else {
238            break;
239        };
240        let id_end = id_rel + end_rel;
241        let Some(anchor) = window.get(id_rel..id_end).map(str::to_string) else {
242            break;
243        };
244        let Some(gt_rel) = window.get(id_end..).and_then(|s| s.find('>')) else {
245            break;
246        };
247        let text_start = id_end + gt_rel + 1;
248        let Some(lt_rel) = window.get(text_start..).and_then(|s| s.find('<')) else {
249            break;
250        };
251        let text_end = text_start + lt_rel;
252        let Some(text) = window
253            .get(text_start..text_end)
254            .map(|s| s.trim().to_string())
255        else {
256            break;
257        };
258        if !text.is_empty() {
259            toc.push(TocEntry {
260                level,
261                anchor,
262                text,
263            });
264        }
265        rest = match window.get(text_end..) {
266            Some(r) => r,
267            None => break,
268        };
269    }
270    toc
271}