Skip to main content

devpage_core/render/
frame.rs

1//! The frame each kind of document is shown in: a site's page, a doc's
2//! chapters on one page, a deck's slides, and the page for a document file
3//! that can't be loaded — with the problems listed above the content.
4
5use 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
16/// A site page's tab title: `<page> · <site>`, or just the site's name when
17/// the page is titled like it (trimmed, ignoring case).
18pub 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
27/// The page's `<html>` tag, carrying the served folder's mount when it has
28/// one, for the page script and the design script to ask their endpoints
29/// under.
30pub 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
37/// The page script's tag, for the head: deferred, so it is fetched with
38/// everything else the head names and runs once the page is parsed. In print mode it keeps no live connection and shows
39/// no controls; with comments off (`devpage --no-comments`) it shows no
40/// comment threads and offers no way to start one.
41fn 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
55/// The whole page for one Markdown file: navigation, the rendered content and
56/// the scripts that mount its widgets and keep it live. `comments` is whether
57/// comments are on.
58/// `found` is the page's problems, listed above it.
59pub 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, &current, comments),
93        sidebar = sidebar(document, &current),
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
112/// A doc: every chapter on one page, in order, with an outline of the
113/// chapters' headings beside them. In print mode the outline and the live
114/// connection are left out and the page size is the doc's paper.
115pub 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    // Several chapters share one page, so each one's ids are prefixed with its
127    // name, and links to a chapter or its headings point at those ids.
128    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        // A link to a chapter lands on its section, which only needs an id
156        // when there is more than one — and then can't clash with a heading's,
157        // which carries the chapter's prefix.
158        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        // A lone Markdown file's title is its own first heading; don't repeat it.
214        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
240/// Prefixes a chapter's ids with its name and points links at the doc's ids:
241/// `#why` → `#context--why`, `rollout.md#steps` → `#rollout--steps`,
242/// `rollout.md` → `#rollout`.
243fn 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
281/// Points a file's relative links and images at their served addresses. A
282/// doc or a deck is served at its document file's address, so a chapter or
283/// slide from another folder would otherwise resolve its links against the
284/// wrong one.
285fn 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    // Attributes — a diagram's links among them, drawn already.
290    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
317/// Resolves `.` and `..` in a path without touching the disk, so a link to a
318/// file that doesn't exist yet still gets an address (and a problem).
319fn 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
333/// A document file that can't be loaded: a page listing what is wrong with it.
334pub 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
362/// The page's problems, listed above it, with each broken link marked.
363fn 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    // The links as written, for the page script to mark where they stand.
372    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
381/// A deck: every slide on its own 1920 × 1080 stage, scaled to the window as a
382/// whole, one shown at a time. In print mode each slide is one 16:9 page.
383pub 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
440/// The `h1` and `h2` headings of rendered HTML: level, id and text.
441fn 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
480/// A site page's body classes, which name its frame: a page with another frame
481/// can't be swapped in part.
482fn 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}