devpage-core 0.3.0

devpage's core: documents, rendering, link checking, comments and designs, with no I/O runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! The frame phase: content put inside the frame its document is shown in —
//! a site's page, a doc's chapters on one page, a deck's slides — with the
//! problems found listed above it; and the page for a document file that
//! can't be loaded.

use std::path::{Path, PathBuf};

use crate::addresses::{Owned, address};
use crate::document::{Document, Paper, Pdf};
use crate::folder::{ServedFolder, lexical};
use crate::html::{Link, escape};
use crate::markup::title;
use crate::nav;
use crate::problem::Problem;
use crate::widgets::Widgets;

use super::content::Rendered;
use super::navbar;
use super::sidebar::sidebar;

/// A site page's tab title: `<page> · <site>`, or just the site's name when
/// the page is titled like it (trimmed, ignoring case).
pub(super) fn tab_title(page: &str, site: &str) -> String {
    let (page, site) = (page.trim(), site.trim());
    if page.to_lowercase() == site.to_lowercase() {
        site.to_string()
    } else {
        format!("{page} · {site}")
    }
}

/// The page's `<html>` tag, carrying the served folder's mount when it has
/// one, for the page script and the design script to ask their endpoints
/// under.
pub(super) fn html_open(served: &ServedFolder) -> String {
    match served.mount() {
        "" => r#"<html lang="en">"#.to_string(),
        mount => format!(r#"<html lang="en" data-mount="{}">"#, escape(mount)),
    }
}

/// The page script's tag, for the head: deferred, so it is fetched with
/// everything else the head names and runs once the page is parsed. In print
/// mode it keeps no live connection and shows no controls; with comments off
/// (`devpage --no-comments`) it shows no comment threads and offers no way to
/// start one.
fn page_script(print: bool, comments: bool) -> String {
    let setting = if print {
        " data-print"
    } else if !comments {
        " data-no-comments"
    } else {
        ""
    };
    format!(
        "<script defer fetchpriority=\"high\" src=\"{}\"{setting}></script>",
        address(Owned::Asset("devpage.js"))
    )
}

/// The whole page for one Markdown file of the site `document`: navigation,
/// the file's `rendered` content and the scripts that mount its widgets and
/// keep it live. `comments` is whether comments are on; `found` is the page's
/// problems, listed above it. The navbar and the sidebar are drawn from one
/// navigation tree, built once for the page. `None` for a file outside the
/// served folder, which is never shown.
pub fn page(
    document: &Document,
    widgets: &Widgets,
    rendered: &Rendered,
    comments: bool,
    found: &[Problem],
) -> Option<String> {
    let page = title(rendered.source(), rendered.file());
    framed(
        document,
        widgets,
        rendered.file(),
        &page,
        rendered.html(),
        comments,
        found,
    )
}

/// The site `document`'s page for an address with nothing at it, `rendered`
/// from the site's `404.md`. Shown at that address, not its own, so its
/// relative links are pointed at their served addresses; it shows no
/// comments and lists no problems — `devpage check` reports its own.
pub fn missing(document: &Document, widgets: &Widgets, rendered: &Rendered) -> Option<String> {
    let page = title(rendered.source(), rendered.file());
    let content = rebase(rendered.html(), rendered.file(), document);
    framed(
        document,
        widgets,
        rendered.file(),
        &page,
        &content,
        false,
        &[],
    )
}

/// A page the site `document` makes from something other than a file of its
/// own — a code reference's — `rendered` at the address it is shown at, and
/// the sidebar open at `current`: the page itself, or the nearest page above
/// it the sidebar lists — listing `found` above it. It shows no comments,
/// which belong to files.
pub fn generated(
    document: &Document,
    widgets: &Widgets,
    rendered: &Rendered,
    current: &Path,
    found: &[Problem],
) -> Option<String> {
    let page = title(rendered.source(), rendered.file());
    let html = framed(
        document,
        widgets,
        current,
        &page,
        rendered.html(),
        false,
        found,
    )?;
    // The page's own address, not the one the sidebar is open at.
    let shown = document.url(current)?;
    let own = document.url(rendered.file())?;
    Some(html.replacen(
        &format!("<article data-source=\"{}\">", escape(&shown)),
        &format!("<article data-source=\"{}\">", escape(&own)),
        1,
    ))
}

/// devpage's own page for `address`, with nothing at it, when the site
/// `document` has no `404.md`: in the site's frame, as its `404.md` would be,
/// offering `meant` — the address it most likely meant — and the site's root.
pub fn nothing_at(
    document: &Document,
    widgets: &Widgets,
    address: &str,
    meant: Option<&str>,
) -> Option<String> {
    let content = nothing_at_content(document, address, meant);
    framed(
        document,
        widgets,
        &document.base.join("404.md"),
        NOT_FOUND,
        &content,
        false,
        &[],
    )
}

/// devpage's own page for `asked`, an address with nothing at it, outside any site:
/// alone, in the theme of `entry`, the served document, offering `meant` and
/// where `/` leads.
pub fn nothing_at_alone(entry: &Document, asked: &str, meant: Option<&str>) -> String {
    format!(
        r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{NOT_FOUND} · {document}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
</head>
<body class="missing" data-build="{build}">
<main id="devpage-page"><article>{content}</article></main>
</body>
</html>"#,
        html = html_open(&entry.served),
        stylesheet = address(Owned::Asset("style.css")),
        build = crate::addresses::BUILD,
        document = escape(&entry.title),
        theme = navbar::head(entry),
        content = nothing_at_content(entry, asked, meant),
    )
}

/// The heading of devpage's own page for an address with nothing at it.
const NOT_FOUND: &str = "Page not found";

/// What devpage's own page for `address` says: nothing is there, `meant` may
/// be, and the way to `document`'s first page. Written as HTML, every part
/// escaped: the address is whatever was asked for.
fn nothing_at_content(document: &Document, address: &str, meant: Option<&str>) -> String {
    let meant = meant.map_or_else(String::new, |meant| {
        format!(
            r#"<p>Did you mean <a href="{0}">{0}</a>?</p>"#,
            escape(meant)
        )
    });
    format!(
        r#"<h1>{NOT_FOUND}</h1><p>There is nothing at <code>{address}</code>.</p>{meant}<p><a href="{home}">Go to {title}</a></p>"#,
        address = escape(address),
        home = escape(&document.entry()),
        title = escape(&document.title),
    )
}

/// A site page: the frame round `content`, the HTML of `file`, whose page is
/// titled `page`. `None` for a file outside the served folder.
fn framed(
    document: &Document,
    widgets: &Widgets,
    file: &Path,
    page: &str,
    content: &str,
    comments: bool,
    found: &[Problem],
) -> Option<String> {
    let _render = tracing::info_span!("render").entered();
    let current = document.url(file)?;
    let tree = if document.sidebar || !document.navbar.is_empty() {
        nav::tree(document)
    } else {
        Vec::new()
    };
    Some(format!(
        r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{tab}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{script}
{widgets}
</head>
<body class="{body_class}" data-build="{build}">
{navbar}{sidebar}{corner}
<main id="devpage-page">{problems}<article data-source="{current}">{content}</article></main>
</body>
</html>"#,
        html = html_open(&document.served),
        stylesheet = address(Owned::Asset("style.css")),
        build = crate::addresses::BUILD,
        tab = escape(&tab_title(page, &document.title)),
        theme = navbar::head(document),
        body_class = site_class(document),
        navbar = navbar::render(document, &tree, &current, comments),
        sidebar = sidebar(document, &tree, &current),
        script = page_script(false, comments),
        corner = if document.navbar.is_empty() {
            navbar::corner(document, comments)
        } else {
            String::new()
        },
        problems = problems(found),
        widgets = widgets.head(
            content,
            if document.sidebar {
                &[crate::widgets::SIDEBAR]
            } else {
                &[]
            }
        ),
    ))
}

/// A package workspace uses the ordinary site frame and React lifecycle, with
/// the available content area allocated to the tool instead of an article.
pub fn workspace(
    document: &Document,
    widgets: &Widgets,
    _file: &Path,
    title: &str,
    content: &str,
    comments: bool,
) -> String {
    format!(
        r#"<!doctype html>
{html}<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>{theme}<link rel="stylesheet" href="{style}">{script}{widgets}</head>
<body class="site no-sidebar devpage-workspace" data-build="{build}">
<main id="devpage-page">{content}</main></body></html>"#,
        html = html_open(&document.served),
        title = escape(&tab_title(title, &document.title)),
        theme = navbar::head(document),
        style = address(Owned::Asset("style.css")),
        script = page_script(false, comments),
        widgets = widgets.head(content, &[]),
        build = crate::addresses::BUILD,
    )
}

/// A doc: every chapter's `rendered` content on one page, in order, with an
/// outline of the chapters' headings beside them. In print mode the outline
/// and the live connection are left out and the page size is the doc's paper.
pub fn doc(
    document: &Document,
    widgets: &Widgets,
    chapters: &[Rendered],
    pdf: &Pdf,
    print: bool,
    comments: bool,
    found: &[Problem],
) -> String {
    let _render = tracing::info_span!("render").entered();
    let mut content = String::new();
    let mut outline = String::new();
    let files: Vec<PathBuf> = chapters.iter().map(|c| c.file().to_path_buf()).collect();
    let names = chapter_names(&files, &document.served);
    for rendered in chapters {
        let chapter = rendered.file();
        let mut html = rendered.html().to_string();
        if chapters.len() > 1 {
            html = scope_ids(&html, chapter, &names, &document.served);
        }
        let html = rebase(&html, chapter, document);
        for (level, id, text) in headings(&html) {
            outline.push_str(&format!(
                "<li class=\"h{level}\"><a href=\"#{id}\">{text}</a></li>"
            ));
        }
        // A link to a chapter lands on its section, which only needs an id
        // when there is more than one — and then can't clash with a heading's,
        // which carries the chapter's prefix.
        let id = if chapters.len() > 1 {
            format!(
                " id=\"{}\"",
                chapter_name(chapter, &names, &document.served)
            )
        } else {
            String::new()
        };
        content.push_str(&format!(
            "<section class=\"chapter\"{id} data-source=\"{}\">{html}</section>",
            document.part_url(chapter)
        ));
    }
    let paper = match pdf.paper {
        Paper::A4 => "A4",
        Paper::Letter => "letter",
    };
    let outline = if print {
        String::new()
    } else {
        format!(
            "<nav id=\"devpage-nav\" class=\"outline\"><a class=\"document-title current\" href=\"#\">{}{}</a><ul>{outline}</ul></nav>",
            navbar::logo(document),
            escape(&document.title)
        )
    };
    format!(
        r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{script}
{widgets}
<style>@page {{ size: {paper}; margin: 22mm 18mm; }}</style>
</head>
<body class="doc{print_class}" data-build="{build}">
{corner}{outline}
<main id="devpage-page">{problems}<article>{heading}{content}</article></main>
</body>
</html>"#,
        html = html_open(&document.served),
        stylesheet = address(Owned::Asset("style.css")),
        build = crate::addresses::BUILD,
        title = escape(&document.title),
        theme = navbar::head(document),
        corner = if print {
            String::new()
        } else {
            navbar::corner(document, comments)
        },
        widgets = widgets.head(&content, &[]),
        // A lone Markdown file's title is its own first heading; don't repeat it.
        heading = if document.file_name.ends_with(".md") {
            String::new()
        } else {
            format!("<p class=\"doc-title\">{}</p>", escape(&document.title))
        },
        print_class = if print { " print" } else { "" },
        script = page_script(print, comments),
        problems = if print {
            String::new()
        } else {
            problems(found)
        },
    )
}

/// Several chapters share one page, so each one's ids are prefixed with its
/// name — its file's stem — and links to a chapter or its headings point at
/// those ids: each chapter, as the served folder names it, with its name.
pub(super) fn chapter_names(chapters: &[PathBuf], served: &ServedFolder) -> Vec<(PathBuf, String)> {
    chapters
        .iter()
        .map(|chapter| {
            let canonical = served.inside(chapter).unwrap_or_else(|| chapter.clone());
            let name = chapter
                .file_stem()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();
            (canonical, name)
        })
        .collect()
}

/// `chapter`'s name among `names`, as [`chapter_names`] made them; empty when
/// it is not one of them.
fn chapter_name(chapter: &Path, names: &[(PathBuf, String)], served: &ServedFolder) -> String {
    let canonical = served
        .inside(chapter)
        .unwrap_or_else(|| chapter.to_path_buf());
    names
        .iter()
        .find(|(path, _)| *path == canonical)
        .map(|(_, name)| name.clone())
        .unwrap_or_default()
}

/// Prefixes a chapter's ids with its name and points links at the doc's ids:
/// `#why` → `#context--why`, `rollout.md#steps` → `#rollout--steps`,
/// `rollout.md` → `#rollout`.
fn scope_ids(
    html: &str,
    chapter: &Path,
    names: &[(PathBuf, String)],
    served: &ServedFolder,
) -> String {
    let own = chapter_name(chapter, names, served);
    let html = html.replace(" id=\"", &format!(" id=\"{own}--"));
    let mut out = String::new();
    let mut rest = html.as_str();
    while let Some(at) = rest.find(" href=\"") {
        out.push_str(&rest[..at + 7]);
        rest = &rest[at + 7..];
        let end = rest.find('"').unwrap_or(rest.len());
        let href = &rest[..end];
        let target = match Link::classify(href) {
            Link::File { path: "", fragment } => Some((own.clone(), fragment)),
            Link::File { path, fragment } => {
                let resolved =
                    served.inside(&chapter.parent().unwrap_or(Path::new(".")).join(path));
                names
                    .iter()
                    .find(|(file, _)| Some(file) == resolved.as_ref())
                    .map(|(_, name)| (name.clone(), fragment))
            }
            Link::Web(_) | Link::Elsewhere => None,
        };
        match target {
            Some((name, "")) => out.push_str(&format!("#{name}")),
            Some((name, fragment)) => out.push_str(&format!("#{name}--{fragment}")),
            None => out.push_str(href),
        }
        rest = &rest[end..];
    }
    out.push_str(rest);
    out
}

/// Points a file's relative links and images at their served addresses. A
/// doc or a deck is served at its document file's address, so a chapter or
/// slide from another folder would otherwise resolve its links against the
/// wrong one.
fn rebase(html: &str, file: &Path, document: &Document) -> String {
    let folder = file.parent().unwrap_or(Path::new("."));
    let mut out = String::new();
    let mut rest = html;
    // Attributes — a diagram's links among them, drawn already.
    const STARTS: [(&str, &str); 2] = [(" href=\"", "\""), (" src=\"", "\"")];
    loop {
        let next = STARTS
            .iter()
            .filter_map(|(start, end)| rest.find(start).map(|at| (at + start.len(), *end)))
            .min();
        let Some((start, close)) = next else { break };
        out.push_str(&rest[..start]);
        rest = &rest[start..];
        let end = rest.find(close).unwrap_or(rest.len());
        let value = &rest[..end];
        match Link::classify(value) {
            // A path from the top is an address already.
            // A file outside the served folder has no address: the link
            // keeps its target as written, and the check reports it.
            Link::File { path, fragment } if !path.is_empty() && !path.starts_with('/') => {
                match document.url(&lexical(&folder.join(path))) {
                    Some(address) => {
                        out.push_str(&address);
                        if value.contains('#') {
                            out.push('#');
                            out.push_str(fragment);
                        }
                    }
                    None => out.push_str(value),
                }
            }
            _ => out.push_str(value),
        }
        rest = &rest[end..];
    }
    out.push_str(rest);
    out
}

/// A document file that can't be loaded: a page listing what is wrong with
/// it — `None` for a file outside the served folder, which is never shown.
pub fn invalid(entry: &Document, file: &Path, error: &str) -> Option<String> {
    let address = entry.url(file)?;
    Some(format!(
        r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{address} · {document}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{page_script}
</head>
<body class="invalid" data-build="{build}">
<main id="devpage-page"><div class="problems"><b>{address} is not a valid document</b><ul><li>{error}</li></ul></div></main>
</body>
</html>"#,
        html = html_open(&entry.served),
        stylesheet = crate::addresses::address(Owned::Asset("style.css")),
        build = crate::addresses::BUILD,
        page_script = page_script(false, true),
        address = escape(&address),
        document = escape(&entry.title),
        theme = navbar::head(entry),
        error = escape(error),
    ))
}

/// The page's problems, listed above it, with each broken link marked.
fn problems(found: &[Problem]) -> String {
    if found.is_empty() {
        return String::new();
    }
    let items: String = found
        .iter()
        .map(|problem| format!("<li>{}</li>", escape(&problem.to_string())))
        .collect();
    // The links as written, for the page script to mark where they stand.
    let broken: Vec<&str> = found.iter().filter_map(|p| p.target.as_deref()).collect();
    format!(
        "<div class=\"problems\" data-broken=\"{}\"><b>{} problem{}</b><ul>{items}</ul></div>",
        escape(&serde_json::to_string(&broken).unwrap_or_default()),
        found.len(),
        if found.len() == 1 { "" } else { "s" }
    )
}

/// A deck: every slide's `rendered` content on its own 1920 × 1080 stage,
/// scaled to the window as a whole, one shown at a time. In print mode each
/// slide is one 16:9 page.
pub fn slides(
    document: &Document,
    widgets: &Widgets,
    slides: &[Rendered],
    print: bool,
    comments: bool,
    found: &[Problem],
) -> String {
    let _render = tracing::info_span!("render").entered();
    let mut content = String::new();
    for (index, slide) in slides.iter().enumerate() {
        content.push_str(&format!(
            "<section class=\"slide\" data-slide=\"{}\" data-source=\"{}\"><div class=\"slide-body\">{}</div></section>",
            index + 1,
            document.part_url(slide.file()),
            rebase(slide.html(), slide.file(), document)
        ));
    }
    format!(
        r#"<!doctype html>
{html}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
{theme}
<link rel="stylesheet" href="{stylesheet}">
{script}
{widgets}
<style>@page {{ size: 1920px 1080px; margin: 0; }}</style>
</head>
<body class="slides{print_class}" data-build="{build}">
{corner}<main id="devpage-page" class="deck">{problems}{content}</main>
</body>
</html>"#,
        html = html_open(&document.served),
        stylesheet = address(Owned::Asset("style.css")),
        build = crate::addresses::BUILD,
        title = escape(&document.title),
        theme = navbar::head(document),
        corner = if print {
            String::new()
        } else {
            navbar::corner(document, comments)
        },
        widgets = widgets.head(&content, &[]),
        print_class = if print { " print" } else { "" },
        script = page_script(print, comments),
        problems = if print {
            String::new()
        } else {
            problems(found)
        },
    )
}

/// The `h1` and `h2` headings of rendered HTML: level, id and text.
fn headings(html: &str) -> Vec<(u8, String, String)> {
    let mut found = Vec::new();
    let mut rest = html;
    while let Some(start) = rest.find("<h") {
        rest = &rest[start + 2..];
        let level = rest.as_bytes().first().copied().unwrap_or(0);
        if level != b'1' && level != b'2' {
            continue;
        }
        let close = format!("</h{}>", level as char);
        let Some(end) = rest.find(&close) else { break };
        let inner = &rest[..end];
        let id = inner
            .split("id=\"")
            .nth(1)
            .and_then(|tail| tail.split('"').next())
            .unwrap_or_default()
            .to_string();
        let text = strip_tags(inner.split_once('>').map_or(inner, |(_, body)| body));
        found.push((level - b'0', id, text));
        rest = &rest[end..];
    }
    found
}

/// `html`'s text with every tag left out, trimmed; entities stay as written.
fn strip_tags(html: &str) -> String {
    let mut text = String::new();
    let mut in_tag = false;
    for c in html.chars() {
        match c {
            '<' => in_tag = true,
            '>' => in_tag = false,
            c if !in_tag => text.push(c),
            _ => {}
        }
    }
    text.trim().to_string()
}

/// A site page's body classes, which name its frame: a page with another frame
/// can't be swapped in part.
fn site_class(document: &Document) -> String {
    let mut class = String::from("site");
    if !document.navbar.is_empty() {
        class.push_str(" with-navbar");
    }
    if !document.sidebar {
        class.push_str(" no-sidebar");
    }
    class
}