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/// The chrome stylesheet, embedded at compile time and emitted by the
17/// site builder as `/_assets/layout.css`.
18pub const LAYOUT_CSS: &str = include_str!("layout.css");
19
20/// One group in the sidebar nav tree (a top-level directory).
21#[derive(Debug, Clone, PartialEq)]
22pub struct NavGroup {
23    /// Group label (the directory's display name).
24    pub label: String,
25    /// Items in document order: (route, title).
26    pub items: Vec<(String, String)>,
27    /// Whether this group contains the active page.
28    pub active: bool,
29}
30
31/// One table-of-contents entry (h2/h3 with their anchor ids).
32#[derive(Debug, Clone, PartialEq)]
33pub struct TocEntry {
34    /// Heading level (2 or 3 — h1 is the page title).
35    pub level: u8,
36    /// Anchor id from docs-core's heading emission.
37    pub anchor: String,
38    /// Heading text.
39    pub text: String,
40}
41
42/// Everything the layout needs to wrap one page.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Chrome {
45    /// Sidebar groups, in display order.
46    pub nav: Vec<NavGroup>,
47    /// This page's route (marks the active nav item).
48    pub active_route: String,
49    /// This page's TOC (h2/h3 with anchors), possibly empty.
50    pub toc: Vec<TocEntry>,
51    /// Previous page: (route, title).
52    pub prev: Option<(String, String)>,
53    /// Next page: (route, title).
54    pub next: Option<(String, String)>,
55    /// Search island chunk URL, when the site wires search. Emitted
56    /// verbatim (a site.toml author includes any base path).
57    pub search_island: Option<String>,
58    /// The search corpus URL handed to the island via props. Prefixed
59    /// with the base path like every other site-relative link.
60    pub search_index: Option<String>,
61}
62
63/// The theme-toggle inline script: toggles `data-theme` on `<html>` and
64/// persists the choice. The one sanctioned inline script in the chrome
65/// (everything else dynamic rides islands).
66const 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>";
67
68/// Wrap a rendered page document with the site chrome. `doc` is the
69/// full `<!doctype html>...<body>content</body></html>` document from
70/// `seo::document`; the body content is lifted into the layout
71/// (header + sidebar + main + TOC + pager) by exact-markup surgery on
72/// markup this crate itself emitted. `base_path` prefixes every
73/// site-relative URL the chrome emits (empty string = served at root).
74#[must_use]
75pub fn page(doc: &str, site_title: &str, chrome: &Chrome, base_path: &str) -> String {
76    // Site-relative URL builder under the (possibly empty) base path.
77    let url = |path: &str| {
78        if base_path.is_empty() {
79            format!("/{path}")
80        } else {
81            format!("{base_path}/{path}")
82        }
83    };
84    let url_string = |path: &str| {
85        let u = url(path);
86        u
87    };
88
89    let mut nav_markup = String::from("<a class=\"brand\" href=\"");
90    nav_markup.push_str(&url(""));
91    nav_markup.push_str("\">");
92    nav_markup.push_str(&html_escape(site_title));
93    nav_markup.push_str("</a>");
94    for group in &chrome.nav {
95        nav_markup.push_str(&format!(
96            "<details class=\"nav-group{}\"><summary>{}</summary>",
97            if group.active { " open active" } else { "" },
98            html_escape(&group.label),
99        ));
100        for (route, title) in &group.items {
101            let class = if *route == chrome.active_route {
102                " class=\"active\""
103            } else {
104                ""
105            };
106            nav_markup.push_str(&format!(
107                "<a href=\"{r}\"{c}>{t}</a>",
108                r = html_escape(&url(route)),
109                c = class,
110                t = html_escape(title),
111            ));
112        }
113        nav_markup.push_str("</details>");
114    }
115
116    let toc_markup = if chrome.toc.len() >= 2 {
117        let mut toc = String::from("<aside class=\"toc\"><p class=\"toc-title\">On this page</p>");
118        for entry in &chrome.toc {
119            toc.push_str(&format!(
120                "<a href=\"#{a}\" class=\"toc-l{lvl}\">{t}</a>",
121                a = html_escape(&entry.anchor),
122                lvl = entry.level,
123                t = html_escape(&entry.text),
124            ));
125        }
126        toc.push_str("</aside>");
127        toc
128    } else {
129        String::new()
130    };
131
132    let pager_markup = |link: &Option<(String, String)>,
133                        class: &'static str,
134                        label: &'static str| {
135        match link {
136            Some((route, title)) => format!(
137                "<a class=\"pager {class}\" href=\"{r}\"><span class=\"pager-label\">{l}</span><span class=\"pager-title\">{t}</span></a>",
138                r = html_escape(&url(route)),
139                l = label,
140                t = html_escape(title),
141            ),
142            None => String::new(),
143        }
144    };
145
146    let search_header = chrome.search_island.as_ref().map_or_else(String::new, |chunk| {
147        let index = chrome
148            .search_index
149            .clone()
150            .unwrap_or_else(|| url("search.json"));
151        format!(
152            "<docs-island component-url=\"{u}\" client=\"idle\"><script type=\"application/json\" data-island-props>{{\"index\":\"{i}\"}}</script></docs-island>",
153            u = html_escape(chunk),
154            i = html_escape(&index),
155        )
156    });
157
158    let css_link = url("_assets/layout.css");
159
160    let doc = doc.replacen(
161        "</head>",
162        &format!(
163            "<link rel=\"stylesheet\" href=\"{}\"></head>",
164            html_escape(&css_link)
165        ),
166        1,
167    );
168    let doc = doc.replacen(
169        "<body>",
170        &format!(
171            "<body><header class=\"site-header\"><a class=\"brand\" href=\"{home}\">{b}</a>{search}<button id=\"theme-toggle\" aria-label=\"toggle theme\"></button></header>\
172<nav class=\"sidebar\">{nav}</nav>\
173<div class=\"page\"><main>",
174            home = html_escape(&url("")),
175            b = html_escape(site_title),
176            search = search_header,
177            nav = nav_markup,
178        ),
179        1,
180    );
181    doc.replacen(
182        "</body></html>",
183        &format!(
184            "<div class=\"pager\">{prev}{next}</div></main>{toc}</div>{THEME_SCRIPT}</body></html>",
185            prev = pager_markup(&chrome.prev, "prev", "Previous"),
186            next = pager_markup(&chrome.next, "next", "Next"),
187            toc = toc_markup,
188        ),
189        1,
190    )
191}
192
193/// Extract the TOC (h2/h3 with anchor ids) from a rendered body. h1 is
194/// the page title and stays out of the TOC; deeper levels rarely carry
195/// anchors worth listing.
196#[must_use]
197pub fn extract_toc(body: &str) -> Vec<TocEntry> {
198    let mut toc = Vec::new();
199    let mut rest = body;
200    loop {
201        let next_pos = match (rest.find("<h2 id=\""), rest.find("<h3 id=\"")) {
202            (Some(a), Some(b)) => Some(a.min(b)),
203            (Some(a), None) => Some(a),
204            (None, Some(b)) => Some(b),
205            (None, None) => None,
206        };
207        let Some(pos) = next_pos else { break };
208        let Some(window) = rest.get(pos..) else { break };
209        let level = if window.starts_with("<h2") { 2 } else { 3 };
210        let Some(id_rel) = window.find("id=\"").map(|p| p + 4) else {
211            break;
212        };
213        let Some(end_rel) = window.get(id_rel..).and_then(|s| s.find('"')) else {
214            break;
215        };
216        let id_end = id_rel + end_rel;
217        let Some(anchor) = window.get(id_rel..id_end).map(str::to_string) else {
218            break;
219        };
220        let Some(gt_rel) = window.get(id_end..).and_then(|s| s.find('>')) else {
221            break;
222        };
223        let text_start = id_end + gt_rel + 1;
224        let Some(lt_rel) = window.get(text_start..).and_then(|s| s.find('<')) else {
225            break;
226        };
227        let text_end = text_start + lt_rel;
228        let Some(text) = window
229            .get(text_start..text_end)
230            .map(|s| s.trim().to_string())
231        else {
232            break;
233        };
234        if !text.is_empty() {
235            toc.push(TocEntry {
236                level,
237                anchor,
238                text,
239            });
240        }
241        rest = match window.get(text_end..) {
242            Some(r) => r,
243            None => break,
244        };
245    }
246    toc
247}