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