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    /// A site: pages reached from its `root` page, with a navbar if it names
24    /// one, and the Topics sidebar unless `sidebar` turns it off.
25    Site {
26        title: String,
27        root: String,
28        watch: Option<Vec<String>>,
29        widgets: Option<String>,
30        structure: Option<String>,
31        navbar: Option<serde_yaml::Mapping>,
32        sidebar: Option<bool>,
33        #[serde(rename = "theme-selector")]
34        theme_selector: Option<bool>,
35        logo: Option<String>,
36        #[serde(default)]
37        extensions: std::collections::BTreeMap<String, crate::extensions::Config>,
38        #[serde(default)]
39        places: Places,
40    },
41    /// A doc: its `chapters` in order, and its settings on paper.
42    Doc {
43        title: String,
44        chapters: Vec<String>,
45        #[serde(default)]
46        pdf: Pdf,
47        widgets: Option<String>,
48        #[serde(rename = "theme-selector")]
49        theme_selector: Option<bool>,
50        logo: Option<String>,
51        #[serde(default)]
52        extensions: std::collections::BTreeMap<String, crate::extensions::Config>,
53        #[serde(default)]
54        places: Places,
55    },
56    /// A deck: its `slides` in order, and what its narrator is told about the
57    /// talk.
58    Slides {
59        title: String,
60        slides: Vec<String>,
61        audience: Option<String>,
62        goal: Option<String>,
63        tone: Option<String>,
64        pronounce: Option<Vec<String>>,
65        widgets: Option<String>,
66        #[serde(rename = "theme-selector")]
67        theme_selector: Option<bool>,
68        logo: Option<String>,
69        #[serde(default)]
70        extensions: std::collections::BTreeMap<String, crate::extensions::Config>,
71        #[serde(default)]
72        places: Places,
73    },
74}
75
76/// The widgets a document shows outside its pages' text, by place: each a
77/// list of widget names, shown in order on every page.
78#[derive(Debug, Clone, Default, Deserialize, serde::Serialize, PartialEq, Eq)]
79#[serde(deny_unknown_fields)]
80pub struct Places {
81    /// Beside the theme selector: at the end of a site's navbar, or in the
82    /// top-right corner of a page with none.
83    #[serde(default)]
84    pub navbar: Vec<String>,
85    /// The panel at the right edge of the window.
86    #[serde(default)]
87    pub panel: Vec<String>,
88    /// Floating over the page, at the middle of the window's bottom edge.
89    #[serde(default)]
90    pub float: Vec<String>,
91}
92
93impl Places {
94    /// Each package places its widgets after the document's own.
95    fn with_packages(mut self, extensions: &[crate::extensions::Binding]) -> Self {
96        for binding in extensions {
97            let places = binding.places();
98            self.navbar.extend(places.navbar);
99            self.panel.extend(places.panel);
100            self.float.extend(places.float);
101        }
102        self
103    }
104
105    /// Each place that names a widget, by its name in the document file.
106    pub fn named(&self) -> Vec<(&'static str, &[String])> {
107        [
108            ("navbar", self.navbar.as_slice()),
109            ("panel", self.panel.as_slice()),
110            ("float", self.float.as_slice()),
111        ]
112        .into_iter()
113        .filter(|(_, widgets)| !widgets.is_empty())
114        .collect()
115    }
116}
117
118/// One link of a site's navbar, as written: a label, an icon or both, and its
119/// target — a path relative to the document file, or an address on the web.
120#[derive(Debug, Clone, PartialEq)]
121pub struct NavLink {
122    /// Its text; `None` when it shows only its icon.
123    pub label: Option<String>,
124    /// The name of its icon, from the key's `(icon)`; `None` when it has none.
125    pub icon: Option<String>,
126    /// Where it leads, as written: a path relative to the document file, or an
127    /// address on the web.
128    pub target: String,
129}
130
131/// An entry of a site's navbar: a link, or a dropdown of links.
132#[derive(Debug, Clone, PartialEq)]
133pub enum NavItem {
134    /// A link on the navbar itself.
135    Link(NavLink),
136    /// A dropdown, with its own label or icon, of `items`.
137    Menu {
138        label: Option<String>,
139        icon: Option<String>,
140        items: Vec<NavLink>,
141    },
142}
143
144/// Splits a navbar key into its label and its `(icon)`: `Docs (book-open)`,
145/// `Docs`, or `(github)` alone.
146fn label_and_icon(key: &str) -> Result<(Option<String>, Option<String>)> {
147    let key = key.trim();
148    let (label, icon) = match key.strip_suffix(')').and_then(|rest| rest.rsplit_once('(')) {
149        Some((label, icon))
150            if !icon.is_empty()
151                && icon
152                    .chars()
153                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') =>
154        {
155            (label.trim(), Some(icon.to_string()))
156        }
157        _ => (key, None),
158    };
159    let label = (!label.is_empty()).then(|| label.to_string());
160    if label.is_none() && icon.is_none() {
161        bail!("navbar has an entry with neither a label nor an icon");
162    }
163    Ok((label, icon))
164}
165
166/// Reads a `navbar` map, in order: `label: target` is a link, `label:` with a
167/// nested map is a dropdown of links, one level deep.
168fn navbar(map: &serde_yaml::Mapping) -> Result<Vec<NavItem>> {
169    let key_text = |key: &serde_yaml::Value| -> Result<String> {
170        match key {
171            serde_yaml::Value::String(text) => Ok(text.clone()),
172            other => bail!("navbar: {other:?} is not a label"),
173        }
174    };
175    let mut items = Vec::new();
176    for (key, value) in map {
177        let key = key_text(key)?;
178        let (label, icon) = label_and_icon(&key)?;
179        match value {
180            serde_yaml::Value::String(target) => items.push(NavItem::Link(NavLink {
181                label,
182                icon,
183                target: target.clone(),
184            })),
185            serde_yaml::Value::Mapping(links) => {
186                let mut menu = Vec::new();
187                for (inner_key, value) in links {
188                    let inner = key_text(inner_key)?;
189                    let serde_yaml::Value::String(target) = value else {
190                        bail!(
191                            "navbar: {inner} under {key} must be a link — dropdowns are one level deep"
192                        );
193                    };
194                    let (label, icon) = label_and_icon(&inner)?;
195                    menu.push(NavLink {
196                        label,
197                        icon,
198                        target: target.clone(),
199                    });
200                }
201                if menu.is_empty() {
202                    bail!("navbar: {key} lists no links");
203                }
204                items.push(NavItem::Menu {
205                    label,
206                    icon,
207                    items: menu,
208                });
209            }
210            _ => bail!("navbar: {key} must be a link or a map of links"),
211        }
212    }
213    Ok(items)
214}
215
216/// A doc's settings on paper.
217#[derive(Debug, Clone, Deserialize, PartialEq)]
218#[serde(deny_unknown_fields)]
219pub struct Pdf {
220    /// The paper size each page is printed on.
221    #[serde(default)]
222    pub paper: Paper,
223    /// The text at the top of every page, where `{page}` and `{pages}` become
224    /// page numbers; `None` leaves it blank.
225    pub header: Option<String>,
226    /// The text at the bottom of every page, numbered as `header` is: `{page} /
227    /// {pages}` unless set.
228    #[serde(default = "default_footer")]
229    pub footer: String,
230}
231
232impl Default for Pdf {
233    fn default() -> Self {
234        Self {
235            paper: Paper::default(),
236            header: None,
237            footer: default_footer(),
238        }
239    }
240}
241
242/// The footer a doc gets when it sets none: `{page} / {pages}`.
243fn default_footer() -> String {
244    "{page} / {pages}".into()
245}
246
247/// The paper size a doc is printed on.
248#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
249pub enum Paper {
250    /// ISO A4: 210 × 297 mm, the default.
251    #[default]
252    A4,
253    /// US Letter: 8.5 × 11 in.
254    Letter,
255}
256
257/// What a document is, with its parts resolved to files.
258#[derive(Debug, Clone, PartialEq)]
259pub enum Kind {
260    /// A site, whose `/` leads to `root`: its page as written, relative to the
261    /// document's folder.
262    Site { root: String },
263    /// A doc: its chapter files in order, and its settings on paper.
264    Doc { chapters: Vec<PathBuf>, pdf: Pdf },
265    /// A deck: its slides in order.
266    Slides {
267        slides: Vec<Slide>,
268        /// Who the talk is for and how it should sound, for its narrator.
269        narration: Narration,
270    },
271    /// A `.design` file, which is the whole document.
272    Design,
273}
274
275/// What a deck tells its narrator about the talk as a whole, as written in
276/// its document file: who it is for, what it should achieve, how it should
277/// sound, and how to say words a voice gets wrong.
278#[derive(Debug, Clone, Default, PartialEq)]
279pub struct Narration {
280    /// Who the talk is for.
281    pub audience: Option<String>,
282    /// What the talk should achieve.
283    pub goal: Option<String>,
284    /// How the talk should sound; `None` leaves the narrator's default tone.
285    pub tone: Option<String>,
286    /// How to say the words a voice gets wrong, one instruction each.
287    pub pronounce: Vec<String>,
288}
289
290/// One slide of a deck: its Markdown file, its notes — the text of its first
291/// `<Notes>`, if it has one — and that `<Notes>`' `delivery`.
292#[derive(Debug, Clone, PartialEq)]
293pub struct Slide {
294    /// The slide's Markdown file: what it shows and its notes are read from.
295    pub file: PathBuf,
296    /// The text of its first `<Notes>`; `None` when it has none.
297    pub notes: Option<String>,
298    /// That `<Notes>`' `delivery`: how the narrator should say it.
299    pub delivery: Option<String>,
300}
301
302impl Slide {
303    /// Reads a slide's notes from its file.
304    fn read(file: PathBuf) -> Self {
305        let source = std::fs::read_to_string(&file).unwrap_or_default();
306        let first = crate::markup::notes(&source).into_iter().next();
307        let (notes, delivery) = match first {
308            Some(note) => (Some(note.text), note.delivery),
309            None => (None, None),
310        };
311        Self {
312            file,
313            notes,
314            delivery,
315        }
316    }
317}
318
319/// Which kind a document file names, read without loading the document.
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum KindName {
322    /// `kind: site` — the nearest one above a page is the site it belongs to.
323    Site,
324    /// `kind: doc` — chapters shown, and printed, as one document.
325    Doc,
326    /// `kind: slides` — a deck, whose `<deck>/<n>.png` addresses are drawn
327    /// from it.
328    Slides,
329}
330
331/// A loaded document: its title, its folder, what it is, and where it is served.
332#[derive(Debug)]
333pub struct Document {
334    /// The extensions the document file configures, bound to it, and the
335    /// live session where it is on.
336    pub extensions: Vec<crate::extensions::Binding>,
337    /// The title it shows: as written, or a Markdown file's first heading —
338    /// its file name when it has none — or a design's file name.
339    pub title: String,
340    /// The folder of the document file, which its paths are relative to.
341    pub base: PathBuf,
342    /// What it is — a site, a doc, slides or a design — with its parts
343    /// resolved.
344    pub kind: Kind,
345    /// The document file's name inside `base`.
346    pub file_name: String,
347    /// The served folder: where devpage was started, or `--root`. Addresses
348    /// are paths in it, and nothing outside it is served.
349    pub served: ServedFolder,
350    /// A site's `watch` list: when set, only matching files refresh pages.
351    watch: Option<GlobSet>,
352    /// Where each `watch` pattern can match: its literal prefix — the
353    /// components before the first with a glob character — joined to `base`.
354    watch_roots: Vec<PathBuf>,
355    /// The folder of the document's project widgets, if it has one.
356    pub widgets: Option<PathBuf>,
357    /// The widgets it shows outside its pages' text: its own and, after
358    /// them, the live session's where that is bound to it.
359    pub places: Places,
360    /// A site's structure folder — its type files — if it names one.
361    pub structure: Option<PathBuf>,
362    /// A site's requirements — its test suites — if it configures them.
363    pub requirements: Option<crate::requirements::Requirements>,
364    /// A site's navbar, in order; empty when it has none.
365    pub navbar: Vec<NavItem>,
366    /// Whether a site shows its Topics sidebar.
367    pub sidebar: bool,
368    /// Whether the page shows the light/dark selector.
369    pub theme_selector: bool,
370    /// The `logo` field as written: an image relative to the document file,
371    /// shown before the title and used as the browser tab's icon.
372    pub logo: Option<String>,
373}
374
375impl Document {
376    /// Loads a document file, `devpage.yml` in a folder, a Markdown file or a
377    /// design, which must lie inside the served folder `served`.
378    pub fn load(path: &Path, served: &ServedFolder) -> Result<Self> {
379        let file = if path.is_dir() {
380            let file = path.join("devpage.yml");
381            if !file.exists() {
382                bail!("{}", no_document_file(path));
383            }
384            file
385        } else {
386            path.to_path_buf()
387        };
388        #[cfg(test)]
389        LOADED.with_borrow_mut(|loaded| loaded.push(file.clone()));
390        let text = std::fs::read_to_string(&file)
391            .with_context(|| format!("reading {}", file.display()))?;
392        std::fs::metadata(served.path())
393            .with_context(|| format!("reading {}", served.path().display()))?;
394        // A bare file name has an empty parent, which means the current folder.
395        let parent = file.parent().filter(|p| !p.as_os_str().is_empty());
396        let parent = parent.unwrap_or(Path::new("."));
397        let Some(base) = served.folder(parent) else {
398            parent.canonicalize()?;
399            bail!(
400                "{} is outside the served folder {}",
401                path.display(),
402                served.path().display()
403            );
404        };
405        let file_name = file
406            .file_name()
407            .unwrap_or_default()
408            .to_string_lossy()
409            .into_owned();
410        if file.extension().is_some_and(|ext| ext == "design") {
411            return Ok(Self {
412                extensions: Vec::new(),
413                served: served.clone(),
414                title: file
415                    .file_stem()
416                    .unwrap_or_default()
417                    .to_string_lossy()
418                    .into_owned(),
419                kind: Kind::Design,
420                base,
421                file_name,
422                watch: None,
423                watch_roots: Vec::new(),
424                widgets: None,
425                places: Places::default(),
426                structure: None,
427                requirements: None,
428                navbar: Vec::new(),
429                sidebar: true,
430                theme_selector: true,
431                logo: None,
432            });
433        }
434        if file.extension().is_some_and(|ext| ext == "md") {
435            // A standalone page inherits the local package defaults.
436            let path = base.join(&file_name);
437            crate::extensions::configure(
438                &path,
439                &base,
440                served,
441                crate::extensions::configured(served, Default::default()),
442            )?;
443            let extensions = crate::extensions::for_document(&path);
444            return Ok(Self {
445                places: Places::default().with_packages(&extensions),
446                extensions,
447                served: served.clone(),
448                title: crate::markup::title(&text, &file),
449                kind: Kind::Doc {
450                    chapters: vec![base.join(&file_name)],
451                    pdf: Pdf::default(),
452                },
453                base,
454                file_name,
455                watch: None,
456                watch_roots: Vec::new(),
457                widgets: None,
458                structure: None,
459                requirements: None,
460                navbar: Vec::new(),
461                sidebar: true,
462                theme_selector: true,
463                logo: None,
464            });
465        }
466        // Named as the served folder names it, with `/` on every platform.
467        let named = served
468            .name(&base.join(&file_name))
469            .unwrap_or_else(|| file.display().to_string());
470        Self::parse(&text, base, file_name, served.clone()).with_context(|| format!("in {named}"))
471    }
472
473    /// Reads a document file's YAML `text`, whose paths are relative to `base`,
474    /// checking each part is an existing file in `served`.
475    fn parse(text: &str, base: PathBuf, file_name: String, served: ServedFolder) -> Result<Self> {
476        // A part must be an existing file inside the served folder.
477        let existing = |field: &str, path: &str| -> Result<PathBuf> {
478            match served.file(&base.join(path)) {
479                Some(file) => Ok(file),
480                None => bail!("{field} {path} does not exist"),
481            }
482        };
483        let mut watch = None;
484        let mut watch_roots = Vec::new();
485        let widget_folder;
486        let mut structure_folder = None;
487        let mut nav_items = Vec::new();
488        let mut show_sidebar = true;
489        let show_selector;
490        let logo_path;
491        let extension_configs;
492        let places;
493        let (title, kind) = match serde_yaml::from_str(text)? {
494            Config::Site {
495                title,
496                root,
497                watch: patterns,
498                widgets,
499                structure,
500                navbar: nav,
501                sidebar,
502                theme_selector,
503                logo,
504                extensions,
505                places: placed,
506            } => {
507                extension_configs = extensions;
508                places = placed;
509                logo_path = logo;
510                widget_folder = widgets;
511                structure_folder = structure;
512                show_selector = theme_selector.unwrap_or(true);
513                show_sidebar = sidebar.unwrap_or(true);
514                if let Some(nav) = nav {
515                    nav_items = navbar(&nav)?;
516                }
517                existing("root", &root)?;
518                if let Some(patterns) = patterns {
519                    let mut set = GlobSetBuilder::new();
520                    for pattern in &patterns {
521                        set.add(
522                            Glob::new(pattern)
523                                .with_context(|| format!("watch pattern {pattern}"))?,
524                        );
525                    }
526                    watch = Some(set.build()?);
527                    watch_roots = patterns
528                        .iter()
529                        .map(|pattern| base.join(literal_prefix(pattern)))
530                        .collect();
531                }
532                (title, Kind::Site { root })
533            }
534            Config::Doc {
535                title,
536                chapters,
537                pdf,
538                widgets,
539                theme_selector,
540                logo,
541                extensions,
542                places: placed,
543            } => {
544                extension_configs = extensions;
545                places = placed;
546                logo_path = logo;
547                widget_folder = widgets;
548                show_selector = theme_selector.unwrap_or(true);
549                if chapters.is_empty() {
550                    bail!("chapters lists no files");
551                }
552                let chapters = chapters
553                    .iter()
554                    .map(|chapter| existing("chapter", chapter))
555                    .collect::<Result<_>>()?;
556                (title, Kind::Doc { chapters, pdf })
557            }
558            Config::Slides {
559                title,
560                slides,
561                audience,
562                goal,
563                tone,
564                pronounce,
565                widgets,
566                theme_selector,
567                logo,
568                extensions,
569                places: placed,
570            } => {
571                extension_configs = extensions;
572                places = placed;
573                logo_path = logo;
574                widget_folder = widgets;
575                show_selector = theme_selector.unwrap_or(true);
576                if slides.is_empty() {
577                    bail!("slides lists no files");
578                }
579                let slides = slides
580                    .iter()
581                    .map(|slide| existing("slide", slide).map(Slide::read))
582                    .collect::<Result<_>>()?;
583                let narration = Narration {
584                    audience,
585                    goal,
586                    tone,
587                    pronounce: pronounce.unwrap_or_default(),
588                };
589                (title, Kind::Slides { slides, narration })
590            }
591        };
592        let widgets = match widget_folder {
593            Some(folder) => match served.folder(&base.join(&folder)) {
594                Some(dir) => Some(dir),
595                None => bail!("widgets {folder} is not a folder"),
596            },
597            None => None,
598        };
599        let structure = match structure_folder {
600            Some(folder) => match served.folder(&base.join(&folder)) {
601                Some(dir) => Some(dir),
602                None => bail!("structure {folder} is not a folder"),
603            },
604            None => None,
605        };
606        let mut extension_configs = crate::extensions::configured(&served, extension_configs);
607        // `code` with no package is the system extension: the code reference,
608        // which only a site has pages for.
609        let code = match extension_configs.get("code") {
610            Some(config) if config.package.is_none() && config.enabled != Some(false) => {
611                if !matches!(kind, Kind::Site { .. }) {
612                    bail!("extensions: code: only a site has a code reference");
613                }
614                extension_configs.remove("code").map(|config| config.config)
615            }
616            _ => None,
617        };
618        // `requirements` with no package is the system extension that holds a
619        // site's constraints to its tests.
620        let requirements = match extension_configs.get("requirements") {
621            Some(config) if config.package.is_none() && config.enabled != Some(false) => {
622                if !matches!(kind, Kind::Site { .. }) {
623                    bail!("extensions: requirements: only a site has requirements");
624                }
625                let config = extension_configs.remove("requirements").map(|c| c.config);
626                Some(
627                    crate::requirements::Requirements::read(
628                        &config.unwrap_or_default(),
629                        &base,
630                        &served,
631                    )
632                    .map_err(|e| anyhow::anyhow!("extensions: requirements: {e:#}"))?,
633                )
634            }
635            _ => None,
636        };
637        crate::code::configure(&base.join(&file_name), &base, &served, code.as_ref())?;
638        crate::extensions::configure(&base.join(&file_name), &base, &served, extension_configs)?;
639        let extensions = crate::extensions::for_document(&base.join(&file_name));
640        let places = places.with_packages(&extensions);
641        Ok(Self {
642            extensions,
643            title,
644            base,
645            kind,
646            file_name,
647            served,
648            watch,
649            watch_roots,
650            widgets,
651            places,
652            structure,
653            requirements,
654            navbar: nav_items,
655            sidebar: show_sidebar,
656            theme_selector: show_selector,
657            logo: logo_path,
658        })
659    }
660
661    /// Where `/` leads: a site's root page, or the document file itself.
662    pub fn entry(&self) -> String {
663        match &self.kind {
664            Kind::Site { root } => self.part_url(&self.base.join(root)),
665            _ => self.part_url(&self.path()),
666        }
667    }
668
669    /// The address of one of the document's parts — its file, a site's
670    /// root, a chapter or a slide.
671    ///
672    /// Panics on any other file outside the served folder: [`Document::load`]
673    /// refuses a document whose part lies outside it, so a part always has
674    /// an address. Any other file's is [`Document::url`].
675    pub fn part_url(&self, part: &Path) -> String {
676        self.part(part, self.url(part))
677    }
678
679    /// The name of one of the document's parts, as its problems show it;
680    /// panics as [`Document::part_url`] does.
681    pub fn part_name(&self, part: &Path) -> String {
682        self.part(part, self.name(part))
683    }
684
685    /// Unwraps `named`, the address or name of `part`: panics when it is
686    /// `None`, as [`Document::part_url`] says.
687    fn part(&self, part: &Path, named: Option<String>) -> String {
688        named.unwrap_or_else(|| {
689            panic!(
690                "{} is no part of {}: it lies outside the served folder {}",
691                part.display(),
692                self.path().display(),
693                self.served.path().display()
694            )
695        })
696    }
697
698    /// The document file itself.
699    pub fn path(&self) -> PathBuf {
700        self.base.join(&self.file_name)
701    }
702
703    /// The logo's address, when the document has one and the file exists in
704    /// the served folder. A logo that doesn't is a problem, not an error:
705    /// the page shows without it.
706    pub fn logo_url(&self) -> Option<String> {
707        let written = self.logo.as_ref()?;
708        let file = self.served.file(&self.base.join(written))?;
709        self.url(&file)
710    }
711
712    /// A file's address: its path from the top of the served folder;
713    /// `None` for a file outside it, which has none.
714    pub fn url(&self, file: &Path) -> Option<String> {
715        self.served.url(file)
716    }
717
718    /// A file's name from the top of the served folder, for labels; `None`
719    /// for a file outside it, which is never named.
720    pub fn name(&self, file: &Path) -> Option<String> {
721        self.served.name(file)
722    }
723
724    /// The file a URL path names, if it lies inside the served folder.
725    pub fn file(&self, url_path: &str) -> Option<PathBuf> {
726        self.served.at(url_path)
727    }
728
729    /// Whether a change to `file` refreshes open pages: always, unless this
730    /// is a site whose `watch` list matches none of it, relative to its folder.
731    pub fn watches(&self, file: &Path) -> bool {
732        let Some(watch) = &self.watch else {
733            return true;
734        };
735        file.strip_prefix(&self.base)
736            .is_ok_and(|relative| watch.is_match(relative))
737    }
738
739    /// Whether this is a site whose `watch` list names `file`, relative to
740    /// its folder.
741    pub fn names(&self, file: &Path) -> bool {
742        self.watch.is_some() && self.watches(file)
743    }
744
745    /// The folders a site's `watch` patterns can name files in: each
746    /// pattern's literal prefix in the site's folder. Empty without a list.
747    pub fn watch_roots(&self) -> &[PathBuf] {
748        &self.watch_roots
749    }
750}
751
752/// A glob pattern's components before the first one with a glob character:
753/// `build/*.svg` gives `build`, `**/*.md` gives nothing.
754fn literal_prefix(pattern: &str) -> PathBuf {
755    Path::new(pattern)
756        .components()
757        .take_while(|part| {
758            !part
759                .as_os_str()
760                .to_string_lossy()
761                .contains(['*', '?', '[', '{'])
762        })
763        .collect()
764}
765
766/// The kind a YAML file names in its top-level `kind`, when it is one of
767/// devpage's three; any other file is not a document file.
768pub fn kind_of(file: &Path) -> Option<KindName> {
769    if !file
770        .extension()
771        .is_some_and(|ext| ext == "yml" || ext == "yaml")
772    {
773        return None;
774    }
775    let text = std::fs::read_to_string(file).ok()?;
776    let value: serde_yaml::Value = serde_yaml::from_str(&text).ok()?;
777    match value.get("kind")?.as_str()? {
778        "site" => Some(KindName::Site),
779        "doc" => Some(KindName::Doc),
780        "slides" => Some(KindName::Slides),
781        _ => None,
782    }
783}
784
785/// What a published document of `kind` downloads as — a doc or slides
786/// printed as a PDF, a design painted as its PNG — as its extension and
787/// media type; `None` for a kind that has no download, a site. The one rule
788/// for it, the server's and `devpage download`'s.
789pub fn downloads_as(kind: &str) -> Option<(&'static str, &'static str)> {
790    match kind {
791        "doc" | "slides" => Some(("pdf", "application/pdf")),
792        "design" => Some(("png", "image/png")),
793        _ => None,
794    }
795}
796
797/// The file a document is saved as when nothing names one — what `devpage
798/// pdf` and `devpage video` write and what a version downloads as: its
799/// `title`, with the characters a file name can't hold replaced by `-`, and
800/// `extension`.
801pub fn download_name(title: &str, extension: &str) -> PathBuf {
802    let name: String = title
803        .chars()
804        .map(|c| match c {
805            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
806            c if c.is_control() => '-',
807            c => c,
808        })
809        .collect();
810    let name = name.trim().trim_start_matches('.');
811    let name = if name.is_empty() { "document" } else { name };
812    PathBuf::from(format!("{name}.{extension}"))
813}
814
815/// What to give devpage instead, for a folder holding no `devpage.yml`: its
816/// `README.md` when it has one, else any Markdown file.
817fn no_document_file(folder: &Path) -> String {
818    let here = folder == Path::new(".");
819    let named = |file: &str| {
820        if here {
821            file.to_string()
822        } else {
823            folder.join(file).display().to_string()
824        }
825    };
826    let file = if folder.join("README.md").is_file() {
827        named("README.md")
828    } else {
829        named("<file>.md")
830    };
831    let folder = if here {
832        "the current folder".to_string()
833    } else {
834        folder.display().to_string()
835    };
836    format!(
837        "{folder} has no devpage.yml\n\n  \
838         Name a Markdown file instead, e.g. {file}\n  \
839         Or make the folder a site: https://devpage.ai/docs/your-first-site-doc-and-deck.md"
840    )
841}
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846
847    #[test]
848    fn a_folder_without_a_document_file_says_what_to_run() {
849        let dir = folder("no-yml");
850        let error = Document::load(&dir, &ServedFolder::canonical(dir.clone()))
851            .unwrap_err()
852            .to_string();
853        assert!(error.contains("has no devpage.yml"), "{error}");
854        assert!(
855            error.contains(&format!("e.g. {}", dir.join("README.md").display())),
856            "{error}"
857        );
858        let bare = dir.join("guides");
859        let error = Document::load(&bare, &ServedFolder::canonical(dir.clone()))
860            .unwrap_err()
861            .to_string();
862        assert!(error.contains("<file>.md"), "{error}");
863    }
864
865    #[test]
866    fn docs_and_slides_download_as_a_pdf_a_design_as_a_png_and_a_site_not() {
867        assert_eq!(downloads_as("doc"), Some(("pdf", "application/pdf")));
868        assert_eq!(downloads_as("slides"), Some(("pdf", "application/pdf")));
869        assert_eq!(downloads_as("design"), Some(("png", "image/png")));
870        assert_eq!(downloads_as("site"), None);
871    }
872
873    #[test]
874    fn the_download_name_is_the_title_made_safe() {
875        assert_eq!(
876            download_name("Offline sync", "pdf"),
877            Path::new("Offline sync.pdf")
878        );
879        assert_eq!(
880            download_name("A/B: why?", "pdf"),
881            Path::new("A-B- why-.pdf")
882        );
883        assert_eq!(download_name("...", "pdf"), Path::new("document.pdf"));
884        assert_eq!(
885            download_name("A/B: v1.2", "mp4"),
886            Path::new("A-B- v1.2.mp4")
887        );
888        assert_eq!(download_name("Screen", "png"), Path::new("Screen.png"));
889    }
890
891    fn folder(name: &str) -> PathBuf {
892        let dir = std::env::temp_dir().join(format!("devpage-doc-{name}-{}", std::process::id()));
893        std::fs::create_dir_all(dir.join("guides")).unwrap();
894        std::fs::write(dir.join("README.md"), "# Home").unwrap();
895        std::fs::write(dir.join("guides/start.md"), "# Start").unwrap();
896        dir.canonicalize().unwrap()
897    }
898
899    fn parse(text: &str, dir: PathBuf) -> Result<Document> {
900        Document::parse(
901            text,
902            dir.clone(),
903            "devpage.yml".into(),
904            ServedFolder::canonical(dir),
905        )
906    }
907
908    #[test]
909    fn parses_each_kind() {
910        let dir = folder("kinds");
911        let site = parse("kind: site\ntitle: Docs\nroot: README.md\n", dir.clone()).unwrap();
912        assert_eq!(site.entry(), "/README.md");
913        let doc = parse(
914            "kind: doc\ntitle: Plan\nchapters: [README.md, guides/start.md]\npdf: {paper: Letter}\n",
915            dir.clone(),
916        )
917        .unwrap();
918        let Kind::Doc { chapters, pdf } = &doc.kind else {
919            panic!("{doc:?}")
920        };
921        assert_eq!(chapters.len(), 2);
922        assert_eq!(pdf.paper, Paper::Letter);
923        assert_eq!(pdf.footer, "{page} / {pages}");
924        assert_eq!(doc.entry(), "/devpage.yml");
925        let slides = parse("kind: slides\ntitle: Talk\nslides: [README.md]\n", dir).unwrap();
926        assert!(matches!(slides.kind, Kind::Slides { .. }));
927    }
928
929    #[test]
930    fn rejects_bad_kinds_fields_and_missing_files() {
931        let dir = folder("bad");
932        for text in [
933            "title: Docs\nroot: README.md\n",
934            "kind: deck\ntitle: Docs\nroot: README.md\n",
935            "kind: site\ntitle: Docs\nroot: nope.md\n",
936            "kind: site\ntitle: Docs\nroot: README.md\ncolour: red\n",
937            "kind: site\ntitle: Docs\nroot: README.md\nwatch: \"*.md\"\n",
938            "kind: site\ntitle: Docs\nroot: README.md\nwatch: [\"a[b\"]\n",
939            "kind: doc\ntitle: Docs\nroot: README.md\nchapters: [README.md]\n",
940            "kind: doc\ntitle: Docs\nchapters: [missing.md]\n",
941            "kind: doc\ntitle: Docs\nchapters: [../outside.md]\n",
942        ] {
943            assert!(parse(text, dir.clone()).is_err(), "{text}");
944        }
945    }
946
947    #[test]
948    fn reads_the_navbar_in_order_and_refuses_bad_shapes() {
949        let dir = folder("navbar");
950        let document = parse(
951            "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",
952            dir.clone(),
953        )
954        .unwrap();
955        assert!(!document.sidebar && !document.theme_selector);
956        let link = |label: Option<&str>, icon: Option<&str>, target: &str| NavLink {
957            label: label.map(String::from),
958            icon: icon.map(String::from),
959            target: target.into(),
960        };
961        assert_eq!(
962            document.navbar,
963            [
964                NavItem::Link(link(Some("Docs"), Some("book-open"), "README.md")),
965                NavItem::Link(link(Some("Plain"), None, "README.md")),
966                NavItem::Menu {
967                    label: Some("More".into()),
968                    icon: Some("layout-grid".into()),
969                    items: vec![link(Some("Talk"), Some("presentation"), "talk.yml")],
970                },
971                NavItem::Link(link(None, Some("github"), "https://github.com/x/y")),
972            ]
973        );
974        // Defaults: a sidebar, a selector, no navbar; a doc and a deck may opt out too.
975        let plain = parse("kind: site\ntitle: T\nroot: README.md\n", dir.clone()).unwrap();
976        assert!(plain.sidebar && plain.theme_selector && plain.navbar.is_empty());
977        assert!(
978            !parse(
979                "kind: doc\ntitle: T\nchapters: [README.md]\ntheme-selector: false\n",
980                dir.clone()
981            )
982            .unwrap()
983            .theme_selector
984        );
985        for text in [
986            // two levels deep, an empty dropdown, a list instead of a map, no label or icon
987            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A:\n    B:\n      C: README.md\n",
988            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A: {}\n",
989            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  - A: README.md\n",
990            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  \"  \": README.md\n",
991            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  A: 3\n",
992            // a navbar and a sidebar belong to sites
993            "kind: doc\ntitle: T\nchapters: [README.md]\nnavbar:\n  A: README.md\n",
994            "kind: slides\ntitle: T\nslides: [README.md]\nsidebar: false\n",
995        ] {
996            assert!(parse(text, dir.clone()).is_err(), "{text}");
997        }
998    }
999
1000    #[test]
1001    fn a_markdown_file_is_a_doc_of_one_chapter() {
1002        let dir = folder("md");
1003        let doc = Document::load(
1004            &dir.join("guides/start.md"),
1005            &ServedFolder::new(&dir).unwrap(),
1006        )
1007        .unwrap();
1008        assert_eq!(doc.title, "Start");
1009        assert!(matches!(&doc.kind, Kind::Doc { chapters, .. } if chapters.len() == 1));
1010    }
1011
1012    #[test]
1013    fn the_served_folder_is_the_boundary_and_addresses_start_there() {
1014        // No .git anywhere: the served folder is whatever devpage was given.
1015        let served = folder("served");
1016        std::fs::write(
1017            served.join("guides/devpage.yml"),
1018            "kind: site\ntitle: G\nroot: start.md\n",
1019        )
1020        .unwrap();
1021        let doc =
1022            Document::load(&served.join("guides"), &ServedFolder::new(&served).unwrap()).unwrap();
1023        assert_eq!(doc.served.path(), served);
1024        assert_eq!(doc.entry(), "/guides/start.md");
1025        assert!(
1026            doc.file("/README.md").is_some(),
1027            "files beside the docs are served"
1028        );
1029        assert!(doc.file("/../x").is_none());
1030
1031        // --root moves the boundary: served from guides/, README.md is outside.
1032        let guides = served.join("guides");
1033        let narrow = Document::load(&guides, &ServedFolder::new(&guides).unwrap()).unwrap();
1034        assert_eq!(narrow.entry(), "/start.md");
1035        assert!(narrow.file("/../README.md").is_none());
1036    }
1037
1038    #[test]
1039    fn a_document_outside_the_served_folder_is_refused() {
1040        let served = folder("outside");
1041        let error = Document::load(
1042            &served.join("README.md"),
1043            &ServedFolder::new(&served.join("guides")).unwrap(),
1044        )
1045        .unwrap_err()
1046        .to_string();
1047        assert!(error.contains("is outside the served folder"), "{error}");
1048    }
1049
1050    #[test]
1051    fn a_site_watch_list_narrows_what_refreshes() {
1052        let dir = folder("watch");
1053        let all = parse("kind: site\ntitle: D\nroot: README.md\n", dir.clone()).unwrap();
1054        assert!(all.watches(&dir.join("logo.png")));
1055        let narrow = parse(
1056            "kind: site\ntitle: D\nroot: README.md\nwatch: [\"**/*.md\"]\n",
1057            dir.clone(),
1058        )
1059        .unwrap();
1060        assert!(narrow.watches(&dir.join("guides/start.md")));
1061        assert!(!narrow.watches(&dir.join("logo.png")));
1062    }
1063
1064    #[test]
1065    fn only_yaml_with_a_devpage_kind_is_a_document_file() {
1066        let dir = folder("kind-of");
1067        std::fs::write(dir.join("site.yml"), "kind: site\ntitle: T\n").unwrap();
1068        std::fs::write(dir.join("deploy.yaml"), "kind: Deployment\n").unwrap();
1069        std::fs::write(dir.join("ci.yml"), "on: push\n").unwrap();
1070        assert_eq!(kind_of(&dir.join("site.yml")), Some(KindName::Site));
1071        assert_eq!(kind_of(&dir.join("deploy.yaml")), None);
1072        assert_eq!(kind_of(&dir.join("ci.yml")), None);
1073        assert_eq!(kind_of(&dir.join("README.md")), None);
1074    }
1075
1076    #[test]
1077    fn a_deck_keeps_its_narration_and_each_slides_notes_and_delivery() {
1078        let dir = folder("notes");
1079        std::fs::write(
1080            dir.join("one.md"),
1081            "# One\n\n<Notes delivery=\"Warm, a smile in the voice.\">\n  Hello, everyone.\n</Notes>\n\n<Notes>second</Notes>\n",
1082        )
1083        .unwrap();
1084        std::fs::write(dir.join("two.md"), "# Two\n\n`<Notes>not these</Notes>`\n").unwrap();
1085        let deck = parse(
1086            "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",
1087            dir.clone(),
1088        )
1089        .unwrap();
1090        let Kind::Slides { slides, narration } = &deck.kind else {
1091            panic!("{deck:?}")
1092        };
1093        assert_eq!(
1094            narration,
1095            &Narration {
1096                audience: Some("Engineers.".to_string()),
1097                goal: Some("They try it.".to_string()),
1098                tone: Some("Warm and brief.".to_string()),
1099                pronounce: vec!["Say \"devpage\" as \"dev page\".".to_string()],
1100            }
1101        );
1102        assert_eq!(slides[0].file, dir.join("one.md"));
1103        assert_eq!(slides[0].notes.as_deref(), Some("Hello, everyone."));
1104        assert_eq!(
1105            slides[0].delivery.as_deref(),
1106            Some("Warm, a smile in the voice.")
1107        );
1108        assert_eq!(slides[1].notes, None);
1109        let plain = parse("kind: slides\ntitle: T\nslides: [one.md]\n", dir.clone()).unwrap();
1110        assert!(
1111            matches!(&plain.kind, Kind::Slides { narration, .. } if *narration == Narration::default())
1112        );
1113        // The narration belongs to slides, and `context` is gone.
1114        for text in [
1115            "kind: doc\ntitle: T\nchapters: [README.md]\naudience: x\n",
1116            "kind: site\ntitle: T\nroot: README.md\ngoal: x\n",
1117            "kind: slides\ntitle: T\nslides: [one.md]\ncontext: x\n",
1118            "kind: slides\ntitle: T\nslides: [one.md]\npronounce: x\n",
1119        ] {
1120            assert!(parse(text, dir.clone()).is_err(), "{text}");
1121        }
1122    }
1123}