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