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