devpage 0.2.1

Live documents from a repository: sites, docs and slides from Markdown, and UI designs drawn from code — with comments, link checking and PDF
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! A document: what a document file says to show — a site, a doc or slides —
//! or a lone Markdown file, which is a doc of one chapter.

use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use anyhow::{Context, Result, bail};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::Deserialize;

/// The YAML as written, tagged by `kind`. Paths are relative to its folder.
#[derive(Debug, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
enum Config {
    Site {
        title: String,
        root: String,
        watch: Option<Vec<String>>,
        widgets: Option<String>,
        navbar: Option<serde_yaml::Mapping>,
        sidebar: Option<bool>,
        #[serde(rename = "theme-selector")]
        theme_selector: Option<bool>,
        logo: Option<String>,
    },
    Doc {
        title: String,
        chapters: Vec<String>,
        #[serde(default)]
        pdf: Pdf,
        widgets: Option<String>,
        #[serde(rename = "theme-selector")]
        theme_selector: Option<bool>,
        logo: Option<String>,
    },
    Slides {
        title: String,
        slides: Vec<String>,
        audience: Option<String>,
        goal: Option<String>,
        tone: Option<String>,
        pronounce: Option<Vec<String>>,
        widgets: Option<String>,
        #[serde(rename = "theme-selector")]
        theme_selector: Option<bool>,
        logo: Option<String>,
    },
}

/// One link of a site's navbar, as written: a label, an icon or both, and its
/// target — a path relative to the document file, or an address on the web.
#[derive(Debug, Clone, PartialEq)]
pub struct NavLink {
    pub label: Option<String>,
    pub icon: Option<String>,
    pub target: String,
}

/// An entry of a site's navbar: a link, or a dropdown of links.
#[derive(Debug, Clone, PartialEq)]
pub enum NavItem {
    Link(NavLink),
    Menu {
        label: Option<String>,
        icon: Option<String>,
        items: Vec<NavLink>,
    },
}

/// Splits a navbar key into its label and its `(icon)`: `Docs (book-open)`,
/// `Docs`, or `(github)` alone.
fn label_and_icon(key: &str) -> Result<(Option<String>, Option<String>)> {
    let key = key.trim();
    let (label, icon) = match key.strip_suffix(')').and_then(|rest| rest.rsplit_once('(')) {
        Some((label, icon))
            if !icon.is_empty()
                && icon
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') =>
        {
            (label.trim(), Some(icon.to_string()))
        }
        _ => (key, None),
    };
    let label = (!label.is_empty()).then(|| label.to_string());
    if label.is_none() && icon.is_none() {
        bail!("navbar has an entry with neither a label nor an icon");
    }
    Ok((label, icon))
}

/// Reads a `navbar` map, in order: `label: target` is a link, `label:` with a
/// nested map is a dropdown of links, one level deep.
fn navbar(map: &serde_yaml::Mapping) -> Result<Vec<NavItem>> {
    let key_text = |key: &serde_yaml::Value| -> Result<String> {
        match key {
            serde_yaml::Value::String(text) => Ok(text.clone()),
            other => bail!("navbar: {other:?} is not a label"),
        }
    };
    let mut items = Vec::new();
    for (key, value) in map {
        let key = key_text(key)?;
        let (label, icon) = label_and_icon(&key)?;
        match value {
            serde_yaml::Value::String(target) => items.push(NavItem::Link(NavLink {
                label,
                icon,
                target: target.clone(),
            })),
            serde_yaml::Value::Mapping(links) => {
                let mut menu = Vec::new();
                for (inner_key, value) in links {
                    let inner = key_text(inner_key)?;
                    let serde_yaml::Value::String(target) = value else {
                        bail!(
                            "navbar: {inner} under {key} must be a link — dropdowns are one level deep"
                        );
                    };
                    let (label, icon) = label_and_icon(&inner)?;
                    menu.push(NavLink {
                        label,
                        icon,
                        target: target.clone(),
                    });
                }
                if menu.is_empty() {
                    bail!("navbar: {key} lists no links");
                }
                items.push(NavItem::Menu {
                    label,
                    icon,
                    items: menu,
                });
            }
            _ => bail!("navbar: {key} must be a link or a map of links"),
        }
    }
    Ok(items)
}

