1use crate::directives::html_escape;
15
16pub const LAYOUT_CSS: &str = include_str!("layout.css");
19
20#[derive(Debug, Clone, PartialEq)]
22pub struct NavGroup {
23 pub label: String,
25 pub items: Vec<(String, String)>,
27 pub active: bool,
29}
30
31#[derive(Debug, Clone, PartialEq)]
33pub struct TocEntry {
34 pub level: u8,
36 pub anchor: String,
38 pub text: String,
40}
41
42#[derive(Debug, Clone, PartialEq)]
44pub struct Chrome {
45 pub nav: Vec<NavGroup>,
47 pub active_route: String,
49 pub toc: Vec<TocEntry>,
51 pub prev: Option<(String, String)>,
53 pub next: Option<(String, String)>,
55 pub search_island: Option<String>,
58 pub search_index: Option<String>,
61}
62
63const 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#[must_use]
75pub fn page(doc: &str, site_title: &str, chrome: &Chrome, base_path: &str) -> String {
76 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#[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}