Skip to main content

devpage_core/
nav.rs

1//! Navigation: the tree a document's pages form through their `## Topics` sections.
2//!
3//! A page's children are the links listed under its `## Topics` heading — the
4//! first link of each list item, labelled with that link's text — in list order.
5//! `### headings` inside Topics group them. The tree starts at the root page.
6
7use std::collections::{HashMap, HashSet};
8use std::path::{Path, PathBuf};
9
10use comrak::nodes::{AstNode, NodeValue};
11use comrak::{Arena, Options, parse_document};
12
13use crate::document::Document;
14
15/// One entry of the tree: a page and its own children. A page listed more
16/// than once is an entry only at its position: its shallowest listing, the
17/// first in reading order on a tie. Every other listing — the root page's
18/// among them — is left out of the tree.
19#[derive(Debug, PartialEq)]
20pub struct Entry {
21    pub label: String,
22    pub file: PathBuf,
23    pub children: Vec<Group>,
24}
25
26/// Children under one `###` heading of a Topics section; `title` is `None` for
27/// links listed before any group heading.
28#[derive(Debug, PartialEq)]
29pub struct Group {
30    pub title: Option<String>,
31    pub entries: Vec<Entry>,
32}
33
34/// A link listed in a Topics section, before it is resolved to a file.
35#[derive(Debug, PartialEq)]
36pub struct Topic {
37    pub group: Option<String>,
38    pub label: String,
39    pub href: String,
40}
41
42/// The children of the root page, recursively. Each page is in the tree only
43/// at its position (see [`Entry`]); the root's position is the top, so cycles
44/// end.
45pub fn tree(document: &Document) -> Vec<Group> {
46    let crate::document::Kind::Site { root } = &document.kind else {
47        return Vec::new();
48    };
49    let root = document.base.join(root);
50    let homes = homes(document, &root);
51    children(document, &root, &homes)
52}
53
54/// Where each page listed in the tree has its position: the page listing it
55/// and the listing's index among that page's Topics links. Found level by
56/// level from the root, so the shallowest listing wins, then the first.
57fn homes(document: &Document, root: &Path) -> HashMap<PathBuf, (PathBuf, usize)> {
58    let mut homes = HashMap::new();
59    let mut seen = HashSet::from([root.to_path_buf()]);
60    let mut level = vec![root.to_path_buf()];
61    while !level.is_empty() {
62        let mut next = Vec::new();
63        for page in &level {
64            let Ok(source) = std::fs::read_to_string(page) else {
65                continue;
66            };
67            for (index, topic) in topics(&source).into_iter().enumerate() {
68                let file = match resolve(document, page, &topic.href) {
69                    Target::Page(file) | Target::Document(file) => file,
70                    Target::None | Target::Problem(_) => continue,
71                };
72                if seen.insert(file.clone()) {
73                    homes.insert(file.clone(), (page.clone(), index));
74                    next.push(file);
75                }
76            }
77        }
78        level = next;
79    }
80    homes
81}
82
83fn children(
84    document: &Document,
85    page: &Path,
86    homes: &HashMap<PathBuf, (PathBuf, usize)>,
87) -> Vec<Group> {
88    let Ok(source) = std::fs::read_to_string(page) else {
89        return Vec::new();
90    };
91    let mut groups: Vec<Group> = Vec::new();
92    for (index, topic) in topics(&source).into_iter().enumerate() {
93        let (file, page_target) = match resolve(document, page, &topic.href) {
94            Target::Page(file) => (file, true),
95            Target::Document(file) => (file, false),
96            Target::None | Target::Problem(_) => continue,
97        };
98        let home = homes
99            .get(&file)
100            .is_some_and(|(parent, at)| parent == page && *at == index);
101        if !home {
102            continue;
103        }
104        let entry = Entry {
105            label: topic.label,
106            children: if page_target {
107                children(document, &file, homes)
108            } else {
109                Vec::new()
110            },
111            file,
112        };
113        match groups.last_mut() {
114            Some(group) if group.title == topic.group => group.entries.push(entry),
115            _ => groups.push(Group {
116                title: topic.group,
117                entries: vec![entry],
118            }),
119        }
120    }
121    groups
122}
123
124/// What a Topics link names in a site's sidebar.
125#[derive(Debug, PartialEq)]
126pub enum Target {
127    /// A page in the site's folder: an entry with its own children.
128    Page(PathBuf),
129    /// A document file: an entry that opens that document, with no children.
130    Document(PathBuf),
131    /// Not an entry: another website, a `#fragment`, any other file.
132    None,
133    /// Left out, and a problem: a missing file, or a page outside the site.
134    Problem(String),
135}
136
137/// What a Topics link on `page` names.
138pub fn resolve(document: &Document, page: &Path, href: &str) -> Target {
139    if href.contains(':') || href.starts_with('#') {
140        return Target::None;
141    }
142    let path = href.split('#').next().unwrap_or(href);
143    let Some(target) = page
144        .parent()
145        .and_then(|folder| document.served.file(&folder.join(path)))
146    else {
147        return Target::Problem(format!("Topics entry {href} — no such file"));
148    };
149    if target.extension().is_some_and(|ext| ext == "md") {
150        if target.starts_with(&document.base) {
151            Target::Page(target)
152        } else {
153            Target::Problem(format!("Topics entry {href} — outside the site's folder"))
154        }
155    } else if crate::document::kind_of(&target).is_some() {
156        Target::Document(target)
157    } else {
158        Target::None
159    }
160}
161
162/// The links listed in a page's `## Topics` section, in order.
163pub fn topics(source: &str) -> Vec<Topic> {
164    let arena = Arena::new();
165    let root = parse_document(&arena, source, &Options::default());
166    let mut topics = Vec::new();
167    let mut in_topics = false;
168    let mut group = None;
169    for node in root.children() {
170        let value = node.data.borrow().value.clone();
171        match value {
172            NodeValue::Heading(heading) if heading.level <= 2 => {
173                in_topics = heading.level == 2 && text(node).trim() == "Topics";
174                group = None;
175            }
176            NodeValue::Heading(heading) if in_topics && heading.level == 3 => {
177                group = Some(text(node).trim().to_string());
178            }
179            NodeValue::List(_) if in_topics => {
180                for item in node.children() {
181                    if let Some((label, href)) = first_link(item) {
182                        topics.push(Topic {
183                            group: group.clone(),
184                            label,
185                            href,
186                        });
187                    }
188                }
189            }
190            _ => {}
191        }
192    }
193    topics
194}
195
196fn first_link<'a>(node: &'a AstNode<'a>) -> Option<(String, String)> {
197    node.descendants()
198        .find_map(|descendant| match &descendant.data.borrow().value {
199            NodeValue::Link(link) => Some((text(descendant).trim().to_string(), link.url.clone())),
200            _ => None,
201        })
202}
203
204fn text<'a>(node: &'a AstNode<'a>) -> String {
205    node.descendants()
206        .filter_map(|descendant| match &descendant.data.borrow().value {
207            NodeValue::Text(text) => Some(text.to_string()),
208            NodeValue::Code(code) => Some(code.literal.clone()),
209            _ => None,
210        })
211        .collect()
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn reads_links_and_groups_from_the_topics_section_only() {
220        let source = "# Home\n\nSee the [viewer](viewer.md) in passing.\n\n## Topics\n\n\
221                      - [Vision](vision.md) — why\n\n### The system\n\n- [Viewer](boxes/viewer/README.md)\n\
222                      - [Engineering](boxes/engineering/README.md)\n\n## Afterwards\n\n- [Ignored](x.md)\n";
223        let found = topics(source);
224        let labels: Vec<_> = found
225            .iter()
226            .map(|t| (t.group.as_deref(), t.label.as_str(), t.href.as_str()))
227            .collect();
228        assert_eq!(
229            labels,
230            vec![
231                (None, "Vision", "vision.md"),
232                (Some("The system"), "Viewer", "boxes/viewer/README.md"),
233                (
234                    Some("The system"),
235                    "Engineering",
236                    "boxes/engineering/README.md"
237                ),
238            ]
239        );
240    }
241
242    #[test]
243    fn a_page_listed_twice_is_in_the_tree_only_at_its_shallowest_listing() {
244        let dir = std::env::temp_dir().join(format!("devpage-nav-home-{}", std::process::id()));
245        std::fs::create_dir_all(&dir).unwrap();
246        std::fs::write(
247            dir.join("devpage.yml"),
248            "kind: site\ntitle: T\nroot: README.md\n",
249        )
250        .unwrap();
251        // Reading order meets `start` under `system` first, one level deeper.
252        std::fs::write(
253            dir.join("README.md"),
254            "# Home\n\n## Topics\n\n- [System](system.md)\n- [Start](start.md)\n",
255        )
256        .unwrap();
257        std::fs::write(
258            dir.join("system.md"),
259            "# System\n\n## Topics\n\n- [Start](start.md)\n",
260        )
261        .unwrap();
262        std::fs::write(
263            dir.join("start.md"),
264            "# Start\n\n## Topics\n\n- [First](first.md)\n",
265        )
266        .unwrap();
267        std::fs::write(dir.join("first.md"), "# First\n").unwrap();
268        let document = Document::load(&dir, &dir).unwrap();
269
270        let tree = tree(&document);
271        let [system, start] = &tree[0].entries[..] else {
272            panic!("two top-level entries");
273        };
274        assert_eq!(
275            start.label, "Start",
276            "the top-level listing is the position"
277        );
278        assert_eq!(start.children[0].entries[0].label, "First");
279        assert!(system.children.is_empty(), "a second listing is left out");
280    }
281
282    #[test]
283    fn builds_the_tree_and_stops_at_cycles() {
284        let dir = std::env::temp_dir().join(format!("devpage-nav-{}", std::process::id()));
285        std::fs::create_dir_all(dir.join("guide")).unwrap();
286        std::fs::write(
287            dir.join("devpage.yml"),
288            "kind: site\ntitle: T\nroot: README.md\n",
289        )
290        .unwrap();
291        std::fs::write(
292            dir.join("README.md"),
293            "# Home\n\n## Topics\n\n- [Guide](guide/README.md)\n- [Missing](nope.md)\n- [Talk](talk.yml)\n",
294        )
295        .unwrap();
296        std::fs::write(
297            dir.join("talk.yml"),
298            "kind: slides\ntitle: T\nslides: [README.md]\n",
299        )
300        .unwrap();
301        std::fs::write(
302            dir.join("guide/README.md"),
303            "# Guide\n\n## Topics\n\n- [Back home](../README.md)\n- [Step](step.md)\n",
304        )
305        .unwrap();
306        std::fs::write(dir.join("guide/step.md"), "# Step\n").unwrap();
307        let document = Document::load(&dir, &dir).unwrap();
308
309        let tree = tree(&document);
310        assert_eq!(tree.len(), 1);
311        let talk = &tree[0].entries[1];
312        assert_eq!(talk.label, "Talk", "a document file is an entry");
313        assert!(talk.children.is_empty());
314        let guide = &tree[0].entries[0];
315        assert_eq!(guide.label, "Guide");
316        let under_guide: Vec<_> = guide.children[0]
317            .entries
318            .iter()
319            .map(|e| e.label.as_str())
320            .collect();
321        assert_eq!(
322            under_guide,
323            vec!["Step"],
324            "a link back to the root is left out"
325        );
326    }
327
328    #[test]
329    fn a_page_outside_the_site_or_a_missing_one_is_a_problem() {
330        let dir = std::env::temp_dir().join(format!("devpage-nav-out-{}", std::process::id()));
331        std::fs::create_dir_all(dir.join("site")).unwrap();
332        let dir = dir.canonicalize().unwrap();
333        std::fs::write(dir.join("outside.md"), "# Out\n").unwrap();
334        std::fs::write(dir.join("site/README.md"), "# Home\n").unwrap();
335        std::fs::write(
336            dir.join("site/devpage.yml"),
337            "kind: site\ntitle: T\nroot: README.md\n",
338        )
339        .unwrap();
340        let document = Document::load(&dir.join("site"), &dir).unwrap();
341        let page = dir.join("site/README.md");
342        assert!(matches!(
343            resolve(&document, &page, "../outside.md"),
344            Target::Problem(message) if message.contains("outside the site's folder")
345        ));
346        assert!(matches!(
347            resolve(&document, &page, "nope.md"),
348            Target::Problem(_)
349        ));
350        assert_eq!(
351            resolve(&document, &page, "https://example.com"),
352            Target::None
353        );
354        assert_eq!(resolve(&document, &page, "#top"), Target::None);
355    }
356}