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}{navigator}{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 navigator = navigator(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
266fn navigator(document: &Document, tree: &[nav::Group], current: &str) -> String {
272 let links = navbar::navigator_links(document, tree, current);
273 let sidebar = sidebar(document, tree, current);
274 if links.is_empty() && sidebar.is_empty() {
275 return String::new();
276 }
277 format!("<div id=\"devpage-navigator\" class=\"navigator\">{links}{sidebar}</div>")
278}
279
280pub fn workspace(
283 document: &Document,
284 widgets: &Widgets,
285 _file: &Path,
286 title: &str,
287 content: &str,
288 comments: bool,
289) -> String {
290 format!(
291 r#"<!doctype html>
292{html}<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
293<title>{title}</title>{theme}<link rel="stylesheet" href="{style}">{script}{widgets}</head>
294<body class="site no-sidebar devpage-workspace" data-build="{build}">
295<main id="devpage-page">{content}</main></body></html>"#,
296 html = html_open(&document.served),
297 title = escape(&tab_title(title, &document.title)),
298 theme = navbar::head(document),
299 style = address(Owned::Asset("style.css")),
300 script = page_script(false, comments),
301 widgets = widgets.head(content, &[]),
302 build = crate::addresses::BUILD,
303 )
304}
305
306pub fn doc(
310 document: &Document,
311 widgets: &Widgets,
312 chapters: &[Rendered],
313 pdf: &Pdf,
314 print: bool,
315 comments: bool,
316 found: &[Problem],
317) -> String {
318 let _render = tracing::info_span!("render").entered();
319 let mut content = String::new();
320 let mut outline = String::new();
321 let files: Vec<PathBuf> = chapters.iter().map(|c| c.file().to_path_buf()).collect();
322 let names = chapter_names(&files, &document.served);
323 for rendered in chapters {
324 let chapter = rendered.file();
325 let mut html = rendered.html().to_string();
326 if chapters.len() > 1 {
327 html = scope_ids(&html, chapter, &names, &document.served);
328 }
329 let html = rebase(&html, chapter, document);
330 for (level, id, text) in headings(&html) {
331 outline.push_str(&format!(
332 "<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
333 ));
334 }
335 let id = if chapters.len() > 1 {
339 format!(
340 " id=\"{}\"",
341 chapter_name(chapter, &names, &document.served)
342 )
343 } else {
344 String::new()
345 };
346 content.push_str(&format!(
347 "<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
348 document.part_url(chapter)
349 ));
350 }
351 let paper = match pdf.paper {
352 Paper::A4 => "A4",
353 Paper::Letter => "letter",
354 };
355 let outline = if print {
356 String::new()
357 } else {
358 format!(
359 "<nav id=\"devpage-nav\" class=\"outline navigator\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
360 navbar::logo(document),
361 escape(&document.title)
362 )
363 };
364 format!(
365 r#"<!doctype html>
366{html}
367<head>
368<meta charset="utf-8">
369<meta name="viewport" content="width=device-width, initial-scale=1">
370<title>{title}</title>
371{theme}
372<link rel="stylesheet" href="{stylesheet}">
373{script}
374{widgets}
375<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
376</head>
377<body class="doc{print_class}" data-build="{build}">
378{corner}{outline}
379<main id="devpage-page">{problems}<article>{heading}{content}</article></main>
380</body>
381</html>"#,
382 html = html_open(&document.served),
383 stylesheet = address(Owned::Asset("style.css")),
384 build = crate::addresses::BUILD,
385 title = escape(&document.title),
386 theme = navbar::head(document),
387 corner = if print {
388 String::new()
389 } else {
390 navbar::corner(document, comments)
391 },
392 widgets = widgets.head(&content, &[]),
393 heading = if document.file_name.ends_with(".md") {
395 String::new()
396 } else {
397 format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
398 },
399 print_class = if print { " print" } else { "" },
400 script = page_script(print, comments),
401 problems = if print {
402 String::new()
403 } else {
404 problems(found)
405 },
406 )
407}
408
409pub(super) fn chapter_names(chapters: &[PathBuf], served: &ServedFolder) -> Vec<(PathBuf, String)> {
413 chapters
414 .iter()
415 .map(|chapter| {
416 let canonical = served.inside(chapter).unwrap_or_else(|| chapter.clone());
417 let name = chapter
418 .file_stem()
419 .unwrap_or_default()
420 .to_string_lossy()
421 .into_owned();
422 (canonical, name)
423 })
424 .collect()
425}
426
427fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
430 let canonical = served
431 .inside(chapter)
432 .unwrap_or_else(|| chapter.to_path_buf());
433 names
434 .iter()
435 .find(|(path, _)| *path == canonical)
436 .map(|(_, name)| name.clone())
437 .unwrap_or_default()
438}
439
440fn scope_ids(
444 html: &str,
445 chapter: &Path,
446 names: &[(PathBuf, String)],
447 served: &ServedFolder,
448) -> String {
449 let own = chapter_name(chapter, names, served);
450 let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
451 let mut out = String::new();
452 let mut rest = html.as_str();
453 while let Some(at) = rest.find(" href=\"") {
454 out.push_str(&rest[..at + 7]);
455 rest = &rest[at + 7..];
456 let end = rest.find('"').unwrap_or(rest.len());
457 let href = &rest[..end];
458 let target = match Link::classify(href) {
459 Link::File { path: "", fragment } => Some((own.clone(), fragment)),
460 Link::File { path, fragment } => {
461 let resolved =
462 served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
463 names
464 .iter()
465 .find(|(file, _)| Some(file) == resolved.as_ref())
466 .map(|(_, name)| (name.clone(), fragment))
467 }
468 Link::Web(_) | Link::Elsewhere => None,
469 };
470 match target {
471 Some((name, "")) => out.push_str(&format!("#{name}")),
472 Some((name, fragment)) => out.push_str(&format!("#{name}--{fragment}")),
473 None => out.push_str(href),
474 }
475 rest = &rest[end..];
476 }
477 out.push_str(rest);
478 out
479}
480
481fn rebase(html: &str, file: &Path, document: &Document) -> String {
486 let folder = file.parent().unwrap_or(Path::new("."));
487 let mut out = String::new();
488 let mut rest = html;
489 const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
491 loop {
492 let next = STARTS
493 .iter()
494 .filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
495 .min();
496 let Some((start, close)) = next else { break };
497 out.push_str(&rest[..start]);
498 rest = &rest[start..];
499 let end = rest.find(close).unwrap_or(rest.len());
500 let value = &rest[..end];
501 match Link::classify(value) {
502 Link::File { path, fragment } if !path.is_empty() && !path.starts_with('/') => {
506 match document.url(&lexical(&folder.join(path))) {
507 Some(address) => {
508 out.push_str(&address);
509 if value.contains('#') {
510 out.push('#');
511 out.push_str(fragment);
512 }
513 }
514 None => out.push_str(value),
515 }
516 }
517 _ => out.push_str(value),
518 }
519 rest = &rest[end..];
520 }
521 out.push_str(rest);
522 out
523}
524
525pub fn invalid(entry: &Document, file: &Path, error: &str) -> Option<String> {
528 let address = entry.url(file)?;
529 Some(format!(
530 r#"<!doctype html>
531{html}
532<head>
533<meta charset="utf-8">
534<meta name="viewport" content="width=device-width, initial-scale=1">
535<title>{address} · {document}</title>
536{theme}
537<link rel="stylesheet" href="{stylesheet}">
538{page_script}
539</head>
540<body class="invalid" data-build="{build}">
541<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
542</body>
543</html>"#,
544 html = html_open(&entry.served),
545 stylesheet = crate::addresses::address(Owned::Asset("style.css")),
546 build = crate::addresses::BUILD,
547 page_script = page_script(false, true),
548 address = escape(&address),
549 document = escape(&entry.title),
550 theme = navbar::head(entry),
551 error = escape(error),
552 ))
553}
554
555fn problems(found: &[Problem]) -> String {
557 if found.is_empty() {
558 return String::new();
559 }
560 let items: String = found
561 .iter()
562 .map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
563 .collect();
564 let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
566 format!(
567 "<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
568 escape(&serde_json::to_string(&broken).unwrap_or_default()),
569 found.len(),
570 if found.len() == 1 { "" } else { "s" }
571 )
572}
573
574pub fn slides(
578 document: &Document,
579 widgets: &Widgets,
580 slides: &[Rendered],
581 print: bool,
582 comments: bool,
583 found: &[Problem],
584) -> String {
585 let _render = tracing::info_span!("render").entered();
586 let mut content = String::new();
587 for (index, slide) in slides.iter().enumerate() {
588 content.push_str(&format!(
589 "<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
590 index + 1,
591 document.part_url(slide.file()),
592 rebase(slide.html(), slide.file(), document)
593 ));
594 }
595 format!(
596 r#"<!doctype html>
597{html}
598<head>
599<meta charset="utf-8">
600<meta name="viewport" content="width=device-width, initial-scale=1">
601<title>{title}</title>
602{theme}
603<link rel="stylesheet" href="{stylesheet}">
604{script}
605{widgets}
606<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
607</head>
608<body class="slides{print_class}" data-build="{build}">
609{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
610</body>
611</html>"#,
612 html = html_open(&document.served),
613 stylesheet = address(Owned::Asset("style.css")),
614 build = crate::addresses::BUILD,
615 title = escape(&document.title),
616 theme = navbar::head(document),
617 corner = if print {
618 String::new()
619 } else {
620 navbar::corner(document, comments)
621 },
622 widgets = widgets.head(&content, &[]),
623 print_class = if print { " print" } else { "" },
624 script = page_script(print, comments),
625 problems = if print {
626 String::new()
627 } else {
628 problems(found)
629 },
630 )
631}
632
633fn headings(html: &str) -> Vec<(u8, String, String)> {
635 let mut found = Vec::new();
636 let mut rest = html;
637 while let Some(start) = rest.find("<h") {
638 rest = &rest[start + 2..];
639 let level = rest.as_bytes().first().copied().unwrap_or(0);
640 if level != b'1' && level != b'2' {
641 continue;
642 }
643 let close = format!("</h{}>", level as char);
644 let Some(end) = rest.find(&close) else { break };
645 let inner = &rest[..end];
646 let id = inner
647 .split("id=\"")
648 .nth(1)
649 .and_then(|tail| tail.split('"').next())
650 .unwrap_or_default()
651 .to_string();
652 let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
653 found.push((level - b'0', id, text));
654 rest = &rest[end..];
655 }
656 found
657}
658
659fn strip_tags(html: &str) -> String {
661 let mut text = String::new();
662 let mut in_tag = false;
663 for c in html.chars() {
664 match c {
665 '<' => in_tag = true,
666 '>' => in_tag = false,
667 c if !in_tag => text.push(c),
668 _ => {}
669 }
670 }
671 text.trim().to_string()
672}
673
674fn site_class(document: &Document) -> String {
677 let mut class = String::from("site");
678 if !document.navbar.is_empty() {
679 class.push_str(" with-navbar");
680 }
681 if !document.sidebar {
682 class.push_str(" no-sidebar");
683 }
684 class
685}