1use crate::directives::html_escape;
15
16fn 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
25pub const LAYOUT_CSS: &str = include_str!("layout.css");
28
29#[derive(Debug, Clone, PartialEq)]
31pub struct NavGroup {
32 pub label: String,
34 pub items: Vec<(String, String)>,
36 pub active: bool,
38}
39
40#[derive(Debug, Clone, PartialEq)]
42pub struct TocEntry {
43 pub level: u8,
45 pub anchor: String,
47 pub text: String,
49}
50
51#[derive(Debug, Clone, PartialEq)]
53pub struct Chrome {
54 pub nav: Vec<NavGroup>,
56 pub active_route: String,
58 pub toc: Vec<TocEntry>,
60 pub prev: Option<(String, String)>,
62 pub next: Option<(String, String)>,
64 pub search_island: Option<String>,
67 pub search_index: Option<String>,
70 pub search_wasm: Option<String>,
73 pub search_bin: Option<String>,
75}
76
77const 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#[must_use]
89pub fn page(doc: &str, site_title: &str, chrome: &Chrome, base_path: &str) -> String {
90 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#[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}