Skip to main content

devpage_core/page/
frame.rs

1//! The frame phase: content put inside the frame its document is shown in —
2//! a site's page, a doc's chapters on one page, a deck's slides — with the
3//! problems found listed above it; and the page for a document file that
4//! can't be loaded.
5
6use 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
21/// A site page's tab title: `<page> · <site>`, or just the site's name when
22/// the page is titled like it (trimmed, ignoring case).
23pub(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
32/// The page's `<html>` tag, carrying the served folder's mount when it has
33/// one, for the page script and the design script to ask their endpoints
34/// under.
35pub(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
42/// The page script's tag, for the head: deferred, so it is fetched with
43/// everything else the head names and runs once the page is parsed. In print mode it keeps no live connection and shows
44/// no controls; with comments off (`devpage --no-comments`) it shows no
45/// comment threads and offers no way to start one.
46fn page_script(print: bool, comments: bool) -> String {
47    let setting = if print {
48        " data-print"
49    } else if !comments {
50        " data-no-comments"
51    } else {
52        ""
53    };
54    format!(
55        "<script defer fetchpriority=\"high\" src=\"{}\"{setting}></script>",
56        address(Owned::Asset("devpage.js"))
57    )
58}
59
60/// The whole page for one Markdown file of the site `document`: navigation,
61/// the file's `rendered` content and the scripts that mount its widgets and
62/// keep it live. `comments` is whether comments are on; `found` is the page's
63/// problems, listed above it. The navbar and the sidebar are drawn from one
64/// navigation tree, built once for the page. `None` for a file outside the
65/// served folder, which is never shown.
66pub fn page(
67    document: &Document,
68    widgets: &Widgets,
69    rendered: &Rendered,
70    comments: bool,
71    found: &[Problem],
72) -> Option<String> {
73    let _render = tracing::info_span!("render").entered();
74    let current = document.url(rendered.file())?;
75    let content = rendered.html();
76    let tree = if document.sidebar || !document.navbar.is_empty() {
77        nav::tree(document)
78    } else {
79        Vec::new()
80    };
81    Some(format!(
82        r#"<!doctype html>
83{html}
84<head>
85<meta charset="utf-8">
86<meta name="viewport" content="width=device-width, initial-scale=1">
87<title>{tab}</title>
88{theme}
89<link rel="stylesheet" href="{stylesheet}">
90{script}
91{widgets}
92</head>
93<body class="{body_class}" data-build="{build}">
94{navbar}{sidebar}{corner}
95<main id="devpage-page">{problems}<article data-source="{current}">{content}</article></main>
96</body>
97</html>"#,
98        html = html_open(&document.served),
99        stylesheet = address(Owned::Asset("style.css")),
100        build = crate::addresses::BUILD,
101        tab = escape(&tab_title(
102            &title(rendered.source(), rendered.file()),
103            &document.title
104        )),
105        theme = navbar::head(document),
106        body_class = site_class(document),
107        navbar = navbar::render(document, &tree, &current, comments),
108        sidebar = sidebar(document, &tree, &current),
109        script = page_script(false, comments),
110        corner = if document.navbar.is_empty() {
111            navbar::corner(document, comments)
112        } else {
113            String::new()
114        },
115        problems = problems(found),
116        widgets = widgets.head(
117            content,
118            if document.sidebar {
119                &[crate::widgets::SIDEBAR]
120            } else {
121                &[]
122            }
123        ),
124    ))
125}
126
127/// A doc: every chapter's `rendered` content on one page, in order, with an
128/// outline of the chapters' headings beside them. In print mode the outline
129/// and the live connection are left out and the page size is the doc's paper.
130pub fn doc(
131    document: &Document,
132    widgets: &Widgets,
133    chapters: &[Rendered],
134    pdf: &Pdf,
135    print: bool,
136    comments: bool,
137    found: &[Problem],
138) -> String {
139    let _render = tracing::info_span!("render").entered();
140    let mut content = String::new();
141    let mut outline = String::new();
142    let files: Vec<PathBuf> = chapters.iter().map(|c| c.file().to_path_buf()).collect();
143    let names = chapter_names(&files, &document.served);
144    for rendered in chapters {
145        let chapter = rendered.file();
146        let mut html = rendered.html().to_string();
147        if chapters.len() > 1 {
148            html = scope_ids(&html, chapter, &names, &document.served);
149        }
150        let html = rebase(&html, chapter, document);
151        for (level, id, text) in headings(&html) {
152            outline.push_str(&format!(
153                "<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
154            ));
155        }
156        // A link to a chapter lands on its section, which only needs an id
157        // when there is more than one — and then can't clash with a heading's,
158        // which carries the chapter's prefix.
159        let id = if chapters.len() > 1 {
160            format!(
161                " id=\"{}\"",
162                chapter_name(chapter, &names, &document.served)
163            )
164        } else {
165            String::new()
166        };
167        content.push_str(&format!(
168            "<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
169            document.part_url(chapter)
170        ));
171    }
172    let paper = match pdf.paper {
173        Paper::A4 => "A4",
174        Paper::Letter => "letter",
175    };
176    let outline = if print {
177        String::new()
178    } else {
179        format!(
180            "<nav id=\"devpage-nav\" class=\"outline\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
181            navbar::logo(document),
182            escape(&document.title)
183        )
184    };
185    format!(
186        r#"<!doctype html>
187{html}
188<head>
189<meta charset="utf-8">
190<meta name="viewport" content="width=device-width, initial-scale=1">
191<title>{title}</title>
192{theme}
193<link rel="stylesheet" href="{stylesheet}">
194{script}
195{widgets}
196<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
197</head>
198<body class="doc{print_class}" data-build="{build}">
199{corner}{outline}
200<main id="devpage-page">{problems}<article>{heading}{content}</article></main>
201</body>
202</html>"#,
203        html = html_open(&document.served),
204        stylesheet = address(Owned::Asset("style.css")),
205        build = crate::addresses::BUILD,
206        title = escape(&document.title),
207        theme = navbar::head(document),
208        corner = if print {
209            String::new()
210        } else {
211            navbar::corner(document, comments)
212        },
213        widgets = widgets.head(&content, &[]),
214        // A lone Markdown file's title is its own first heading; don't repeat it.
215        heading = if document.file_name.ends_with(".md") {
216            String::new()
217        } else {
218            format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
219        },
220        print_class = if print { " print" } else { "" },
221        script = page_script(print, comments),
222        problems = if print {
223            String::new()
224        } else {
225            problems(found)
226        },
227    )
228}
229
230/// Several chapters share one page, so each one's ids are prefixed with its
231/// name — its file's stem — and links to a chapter or its headings point at
232/// those ids: each chapter, as the served folder names it, with its name.
233pub(super) fn chapter_names(chapters: &[PathBuf], served: &ServedFolder) -> Vec<(PathBuf, String)> {
234    chapters
235        .iter()
236        .map(|chapter| {
237            let canonical = served.inside(chapter).unwrap_or_else(|| chapter.clone());
238            let name = chapter
239                .file_stem()
240                .unwrap_or_default()
241                .to_string_lossy()
242                .into_owned();
243            (canonical, name)
244        })
245        .collect()
246}
247
248fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
249    let canonical = served
250        .inside(chapter)
251        .unwrap_or_else(|| chapter.to_path_buf());
252    names
253        .iter()
254        .find(|(path, _)| *path == canonical)
255        .map(|(_, name)| name.clone())
256        .unwrap_or_default()
257}
258
259/// Prefixes a chapter's ids with its name and points links at the doc's ids:
260/// `#why` → `#context--why`, `rollout.md#steps` → `#rollout--steps`,
261/// `rollout.md` → `#rollout`.
262fn scope_ids(
263    html: &str,
264    chapter: &Path,
265    names: &[(PathBuf, String)],
266    served: &ServedFolder,
267) -> String {
268    let own = chapter_name(chapter, names, served);
269    let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
270    let mut out = String::new();
271    let mut rest = html.as_str();
272    while let Some(at) = rest.find(" href=\"") {
273        out.push_str(&rest[..at + 7]);
274        rest = &rest[at + 7..];
275        let end = rest.find('"').unwrap_or(rest.len());
276        let href = &rest[..end];
277        let target = match Link::classify(href) {
278            Link::File { path: "", fragment } => Some((own.clone(), fragment)),
279            Link::File { path, fragment } => {
280                let resolved =
281                    served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
282                names
283                    .iter()
284                    .find(|(file, _)| Some(file) == resolved.as_ref())
285                    .map(|(_, name)| (name.clone(), fragment))
286            }
287            Link::Web(_) | Link::Elsewhere => None,
288        };
289        match target {
290            Some((name, "")) => out.push_str(&format!("#{name}")),
291            Some((name, fragment)) => out.push_str(&format!("#{name}--{fragment}")),
292            None => out.push_str(href),
293        }
294        rest = &rest[end..];
295    }
296    out.push_str(rest);
297    out
298}
299
300/// Points a file's relative links and images at their served addresses. A
301/// doc or a deck is served at its document file's address, so a chapter or
302/// slide from another folder would otherwise resolve its links against the
303/// wrong one.
304fn rebase(html: &str, file: &Path, document: &Document) -> String {
305    let folder = file.parent().unwrap_or(Path::new("."));
306    let mut out = String::new();
307    let mut rest = html;
308    // Attributes — a diagram's links among them, drawn already.
309    const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
310    loop {
311        let next = STARTS
312            .iter()
313            .filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
314            .min();
315        let Some((start, close)) = next else { break };
316        out.push_str(&rest[..start]);
317        rest = &rest[start..];
318        let end = rest.find(close).unwrap_or(rest.len());
319        let value = &rest[..end];
320        match Link::classify(value) {
321            // A path from the top is an address already.
322            // A file outside the served folder has no address: the link
323            // keeps its target as written, and the check reports it.
324            Link::File { path, fragment } if !path.is_empty() && !path.starts_with('/') => {
325                match document.url(&lexical(&folder.join(path))) {
326                    Some(address) => {
327                        out.push_str(&address);
328                        if value.contains('#') {
329                            out.push('#');
330                            out.push_str(fragment);
331                        }
332                    }
333                    None => out.push_str(value),
334                }
335            }
336            _ => out.push_str(value),
337        }
338        rest = &rest[end..];
339    }
340    out.push_str(rest);
341    out
342}
343
344/// A document file that can't be loaded: a page listing what is wrong with
345/// it — `None` for a file outside the served folder, which is never shown.
346pub fn invalid(entry: &Document, file: &Path, error: &str) -> Option<String> {
347    let address = entry.url(file)?;
348    Some(format!(
349        r#"<!doctype html>
350{html}
351<head>
352<meta charset="utf-8">
353<meta name="viewport" content="width=device-width, initial-scale=1">
354<title>{address} · {document}</title>
355{theme}
356<link rel="stylesheet" href="{stylesheet}">
357{page_script}
358</head>
359<body class="invalid" data-build="{build}">
360<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
361</body>
362</html>"#,
363        html = html_open(&entry.served),
364        stylesheet = crate::addresses::address(Owned::Asset("style.css")),
365        build = crate::addresses::BUILD,
366        page_script = page_script(false, true),
367        address = escape(&address),
368        document = escape(&entry.title),
369        theme = navbar::head(entry),
370        error = escape(error),
371    ))
372}
373
374/// The page's problems, listed above it, with each broken link marked.
375fn problems(found: &[Problem]) -> String {
376    if found.is_empty() {
377        return String::new();
378    }
379    let items: String = found
380        .iter()
381        .map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
382        .collect();
383    // The links as written, for the page script to mark where they stand.
384    let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
385    format!(
386        "<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
387        escape(&serde_json::to_string(&broken).unwrap_or_default()),
388        found.len(),
389        if found.len() == 1 { "" } else { "s" }
390    )
391}
392
393/// A deck: every slide's `rendered` content on its own 1920 × 1080 stage,
394/// scaled to the window as a whole, one shown at a time. In print mode each
395/// slide is one 16:9 page.
396pub fn slides(
397    document: &Document,
398    widgets: &Widgets,
399    slides: &[Rendered],
400    print: bool,
401    comments: bool,
402    found: &[Problem],
403) -> String {
404    let _render = tracing::info_span!("render").entered();
405    let mut content = String::new();
406    for (index, slide) in slides.iter().enumerate() {
407        content.push_str(&format!(
408            "<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
409            index + 1,
410            document.part_url(slide.file()),
411            rebase(slide.html(), slide.file(), document)
412        ));
413    }
414    format!(
415        r#"<!doctype html>
416{html}
417<head>
418<meta charset="utf-8">
419<meta name="viewport" content="width=device-width, initial-scale=1">
420<title>{title}</title>
421{theme}
422<link rel="stylesheet" href="{stylesheet}">
423{script}
424{widgets}
425<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
426</head>
427<body class="slides{print_class}" data-build="{build}">
428{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
429</body>
430</html>"#,
431        html = html_open(&document.served),
432        stylesheet = address(Owned::Asset("style.css")),
433        build = crate::addresses::BUILD,
434        title = escape(&document.title),
435        theme = navbar::head(document),
436        corner = if print {
437            String::new()
438        } else {
439            navbar::corner(document, comments)
440        },
441        widgets = widgets.head(&content, &[]),
442        print_class = if print { " print" } else { "" },
443        script = page_script(print, comments),
444        problems = if print {
445            String::new()
446        } else {
447            problems(found)
448        },
449    )
450}
451
452/// The `h1` and `h2` headings of rendered HTML: level, id and text.
453fn headings(html: &str) -> Vec<(u8, String, String)> {
454    let mut found = Vec::new();
455    let mut rest = html;
456    while let Some(start) = rest.find("<h") {
457        rest = &rest[start + 2..];
458        let level = rest.as_bytes().first().copied().unwrap_or(0);
459        if level != b'1' && level != b'2' {
460            continue;
461        }
462        let close = format!("</h{}>", level as char);
463        let Some(end) = rest.find(&close) else { break };
464        let inner = &rest[..end];
465        let id = inner
466            .split("id=\"")
467            .nth(1)
468            .and_then(|tail| tail.split('"').next())
469            .unwrap_or_default()
470            .to_string();
471        let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
472        found.push((level - b'0', id, text));
473        rest = &rest[end..];
474    }
475    found
476}
477
478fn strip_tags(html: &str) -> String {
479    let mut text = String::new();
480    let mut in_tag = false;
481    for c in html.chars() {
482        match c {
483            '<' => in_tag = true,
484            '>' => in_tag = false,
485            c if !in_tag => text.push(c),
486            _ => {}
487        }
488    }
489    text.trim().to_string()
490}
491
492/// A site page's body classes, which name its frame: a page with another frame
493/// can't be swapped in part.
494fn site_class(document: &Document) -> String {
495    let mut class = String::from("site");
496    if !document.navbar.is_empty() {
497        class.push_str(" with-navbar");
498    }
499    if !document.sidebar {
500        class.push_str(" no-sidebar");
501    }
502    class
503}