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