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