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
44/// mode it keeps no live connection and shows no controls; with comments off
45/// (`devpage --no-comments`) it shows no comment threads and offers no way to
46/// start one.
47fn 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
61/// The whole page for one Markdown file of the site `document`: navigation,
62/// the file's `rendered` content and the scripts that mount its widgets and
63/// keep it live. `comments` is whether comments are on; `found` is the page's
64/// problems, listed above it. The navbar and the sidebar are drawn from one
65/// navigation tree, built once for the page. `None` for a file outside the
66/// served folder, which is never shown.
67pub 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
86/// The site `document`'s page for an address with nothing at it, `rendered`
87/// from the site's `404.md`. Shown at that address, not its own, so its
88/// relative links are pointed at their served addresses; it shows no
89/// comments and lists no problems — `devpage check` reports its own.
90pub 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
104/// A page the site `document` makes from something other than a file of its
105/// own — a code reference's — `rendered` at the address it is shown at, and
106/// the sidebar open at `current`: the page itself, or the nearest page above
107/// it the sidebar lists — listing `found` above it. It shows no comments,
108/// which belong to files.
109pub 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    // The page's own address, not the one the sidebar is open at.
127    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
136/// devpage's own page for `address`, with nothing at it, when the site
137/// `document` has no `404.md`: in the site's frame, as its `404.md` would be,
138/// offering `meant` — the address it most likely meant — and the site's root.
139pub 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
157/// devpage's own page for `asked`, an address with nothing at it, outside any site:
158/// alone, in the theme of `entry`, the served document, offering `meant` and
159/// where `/` leads.
160pub 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
184/// The heading of devpage's own page for an address with nothing at it.
185const NOT_FOUND: &str = "Page not found";
186
187/// What devpage's own page for `address` says: nothing is there, `meant` may
188/// be, and the way to `document`'s first page. Written as HTML, every part
189/// escaped: the address is whatever was asked for.
190fn 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
205/// A site page: the frame round `content`, the HTML of `file`, whose page is
206/// titled `page`. `None` for a file outside the served folder.
207fn 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, &current, comments),
247        sidebar = sidebar(document, &tree, &current),
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
266/// A package workspace uses the ordinary site frame and React lifecycle, with
267/// the available content area allocated to the tool instead of an article.
268pub 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
292/// A doc: every chapter's `rendered` content on one page, in order, with an
293/// outline of the chapters' headings beside them. In print mode the outline
294/// and the live connection are left out and the page size is the doc's paper.
295pub 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        // A link to a chapter lands on its section, which only needs an id
322        // when there is more than one — and then can't clash with a heading's,
323        // which carries the chapter's prefix.
324        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        // A lone Markdown file's title is its own first heading; don't repeat it.
380        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
395/// Several chapters share one page, so each one's ids are prefixed with its
396/// name — its file's stem — and links to a chapter or its headings point at
397/// those ids: each chapter, as the served folder names it, with its name.
398pub(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
413/// `chapter`'s name among `names`, as [`chapter_names`] made them; empty when
414/// it is not one of them.
415fn 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
426/// Prefixes a chapter's ids with its name and points links at the doc's ids:
427/// `#why` → `#context--why`, `rollout.md#steps` → `#rollout--steps`,
428/// `rollout.md` → `#rollout`.
429fn 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
467/// Points a file's relative links and images at their served addresses. A
468/// doc or a deck is served at its document file's address, so a chapter or
469/// slide from another folder would otherwise resolve its links against the
470/// wrong one.
471fn 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    // Attributes — a diagram's links among them, drawn already.
476    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            // A path from the top is an address already.
489            // A file outside the served folder has no address: the link
490            // keeps its target as written, and the check reports it.
491            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
511/// A document file that can't be loaded: a page listing what is wrong with
512/// it — `None` for a file outside the served folder, which is never shown.
513pub 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
541/// The page's problems, listed above it, with each broken link marked.
542fn 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    // The links as written, for the page script to mark where they stand.
551    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
560/// A deck: every slide's `rendered` content on its own 1920 × 1080 stage,
561/// scaled to the window as a whole, one shown at a time. In print mode each
562/// slide is one 16:9 page.
563pub 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
619/// The `h1` and `h2` headings of rendered HTML: level, id and text.
620fn 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
645/// `html`'s text with every tag left out, trimmed; entities stay as written.
646fn 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
660/// A site page's body classes, which name its frame: a page with another frame
661/// can't be swapped in part.
662fn 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}