1use std::path::{Path, PathBuf};
7
8use crate::addresses::{Owned, address};
9use crate::document::{Document, Kind, 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 extension(
143 document: &Document,
144 widgets: &Widgets,
145 rendered: &Rendered,
146 source: &str,
147) -> Option<String> {
148 let own = document.url(rendered.file())?;
149 let (html, tag) = match &document.kind {
150 Kind::Site { .. } => {
151 let page = title(rendered.source(), rendered.file());
152 let file = rendered.file();
153 let html = framed(document, widgets, file, &page, rendered.html(), false, &[])?;
154 (html, "<article")
155 }
156 kind => {
157 let pdf = match kind {
158 Kind::Doc { pdf, .. } => pdf.clone(),
159 _ => Pdf::default(),
160 };
161 let chapters = std::slice::from_ref(rendered);
162 let html = doc(document, widgets, chapters, &pdf, false, false, &[]);
163 (html, "<section class=\"chapter\"")
164 }
165 };
166 Some(html.replacen(
167 &format!("{tag} data-source=\"{}\">", escape(&own)),
168 &format!("{tag} data-source=\"{}\">", escape(source)),
169 1,
170 ))
171}
172
173pub fn nothing_at(
177 document: &Document,
178 widgets: &Widgets,
179 address: &str,
180 meant: Option<&str>,
181) -> Option<String> {
182 let content = nothing_at_content(document, address, meant);
183 framed(
184 document,
185 widgets,
186 &document.base.join("404.md"),
187 NOT_FOUND,
188 &content,
189 false,
190 &[],
191 )
192}
193
194pub fn nothing_at_alone(entry: &Document, asked: &str, meant: Option<&str>) -> String {
198 format!(
199 r#"<!doctype html>
200{html}
201<head>
202<meta charset="utf-8">
203<meta name="viewport" content="width=device-width, initial-scale=1">
204<title>{NOT_FOUND} · {document}</title>
205{theme}
206<link rel="stylesheet" href="{stylesheet}">
207</head>
208<body class="missing" data-build="{build}">
209<main id="devpage-page"><article>{content}</article></main>
210</body>
211</html>"#,
212 html = html_open(&entry.served),
213 stylesheet = address(Owned::Asset("style.css")),
214 build = crate::addresses::BUILD,
215 document = escape(&entry.title),
216 theme = navbar::head(entry),
217 content = nothing_at_content(entry, asked, meant),
218 )
219}
220
221const NOT_FOUND: &str = "Page not found";
223
224fn nothing_at_content(document: &Document, address: &str, meant: Option<&str>) -> String {
228 let meant = meant.map_or_else(String::new, |meant| {
229 format!(
230 r#"<p>Did you mean <a href="{0}">{0}</a>?</p>"#,
231 escape(meant)
232 )
233 });
234 format!(
235 r#"<h1>{NOT_FOUND}</h1><p>There is nothing at <code>{address}</code>.</p>{meant}<p><a href="{home}">Go to {title}</a></p>"#,
236 address = escape(address),
237 home = escape(&document.entry()),
238 title = escape(&document.title),
239 )
240}
241
242fn framed(
245 document: &Document,
246 widgets: &Widgets,
247 file: &Path,
248 page: &str,
249 content: &str,
250 comments: bool,
251 found: &[Problem],
252) -> Option<String> {
253 let _render = tracing::info_span!("render").entered();
254 let current = document.url(file)?;
255 let tree = if document.sidebar || !document.navbar.is_empty() {
256 nav::tree(document)
257 } else {
258 Vec::new()
259 };
260 Some(format!(
261 r#"<!doctype html>
262{html}
263<head>
264<meta charset="utf-8">
265<meta name="viewport" content="width=device-width, initial-scale=1">
266<title>{tab}</title>
267{theme}
268<link rel="stylesheet" href="{stylesheet}">
269{script}
270{widgets}
271</head>
272<body class="{body_class}" data-build="{build}">
273{navbar}{navigator}{corner}
274<main id="devpage-page">{problems}<article data-source="{current}">{content}</article></main>
275</body>
276</html>"#,
277 html = html_open(&document.served),
278 stylesheet = address(Owned::Asset("style.css")),
279 build = crate::addresses::BUILD,
280 tab = escape(&tab_title(page, &document.title)),
281 theme = navbar::head(document),
282 body_class = site_class(document),
283 navbar = navbar::render(document, &tree, ¤t, comments),
284 navigator = navigator(document, &tree, ¤t),
285 script = page_script(false, comments),
286 corner = if document.navbar.is_empty() {
287 navbar::corner(document, comments)
288 } else {
289 String::new()
290 },
291 problems = problems(found),
292 widgets = widgets.head(
293 content,
294 if document.sidebar {
295 &[crate::widgets::SIDEBAR]
296 } else {
297 &[]
298 }
299 ),
300 ))
301}
302
303fn navigator(document: &Document, tree: &[nav::Group], current: &str) -> String {
309 let links = navbar::navigator_links(document, tree, current);
310 let sidebar = sidebar(document, tree, current);
311 if links.is_empty() && sidebar.is_empty() {
312 return String::new();
313 }
314 format!("<div id=\"devpage-navigator\" class=\"navigator\">{links}{sidebar}</div>")
315}
316
317pub fn workspace(
320 document: &Document,
321 widgets: &Widgets,
322 _file: &Path,
323 title: &str,
324 content: &str,
325 comments: bool,
326) -> String {
327 format!(
328 r#"<!doctype html>
329{html}<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
330<title>{title}</title>{theme}<link rel="stylesheet" href="{style}">{script}{widgets}</head>
331<body class="site no-sidebar devpage-workspace" data-build="{build}">
332<main id="devpage-page">{content}</main></body></html>"#,
333 html = html_open(&document.served),
334 title = escape(&tab_title(title, &document.title)),
335 theme = navbar::head(document),
336 style = address(Owned::Asset("style.css")),
337 script = page_script(false, comments),
338 widgets = widgets.head(content, &[]),
339 build = crate::addresses::BUILD,
340 )
341}
342
343pub fn doc(
347 document: &Document,
348 widgets: &Widgets,
349 chapters: &[Rendered],
350 pdf: &Pdf,
351 print: bool,
352 comments: bool,
353 found: &[Problem],
354) -> String {
355 let _render = tracing::info_span!("render").entered();
356 let mut content = String::new();
357 let mut outline = String::new();
358 let files: Vec<PathBuf> = chapters.iter().map(|c| c.file().to_path_buf()).collect();
359 let names = chapter_names(&files, &document.served);
360 for rendered in chapters {
361 let chapter = rendered.file();
362 let mut html = rendered.html().to_string();
363 if chapters.len() > 1 {
364 html = scope_ids(&html, chapter, &names, &document.served);
365 }
366 let html = rebase(&html, chapter, document);
367 for (level, id, text) in headings(&html) {
368 outline.push_str(&format!(
369 "<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
370 ));
371 }
372 let id = if chapters.len() > 1 {
376 format!(
377 " id=\"{}\"",
378 chapter_name(chapter, &names, &document.served)
379 )
380 } else {
381 String::new()
382 };
383 content.push_str(&format!(
384 "<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
385 document.part_url(chapter)
386 ));
387 }
388 let paper = match pdf.paper {
389 Paper::A4 => "A4",
390 Paper::Letter => "letter",
391 };
392 let outline = if print {
393 String::new()
394 } else {
395 format!(
396 "<nav id=\"devpage-nav\" class=\"outline navigator\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
397 navbar::logo(document),
398 escape(&document.title)
399 )
400 };
401 format!(
402 r#"<!doctype html>
403{html}
404<head>
405<meta charset="utf-8">
406<meta name="viewport" content="width=device-width, initial-scale=1">
407<title>{title}</title>
408{theme}
409<link rel="stylesheet" href="{stylesheet}">
410{script}
411{widgets}
412<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
413</head>
414<body class="doc{print_class}" data-build="{build}">
415{corner}{outline}
416<main id="devpage-page">{problems}<article>{heading}{content}</article></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 = navbar::head(document),
424 corner = if print {
425 String::new()
426 } else {
427 navbar::corner(document, comments)
428 },
429 widgets = widgets.head(&content, &[]),
430 heading = if document.file_name.ends_with(".md") {
432 String::new()
433 } else {
434 format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
435 },
436 print_class = if print { " print" } else { "" },
437 script = page_script(print, comments),
438 problems = if print {
439 String::new()
440 } else {
441 problems(found)
442 },
443 )
444}
445
446pub(super) fn chapter_names(chapters: &[PathBuf], served: &ServedFolder) -> Vec<(PathBuf, String)> {
450 chapters
451 .iter()
452 .map(|chapter| {
453 let canonical = served.inside(chapter).unwrap_or_else(|| chapter.clone());
454 let name = chapter
455 .file_stem()
456 .unwrap_or_default()
457 .to_string_lossy()
458 .into_owned();
459 (canonical, name)
460 })
461 .collect()
462}
463
464fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
467 let canonical = served
468 .inside(chapter)
469 .unwrap_or_else(|| chapter.to_path_buf());
470 names
471 .iter()
472 .find(|(path, _)| *path == canonical)
473 .map(|(_, name)| name.clone())
474 .unwrap_or_default()
475}
476
477fn scope_ids(
481 html: &str,
482 chapter: &Path,
483 names: &[(PathBuf, String)],
484 served: &ServedFolder,
485) -> String {
486 let own = chapter_name(chapter, names, served);
487 let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
488 let mut out = String::new();
489 let mut rest = html.as_str();
490 while let Some(at) = rest.find(" href=\"") {
491 out.push_str(&rest[..at + 7]);
492 rest = &rest[at + 7..];
493 let end = rest.find('"').unwrap_or(rest.len());
494 let href = &rest[..end];
495 let target = match Link::classify(href) {
496 Link::File { path: "", fragment } => Some((own.clone(), fragment)),
497 Link::File { path, fragment } => {
498 let resolved =
499 served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
500 names
501 .iter()
502 .find(|(file, _)| Some(file) == resolved.as_ref())
503 .map(|(_, name)| (name.clone(), fragment))
504 }
505 Link::Web(_) | Link::Elsewhere => None,
506 };
507 match target {
508 Some((name, "")) => out.push_str(&format!("#{name}")),
509 Some((name, fragment)) => out.push_str(&format!("#{name}--{fragment}")),
510 None => out.push_str(href),
511 }
512 rest = &rest[end..];
513 }
514 out.push_str(rest);
515 out
516}
517
518fn rebase(html: &str, file: &Path, document: &Document) -> String {
523 let folder = file.parent().unwrap_or(Path::new("."));
524 let mut out = String::new();
525 let mut rest = html;
526 const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
528 loop {
529 let next = STARTS
530 .iter()
531 .filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
532 .min();
533 let Some((start, close)) = next else { break };
534 out.push_str(&rest[..start]);
535 rest = &rest[start..];
536 let end = rest.find(close).unwrap_or(rest.len());
537 let value = &rest[..end];
538 match Link::classify(value) {
539 Link::File { path, fragment } if !path.is_empty() && !path.starts_with('/') => {
543 match document.url(&lexical(&folder.join(path))) {
544 Some(address) => {
545 out.push_str(&address);
546 if value.contains('#') {
547 out.push('#');
548 out.push_str(fragment);
549 }
550 }
551 None => out.push_str(value),
552 }
553 }
554 _ => out.push_str(value),
555 }
556 rest = &rest[end..];
557 }
558 out.push_str(rest);
559 out
560}
561
562pub fn invalid(entry: &Document, file: &Path, error: &str) -> Option<String> {
565 let address = entry.url(file)?;
566 Some(format!(
567 r#"<!doctype html>
568{html}
569<head>
570<meta charset="utf-8">
571<meta name="viewport" content="width=device-width, initial-scale=1">
572<title>{address} · {document}</title>
573{theme}
574<link rel="stylesheet" href="{stylesheet}">
575{page_script}
576</head>
577<body class="invalid" data-build="{build}">
578<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
579</body>
580</html>"#,
581 html = html_open(&entry.served),
582 stylesheet = crate::addresses::address(Owned::Asset("style.css")),
583 build = crate::addresses::BUILD,
584 page_script = page_script(false, true),
585 address = escape(&address),
586 document = escape(&entry.title),
587 theme = navbar::head(entry),
588 error = escape(error),
589 ))
590}
591
592fn problems(found: &[Problem]) -> String {
594 if found.is_empty() {
595 return String::new();
596 }
597 let items: String = found
598 .iter()
599 .map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
600 .collect();
601 let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
603 format!(
604 "<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
605 escape(&serde_json::to_string(&broken).unwrap_or_default()),
606 found.len(),
607 if found.len() == 1 { "" } else { "s" }
608 )
609}
610
611pub fn slides(
615 document: &Document,
616 widgets: &Widgets,
617 slides: &[Rendered],
618 print: bool,
619 comments: bool,
620 found: &[Problem],
621) -> String {
622 let _render = tracing::info_span!("render").entered();
623 let mut content = String::new();
624 for (index, slide) in slides.iter().enumerate() {
625 content.push_str(&format!(
626 "<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
627 index + 1,
628 document.part_url(slide.file()),
629 rebase(slide.html(), slide.file(), document)
630 ));
631 }
632 format!(
633 r#"<!doctype html>
634{html}
635<head>
636<meta charset="utf-8">
637<meta name="viewport" content="width=device-width, initial-scale=1">
638<title>{title}</title>
639{theme}
640<link rel="stylesheet" href="{stylesheet}">
641{script}
642{widgets}
643<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
644</head>
645<body class="slides{print_class}" data-build="{build}">
646{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
647</body>
648</html>"#,
649 html = html_open(&document.served),
650 stylesheet = address(Owned::Asset("style.css")),
651 build = crate::addresses::BUILD,
652 title = escape(&document.title),
653 theme = navbar::head(document),
654 corner = if print {
655 String::new()
656 } else {
657 navbar::corner(document, comments)
658 },
659 widgets = widgets.head(&content, &[]),
660 print_class = if print { " print" } else { "" },
661 script = page_script(print, comments),
662 problems = if print {
663 String::new()
664 } else {
665 problems(found)
666 },
667 )
668}
669
670fn headings(html: &str) -> Vec<(u8, String, String)> {
672 let mut found = Vec::new();
673 let mut rest = html;
674 while let Some(start) = rest.find("<h") {
675 rest = &rest[start + 2..];
676 let level = rest.as_bytes().first().copied().unwrap_or(0);
677 if level != b'1' && level != b'2' {
678 continue;
679 }
680 let close = format!("</h{}>", level as char);
681 let Some(end) = rest.find(&close) else { break };
682 let inner = &rest[..end];
683 let id = inner
684 .split("id=\"")
685 .nth(1)
686 .and_then(|tail| tail.split('"').next())
687 .unwrap_or_default()
688 .to_string();
689 let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
690 found.push((level - b'0', id, text));
691 rest = &rest[end..];
692 }
693 found
694}
695
696fn strip_tags(html: &str) -> String {
698 let mut text = String::new();
699 let mut in_tag = false;
700 for c in html.chars() {
701 match c {
702 '<' => in_tag = true,
703 '>' => in_tag = false,
704 c if !in_tag => text.push(c),
705 _ => {}
706 }
707 }
708 text.trim().to_string()
709}
710
711fn site_class(document: &Document) -> String {
714 let mut class = String::from("site");
715 if !document.navbar.is_empty() {
716 class.push_str(" with-navbar");
717 }
718 if !document.sidebar {
719 class.push_str(" no-sidebar");
720 }
721 class
722}