/// A doc's settings on paper.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Pdf {
    #[serde(default)]
    pub paper: Paper,
    pub header: Option<String>,
    #[serde(default = "default_footer")]
    pub footer: String,
}

impl Default for Pdf {
    fn default() -> Self {
        Self {
            paper: Paper::default(),
            header: None,
            footer: default_footer(),
        }
    }
}

fn default_footer() -> String {
    "{page} / {pages}".into()
}

#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
pub enum Paper {
    #[default]
    A4,
    Letter,
}

/// What a document is, with its parts resolved to files.
#[derive(Debug, Clone, PartialEq)]
pub enum Kind {
    Site {
        root: String,
    },
    Doc {
        chapters: Vec<PathBuf>,
        pdf: Pdf,
    },
    Slides {
        slides: Vec<Slide>,
        /// Who the talk is for and how it should sound, for its narrator.
        narration: Narration,
    },
    /// A `.design` file, which is the whole document.
    Design,
}

/// What a deck tells its narrator about the talk as a whole, as written in
/// its document file: who it is for, what it should achieve, how it should
/// sound, and how to say words a voice gets wrong.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Narration {
    pub audience: Option<String>,
    pub goal: Option<String>,
    pub tone: Option<String>,
    pub pronounce: Vec<String>,
}

/// One slide of a deck: its Markdown file, its notes — the text of its first
/// `<Notes>`, if it has one — and that `<Notes>`' `delivery`.
#[derive(Debug, Clone, PartialEq)]
pub struct Slide {
    pub file: PathBuf,
    pub notes: Option<String>,
    pub delivery: Option<String>,
}

impl Slide {
    /// Reads a slide's notes from its file.
    fn read(file: PathBuf) -> Self {
        let source = std::fs::read_to_string(&file).unwrap_or_default();
        let first = crate::widgets::notes(&source).into_iter().next();
        let (notes, delivery) = match first {
            Some(note) => (Some(note.text), note.delivery),
            None => (None, None),
        };
        Self {
            file,
            notes,
            delivery,
        }
    }
}

/// Which kind a document file names, read without loading the document.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KindName {
    Site,
    Doc,
    Slides,
}

/// A loaded document: its title, its folder, what it is, and where it is served.
#[derive(Debug)]
pub struct Document {
    pub title: String,
    pub base: PathBuf,
    pub kind: Kind,
    /// The document file's name inside `base`.
    pub file_name: String,
    /// The served folder: where devpage was started, or `--root`. Addresses
    /// are paths in it, and nothing outside it is served.
    pub served: PathBuf,
    /// A site's `watch` list: when set, only matching files refresh pages.
    watch: Option<GlobSet>,
    /// Where each `watch` pattern can match: its literal prefix — the
    /// components before the first with a glob character — joined to `base`.
    watch_roots: Vec<PathBuf>,
    /// The folder of the document's project widgets, if it has one.
    pub widgets: Option<PathBuf>,
    /// A site's navbar, in order; empty when it has none.
    pub navbar: Vec<NavItem>,
    /// Whether a site shows its Topics sidebar.
    pub sidebar: bool,
    /// Whether the page shows the light/dark selector.
    pub theme_selector: bool,
    /// The `logo` field as written: an image relative to the document file,
    /// shown before the title and used as the browser tab's icon.
    pub logo: Option<String>,
}

