Skip to main content

devpage_core/
document.rs

1//! A document: what a document file says to show — a site, a doc or slides —
2//! or a lone Markdown file, which is a doc of one chapter.
3
4use std::path::{Path, PathBuf};
5
6use anyhow::{Context, Result, bail};
7
8use crate::folder::ServedFolder;
9use globset::{Glob, GlobSet, GlobSetBuilder};
10use serde::Deserialize;
11
12#[cfg(test)]
13thread_local! {
14    /// Every document file loaded on this thread, for the tests: how often a
15    /// pass loads each.
16    pub(crate) static LOADED: std::cell::RefCell<Vec<PathBuf>> = Default::default();
17}
18
19/// The YAML as written, tagged by `kind`. Paths are relative to its folder.
20#[derive(Debug, Deserialize)]
21#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
22enum Config {
23    Site {
24        title: String,
25        root: String,
26        watch: Option<Vec<String>>,
27        widgets: Option<String>,
28        navbar: Option<serde_yaml::Mapping>,
29        sidebar: Option<bool>,
30        #[serde(rename = "theme-selector")]
31        theme_selector: Option<bool>,
32        logo: Option<String>,
33    },
34    Doc {
35        title: String,
36        chapters: Vec<String>,
37        #[serde(default)]
38        pdf: Pdf,
39        widgets: Option<String>,
40        #[serde(rename = "theme-selector")]
41        theme_selector: Option<bool>,
42        logo: Option<String>,
43    },
44    Slides {
45        title: String,
46        slides: Vec<String>,
47        audience: Option<String>,
48        goal: Option<String>,
49        tone: Option<String>,
50        pronounce: Option<Vec<String>>,
51        widgets: Option<String>,
52        #[serde(rename = "theme-selector")]
53        theme_selector: Option<bool>,
54        logo: Option<String>,
55    },
56}
57
58/// One link of a site's navbar, as written: a label, an icon or both, and its
59/// target — a path relative to the document file, or an address on the web.
60#[derive(Debug, Clone, PartialEq)]
61pub struct NavLink {
62    pub label: Option<String>,
63    pub icon: Option<String>,
64    pub target: String,
65}
66
67/// An entry of a site's navbar: a link, or a dropdown of links.
68#[derive(Debug, Clone, PartialEq)]
69pub enum NavItem {
70    Link(NavLink),
71    Menu {
72        label: Option<String>,
73        icon: Option<String>,
74        items: Vec<NavLink>,
75    },
76}
77
78/// Splits a navbar key into its label and its `(icon)`: `Docs (book-open)`,
79/// `Docs`, or `(github)` alone.
80fn label_and_icon(key: &str) -> Result<(Option<String>, Option<String>)> {
81    let key = key.trim();
82    let (label, icon) = match key.strip_suffix(')').and_then(|rest| rest.rsplit_once('(')) {
83        Some((label, icon))
84            if !icon.is_empty()
85                && icon
86                    .chars()
87                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') =>
88        {
89            (label.trim(), Some(icon.to_string()))
90        }
91        _ => (key, None),
92    };
93    let label = (!label.is_empty()).then(|| label.to_string());
94    if label.is_none() && icon.is_none() {
95        bail!("navbar has an entry with neither a label nor an icon");
96    }
97    Ok((label, icon))
98}
99
100/// Reads a `navbar` map, in order: `label: target` is a link, `label:` with a
101/// nested map is a dropdown of links, one level deep.
102fn navbar(map: &serde_yaml::Mapping) -> Result<Vec<NavItem>> {
103    let key_text = |key: &serde_yaml::Value| -> Result<String> {
104        match key {
105            serde_yaml::Value::String(text) => Ok(text.clone()),
106            other => bail!("navbar: {other:?} is not a label"),
107        }
108    };
109    let mut items = Vec::new();
110    for (key, value) in map {
111        let key = key_text(key)?;
112        let (label, icon) = label_and_icon(&key)?;
113        match value {
114            serde_yaml::Value::String(target) => items.push(NavItem::Link(NavLink {
115                label,
116                icon,
117                target: target.clone(),
118            })),
119            serde_yaml::Value::Mapping(links) => {
120                let mut menu = Vec::new();
121                for (inner_key, value) in links {
122                    let inner = key_text(inner_key)?;
123                    let serde_yaml::Value::String(target) = value else {
124                        bail!(
125                            "navbar: {inner} under {key} must be a link — dropdowns are one level deep"
126                        );
127                    };
128                    let (label, icon) = label_and_icon(&inner)?;
129                    menu.push(NavLink {
130                        label,
131                        icon,
132                        target: target.clone(),
133                    });
134                }
135                if menu.is_empty() {
136                    bail!("navbar: {key} lists no links");
137                }
138                items.push(NavItem::Menu {
139                    label,
140                    icon,
141                    items: menu,
142                });
143            }
144            _ => bail!("navbar: {key} must be a link or a map of links"),
145        }
146    }
147    Ok(items)
148}
149
150/// A doc's settings on paper.
151#[derive(Debug, Clone, Deserialize, PartialEq)]
152#[serde(deny_unknown_fields)]
153pub struct Pdf {
154    #[serde(default)]
155    pub paper: Paper,
156    pub header: Option<String>,
157    #[serde(default = "default_footer")]
158    pub footer: String,
159}
160
161impl Default for Pdf {
162    fn default() -> Self {
163        Self {
164            paper: Paper::default(),
165            header: None,
166            footer: default_footer(),
167        }
168    }
169}
170
171fn default_footer() -> String {
172    "{page} / {pages}".into()
173}
174
175#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
176pub enum Paper {
177    #[default]
178    A4,
179    Letter,
180}
181
182/// What a document is, with its parts resolved to files.
183#[derive(Debug, Clone, PartialEq)]
184pub enum Kind {
185    Site {
186        root: String,
187    },
188    Doc {
189        chapters: Vec<PathBuf>,
190        pdf: Pdf,
191    },
192    Slides {
193        slides: Vec<Slide>,
194        /// Who the talk is for and how it should sound, for its narrator.
195        narration: Narration,
196    },
197    /// A `.design` file, which is the whole document.
198    Design,
199}
200
201/// What a deck tells its narrator about the talk as a whole, as written in
202/// its document file: who it is for, what it should achieve, how it should
203/// sound, and how to say words a voice gets wrong.
204#[derive(Debug, Clone, Default, PartialEq)]
205pub struct Narration {
206    pub audience: Option<String>,
207    pub goal: Option<String>,
208    pub tone: Option<String>,
209    pub pronounce: Vec<String>,
210}
211
212/// One slide of a deck: its Markdown file, its notes — the text of its first
213/// `<Notes>`, if it has one — and that `<Notes>`' `delivery`.
214#[derive(Debug, Clone, PartialEq)]
215pub struct Slide {
216    pub file: PathBuf,
217    pub notes: Option<String>,
218    pub delivery: Option<String>,
219}
220
221impl Slide {
222    /// Reads a slide's notes from its file.
223    fn read(file: PathBuf) -> Self {
224        let source = std::fs::read_to_string(&file).unwrap_or_default();
225        let first = crate::markup::notes(&source).into_iter().next();
226        let (notes, delivery) = match first {
227            Some(note) => (Some(note.text), note.delivery),
228            None => (None, None),
229        };
230        Self {
231            file,
232            notes,
233            delivery,
234        }
235    }
236}
237
238/// Which kind a document file names, read without loading the document.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum KindName {
241    Site,
242    Doc,
243    Slides,
244}
245
246/// A loaded document: its title, its folder, what it is, and where it is served.
247#[derive(Debug)]
248pub struct Document {
249    pub title: String,
250    pub base: PathBuf,
251    pub kind: Kind,
252    /// The document file's name inside `base`.
253    pub file_name: String,
254    /// The served folder: where devpage was started, or `--root`. Addresses
255    /// are paths in it, and nothing outside it is served.
256    pub served: ServedFolder,
257    /// A site's `watch` list: when set, only matching files refresh pages.
258    watch: Option<GlobSet>,
259    /// Where each `watch` pattern can match: its literal prefix — the
260    /// components before the first with a glob character — joined to `base`.
261    watch_roots: Vec<PathBuf>,
262    /// The folder of the document's project widgets, if it has one.
263    pub widgets: Option<PathBuf>,
264    /// A site's navbar, in order; empty when it has none.
265    pub navbar: Vec<NavItem>,
266    /// Whether a site shows its Topics sidebar.
267    pub sidebar: bool,
268    /// Whether the page shows the light/dark selector.
269    pub theme_selector: bool,
270    /// The `logo` field as written: an image relative to the document file,
271    /// shown before the title and used as the browser tab's icon.
272    pub logo: Option<String>,
273}
274
275impl Document {
276    /// Loads a document file, `devpage.yml` in a folder, a Markdown file or a
277    /// design, which must lie inside the served folder `served`.
278    pub fn load(path: &Path, served: &ServedFolder) -> Result<Self> {
279        let file = if path.is_dir() {
280            path.join("devpage.yml")
281        } else {
282            path.to_path_buf()
283        };
284        #[cfg(test)]
285        LOADED.with_borrow_mut(|loaded| loaded.push(file.clone()));
286        let text = std::fs::read_to_string(&file)
287            .with_context(|| format!("reading {}", file.display()))?;
288        std::fs::metadata(served.path())
289            .with_context(|| format!("reading {}", served.path().display()))?;
290        // A bare file name has an empty parent, which means the current folder.
291        let parent = file.parent().filter(|p| !p.as_os_str().is_empty());
292        let parent = parent.unwrap_or(Path::new("."));
293        let Some(base) = served.folder(parent) else {
294            parent.canonicalize()?;
295            bail!(
296                "{} is outside the served folder {}",
297                path.display(),
298                served.path().display()
299            );
300        };
301        let file_name = file
302            .file_name()
303            .unwrap_or_default()
304            .to_string_lossy()
305            .into_owned();
306        if file.extension().is_some_and(|ext| ext == "design") {
307            return Ok(Self {
308                served: served.clone(),
309                title: file
310                    .file_stem()
311                    .unwrap_or_default()
312                    .to_string_lossy()
313                    .into_owned(),
314                kind: Kind::Design,
315                base,
316                file_name,
317                watch: None,
318                watch_roots: Vec::new(),
319                widgets: None,
320                navbar: Vec::new(),
321                sidebar: true,
322                theme_selector: true,
323                logo: None,
324            });
325        }
326        if file.extension().is_some_and(|ext| ext == "md") {
327            return Ok(Self {
328                served: served.clone(),
329                title: crate::markup::title(&text, &file),
330                kind: Kind::Doc {
331                    chapters: vec![base.join(&file_name)],
332                    pdf: Pdf::default(),
333                },
334                base,
335                file_name,
336                watch: None,
337                watch_roots: Vec::new(),
338                widgets: None,
339                navbar: Vec::new(),
340                sidebar: true,
341                theme_selector: true,
342                logo: None,
343            });
344        }
345        // Named as the served folder names it, with `/` on every platform.
346        let named = served
347            .name(&base.join(&file_name))
348            .unwrap_or_else(|| file.display().to_string());
349        Self::parse(&text, base, file_name, served.clone()).with_context(|| format!("in {named}"))
350    }
351
352    fn parse(text: &str, base: PathBuf, file_name: String, served: ServedFolder) -> Result<Self> {
353        // A part must be an existing file inside the served folder.
354        let existing = |field: &str, path: &str| -> Result<PathBuf> {
355            match served.file(&base.join(path)) {
356                Some(file) => Ok(file),
357                None => bail!("{field} {path} does not exist"),
358            }
359        };
360        let mut watch = None;
361        let mut watch_roots = Vec::new();
362        let widget_folder;
363        let mut nav_items = Vec::new();
364        let mut show_sidebar = true;
365        let show_selector;
366        let logo_path;
367        let (title, kind) = match serde_yaml::from_str(text)? {
368            Config::Site {
369                title,
370                root,
371                watch: patterns,
372                widgets,
373                navbar: nav,
374                sidebar,
375                theme_selector,
376                logo,
377            } => {
378                logo_path = logo;
379                widget_folder = widgets;
380                show_selector = theme_selector.unwrap_or(true);
381                show_sidebar = sidebar.unwrap_or(true);
382                if let Some(nav) = nav {
383                    nav_items = navbar(&nav)?;
384                }
385                existing("root", &root)?;
386                if let Some(patterns) = patterns {
387                    let mut set = GlobSetBuilder::new();
388                    for pattern in &patterns {
389                        set.add(
390                            Glob::new(pattern)
391                                .with_context(|| format!("watch pattern {pattern}"))?,
392                        );
393                    }
394                    watch = Some(set.build()?);
395                    watch_roots = patterns
396                        .iter()
397                        .map(|pattern| base.join(literal_prefix(pattern)))
398                        .collect();
399                }
400                (title, Kind::Site { root })
401            }
402            Config::Doc {
403                title,
404                chapters,
405                pdf,
406                widgets,
407                theme_selector,
408                logo,
409            } => {
410                logo_path = logo;
411                widget_folder = widgets;
412                show_selector = theme_selector.unwrap_or(true);
413                if chapters.is_empty() {
414                    bail!("chapters lists no files");
415                }
416                let chapters = chapters
417                    .iter()
418                    .map(|chapter| existing("chapter", chapter))
419                    .collect::<Result<_>>()?;
420                (title, Kind::Doc { chapters, pdf })
421            }
422            Config::Slides {
423                title,
424                slides,
425                audience,
426                goal,
427                tone,
428                pronounce,
429                widgets,
430                theme_selector,
431                logo,
432            } => {
433                logo_path = logo;
434                widget_folder = widgets;
435                show_selector = theme_selector.unwrap_or(true);
436                if slides.is_empty() {
437                    bail!("slides lists no files");
438                }
439                let slides = slides
440                    .iter()
441                    .map(|slide| existing("slide", slide).map(Slide::read))
442                    .collect::<Result<_>>()?;
443                let narration = Narration {
444                    audience,
445                    goal,
446                    tone,
447                    pronounce: pronounce.unwrap_or_default(),
448                };
449                (title, Kind::Slides { slides, narration })
450            }
451        };
452        let widgets = match widget_folder {
453            Some(folder) => match served.folder(&base.join(&folder)) {
454                Some(dir) => Some(dir),
455                None => bail!("widgets {folder} is not a folder"),
456            },
457            None => None,
458        };
459        Ok(Self {
460            title,
461            base,
462            kind,
463            file_name,
464            served,
465            watch,
466            watch_roots,
467            widgets,
468            navbar: nav_items,
469            sidebar: show_sidebar,
470            theme_selector: show_selector,
471            logo: logo_path,
472        })
473    }
474
475    /// Where `/` leads: a site's root page, or the document file itself.
476    pub fn entry(&self) -> String {
477        match &self.kind {
478            Kind::Site { root } => self.part_url(&self.base.join(root)),
479            _ => self.part_url(&self.path()),
480        }
481    }
482
483    /// The address of one of the document's parts — its file, a site's
484    /// root, a chapter or a slide.
485    ///
486    /// Panics on any other file outside the served folder: [`Document::load`]
487    /// refuses a document whose part lies outside it, so a part always has
488    /// an address. Any other file's is [`Document::url`].
489    pub fn part_url(&self, part: &Path) -> String {
490        self.part(part, self.url(part))
491    }
492
493    /// The name of one of the document's parts, as its problems show it;
494    /// panics as [`Document::part_url`] does.
495    pub fn part_name(&self, part: &Path) -> String {
496        self.part(part, self.name(part))
497    }
498
499    fn part(&self, part: &Path, named: Option<String>) -> String {
500        named.unwrap_or_else(|| {
501            panic!(
502                "{} is no part of {}: it lies outside the served folder {}",
503                part.display(),
504                self.path().display(),
505                self.served.path().display()
506            )
507        })
508    }
509
510    /// The document file itself.
511    pub fn path(&self) -> PathBuf {
512        self.base.join(&self.file_name)
513    }
514
515    /// The logo's address, when the document has one and the file exists in
516    /// the served folder. A logo that doesn't is a problem, not an error:
517    /// the page shows without it.
518    pub fn logo_url(&self) -> Option<String> {
519        let written = self.logo.as_ref()?;
520        let file = self.served.file(&self.base.join(written))?;
521        self.url(&file)
522    }
523
524    /// A file's address: its path from the top of the served folder;
525    /// `None` for a file outside it, which has none.
526    pub fn url(&self, file: &Path) -> Option<String> {
527        self.served.url(file)
528    }
529
530    /// A file's name from the top of the served folder, for labels; `None`
531    /// for a file outside it, which is never named.
532    pub fn name(&self, file: &Path) -> Option<String> {
533        self.served.name(file)
534    }
535
536    /// The file a URL path names, if it lies inside the served folder.
537    pub fn file(&self, url_path: &str) -> Option<PathBuf> {
538        self.served.at(url_path)
539    }
540
541    /// Whether a change to `file` refreshes open pages: always, unless this
542    /// is a site whose `watch` list matches none of it, relative to its folder.
543    pub fn watches(&self, file: &Path) -> bool {
544        let Some(watch) = &self.watch else {
545            return true;
546        };
547        file.strip_prefix(&self.base)
548            .is_ok_and(|relative| watch.is_match(relative))
549    }
550
551    /// Whether this is a site whose `watch` list names `file`, relative to
552    /// its folder.
553    pub fn names(&self, file: &Path) -> bool {
554        self.watch.is_some() && self.watches(file)
555    }
556
557    /// The folders a site's `watch` patterns can name files in: each
558    /// pattern's literal prefix in the site's folder. Empty without a list.
559    pub fn watch_roots(&self) -> &[PathBuf] {
560        &self.watch_roots
561    }
562}
563
564/// A glob pattern's components before the first one with a glob character:
565/// `build/*.svg` gives `build`, `**/*.md` gives nothing.
566fn literal_prefix(pattern: &str) -> PathBuf {
567    Path::new(pattern)
568        .components()
569        .take_while(|part| {
570            !part
571                .as_os_str()
572                .to_string_lossy()
573                .contains(['*', '?', '[', '{'])
574        })
575        .collect()
576}
577
578/// The kind a YAML file names in its top-level `kind`, when it is one of
579/// devpage's three; any other file is not a document file.
580pub fn kind_of(file: &Path) -> Option<KindName> {
581    if !file
582        .extension()
583        .is_some_and(|ext| ext == "yml" || ext == "yaml")
584    {
585        return None;
586    }
587    let text = std::fs::read_to_string(file).ok()?;
588    let value: serde_yaml::Value = serde_yaml::from_str(&text).ok()?;
589    match value.get("kind")?.as_str()? {
590        "site" => Some(KindName::Site),
591        "doc" => Some(KindName::Doc),
592        "slides" => Some(KindName::Slides),
593        _ => None,
594    }
595}
596
597/// What a published document of `kind` downloads as — a doc or slides
598/// printed as a PDF, a design painted as its PNG — as its extension and
599/// media type; `None` for a kind that has no download, a site. The one rule
600/// for it, the server's and `devpage download`'s.
601pub fn downloads_as(kind: &str) -> Option<(&'static str, &'static str)> {
602    match kind {
603        "doc" | "slides" => Some(("pdf", "application/pdf")),
604        "design" => Some(("png", "image/png")),
605        _ => None,
606    }
607}
608
609/// The file a document is saved as when nothing names one — what `devpage
610/// pdf` and `devpage video` write and what a version downloads as: its
611/// `title`, with the characters a file name can't hold replaced by `-`, and
612/// `extension`.
613pub fn download_name(title: &str, extension: &str) -> PathBuf {
614    let name: String = title
615        .chars()
616        .map(|c| match c {
617            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
618            c if c.is_control() => '-',
619            c => c,
620        })
621        .collect();
622    let name = name.trim().trim_start_matches('.');
623    let name = if name.is_empty() { "document" } else { name };
624    PathBuf::from(format!("{name}.{extension}"))
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630
631    #[test]
632    fn docs_and_slides_download_as_a_pdf_a_design_as_a_png_and_a_site_not() {
633        assert_eq!(downloads_as("doc"), Some(("pdf", "application/pdf")));
634        assert_eq!(downloads_as("slides"), Some(("pdf", "application/pdf")));
635        assert_eq!(downloads_as("design"), Some(("png", "image/png")));
636        assert_eq!(downloads_as("site"), None);
637    }
638
639    #[test]
640    fn the_download_name_is_the_title_made_safe() {
641        assert_eq!(
642            download_name("Offline sync", "pdf"),
643            Path::new("Offline sync.pdf")
644        );
645        assert_eq!(
646            download_name("A/B: why?", "pdf"),
647            Path::new("A-B- why-.pdf")
648        );
649        assert_eq!(download_name("...", "pdf"), Path::new("document.pdf"));
650        assert_eq!(
651            download_name("A/B: v1.2", "mp4"),
652            Path::new("A-B- v1.2.mp4")
653        );
654        assert_eq!(download_name("Screen", "png"), Path::new("Screen.png"));
655    }
656
657    fn folder(name: &str) -> PathBuf {
658        let dir = std::env::temp_dir().join(format!("devpage-doc-{name}-{}", std::process::id()));
659        std::fs::create_dir_all(dir.join("guides")).unwrap();
660        std::fs::write(dir.join("README.md"), "# Home").unwrap();
661        std::fs::write(dir.join("guides/start.md"), "# Start").unwrap();
662        dir.canonicalize().unwrap()
663    }
664
665    fn parse(text: &str, dir: PathBuf) -> Result<Document> {
666        Document::parse(
667            text,
668            dir.clone(),
669            "devpage.yml".into(),
670            ServedFolder::canonical(dir),
671        )
672    }
673
674    #[test]
675    fn parses_each_kind() {
676        let dir = folder("kinds");
677        let site = parse("kind: site\ntitle: Docs\nroot: README.md\n", dir.clone()).unwrap();
678        assert_eq!(site.entry(), "/README.md");
679        let doc = parse(
680            "kind: doc\ntitle: Plan\nchapters: [README.md, guides/start.md]\npdf: {paper: Letter}\n",
681            dir.clone(),
682        )
683        .unwrap();
684        let Kind::Doc { chapters, pdf } = &doc.kind else {
685            panic!("{doc:?}")
686        };
687        assert_eq!(chapters.len(), 2);
688        assert_eq!(pdf.paper, Paper::Letter);
689        assert_eq!(pdf.footer, "{page} / {pages}");
690        assert_eq!(doc.entry(), "/devpage.yml");
691        let slides = parse("kind: slides\ntitle: Talk\nslides: [README.md]\n", dir).unwrap();
692        assert!(matches!(slides.kind, Kind::Slides { .. }));
693    }
694
695    #[test]
696    fn rejects_bad_kinds_fields_and_missing_files() {
697        let dir = folder("bad");
698        for text in [
699            "title: Docs\nroot: README.md\n",
700            "kind: deck\ntitle: Docs\nroot: README.md\n",
701            "kind: site\ntitle: Docs\nroot: nope.md\n",
702            "kind: site\ntitle: Docs\nroot: README.md\ncolour: red\n",
703            "kind: site\ntitle: Docs\nroot: README.md\nwatch: \"*.md\"\n",
704            "kind: site\ntitle: Docs\nroot: README.md\nwatch: [\"a[b\"]\n",
705            "kind: doc\ntitle: Docs\nroot: README.md\nchapters: [README.md]\n",
706            "kind: doc\ntitle: Docs\nchapters: [missing.md]\n",
707            "kind: doc\ntitle: Docs\nchapters: [../outside.md]\n",
708        ] {
709            assert!(parse(text, dir.clone()).is_err(), "{text}");
710        }
711    }
712
713    #[test]
714    fn reads_the_navbar_in_order_and_refuses_bad_shapes() {
715        let dir = folder("navbar");
716        let document = parse(
717            "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",
718            dir.clone(),
719        )
720        .unwrap();
721        assert!(!document.sidebar && !document.theme_selector);
722        let link = |label: Option<&str>, icon: Option<&str>, target: &str| NavLink {
723            label: label.map(String::from),
724            icon: icon.map(String::from),
725            target: target.into(),
726        };
727        assert_eq!(
728            document.navbar,
729            [
730                NavItem::Link(link(Some("Docs"), Some("book-open"), "README.md")),
731                NavItem::Link(link(Some("Plain"), None, "README.md")),
732                NavItem::Menu {
733                    label: Some("More".into()),
734                    icon: Some("layout-grid".into()),
735                    items: vec![link(Some("Talk"), Some("presentation"), "talk.yml")],
736                },
737                NavItem::Link(link(None, Some("github"), "https://github.com/x/y")),
738            ]
739        );
740        // Defaults: a sidebar, a selector, no navbar; a doc and a deck may opt out too.
741        let plain = parse("kind: site\ntitle: T\nroot: README.md\n", dir.clone()).unwrap();
742        assert!(plain.sidebar && plain.theme_selector && plain.navbar.is_empty());
743        assert!(
744            !parse(
745                "kind: doc\ntitle: T\nchapters: [README.md]\ntheme-selector: false\n",
746                dir.clone()
747            )
748            .unwrap()
749            .theme_selector
750        );
751        for text in [
752            // two levels deep, an empty dropdown, a list instead of a map, no label or icon
753            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A:\n    B:\n      C: README.md\n",
754            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A: {}\n",
755            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  - A: README.md\n",
756            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  \"  \": README.md\n",
757            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A: 3\n",
758            // a navbar and a sidebar belong to sites
759            "kind: doc\ntitle: T\nchapters: [README.md]\nnavbar:\n  A: README.md\n",
760            "kind: slides\ntitle: T\nslides: [README.md]\nsidebar: false\n",
761        ] {
762            assert!(parse(text, dir.clone()).is_err(), "{text}");
763        }
764    }
765
766    #[test]
767    fn a_markdown_file_is_a_doc_of_one_chapter() {
768        let dir = folder("md");
769        let doc = Document::load(
770            &dir.join("guides/start.md"),
771            &ServedFolder::new(&dir).unwrap(),
772        )
773        .unwrap();
774        assert_eq!(doc.title, "Start");
775        assert!(matches!(&doc.kind, Kind::Doc { chapters, .. } if chapters.len() == 1));
776    }
777
778    #[test]
779    fn the_served_folder_is_the_boundary_and_addresses_start_there() {
780        // No .git anywhere: the served folder is whatever devpage was given.
781        let served = folder("served");
782        std::fs::write(
783            served.join("guides/devpage.yml"),
784            "kind: site\ntitle: G\nroot: start.md\n",
785        )
786        .unwrap();
787        let doc =
788            Document::load(&served.join("guides"), &ServedFolder::new(&served).unwrap()).unwrap();
789        assert_eq!(doc.served.path(), served);
790        assert_eq!(doc.entry(), "/guides/start.md");
791        assert!(
792            doc.file("/README.md").is_some(),
793            "files beside the docs are served"
794        );
795        assert!(doc.file("/../x").is_none());
796
797        // --root moves the boundary: served from guides/, README.md is outside.
798        let guides = served.join("guides");
799        let narrow = Document::load(&guides, &ServedFolder::new(&guides).unwrap()).unwrap();
800        assert_eq!(narrow.entry(), "/start.md");
801        assert!(narrow.file("/../README.md").is_none());
802    }
803
804    #[test]
805    fn a_document_outside_the_served_folder_is_refused() {
806        let served = folder("outside");
807        let error = Document::load(
808            &served.join("README.md"),
809            &ServedFolder::new(&served.join("guides")).unwrap(),
810        )
811        .unwrap_err()
812        .to_string();
813        assert!(error.contains("is outside the served folder"), "{error}");
814    }
815
816    #[test]
817    fn a_site_watch_list_narrows_what_refreshes() {
818        let dir = folder("watch");
819        let all = parse("kind: site\ntitle: D\nroot: README.md\n", dir.clone()).unwrap();
820        assert!(all.watches(&dir.join("logo.png")));
821        let narrow = parse(
822            "kind: site\ntitle: D\nroot: README.md\nwatch: [\"**/*.md\"]\n",
823            dir.clone(),
824        )
825        .unwrap();
826        assert!(narrow.watches(&dir.join("guides/start.md")));
827        assert!(!narrow.watches(&dir.join("logo.png")));
828    }
829
830    #[test]
831    fn only_yaml_with_a_devpage_kind_is_a_document_file() {
832        let dir = folder("kind-of");
833        std::fs::write(dir.join("site.yml"), "kind: site\ntitle: T\n").unwrap();
834        std::fs::write(dir.join("deploy.yaml"), "kind: Deployment\n").unwrap();
835        std::fs::write(dir.join("ci.yml"), "on: push\n").unwrap();
836        assert_eq!(kind_of(&dir.join("site.yml")), Some(KindName::Site));
837        assert_eq!(kind_of(&dir.join("deploy.yaml")), None);
838        assert_eq!(kind_of(&dir.join("ci.yml")), None);
839        assert_eq!(kind_of(&dir.join("README.md")), None);
840    }
841
842    #[test]
843    fn a_deck_keeps_its_narration_and_each_slides_notes_and_delivery() {
844        let dir = folder("notes");
845        std::fs::write(
846            dir.join("one.md"),
847            "# One\n\n<Notes delivery=\"Warm, a smile in the voice.\">\n  Hello, everyone.\n</Notes>\n\n<Notes>second</Notes>\n",
848        )
849        .unwrap();
850        std::fs::write(dir.join("two.md"), "# Two\n\n`<Notes>not these</Notes>`\n").unwrap();
851        let deck = parse(
852            "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",
853            dir.clone(),
854        )
855        .unwrap();
856        let Kind::Slides { slides, narration } = &deck.kind else {
857            panic!("{deck:?}")
858        };
859        assert_eq!(
860            narration,
861            &Narration {
862                audience: Some("Engineers.".to_string()),
863                goal: Some("They try it.".to_string()),
864                tone: Some("Warm and brief.".to_string()),
865                pronounce: vec!["Say \"devpage\" as \"dev page\".".to_string()],
866            }
867        );
868        assert_eq!(slides[0].file, dir.join("one.md"));
869        assert_eq!(slides[0].notes.as_deref(), Some("Hello, everyone."));
870        assert_eq!(
871            slides[0].delivery.as_deref(),
872            Some("Warm, a smile in the voice.")
873        );
874        assert_eq!(slides[1].notes, None);
875        let plain = parse("kind: slides\ntitle: T\nslides: [one.md]\n", dir.clone()).unwrap();
876        assert!(
877            matches!(&plain.kind, Kind::Slides { narration, .. } if *narration == Narration::default())
878        );
879        // The narration belongs to slides, and `context` is gone.
880        for text in [
881            "kind: doc\ntitle: T\nchapters: [README.md]\naudience: x\n",
882            "kind: site\ntitle: T\nroot: README.md\ngoal: x\n",
883            "kind: slides\ntitle: T\nslides: [one.md]\ncontext: x\n",
884            "kind: slides\ntitle: T\nslides: [one.md]\npronounce: x\n",
885        ] {
886            assert!(parse(text, dir.clone()).is_err(), "{text}");
887        }
888    }
889}