Skip to main content

devpage_core/
navbar.rs

1//! A site's navbar — its title, then the links, dropdowns and icons its
2//! `navbar` field lists — and the light/dark selector every page carries.
3
4use std::path::{Path, PathBuf};
5
6use crate::document::{Document, NavItem, NavLink};
7use crate::problem::Problem;
8use crate::{icons, nav};
9
10/// Where a navbar link goes: an address on the web as written, or a file in
11/// the served folder by its address. `file` is set for the latter, whether or
12/// not it exists.
13struct Target {
14    href: String,
15    file: Option<PathBuf>,
16}
17
18fn target(document: &Document, written: &str) -> Target {
19    if written.contains("://") || written.starts_with("mailto:") {
20        return Target {
21            href: written.to_string(),
22            file: None,
23        };
24    }
25    let (path, fragment) = written.split_once('#').unwrap_or((written, ""));
26    let file = normalize(&document.base.join(path));
27    let mut href = document.url(&file);
28    if !fragment.is_empty() {
29        href.push('#');
30        href.push_str(fragment);
31    }
32    Target {
33        href,
34        file: Some(file),
35    }
36}
37
38fn normalize(path: &Path) -> PathBuf {
39    let mut out = PathBuf::new();
40    for part in path.components() {
41        match part {
42            std::path::Component::ParentDir => {
43                out.pop();
44            }
45            std::path::Component::CurDir => {}
46            other => out.push(other),
47        }
48    }
49    out
50}
51
52/// The site name an icon-only link to the web is known by: `github.com`.
53fn host(href: &str) -> String {
54    href.split("://")
55        .nth(1)
56        .unwrap_or(href)
57        .split('/')
58        .next()
59        .unwrap_or(href)
60        .trim_start_matches("www.")
61        .to_string()
62}
63
64/// Every link the navbar holds, dropdowns opened.
65fn links(document: &Document) -> impl Iterator<Item = &NavLink> {
66    document.navbar.iter().flat_map(|item| match item {
67        NavItem::Link(link) => std::slice::from_ref(link).iter(),
68        NavItem::Menu { items, .. } => items.iter(),
69    })
70}
71
72/// The navbar's problems: a link to a file that isn't in the served folder,
73/// and an icon devpage doesn't have. They belong to the document file.
74pub fn problems(document: &Document) -> Vec<Problem> {
75    let file = document.name(&document.path());
76    let mut problems = Vec::new();
77    let mut icon = |name: &Option<String>| {
78        if let Some(name) = name
79            && !icons::exists(name)
80        {
81            problems.push(Problem {
82                file: file.clone(),
83                line: None,
84                message: format!("navbar: no icon named {name}"),
85                target: None,
86            });
87        }
88    };
89    for item in &document.navbar {
90        if let NavItem::Menu { icon: name, .. } = item {
91            icon(name);
92        }
93    }
94    for link in links(document) {
95        icon(&link.icon);
96    }
97    for link in links(document) {
98        if let Some(path) = target(document, &link.target).file {
99            let inside = document.served.file(&path).is_some();
100            if !inside {
101                problems.push(Problem {
102                    file: file.clone(),
103                    line: None,
104                    message: format!("navbar: {} — no such file", link.target),
105                    target: Some(link.target.clone()),
106                });
107            }
108        }
109    }
110    problems
111}
112
113/// Where the navbar leads, for the link checker: the files it names that
114/// exist, and its addresses on the web.
115pub fn reached(document: &Document) -> (Vec<PathBuf>, Vec<String>) {
116    let mut files = Vec::new();
117    let mut web = Vec::new();
118    for link in links(document) {
119        match target(document, &link.target).file {
120            Some(path) => {
121                if let Some(real) = document.served.file(&path) {
122                    files.push(real);
123                }
124            }
125            None if !link.target.starts_with("mailto:") => web.push(link.target.clone()),
126            None => {}
127        }
128    }
129    (files, web)
130}
131
132/// The address of the navbar link that holds the page shown: the link to the
133/// page itself, or else to its nearest ancestor in the sidebar tree, the root
134/// page holding them all.
135fn active(document: &Document, current: &str) -> Option<String> {
136    let targets: Vec<String> = links(document)
137        .map(|link| target(document, &link.target).href)
138        .collect();
139    if targets.iter().any(|href| href == current) {
140        return Some(current.to_string());
141    }
142    fn path(
143        document: &Document,
144        groups: &[nav::Group],
145        current: &str,
146        trail: &mut Vec<String>,
147    ) -> bool {
148        for entry in groups.iter().flat_map(|group| &group.entries) {
149            trail.push(document.url(&entry.file));
150            if trail.last().is_some_and(|url| url == current)
151                || path(document, &entry.children, current, trail)
152            {
153                return true;
154            }
155            trail.pop();
156        }
157        false
158    }
159    let mut trail = vec![document.entry()];
160    let found = trail[0] == current || path(document, &nav::tree(document), current, &mut trail);
161    if !found {
162        return None;
163    }
164    trail.into_iter().rev().find(|url| targets.contains(url))
165}
166
167fn escape(text: &str) -> String {
168    text.replace('&', "&amp;")
169        .replace('<', "&lt;")
170        .replace('>', "&gt;")
171        .replace('"', "&quot;")
172}
173
174fn icon(name: &Option<String>) -> String {
175    name.as_deref().and_then(icons::svg).unwrap_or_default()
176}
177
178/// One link, in the bar or in a dropdown.
179fn link(document: &Document, link: &NavLink, active: Option<&str>, class: &str) -> String {
180    let to = target(document, &link.target);
181    let current = active == Some(to.href.as_str());
182    let external = to.file.is_none();
183    let (label, extra) = match &link.label {
184        Some(label) => (format!("<span>{}</span>", escape(label)), String::new()),
185        None => {
186            let name = if external {
187                host(&to.href)
188            } else {
189                link.target.clone()
190            };
191            (
192                String::new(),
193                format!(" title=\"{0}\" aria-label=\"{0}\"", escape(&name)),
194            )
195        }
196    };
197    format!(
198        "<a class=\"{class}{only}{current}\" href=\"{href}\"{extra}{aria}{rel}>{icon}{label}</a>",
199        only = if link.label.is_none() {
200            " icon-only"
201        } else {
202            ""
203        },
204        current = if current { " current" } else { "" },
205        href = escape(&to.href),
206        aria = if current {
207            " aria-current=\"page\""
208        } else {
209            ""
210        },
211        rel = if external { " rel=\"noopener\"" } else { "" },
212        icon = icon(&link.icon),
213    )
214}
215
216/// The bar across the top of a site's pages, when its document file sets
217/// `navbar`; `current` is the page's address, and `comments` whether
218/// comments are on.
219pub fn render(document: &Document, current: &str, comments: bool) -> String {
220    if document.navbar.is_empty() {
221        return String::new();
222    }
223    let active = active(document, current);
224    let active = active.as_deref();
225    let mut items = String::new();
226    for item in &document.navbar {
227        match item {
228            NavItem::Link(one) => items.push_str(&link(document, one, active, "navbar-link")),
229            NavItem::Menu {
230                label,
231                icon: name,
232                items: menu,
233            } => {
234                let holds_current = menu
235                    .iter()
236                    .any(|one| active == Some(target(document, &one.target).href.as_str()));
237                let entries: String = menu
238                    .iter()
239                    .map(|one| link(document, one, active, "navbar-entry"))
240                    .collect();
241                items.push_str(&format!(
242                    "<div class=\"navbar-menu{current}\"><button type=\"button\" class=\"navbar-link\" aria-haspopup=\"true\" aria-expanded=\"false\">{icon}<span>{label}</span>{chevron}</button><div class=\"navbar-dropdown\" role=\"menu\">{entries}</div></div>",
243                    current = if holds_current { " current" } else { "" },
244                    icon = icon(name),
245                    label = escape(label.as_deref().unwrap_or("")),
246                    chevron = icons::svg("chevron-down").unwrap_or_default(),
247                ));
248            }
249        }
250    }
251    format!(
252        "<header id=\"devpage-navbar\"><div class=\"navbar-inner\"><a class=\"navbar-title{root}\" href=\"{home}\">{logo}{title}</a><nav class=\"navbar-links\" aria-label=\"{title}\">{items}</nav><div class=\"navbar-end\">{selector}<button type=\"button\" class=\"navbar-toggle\" aria-expanded=\"false\" aria-label=\"Menu\">{menu}</button></div></div></header>",
253        root = if current == document.entry() {
254            " current"
255        } else {
256            ""
257        },
258        home = escape(&document.entry()),
259        logo = logo(document),
260        title = escape(&document.title),
261        selector = controls(document, comments),
262        menu = icons::svg("menu").unwrap_or_default(),
263    )
264}
265
266/// The document's logo, to sit before its title; nothing when it has none.
267/// It is decoration beside the title it repeats, so it has no alt text.
268pub fn logo(document: &Document) -> String {
269    match document.logo_url() {
270        Some(url) => format!("<img class=\"logo\" src=\"{}\" alt=\"\">", escape(&url)),
271        None => String::new(),
272    }
273}
274
275/// A logo that names no image in the served folder. It belongs to the
276/// document file, like a broken navbar link.
277pub fn logo_problem(document: &Document) -> Option<Problem> {
278    let written = document.logo.as_ref()?;
279    if document.logo_url().is_some() {
280        return None;
281    }
282    Some(Problem {
283        file: document.name(&document.path()),
284        line: None,
285        message: format!("logo: {written} — no such file"),
286        target: Some(written.clone()),
287    })
288}
289
290/// The theme selector, when the document shows one: one button that switches
291/// between light and dark. It carries both icons; the stylesheet shows the one
292/// for the theme a click switches to — the moon in light, the sun in dark.
293pub fn selector(document: &Document) -> String {
294    if !document.theme_selector {
295        return String::new();
296    }
297    theme_toggle()
298}
299
300/// The light/dark button itself, for a page that shows one.
301pub fn theme_toggle() -> String {
302    format!(
303        "<button type=\"button\" class=\"theme-toggle\" title=\"Switch theme\" aria-label=\"Switch theme\">{}</button>",
304        theme_icons()
305    )
306}
307
308/// The switch's two faces — a moon to switch to dark, a sun to switch to
309/// light — which the stylesheet shows one at a time: the page's switch and
310/// an embedded design's own.
311pub fn theme_icons() -> String {
312    format!(
313        "<span class=\"to-dark\">{}</span><span class=\"to-light\">{}</span>",
314        icons::svg("moon").unwrap_or_default(),
315        icons::svg("sun").unwrap_or_default()
316    )
317}
318
319/// An embedded design's own theme switch, hidden until the design script
320/// finds the design themed; it turns only that embed.
321pub fn design_theme_toggle() -> String {
322    format!(
323        "<button type=\"button\" class=\"design-theme\" hidden title=\"Switch this design's theme\" aria-label=\"Switch this design's theme\">{}</button>",
324        theme_icons()
325    )
326}
327
328/// The comment-mode switch: commenting is opt-in, so the hover icon and the
329/// selection's Comment button only appear while it is pressed. The page script
330/// remembers the choice; threads show either way. Its icon is the speech
331/// bubble the paragraph button uses.
332pub fn comment_mode() -> String {
333    "<button type=\"button\" class=\"comment-mode\" title=\"Comment mode\" aria-label=\"Comment mode\" aria-pressed=\"false\"><svg viewBox=\"0 0 20 20\" width=\"17\" height=\"17\" aria-hidden=\"true\"><path d=\"M4 3.5h12A1.5 1.5 0 0 1 17.5 5v8a1.5 1.5 0 0 1-1.5 1.5H9l-3.5 3v-3H4A1.5 1.5 0 0 1 2.5 13V5A1.5 1.5 0 0 1 4 3.5Z\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/></svg></button>".to_string()
334}
335
336/// The page's own controls, in the navbar's end or the corner: the
337/// comment-mode switch while comments are on, then the theme selector when
338/// the document shows one.
339pub fn controls(document: &Document, comments: bool) -> String {
340    let mode = if comments {
341        comment_mode()
342    } else {
343        String::new()
344    };
345    format!("{mode}{}", selector(document))
346}
347
348/// The controls for a page with no navbar to hold them: the top-right corner.
349pub fn corner(document: &Document, comments: bool) -> String {
350    format!(
351        "<div id=\"devpage-corner\">{}</div>",
352        controls(document, comments)
353    )
354}
355
356/// What every page of a document puts in its head: the logo as the browser
357/// tab's icon, and a script that sets the theme before the page paints, so it
358/// never flashes the wrong one — the theme the reader switched to, if the page
359/// offers the switch and they used it, else the system's setting.
360pub fn head(document: &Document) -> String {
361    let icon = match document.logo_url() {
362        Some(url) => format!("<link rel=\"icon\" href=\"{}\">\n", escape(&url)),
363        None => String::new(),
364    };
365    format!("{icon}{}", theme_script(document.theme_selector))
366}
367
368/// The script that sets the theme before the page paints: the one the reader
369/// switched to, when the page offers the switch and they used it, else the
370/// system's setting.
371pub fn theme_script(switchable: bool) -> String {
372    let stored = if switchable {
373        r#"try{c=localStorage.getItem("devpage-theme")}catch(e){}"#
374    } else {
375        ""
376    };
377    format!(
378        r#"<script>(function(){{var c;{stored}var d=document.documentElement;d.dataset.theme=c==="light"||c==="dark"?c:(matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}})()</script>"#
379    )
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    fn site(dir: &Path, yaml: &str) -> Document {
387        std::fs::write(dir.join("devpage.yml"), yaml).unwrap();
388        Document::load(&dir.join("devpage.yml"), dir).unwrap()
389    }
390
391    fn folder(name: &str) -> PathBuf {
392        let dir =
393            std::env::temp_dir().join(format!("devpage-navbar-{name}-{}", std::process::id()));
394        let _ = std::fs::remove_dir_all(&dir);
395        std::fs::create_dir_all(dir.join("guide")).unwrap();
396        std::fs::write(
397            dir.join("README.md"),
398            "# Home\n\n## Topics\n\n- [Guide](guide/README.md)\n",
399        )
400        .unwrap();
401        std::fs::write(
402            dir.join("guide/README.md"),
403            "# Guide\n\n## Topics\n\n- [Deep](deep.md)\n",
404        )
405        .unwrap();
406        std::fs::write(dir.join("guide/deep.md"), "# Deep\n").unwrap();
407        std::fs::write(
408            dir.join("talk.yml"),
409            "kind: slides\ntitle: Talk\nslides: [guide/deep.md]\n",
410        )
411        .unwrap();
412        dir.canonicalize().unwrap()
413    }
414
415    const NAVBAR: &str = "kind: site\ntitle: Garden\nroot: README.md\nnavbar:\n  Home (house): README.md\n  Guide: guide/README.md\n  More (layout-grid):\n    Talk (presentation): talk.yml\n    Site: https://example.com/garden\n  (github): https://github.com/someone/garden\n";
416
417    #[test]
418    fn renders_links_dropdowns_icons_and_icon_only_links_in_order() {
419        let dir = folder("render");
420        let document = site(&dir, NAVBAR);
421        let html = render(&document, "/guide/deep.md", true);
422        let order: Vec<usize> = ["Home", "Guide", "More", "Talk", "github.com"]
423            .iter()
424            .map(|text| {
425                html.find(text)
426                    .unwrap_or_else(|| panic!("{text} in {html}"))
427            })
428            .collect();
429        assert!(order.windows(2).all(|pair| pair[0] < pair[1]), "{html}");
430        assert!(html.contains("href=\"/README.md\""), "{html}");
431        assert!(html.contains("href=\"/talk.yml\""), "{html}");
432        assert!(html.contains("aria-haspopup=\"true\""), "{html}");
433        assert!(html.contains("class=\"navbar-link icon-only\" href=\"https://github.com/someone/garden\" title=\"github.com\""), "{html}");
434        // house, layout-grid, chevron, presentation, github, menu, and the switch's moon and sun.
435        assert_eq!(html.matches("<svg class=\"icon\"").count(), 8, "{html}");
436    }
437
438    #[test]
439    fn highlights_the_link_holding_the_page_shown() {
440        let dir = folder("current");
441        let document = site(&dir, NAVBAR);
442        // A page deep under the guide lights the guide, not home.
443        let deep = render(&document, "/guide/deep.md", true);
444        assert!(
445            deep.contains("class=\"navbar-link current\" href=\"/guide/README.md\""),
446            "{deep}"
447        );
448        assert!(
449            !deep.contains("class=\"navbar-link current\" href=\"/README.md\""),
450            "{deep}"
451        );
452        // The root page lights home.
453        let home = render(&document, "/README.md", true);
454        assert!(
455            home.contains("class=\"navbar-link current\" href=\"/README.md\""),
456            "{home}"
457        );
458        // A deck in a dropdown lights its dropdown.
459        let talk = render(&document, "/talk.yml", true);
460        assert!(talk.contains("class=\"navbar-menu current\""), "{talk}");
461    }
462
463    #[test]
464    fn missing_files_and_unknown_icons_are_problems() {
465        let dir = folder("problems");
466        let document = site(
467            &dir,
468            "kind: site\ntitle: T\nroot: README.md\nnavbar:\n  Gone (no-such-icon): gone.md\n  Out: ../../outside.md\n  Web: https://example.com\n",
469        );
470        let found: Vec<String> = problems(&document).iter().map(|p| p.to_string()).collect();
471        assert_eq!(
472            found,
473            [
474                "devpage.yml: navbar: no icon named no-such-icon",
475                "devpage.yml: navbar: gone.md — no such file",
476                "devpage.yml: navbar: ../../outside.md — no such file",
477            ],
478            "{found:?}"
479        );
480    }
481
482    #[test]
483    fn no_navbar_renders_nothing_and_the_selector_can_be_turned_off() {
484        let dir = folder("off");
485        let plain = site(&dir, "kind: site\ntitle: T\nroot: README.md\n");
486        assert_eq!(render(&plain, "/README.md", true), "");
487        assert!(corner(&plain, true).contains("class=\"theme-toggle\""));
488        assert!(head(&plain).contains("localStorage"));
489        let off = site(
490            &dir,
491            "kind: site\ntitle: T\nroot: README.md\ntheme-selector: false\n",
492        );
493        // Commenting is opt-in on every page, so its switch stays when the
494        // theme selector is turned off.
495        assert!(corner(&plain, true).contains("class=\"comment-mode\""));
496        assert!(corner(&off, true).contains("class=\"comment-mode\""));
497        assert!(!corner(&off, true).contains("theme-toggle"));
498        // With comments off there is no switch, in the corner or the navbar.
499        assert!(!corner(&plain, false).contains("comment-mode"));
500        assert!(corner(&plain, false).contains("theme-toggle"));
501        assert!(
502            !head(&off).contains("localStorage"),
503            "the system decides when there is no selector"
504        );
505    }
506
507    #[test]
508    fn a_logo_sits_before_the_title_and_is_the_tab_icon() {
509        let dir = folder("logo");
510        std::fs::write(
511            dir.join("logo.svg"),
512            "<svg xmlns=\"http://www.w3.org/2000/svg\"/>",
513        )
514        .unwrap();
515        let with = site(&dir, &format!("{NAVBAR}logo: logo.svg\n"));
516        let bar = render(&with, "/README.md", true);
517        let img = bar
518            .find("<img class=\"logo\" src=\"/logo.svg\" alt=\"\">")
519            .expect(&bar);
520        assert!(
521            img < bar.find("Garden").unwrap(),
522            "the logo comes first: {bar}"
523        );
524        assert!(head(&with).contains("<link rel=\"icon\" href=\"/logo.svg\">"));
525        assert_eq!(logo_problem(&with), None);
526        // A doc and a deck take one too, for their tab.
527        std::fs::write(
528            dir.join("deck.yml"),
529            "kind: slides\ntitle: D\nslides: [guide/deep.md]\nlogo: logo.svg\n",
530        )
531        .unwrap();
532        let deck = Document::load(&dir.join("deck.yml"), &dir).unwrap();
533        assert!(head(&deck).contains("rel=\"icon\" href=\"/logo.svg\""));
534        // None, no image and no icon.
535        let without = site(&dir, NAVBAR);
536        assert!(!render(&without, "/README.md", true).contains("<img"));
537        assert!(!head(&without).contains("rel=\"icon\""));
538    }
539
540    #[test]
541    fn a_missing_logo_is_a_problem_and_the_page_shows_without_it() {
542        let dir = folder("logo-missing");
543        let document = site(&dir, &format!("{NAVBAR}logo: gone.svg\n"));
544        let problem = logo_problem(&document).expect("a problem");
545        assert_eq!(problem.message, "logo: gone.svg — no such file");
546        assert_eq!(problem.file, "devpage.yml");
547        assert!(!render(&document, "/README.md", true).contains("<img"));
548        assert!(!head(&document).contains("rel=\"icon\""));
549        // Outside the served folder is no logo either.
550        let outside = site(&dir, &format!("{NAVBAR}logo: ../../etc/hosts\n"));
551        assert!(logo_problem(&outside).is_some());
552    }
553}