impl Document {
    /// Loads a document file, `devpage.yml` in a folder, a Markdown file or a
    /// design, which must lie inside the served folder `served`.
    pub fn load(path: &Path, served: &Path) -> Result<Self> {
        let file = if path.is_dir() {
            path.join("devpage.yml")
        } else {
            path.to_path_buf()
        };
        let text = std::fs::read_to_string(&file)
            .with_context(|| format!("reading {}", file.display()))?;
        let served = served
            .canonicalize()
            .with_context(|| format!("reading {}", served.display()))?;
        // A bare file name has an empty parent, which means the current folder.
        let parent = file.parent().filter(|p| !p.as_os_str().is_empty());
        let base = parent.unwrap_or(Path::new(".")).canonicalize()?;
        if !base.starts_with(&served) {
            bail!(
                "{} is outside the served folder {}",
                path.display(),
                served.display()
            );
        }
        let file_name = file
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();
        if file.extension().is_some_and(|ext| ext == "design") {
            return Ok(Self {
                served,
                title: file
                    .file_stem()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .into_owned(),
                kind: Kind::Design,
                base,
                file_name,
                watch: None,
                watch_roots: Vec::new(),
                widgets: None,
                navbar: Vec::new(),
                sidebar: true,
                theme_selector: true,
                logo: None,
            });
        }
        if file.extension().is_some_and(|ext| ext == "md") {
            return Ok(Self {
                served,
                title: crate::render::title(&text, &file),
                kind: Kind::Doc {
                    chapters: vec![base.join(&file_name)],
                    pdf: Pdf::default(),
                },
                base,
                file_name,
                watch: None,
                watch_roots: Vec::new(),
                widgets: None,
                navbar: Vec::new(),
                sidebar: true,
                theme_selector: true,
                logo: None,
            });
        }
        Self::parse(&text, base, file_name, served)
            .with_context(|| format!("in {}", file.display()))
    }

    fn parse(text: &str, base: PathBuf, file_name: String, served: PathBuf) -> Result<Self> {
        // A part must be an existing file inside the served folder.
        let existing = |field: &str, path: &str| -> Result<PathBuf> {
            match base.join(path).canonicalize() {
                Ok(file) if file.is_file() && file.starts_with(&served) => Ok(file),
                _ => bail!("{field} {path} does not exist"),
            }
        };
        let mut watch = None;
        let mut watch_roots = Vec::new();
        let widget_folder;
        let mut nav_items = Vec::new();
        let mut show_sidebar = true;
        let show_selector;
        let logo_path;
        let (title, kind) = match serde_yaml::from_str(text)? {
            Config::Site {
                title,
                root,
                watch: patterns,
                widgets,
                navbar: nav,
                sidebar,
                theme_selector,
                logo,
            } => {
                logo_path = logo;
                widget_folder = widgets;
                show_selector = theme_selector.unwrap_or(true);
                show_sidebar = sidebar.unwrap_or(true);
                if let Some(nav) = nav {
                    nav_items = navbar(&nav)?;
                }
                existing("root", &root)?;
                if let Some(patterns) = patterns {
                    let mut set = GlobSetBuilder::new();
                    for pattern in &patterns {
                        set.add(
                            Glob::new(pattern)
                                .with_context(|| format!("watch pattern {pattern}"))?,
                        );
                    }
                    watch = Some(set.build()?);
                    watch_roots = patterns
                        .iter()
                        .map(|pattern| base.join(literal_prefix(pattern)))
                        .collect();
                }
                (title, Kind::Site { root })
            }
            Config::Doc {
                title,
                chapters,
                pdf,
                widgets,
                theme_selector,
                logo,
            } => {
                logo_path = logo;
                widget_folder = widgets;
                show_selector = theme_selector.unwrap_or(true);
                if chapters.is_empty() {
                    bail!("chapters lists no files");
                }
                let chapters = chapters
                    .iter()
                    .map(|chapter| existing("chapter", chapter))
                    .collect::<Result<_>>()?;
                (title, Kind::Doc { chapters, pdf })
            }
            Config::Slides {
                title,
                slides,
                audience,
                goal,
                tone,
                pronounce,
                widgets,
                theme_selector,
                logo,
            } => {
                logo_path = logo;
                widget_folder = widgets;
                show_selector = theme_selector.unwrap_or(true);
                if slides.is_empty() {
                    bail!("slides lists no files");
                }
                let slides = slides
                    .iter()
                    .map(|slide| existing("slide", slide).map(Slide::read))
                    .collect::<Result<_>>()?;
                let narration = Narration {
                    audience,
                    goal,
                    tone,
                    pronounce: pronounce.unwrap_or_default(),
                };
                (title, Kind::Slides { slides, narration })
            }
        };
        let widgets = match widget_folder {
            Some(folder) => match base.join(&folder).canonicalize() {
                Ok(dir) if dir.is_dir() && dir.starts_with(&served) => Some(dir),
                _ => bail!("widgets {folder} is not a folder"),
            },
            None => None,
        };
        Ok(Self {
            title,
            base,
            kind,
            file_name,
            served,
            watch,
            watch_roots,
            widgets,
            navbar: nav_items,
            sidebar: show_sidebar,
            theme_selector: show_selector,
            logo: logo_path,
        })
    }

