1use std::path::{Path, PathBuf};
6
7use crate::addresses::{Owned, address};
8use crate::document::{Document, Paper, Pdf, Slide};
9use crate::problem::Problem;
10use crate::served::ServedFolder;
11use crate::widgets::Widgets;
12
13use super::sidebar::sidebar;
14use super::{escape, markdown_in, title};
15
16pub fn tab_title(page: &str, site: &str) -> String {
19 let (page, site) = (page.trim(), site.trim());
20 if page.to_lowercase() == site.to_lowercase() {
21 site.to_string()
22 } else {
23 format!("{page} · {site}")
24 }
25}
26
27pub fn html_open(served: &ServedFolder) -> String {
31 match served.mount() {
32 "" => r#"<html lang="en">"#.to_string(),
33 mount => format!(r#"<html lang="en" data-mount="{}">"#, escape(mount)),
34 }
35}
36
37fn page_script(print: bool, comments: bool) -> String {
42 let setting = if print {
43 " data-print"
44 } else if !comments {
45 " data-no-comments"
46 } else {
47 ""
48 };
49 format!(
50 "<script defer fetchpriority=\"high\" src=\"{}\"{setting}></script>",
51 address(Owned::Asset("devpage.js"))
52 )
53}
54
55pub fn page(
60 document: &Document,
61 widgets: &Widgets,
62 file: &Path,
63 source: &str,
64 comments: bool,
65 found: &[Problem],
66) -> String {
67 let current = document.url(file);
68 let content = markdown_in(widgets, source);
69 format!(
70 r#"<!doctype html>
71{html}
72<head>
73<meta charset="utf-8">
74<meta name="viewport" content="width=device-width, initial-scale=1">
75<title>{tab}</title>
76{theme}
77<link rel="stylesheet" href="{stylesheet}">
78{script}
79{widgets}
80</head>
81<body class="{body_class}" data-build="{build}">
82{navbar}{sidebar}{corner}
83<main id="devpage-page">{problems}<article data-source="{current}">{content}</article></main>
84</body>
85</html>"#,
86 html = html_open(&document.served),
87 stylesheet = address(Owned::Asset("style.css")),
88 build = crate::addresses::BUILD,
89 tab = escape(&tab_title(&title(source, file), &document.title)),
90 theme = crate::navbar::head(document),
91 body_class = site_class(document),
92 navbar = crate::navbar::render(document, ¤t, comments),
93 sidebar = sidebar(document, ¤t),
94 script = page_script(false, comments),
95 corner = if document.navbar.is_empty() {
96 crate::navbar::corner(document, comments)
97 } else {
98 String::new()
99 },
100 problems = problems(found),
101 widgets = widgets.head(
102 &content,
103 if document.sidebar {
104 &[crate::widgets::SIDEBAR]
105 } else {
106 &[]
107 }
108 ),
109 )
110}
111
112pub fn doc(
116 document: &Document,
117 widgets: &Widgets,
118 chapters: &[PathBuf],
119 pdf: &Pdf,
120 print: bool,
121 comments: bool,
122 found: &[Problem],
123) -> String {
124 let mut content = String::new();
125 let mut outline = String::new();
126 let names: Vec<(PathBuf, String)> = chapters
129 .iter()
130 .map(|chapter| {
131 let canonical = document
132 .served
133 .inside(chapter)
134 .unwrap_or_else(|| chapter.clone());
135 let name = chapter
136 .file_stem()
137 .unwrap_or_default()
138 .to_string_lossy()
139 .into_owned();
140 (canonical, name)
141 })
142 .collect();
143 for chapter in chapters {
144 let source = std::fs::read_to_string(chapter).unwrap_or_default();
145 let mut html = markdown_in(widgets, &source);
146 if chapters.len() > 1 {
147 html = scope_ids(&html, chapter, &names, &document.served);
148 }
149 let html = rebase(&html, chapter, document);
150 for (level, id, text) in headings(&html) {
151 outline.push_str(&format!(
152 "<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
153 ));
154 }
155 let id = if chapters.len() > 1 {
159 format!(
160 " id=\"{}\"",
161 chapter_name(chapter, &names, &document.served)
162 )
163 } else {
164 String::new()
165 };
166 content.push_str(&format!(
167 "<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
168 document.url(chapter)
169 ));
170 }
171 let paper = match pdf.paper {
172 Paper::A4 => "A4",
173 Paper::Letter => "letter",
174 };
175 let outline = if print {
176 String::new()
177 } else {
178 format!(
179 "<nav id=\"devpage-nav\" class=\"outline\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
180 crate::navbar::logo(document),
181 escape(&document.title)
182 )
183 };
184 format!(
185 r#"<!doctype html>
186{html}
187<head>
188<meta charset="utf-8">
189<meta name="viewport" content="width=device-width, initial-scale=1">
190<title>{title}</title>
191{theme}
192<link rel="stylesheet" href="{stylesheet}">
193{script}
194{widgets}
195<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
196</head>
197<body class="doc{print_class}" data-build="{build}">
198{corner}{outline}
199<main id="devpage-page">{problems}<article>{heading}{content}</article></main>
200</body>
201</html>"#,
202 html = html_open(&document.served),
203 stylesheet = address(Owned::Asset("style.css")),
204 build = crate::addresses::BUILD,
205 title = escape(&document.title),
206 theme = crate::navbar::head(document),
207 corner = if print {
208 String::new()
209 } else {
210 crate::navbar::corner(document, comments)
211 },
212 widgets = widgets.head(&content, &[]),
213 heading = if document.file_name.ends_with(".md") {
215 String::new()
216 } else {
217 format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
218 },
219 print_class = if print { " print" } else { "" },
220 script = page_script(print, comments),
221 problems = if print {
222 String::new()
223 } else {
224 problems(found)
225 },
226 )
227}
228
229fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
230 let canonical = served
231 .inside(chapter)
232 .unwrap_or_else(|| chapter.to_path_buf());
233 names
234 .iter()
235 .find(|(path, _)| *path == canonical)
236 .map(|(_, name)| name.clone())
237 .unwrap_or_default()
238}
239
240fn scope_ids(
244 html: &str,
245 chapter: &Path,
246 names: &[(PathBuf, String)],
247 served: &ServedFolder,
248) -> String {
249 let own = chapter_name(chapter, names, served);
250 let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
251 let mut out = String::new();
252 let mut rest = html.as_str();
253 while let Some(at) = rest.find(" href=\"") {
254 out.push_str(&rest[..at + 7]);
255 rest = &rest[at + 7..];
256 let end = rest.find('"').unwrap_or(rest.len());
257 let href = &rest[..end];
258 let (path, fragment) = href.split_once('#').unwrap_or((href, ""));
259 let target = if path.is_empty() {
260 Some(own.clone())
261 } else if href.contains("://") {
262 None
263 } else {
264 let resolved = served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
265 names
266 .iter()
267 .find(|(file, _)| Some(file) == resolved.as_ref())
268 .map(|(_, name)| name.clone())
269 };
270 match target {
271 Some(name) if fragment.is_empty() => out.push_str(&format!("#{name}")),
272 Some(name) => out.push_str(&format!("#{name}--{fragment}")),
273 None => out.push_str(href),
274 }
275 rest = &rest[end..];
276 }
277 out.push_str(rest);
278 out
279}
280
281fn rebase(html: &str, file: &Path, document: &Document) -> String {
286 let folder = file.parent().unwrap_or(Path::new("."));
287 let mut out = String::new();
288 let mut rest = html;
289 const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
291 loop {
292 let next = STARTS
293 .iter()
294 .filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
295 .min();
296 let Some((start, close)) = next else { break };
297 out.push_str(&rest[..start]);
298 rest = &rest[start..];
299 let end = rest.find(close).unwrap_or(rest.len());
300 let value = &rest[..end];
301 if value.is_empty() || value.starts_with(['#', '/']) || value.contains(':') {
302 out.push_str(value);
303 } else {
304 let (path, fragment) = match value.split_once('#') {
305 Some((path, fragment)) => (path, format!("#{fragment}")),
306 None => (value, String::new()),
307 };
308 out.push_str(&document.url(&normalize(&folder.join(path))));
309 out.push_str(&fragment);
310 }
311 rest = &rest[end..];
312 }
313 out.push_str(rest);
314 out
315}
316
317fn normalize(path: &Path) -> PathBuf {
320 let mut out = PathBuf::new();
321 for part in path.components() {
322 match part {
323 std::path::Component::ParentDir => {
324 out.pop();
325 }
326 std::path::Component::CurDir => {}
327 other => out.push(other),
328 }
329 }
330 out
331}
332
333pub fn invalid(entry: &Document, file: &Path, error: &str) -> String {
335 let address = entry.url(file);
336 format!(
337 r#"<!doctype html>
338{html}
339<head>
340<meta charset="utf-8">
341<meta name="viewport" content="width=device-width, initial-scale=1">
342<title>{address} · {document}</title>
343{theme}
344<link rel="stylesheet" href="{stylesheet}">
345{page_script}
346</head>
347<body class="invalid" data-build="{build}">
348<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
349</body>
350</html>"#,
351 html = html_open(&entry.served),
352 stylesheet = crate::addresses::address(Owned::Asset("style.css")),
353 build = crate::addresses::BUILD,
354 page_script = page_script(false, true),
355 address = escape(&address),
356 document = escape(&entry.title),
357 theme = crate::navbar::head(entry),
358 error = escape(error),
359 )
360}
361
362fn problems(found: &[Problem]) -> String {
364 if found.is_empty() {
365 return String::new();
366 }
367 let items: String = found
368 .iter()
369 .map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
370 .collect();
371 let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
373 format!(
374 "<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
375 escape(&serde_json::to_string(&broken).unwrap_or_default()),
376 found.len(),
377 if found.len() == 1 { "" } else { "s" }
378 )
379}
380
381pub fn slides(
384 document: &Document,
385 widgets: &Widgets,
386 slides: &[Slide],
387 print: bool,
388 comments: bool,
389 found: &[Problem],
390) -> String {
391 let files: Vec<PathBuf> = slides.iter().map(|slide| slide.file.clone()).collect();
392 let mut content = String::new();
393 for (index, slide) in files.iter().enumerate() {
394 let source = std::fs::read_to_string(slide).unwrap_or_default();
395 content.push_str(&format!(
396 "<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
397 index + 1,
398 document.url(slide),
399 rebase(&markdown_in(widgets, &source), slide, document)
400 ));
401 }
402 format!(
403 r#"<!doctype html>
404{html}
405<head>
406<meta charset="utf-8">
407<meta name="viewport" content="width=device-width, initial-scale=1">
408<title>{title}</title>
409{theme}
410<link rel="stylesheet" href="{stylesheet}">
411{script}
412{widgets}
413<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
414</head>
415<body class="slides{print_class}" data-build="{build}">
416{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
417</body>
418</html>"#,
419 html = html_open(&document.served),
420 stylesheet = address(Owned::Asset("style.css")),
421 build = crate::addresses::BUILD,
422 title = escape(&document.title),
423 theme = crate::navbar::head(document),
424 corner = if print {
425 String::new()
426 } else {
427 crate::navbar::corner(document, comments)
428 },
429 widgets = widgets.head(&content, &[]),
430 print_class = if print { " print" } else { "" },
431 script = page_script(print, comments),
432 problems = if print {
433 String::new()
434 } else {
435 problems(found)
436 },
437 )
438}
439
440fn headings(html: &str) -> Vec<(u8, String, String)> {
442 let mut found = Vec::new();
443 let mut rest = html;
444 while let Some(start) = rest.find("<h") {
445 rest = &rest[start + 2..];
446 let level = rest.as_bytes().first().copied().unwrap_or(0);
447 if level != b'1' && level != b'2' {
448 continue;
449 }
450 let close = format!("</h{}>", level as char);
451 let Some(end) = rest.find(&close) else { break };
452 let inner = &rest[..end];
453 let id = inner
454 .split("id=\"")
455 .nth(1)
456 .and_then(|tail| tail.split('"').next())
457 .unwrap_or_default()
458 .to_string();
459 let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
460 found.push((level - b'0', id, text));
461 rest = &rest[end..];
462 }
463 found
464}
465
466fn strip_tags(html: &str) -> String {
467 let mut text = String::new();
468 let mut in_tag = false;
469 for c in html.chars() {
470 match c {
471 '<' => in_tag = true,
472 '>' => in_tag = false,
473 c if !in_tag => text.push(c),
474 _ => {}
475 }
476 }
477 text.trim().to_string()
478}
479
480fn site_class(document: &Document) -> String {
483 let mut class = String::from("site");
484 if !document.navbar.is_empty() {
485 class.push_str(" with-navbar");
486 }
487 if !document.sidebar {
488 class.push_str(" no-sidebar");
489 }
490 class
491}