1use std::path::{Path, PathBuf};
7
8use crate::addresses::{Owned, address};
9use crate::document::{Document, Paper, Pdf};
10use crate::folder::{ServedFolder, lexical};
11use crate::html::{Link, escape};
12use crate::markup::title;
13use crate::nav;
14use crate::problem::Problem;
15use crate::widgets::Widgets;
16
17use super::content::Rendered;
18use super::navbar;
19use super::sidebar::sidebar;
20
21pub(super) fn tab_title(page: &str, site: &str) -> String {
24 let (page, site) = (page.trim(), site.trim());
25 if page.to_lowercase() == site.to_lowercase() {
26 site.to_string()
27 } else {
28 format!("{page} · {site}")
29 }
30}
31
32pub(super) fn html_open(served: &ServedFolder) -> String {
36 match served.mount() {
37 "" => r#"<html lang="en">"#.to_string(),
38 mount => format!(r#"<html lang="en" data-mount="{}">"#, escape(mount)),
39 }
40}
41
42fn page_script(print: bool, comments: bool) -> String {
48 let setting = if print {
49 " data-print"
50 } else if !comments {
51 " data-no-comments"
52 } else {
53 ""
54 };
55 format!(
56 "<script defer fetchpriority=\"high\" src=\"{}\"{setting}></script>",
57 address(Owned::Asset("devpage.js"))
58 )
59}
60
61pub fn page(
68 document: &Document,
69 widgets: &Widgets,
70 rendered: &Rendered,
71 comments: bool,
72 found: &[Problem],
73) -> Option<String> {
74 let page = title(rendered.source(), rendered.file());
75 framed(
76 document,
77 widgets,
78 rendered.file(),
79 &page,
80 rendered.html(),
81 comments,
82 found,
83 )
84}
85
86pub fn missing(document: &Document, widgets: &Widgets, rendered: &Rendered) -> Option<String> {
91 let page = title(rendered.source(), rendered.file());
92 let content = rebase(rendered.html(), rendered.file(), document);
93 framed(
94 document,
95 widgets,
96 rendered.file(),
97 &page,
98 &content,
99 false,
100 &[],
101 )
102}
103
104pub fn generated(
110 document: &Document,
111 widgets: &Widgets,
112 rendered: &Rendered,
113 current: &Path,
114 found: &[Problem],
115) -> Option<String> {
116 let page = title(rendered.source(), rendered.file());
117 let html = framed(
118 document,
119 widgets,
120 current,
121 &page,
122 rendered.html(),
123 false,
124 found,
125 )?;
126 let shown = document.url(current)?;
128 let own = document.url(rendered.file())?;
129 Some(html.replacen(
130 &format!("<article data-source=\"{}\">", escape(&shown)),
131 &format!("<article data-source=\"{}\">", escape(&own)),
132 1,
133 ))
134}
135
136pub fn nothing_at(
140 document: &Document,
141 widgets: &Widgets,
142 address: &str,
143 meant: Option<&str>,
144) -> Option<String> {
145 let content = nothing_at_content(document, address, meant);
146 framed(
147 document,
148 widgets,
149 &document.base.join("404.md"),
150 NOT_FOUND,
151 &content,
152 false,
153 &[],
154 )
155}
156
157pub fn nothing_at_alone(entry: &Document, asked: &str, meant: Option<&str>) -> String {
161 format!(
162 r#"<!doctype html>
163{html}
164<head>
165<meta charset="utf-8">
166<meta name="viewport" content="width=device-width, initial-scale=1">
167<title>{NOT_FOUND} · {document}</title>
168{theme}
169<link rel="stylesheet" href="{stylesheet}">
170</head>
171<body class="missing" data-build="{build}">
172<main id="devpage-page"><article>{content}</article></main>
173</body>
174</html>"#,
175 html = html_open(&entry.served),
176 stylesheet = address(Owned::Asset("style.css")),
177 build = crate::addresses::BUILD,
178 document = escape(&entry.title),
179 theme = navbar::head(entry),
180 content = nothing_at_content(entry, asked, meant),
181 )
182}
183
184const NOT_FOUND: &str = "Page not found";
186
187fn nothing_at_content(document: &Document, address: &str, meant: Option<&str>) -> String {
191 let meant = meant.map_or_else(String::new, |meant| {
192 format!(
193 r#"<p>Did you mean <a href="{0}">{0}</a>?</p>"#,
194 escape(meant)
195 )
196 });
197 format!(
198 r#"<h1>{NOT_FOUND}</h1><p>There is nothing at <code>{address}</code>.</p>{meant}<p><a href="{home}">Go to {title}</a></p>"#,
199 address = escape(address),
200 home = escape(&document.entry()),
201 title = escape(&document.title),
202 )
203}
204
205fn framed(
208 document: &Document,
209 widgets: &Widgets,
210 file: &Path,
211 page: &str,
212 content: &str,
213 comments: bool,
214 found: &[Problem],
215) -> Option<String> {
216 let _render = tracing::info_span!("render").entered();
217 let current = document.url(file)?;
218 let tree = if document.sidebar || !document.navbar.is_empty() {
219 nav::tree(document)
220 } else {
221 Vec::new()
222 };
223 Some(format!(
224 r#"<!doctype html>
225{html}
226<head>
227<meta charset="utf-8">
228<meta name="viewport" content="width=device-width, initial-scale=1">
229<title>{tab}</title>
230{theme}
231<link rel="stylesheet" href="{stylesheet}">
232{script}
233{widgets}
234</head>
235<body class="{body_class}" data-build="{build}">
236{navbar}{sidebar}{corner}
237<main id="devpage-page">{problems}<article data-source="{current}">{content}</article></main>
238</body>
239</html>"#,
240 html = html_open(&document.served),
241 stylesheet = address(Owned::Asset("style.css")),
242 build = crate::addresses::BUILD,
243 tab = escape(&tab_title(page, &document.title)),
244 theme = navbar::head(document),
245 body_class = site_class(document),
246 navbar = navbar::render(document, &tree, ¤t, comments),
247 sidebar = sidebar(document, &tree, ¤t),
248 script = page_script(false, comments),
249 corner = if document.navbar.is_empty() {
250 navbar::corner(document, comments)
251 } else {
252 String::new()
253 },
254 problems = problems(found),
255 widgets = widgets.head(
256 content,
257 if document.sidebar {
258 &[crate::widgets::SIDEBAR]
259 } else {
260 &[]
261 }
262 ),
263 ))
264}
265
266pub fn workspace(
269 document: &Document,
270 widgets: &Widgets,
271 _file: &Path,
272 title: &str,
273 content: &str,
274 comments: bool,
275) -> String {
276 format!(
277 r#"<!doctype html>
278{html}<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
279<title>{title}</title>{theme}<link rel="stylesheet" href="{style}">{script}{widgets}</head>
280<body class="site no-sidebar devpage-workspace" data-build="{build}">
281<main id="devpage-page">{content}</main></body></html>"#,
282 html = html_open(&document.served),
283 title = escape(&tab_title(title, &document.title)),
284 theme = navbar::head(document),
285 style = address(Owned::Asset("style.css")),
286 script = page_script(false, comments),
287 widgets = widgets.head(content, &[]),
288 build = crate::addresses::BUILD,
289 )
290}
291
292pub fn doc(
296 document: &Document,
297 widgets: &Widgets,
298 chapters: &[Rendered],
299 pdf: &Pdf,
300 print: bool,
301 comments: bool,
302 found: &[Problem],
303) -> String {
304 let _render = tracing::info_span!("render").entered();
305 let mut content = String::new();
306 let mut outline = String::new();
307 let files: Vec<PathBuf> = chapters.iter().map(|c| c.file().to_path_buf()).collect();
308 let names = chapter_names(&files, &document.served);
309 for rendered in chapters {
310 let chapter = rendered.file();
311 let mut html = rendered.html().to_string();
312 if chapters.len() > 1 {
313 html = scope_ids(&html, chapter, &names, &document.served);
314 }
315 let html = rebase(&html, chapter, document);
316 for (level, id, text) in headings(&html) {
317 outline.push_str(&format!(
318 "<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
319 ));
320 }
321 let id = if chapters.len() > 1 {
325 format!(
326 " id=\"{}\"",
327 chapter_name(chapter, &names, &document.served)
328 )
329 } else {
330 String::new()
331 };
332 content.push_str(&format!(
333 "<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
334 document.part_url(chapter)
335 ));
336 }
337 let paper = match pdf.paper {
338 Paper::A4 => "A4",
339 Paper::Letter => "letter",
340 };
341 let outline = if print {
342 String::new()
343 } else {
344 format!(
345 "<nav id=\"devpage-nav\" class=\"outline\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
346 navbar::logo(document),
347 escape(&document.title)
348 )
349 };
350 format!(
351 r#"<!doctype html>
352{html}
353<head>
354<meta charset="utf-8">
355<meta name="viewport" content="width=device-width, initial-scale=1">
356<title>{title}</title>
357{theme}
358<link rel="stylesheet" href="{stylesheet}">
359{script}
360{widgets}
361<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
362</head>
363<body class="doc{print_class}" data-build="{build}">
364{corner}{outline}
365<main id="devpage-page">{problems}<article>{heading}{content}</article></main>
366</body>
367</html>"#,
368 html = html_open(&document.served),
369 stylesheet = address(Owned::Asset("style.css")),
370 build = crate::addresses::BUILD,
371 title = escape(&document.title),
372 theme = navbar::head(document),
373 corner = if print {
374 String::new()
375 } else {
376 navbar::corner(document, comments)
377 },
378 widgets = widgets.head(&content, &[]),
379 heading = if document.file_name.ends_with(".md") {
381 String::new()
382 } else {
383 format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
384 },
385 print_class = if print { " print" } else { "" },
386 script = page_script(print, comments),
387 problems = if print {
388 String::new()
389 } else {
390 problems(found)
391 },
392 )
393}
394
395pub(super) fn chapter_names(chapters: &[PathBuf], served: &ServedFolder) -> Vec<(PathBuf, String)> {
399 chapters
400 .iter()
401 .map(|chapter| {
402 let canonical = served.inside(chapter).unwrap_or_else(|| chapter.clone());
403 let name = chapter
404 .file_stem()
405 .unwrap_or_default()
406 .to_string_lossy()
407 .into_owned();
408 (canonical, name)
409 })
410 .collect()
411}
412
413fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
416 let canonical = served
417 .inside(chapter)
418 .unwrap_or_else(|| chapter.to_path_buf());
419 names
420 .iter()
421 .find(|(path, _)| *path == canonical)
422 .map(|(_, name)| name.clone())
423 .unwrap_or_default()
424}
425
426fn scope_ids(
430 html: &str,
431 chapter: &Path,
432 names: &[(PathBuf, String)],
433 served: &ServedFolder,
434) -> String {
435 let own = chapter_name(chapter, names, served);
436 let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
437 let mut out = String::new();
438 let mut rest = html.as_str();
439 while let Some(at) = rest.find(" href=\"") {
440 out.push_str(&rest[..at + 7]);
441 rest = &rest[at + 7..];
442 let end = rest.find('"').unwrap_or(rest.len());
443 let href = &rest[..end];
444 let target = match Link::classify(href) {
445 Link::File { path: "", fragment } => Some((own.clone(), fragment)),
446 Link::File { path, fragment } => {
447 let resolved =
448 served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
449 names
450 .iter()
451 .find(|(file, _)| Some(file) == resolved.as_ref())
452 .map(|(_, name)| (name.clone(), fragment))
453 }
454 Link::Web(_) | Link::Elsewhere => None,
455 };
456 match target {
457 Some((name, "")) => out.push_str(&format!("#{name}")),
458 Some((name, fragment)) => out.push_str(&format!("#{name}--{fragment}")),
459 None => out.push_str(href),
460 }
461 rest = &rest[end..];
462 }
463 out.push_str(rest);
464 out
465}
466
467fn rebase(html: &str, file: &Path, document: &Document) -> String {
472 let folder = file.parent().unwrap_or(Path::new("."));
473 let mut out = String::new();
474 let mut rest = html;
475 const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
477 loop {
478 let next = STARTS
479 .iter()
480 .filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
481 .min();
482 let Some((start, close)) = next else { break };
483 out.push_str(&rest[..start]);
484 rest = &rest[start..];
485 let end = rest.find(close).unwrap_or(rest.len());
486 let value = &rest[..end];
487 match Link::classify(value) {
488 Link::File { path, fragment } if !path.is_empty() && !path.starts_with('/') => {
492 match document.url(&lexical(&folder.join(path))) {
493 Some(address) => {
494 out.push_str(&address);
495 if value.contains('#') {
496 out.push('#');
497 out.push_str(fragment);
498 }
499 }
500 None => out.push_str(value),
501 }
502 }
503 _ => out.push_str(value),
504 }
505 rest = &rest[end..];
506 }
507 out.push_str(rest);
508 out
509}
510
511pub fn invalid(entry: &Document, file: &Path, error: &str) -> Option<String> {
514 let address = entry.url(file)?;
515 Some(format!(
516 r#"<!doctype html>
517{html}
518<head>
519<meta charset="utf-8">
520<meta name="viewport" content="width=device-width, initial-scale=1">
521<title>{address} · {document}</title>
522{theme}
523<link rel="stylesheet" href="{stylesheet}">
524{page_script}
525</head>
526<body class="invalid" data-build="{build}">
527<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
528</body>
529</html>"#,
530 html = html_open(&entry.served),
531 stylesheet = crate::addresses::address(Owned::Asset("style.css")),
532 build = crate::addresses::BUILD,
533 page_script = page_script(false, true),
534 address = escape(&address),
535 document = escape(&entry.title),
536 theme = navbar::head(entry),
537 error = escape(error),
538 ))
539}
540
541fn problems(found: &[Problem]) -> String {
543 if found.is_empty() {
544 return String::new();
545 }
546 let items: String = found
547 .iter()
548 .map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
549 .collect();
550 let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
552 format!(
553 "<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
554 escape(&serde_json::to_string(&broken).unwrap_or_default()),
555 found.len(),
556 if found.len() == 1 { "" } else { "s" }
557 )
558}
559
560pub fn slides(
564 document: &Document,
565 widgets: &Widgets,
566 slides: &[Rendered],
567 print: bool,
568 comments: bool,
569 found: &[Problem],
570) -> String {
571 let _render = tracing::info_span!("render").entered();
572 let mut content = String::new();
573 for (index, slide) in slides.iter().enumerate() {
574 content.push_str(&format!(
575 "<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
576 index + 1,
577 document.part_url(slide.file()),
578 rebase(slide.html(), slide.file(), document)
579 ));
580 }
581 format!(
582 r#"<!doctype html>
583{html}
584<head>
585<meta charset="utf-8">
586<meta name="viewport" content="width=device-width, initial-scale=1">
587<title>{title}</title>
588{theme}
589<link rel="stylesheet" href="{stylesheet}">
590{script}
591{widgets}
592<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
593</head>
594<body class="slides{print_class}" data-build="{build}">
595{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
596</body>
597</html>"#,
598 html = html_open(&document.served),
599 stylesheet = address(Owned::Asset("style.css")),
600 build = crate::addresses::BUILD,
601 title = escape(&document.title),
602 theme = navbar::head(document),
603 corner = if print {
604 String::new()
605 } else {
606 navbar::corner(document, comments)
607 },
608 widgets = widgets.head(&content, &[]),
609 print_class = if print { " print" } else { "" },
610 script = page_script(print, comments),
611 problems = if print {
612 String::new()
613 } else {
614 problems(found)
615 },
616 )
617}
618
619fn headings(html: &str) -> Vec<(u8, String, String)> {
621 let mut found = Vec::new();
622 let mut rest = html;
623 while let Some(start) = rest.find("<h") {
624 rest = &rest[start + 2..];
625 let level = rest.as_bytes().first().copied().unwrap_or(0);
626 if level != b'1' && level != b'2' {
627 continue;
628 }
629 let close = format!("</h{}>", level as char);
630 let Some(end) = rest.find(&close) else { break };
631 let inner = &rest[..end];
632 let id = inner
633 .split("id=\"")
634 .nth(1)
635 .and_then(|tail| tail.split('"').next())
636 .unwrap_or_default()
637 .to_string();
638 let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
639 found.push((level - b'0', id, text));
640 rest = &rest[end..];
641 }
642 found
643}
644
645fn strip_tags(html: &str) -> String {
647 let mut text = String::new();
648 let mut in_tag = false;
649 for c in html.chars() {
650 match c {
651 '<' => in_tag = true,
652 '>' => in_tag = false,
653 c if !in_tag => text.push(c),
654 _ => {}
655 }
656 }
657 text.trim().to_string()
658}
659
660fn site_class(document: &Document) -> String {
663 let mut class = String::from("site");
664 if !document.navbar.is_empty() {
665 class.push_str(" with-navbar");
666 }
667 if !document.sidebar {
668 class.push_str(" no-sidebar");
669 }
670 class
671}