    /// Where `/` leads: a site's root page, or the document file itself.
    pub fn entry(&self) -> String {
        match &self.kind {
            Kind::Site { root } => self.url(&self.base.join(root)),
            _ => self.url(&self.path()),
        }
    }

    /// The document file itself.
    pub fn path(&self) -> PathBuf {
        self.base.join(&self.file_name)
    }

    /// The logo's address, when the document has one and the file exists in
    /// the served folder. A logo that doesn't is a problem, not an error:
    /// the page shows without it.
    pub fn logo_url(&self) -> Option<String> {
        let written = self.logo.as_ref()?;
        let file = self.base.join(written).canonicalize().ok()?;
        (file.is_file() && file.starts_with(&self.served)).then(|| self.url(&file))
    }

    /// A file's address: its path from the top of the served folder.
    pub fn url(&self, file: &Path) -> String {
        format!(
            "/{}",
            file.strip_prefix(&self.served).unwrap_or(file).display()
        )
    }

    /// The file a URL path names, if it lies inside the served folder.
    pub fn file(&self, url_path: &str) -> Option<PathBuf> {
        let candidate = self
            .served
            .join(url_path.trim_start_matches('/'))
            .canonicalize()
            .ok()?;
        candidate.starts_with(&self.served).then_some(candidate)
    }

    /// Whether a change to `file` refreshes open pages: always, unless this
    /// is a site whose `watch` list matches none of it, relative to its folder.
    pub fn watches(&self, file: &Path) -> bool {
        let Some(watch) = &self.watch else {
            return true;
        };
        file.strip_prefix(&self.base)
            .is_ok_and(|relative| watch.is_match(relative))
    }

    /// Whether this is a site whose `watch` list names `file`, relative to
    /// its folder.
    pub fn names(&self, file: &Path) -> bool {
        self.watch.is_some() && self.watches(file)
    }

    /// The folders a site's `watch` patterns can name files in: each
    /// pattern's literal prefix in the site's folder. Empty without a list.
    pub fn watch_roots(&self) -> &[PathBuf] {
        &self.watch_roots
    }
}

/// A glob pattern's components before the first one with a glob character:
/// `build/*.svg` gives `build`, `**/*.md` gives nothing.
fn literal_prefix(pattern: &str) -> PathBuf {
    Path::new(pattern)
        .components()
        .take_while(|part| {
            !part
                .as_os_str()
                .to_string_lossy()
                .contains(['*', '?', '[', '{'])
        })
        .collect()
}

/// The document devpage was started with, re-read whenever its file changes,
/// so `/` and the watcher follow the file without a restart. While the file
/// is invalid, the last valid document stays in use and the error is kept to
/// show in its place.
pub struct Entry {
    /// The entry's file: a document file, or a Markdown file served as a doc.
    file: PathBuf,
    state: RwLock<(Arc<Document>, Option<String>)>,
}

impl Entry {
    pub fn new(document: Arc<Document>) -> Self {
        Self {
            file: document.path(),
            state: RwLock::new((document, None)),
        }
    }

    /// The entry document as last read without error.
    pub fn document(&self) -> Arc<Document> {
        self.state.read().unwrap().0.clone()
    }

    /// Why the entry's file can't be read as a document, if it can't now.
    pub fn error(&self) -> Option<String> {
        self.state.read().unwrap().1.clone()
    }

    pub fn file(&self) -> &Path {
        &self.file
    }

    /// Reads the entry's file again: a valid file replaces the document, an
    /// invalid one keeps it and records the error.
    pub fn reload(&self) {
        let served = self.document().served.clone();
        let mut state = self.state.write().unwrap();
        match Document::load(&self.file, &served) {
            Ok(document) => *state = (Arc::new(document), None),
            Err(error) => state.1 = Some(format!("{error:#}")),
        }
    }
}

/// The kind a YAML file names in its top-level `kind`, when it is one of
/// devpage's three; any other file is not a document file.
pub fn kind_of(file: &Path) -> Option<KindName> {
    if !file
        .extension()
        .is_some_and(|ext| ext == "yml" || ext == "yaml")
    {
        return None;
    }
    let text = std::fs::read_to_string(file).ok()?;
    let value: serde_yaml::Value = serde_yaml::from_str(&text).ok()?;
    match value.get("kind")?.as_str()? {
        "site" => Some(KindName::Site),
        "doc" => Some(KindName::Doc),
        "slides" => Some(KindName::Slides),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn folder(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("devpage-doc-{name}-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("guides")).unwrap();
        std::fs::write(dir.join("README.md"), "# Home").unwrap();
        std::fs::write(dir.join("guides/start.md"), "# Start").unwrap();
        dir.canonicalize().unwrap()
    }

    fn parse(text: &str, dir: PathBuf) -> Result<Document> {
        Document::parse(text, dir.clone(), "devpage.yml".into(), dir)
    }

    #[test]
    fn parses_each_kind() {
        let dir = folder("kinds");
        let site = parse("kind: site\ntitle: Docs\nroot: README.md\n", dir.clone()).unwrap();
        assert_eq!(site.entry(), "/README.md");
        let doc = parse(
            "kind: doc\ntitle: Plan\nchapters: [README.md, guides/start.md]\npdf: {paper: Letter}\n",
            dir.clone(),
        )
        .unwrap();
        let Kind::Doc { chapters, pdf } = &doc.kind else {
            panic!("{doc:?}")
        };
        assert_eq!(chapters.len(), 2);
        assert_eq!(pdf.paper, Paper::Letter);
        assert_eq!(pdf.footer, "{page} / {pages}");
        assert_eq!(doc.entry(), "/devpage.yml");
        let slides = parse("kind: slides\ntitle: Talk\nslides: [README.md]\n", dir).unwrap();
        assert!(matches!(slides.kind, Kind::Slides { .. }));
    }

    #[test]
    fn rejects_bad_kinds_fields_and_missing_files() {
        let dir = folder("bad");
        for text in [
            "title: Docs\nroot: README.md\n",
            "kind: deck\ntitle: Docs\nroot: README.md\n",
            "kind: site\ntitle: Docs\nroot: nope.md\n",
            "kind: site\ntitle: Docs\nroot: README.md\ncolour: red\n",
            "kind: site\ntitle: Docs\nroot: README.md\nwatch: \"*.md\"\n",
            "kind: site\ntitle: Docs\nroot: README.md\nwatch: [\"a[b\"]\n",
            "kind: doc\ntitle: Docs\nroot: README.md\nchapters: [README.md]\n",
            "kind: doc\ntitle: Docs\nchapters: [missing.md]\n",
            "kind: doc\ntitle: Docs\nchapters: [../outside.md]\n",
        ] {
            assert!(parse(text, dir.clone()).is_err(), "{text}");
        }
    }

    #[test]
    fn reads_the_navbar_in_order_and_refuses_bad_shapes() {
        let dir = folder("navbar");
        let document = parse(
            "kind: site\ntitle: T\nroot: README.md\nsidebar: false\ntheme-selector: false\nnavbar:\n  Docs (book-open): README.md\n  Plain: README.md\n  More (layout-grid):\n    Talk (presentation): talk.yml\n  (github): https://github.com/x/y\n",
            dir.clone(),
        )
        .unwrap();
        assert!(!document.sidebar && !document.theme_selector);
        let link = |label: Option<&str>, icon: Option<&str>, target: &str| NavLink {
            label: label.map(String::from),
            icon: icon.map(String::from),
            target: target.into(),
        };
        assert_eq!(
            document.navbar,
            [
                NavItem::Link(link(Some("Docs"), Some("book-open"), "README.md")),
                NavItem::Link(link(Some("Plain"), None, "README.md")),
                NavItem::Menu {
                    label: Some("More".into()),
                    icon: Some("layout-grid".into()),
                    items: vec![link(Some("Talk"), Some("presentation"), "talk.yml")],
                },
                NavItem::Link(link(None, Some("github"), "https://github.com/x/y")),
            ]
        );
        // Defaults: a sidebar, a selector, no navbar; a doc and a deck may opt out too.
        let plain = parse("kind: site\ntitle: T\nroot: README.md\n", dir.clone()).unwrap();
        assert!(plain.sidebar && plain.theme_selector && plain.navbar.is_empty());
        assert!(
            !parse(
                "kind: doc\ntitle: T\nchapters: [README.md]\ntheme-selector: false\n",
                dir.clone()
            )
            .unwrap()
            .theme_selector
        );
        for text in [
            // two levels deep, an empty dropdown, a list instead of a map, no label or icon
            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A:\n    B:\n      C: README.md\n",
            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A: {}\n",
            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  - A: README.md\n",
            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  \"  \": README.md\n",
            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A: 3\n",
            // a navbar and a sidebar belong to sites
            "kind: doc\ntitle: T\nchapters: [README.md]\nnavbar:\n  A: README.md\n",
            "kind: slides\ntitle: T\nslides: [README.md]\nsidebar: false\n",
        ] {
            assert!(parse(text, dir.clone()).is_err(), "{text}");
        }
    }

    #[test]
    fn a_markdown_file_is_a_doc_of_one_chapter() {
        let dir = folder("md");
        let doc = Document::load(&dir.join("guides/start.md"), &dir).unwrap();
        assert_eq!(doc.title, "Start");
        assert!(matches!(&doc.kind, Kind::Doc { chapters, .. } if chapters.len() == 1));
    }

    #[test]
    fn the_served_folder_is_the_boundary_and_addresses_start_there() {
        // No .git anywhere: the served folder is whatever devpage was given.
        let served = folder("served");
        std::fs::write(
            served.join("guides/devpage.yml"),
            "kind: site\ntitle: G\nroot: start.md\n",
        )
        .unwrap();
        let doc = Document::load(&served.join("guides"), &served).unwrap();
        assert_eq!(doc.served, served);
        assert_eq!(doc.entry(), "/guides/start.md");
        assert!(
            doc.file("/README.md").is_some(),
            "files beside the docs are served"
        );
        assert!(doc.file("/../x").is_none());

        // --root moves the boundary: served from guides/, README.md is outside.
        let guides = served.join("guides");
        let narrow = Document::load(&guides, &guides).unwrap();
        assert_eq!(narrow.entry(), "/start.md");
        assert!(narrow.file("/../README.md").is_none());
    }

    #[test]
    fn a_document_outside_the_served_folder_is_refused() {
        let served = folder("outside");
        let error = Document::load(&served.join("README.md"), &served.join("guides"))
            .unwrap_err()
            .to_string();
        assert!(error.contains("is outside the served folder"), "{error}");
    }

    #[test]
    fn a_site_watch_list_narrows_what_refreshes() {
        let dir = folder("watch");
        let all = parse("kind: site\ntitle: D\nroot: README.md\n", dir.clone()).unwrap();
        assert!(all.watches(&dir.join("logo.png")));
        let narrow = parse(
            "kind: site\ntitle: D\nroot: README.md\nwatch: [\"**/*.md\"]\n",
            dir.clone(),
        )
        .unwrap();
        assert!(narrow.watches(&dir.join("guides/start.md")));
        assert!(!narrow.watches(&dir.join("logo.png")));
    }

    #[test]
    fn only_yaml_with_a_devpage_kind_is_a_document_file() {
        let dir = folder("kind-of");
        std::fs::write(dir.join("site.yml"), "kind: site\ntitle: T\n").unwrap();
        std::fs::write(dir.join("deploy.yaml"), "kind: Deployment\n").unwrap();
        std::fs::write(dir.join("ci.yml"), "on: push\n").unwrap();
        assert_eq!(kind_of(&dir.join("site.yml")), Some(KindName::Site));
        assert_eq!(kind_of(&dir.join("deploy.yaml")), None);
        assert_eq!(kind_of(&dir.join("ci.yml")), None);
        assert_eq!(kind_of(&dir.join("README.md")), None);
    }

    #[test]
    fn a_deck_keeps_its_narration_and_each_slides_notes_and_delivery() {
        let dir = folder("notes");
        std::fs::write(
            dir.join("one.md"),
            "# One\n\n<Notes delivery=\"Warm, a smile in the voice.\">\n  Hello, everyone.\n</Notes>\n\n<Notes>second</Notes>\n",
        )
        .unwrap();
        std::fs::write(dir.join("two.md"), "# Two\n\n`<Notes>not these</Notes>`\n").unwrap();
        let deck = parse(
            "kind: slides\ntitle: Talk\naudience: Engineers.\ngoal: They try it.\ntone: Warm and brief.\npronounce: ['Say \"devpage\" as \"dev page\".']\nslides: [one.md, two.md]\n",
            dir.clone(),
        )
        .unwrap();
        let Kind::Slides { slides, narration } = &deck.kind else {
            panic!("{deck:?}")
        };
        assert_eq!(
            narration,
            &Narration {
                audience: Some("Engineers.".to_string()),
                goal: Some("They try it.".to_string()),
                tone: Some("Warm and brief.".to_string()),
                pronounce: vec!["Say \"devpage\" as \"dev page\".".to_string()],
            }
        );
        assert_eq!(slides[0].file, dir.join("one.md"));
        assert_eq!(slides[0].notes.as_deref(), Some("Hello, everyone."));
        assert_eq!(
            slides[0].delivery.as_deref(),
            Some("Warm, a smile in the voice.")
        );
        assert_eq!(slides[1].notes, None);
        let plain = parse("kind: slides\ntitle: T\nslides: [one.md]\n", dir.clone()).unwrap();
        assert!(
            matches!(&plain.kind, Kind::Slides { narration, .. } if *narration == Narration::default())
        );
        // The narration belongs to slides, and `context` is gone.
        for text in [
            "kind: doc\ntitle: T\nchapters: [README.md]\naudience: x\n",
            "kind: site\ntitle: T\nroot: README.md\ngoal: x\n",
            "kind: slides\ntitle: T\nslides: [one.md]\ncontext: x\n",
            "kind: slides\ntitle: T\nslides: [one.md]\npronounce: x\n",
        ] {
            assert!(parse(text, dir.clone()).is_err(), "{text}");
        }
    }
}