devpage-core 0.3.2

devpage's core: documents, rendering, link checking, comments and designs, with no I/O runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Navigation: the tree a document's pages form through their `## Topics` sections.
//!
//! A page's children are the links listed under its `## Topics` heading — the
//! first link of each list item, labelled with that link's text — in list order.
//! `### headings` inside Topics group them. The tree starts at the root page.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use comrak::nodes::{AstNode, NodeValue};
use comrak::{Arena, Options, parse_document};

use crate::document::Document;
use crate::html::Link;

/// One entry of the tree: a page and its own children. A page listed more
/// than once is an entry only at its position: its shallowest listing, the
/// first in reading order on a tie. Every other listing — the root page's
/// among them — is left out of the tree.
#[derive(Debug, PartialEq)]
pub struct Entry {
    /// The text of the link that lists it.
    pub label: String,
    /// The page or document file it opens.
    pub file: PathBuf,
    /// Its own children: a page's Topics, a code reference's crates, modules
    /// and types, or none for any other document.
    pub children: Vec<Group>,
}

/// Children under one `###` heading of a Topics section; `title` is `None` for
/// links listed before any group heading.
#[derive(Debug, PartialEq)]
pub struct Group {
    /// The `###` heading; `None` for links listed before any.
    pub title: Option<String>,
    /// Its entries, in list order.
    pub entries: Vec<Entry>,
}

/// A link listed in a Topics section, before it is resolved to a file.
#[derive(Debug, Clone, PartialEq)]
pub struct Topic {
    /// The `###` heading it is listed under; `None` before any.
    pub group: Option<String>,
    /// The link's text, trimmed.
    pub label: String,
    /// The link's target, as written.
    pub href: String,
}

#[cfg(test)]
thread_local! {
    /// Every page whose Topics were read on this thread, for the tests: how
    /// many pages a tree walks.
    pub(crate) static READ: std::cell::RefCell<Vec<PathBuf>> = Default::default();
}

/// The Topics of every page read making one tree, each page read once:
/// `None` for a page that can't be read.
#[derive(Default)]
struct Read(HashMap<PathBuf, Option<Vec<Topic>>>);

impl Read {
    /// `page`'s Topics, read the first time it is asked for; `None` when it
    /// can't be read.
    fn topics(&mut self, page: &Path) -> Option<Vec<Topic>> {
        self.0
            .entry(page.to_path_buf())
            .or_insert_with(|| {
                #[cfg(test)]
                READ.with_borrow_mut(|read| read.push(page.to_path_buf()));
                std::fs::read_to_string(page)
                    .ok()
                    .map(|source| topics(&source))
            })
            .clone()
    }
}

/// The children of the root page, recursively. Each page is in the tree only
/// at its position (see [`Entry`]); the root's position is the top, so cycles
/// end.
pub fn tree(document: &Document) -> Vec<Group> {
    tree_and_topics(document).0
}

/// The [tree](tree), and the Topics of every page read to make it — the
/// root and the pages it lists, directly or not — by page; none for a page
/// that can't be read, which the tree takes as listing none.
pub fn tree_and_topics(document: &Document) -> (Vec<Group>, HashMap<PathBuf, Vec<Topic>>) {
    let _nav = tracing::info_span!("nav").entered();
    let crate::document::Kind::Site { root } = &document.kind else {
        return (Vec::new(), HashMap::new());
    };
    let root = document.base.join(root);
    let mut read = Read::default();
    let homes = homes(document, &root, &mut read);
    let tree = children(document, &root, &homes, &mut read);
    // A page that can't be read lists nothing, as one with no Topics.
    let topics = read
        .0
        .into_iter()
        .map(|(page, topics)| (page, topics.unwrap_or_default()))
        .collect();
    (tree, topics)
}

/// Where each page listed in the tree has its position: the page listing it
/// and the listing's index among that page's Topics links. Found level by
/// level from the root, so the shallowest listing wins, then the first.
fn homes(document: &Document, root: &Path, read: &mut Read) -> HashMap<PathBuf, (PathBuf, usize)> {
    let mut homes = HashMap::new();
    let mut seen = HashSet::from([root.to_path_buf()]);
    let mut level = vec![root.to_path_buf()];
    while !level.is_empty() {
        let mut next = Vec::new();
        for page in &level {
            let Some(topics) = read.topics(page) else {
                continue;
            };
            for (index, topic) in topics.into_iter().enumerate() {
                let file = match resolve(document, page, &topic.href) {
                    Target::Page(file) | Target::Document(file) => file,
                    Target::None | Target::Problem(_) => continue,
                };
                if seen.insert(file.clone()) {
                    homes.insert(file.clone(), (page.clone(), index));
                    next.push(file);
                }
            }
        }
        level = next;
    }
    homes
}

/// The groups of entries `page` lists, recursively: each listed page whose
/// position, by `homes`, is this listing.
fn children(
    document: &Document,
    page: &Path,
    homes: &HashMap<PathBuf, (PathBuf, usize)>,
    read: &mut Read,
) -> Vec<Group> {
    let Some(topics) = read.topics(page) else {
        return Vec::new();
    };
    let mut groups: Vec<Group> = Vec::new();
    for (index, topic) in topics.into_iter().enumerate() {
        let (file, page_target) = match resolve(document, page, &topic.href) {
            Target::Page(file) => (file, true),
            Target::Document(file) => (file, false),
            Target::None | Target::Problem(_) => continue,
        };
        let home = homes
            .get(&file)
            .is_some_and(|(parent, at)| parent == page && *at == index);
        if !home {
            continue;
        }
        let entry = Entry {
            label: topic.label,
            children: if page_target {
                children(document, &file, homes, read)
            } else {
                // A code reference lists its crates, modules and types, as
                // DocC's navigator does.
                crate::code::for_document(&document.path())
                    .map(|index| index.navigator(&file))
                    .unwrap_or_default()
            },
            file,
        };
        match groups.last_mut() {
            Some(group) if group.title == topic.group => group.entries.push(entry),
            _ => groups.push(Group {
                title: topic.group,
                entries: vec![entry],
            }),
        }
    }
    groups
}

/// What a Topics link names in a site's sidebar.
#[derive(Debug, PartialEq)]
pub enum Target {
    /// A page in the site's folder: an entry with its own children.
    Page(PathBuf),
    /// A document file: an entry that opens that document, with no children.
    Document(PathBuf),
    /// Not an entry: another website, a `#fragment`, any other file.
    None,
    /// Left out, and a problem: a missing file, or a page outside the site.
    Problem(String),
}

/// What a Topics link on `page` names.
pub fn resolve(document: &Document, page: &Path, href: &str) -> Target {
    let path = match Link::classify(href) {
        Link::File { path, .. } if !path.is_empty() => path,
        _ => return Target::None,
    };
    let Some(target) = page
        .parent()
        .and_then(|folder| document.served.file(&folder.join(path)))
    else {
        // A page of the site's code reference opens like a document.
        let would_be = crate::folder::lexical(&page.parent().unwrap_or(Path::new(".")).join(path));
        if crate::code::for_document(&document.path())
            .is_some_and(|index| index.page(&would_be).is_some())
        {
            return Target::Document(would_be);
        }
        return Target::Problem(format!("Topics entry {href} — no such file"));
    };
    if target.extension().is_some_and(|ext| ext == "md") {
        if target.starts_with(&document.base) {
            Target::Page(target)
        } else {
            Target::Problem(format!("Topics entry {href} — outside the site's folder"))
        }
    } else if crate::document::kind_of(&target).is_some() {
        Target::Document(target)
    } else {
        Target::None
    }
}

/// The links listed in a page's `## Topics` section, in order.
pub fn topics(source: &str) -> Vec<Topic> {
    let arena = Arena::new();
    let root = parse_document(&arena, source, &Options::default());
    let mut topics = Vec::new();
    let mut in_topics = false;
    let mut group = None;
    for node in root.children() {
        let value = node.data.borrow().value.clone();
        match value {
            NodeValue::Heading(heading) if heading.level <= 2 => {
                in_topics = heading.level == 2 && text(node).trim() == "Topics";
                group = None;
            }
            NodeValue::Heading(heading) if in_topics && heading.level == 3 => {
                group = Some(text(node).trim().to_string());
            }
            NodeValue::List(_) if in_topics => {
                for item in node.children() {
                    if let Some((label, href)) = first_link(item) {
                        topics.push(Topic {
                            group: group.clone(),
                            label,
                            href,
                        });
                    }
                }
            }
            _ => {}
        }
    }
    topics
}

/// The text and target of the first link inside `node`; `None` when it has
/// none.
fn first_link<'a>(node: &'a AstNode<'a>) -> Option<(String, String)> {
    node.descendants()
        .find_map(|descendant| match &descendant.data.borrow().value {
            NodeValue::Link(link) => Some((text(descendant).trim().to_string(), link.url.clone())),
            _ => None,
        })
}

/// The text of `node`: its text and inline code, without the markup.
fn text<'a>(node: &'a AstNode<'a>) -> String {
    node.descendants()
        .filter_map(|descendant| match &descendant.data.borrow().value {
            NodeValue::Text(text) => Some(text.to_string()),
            NodeValue::Code(code) => Some(code.literal.clone()),
            _ => None,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::folder::ServedFolder;

    #[test]
    fn reads_links_and_groups_from_the_topics_section_only() {
        let source = "# Home\n\nSee the [viewer](viewer.md) in passing.\n\n## Topics\n\n\
                      - [Vision](vision.md) — why\n\n### The system\n\n- [Viewer](boxes/viewer/README.md)\n\
                      - [Engineering](boxes/engineering/README.md)\n\n## Afterwards\n\n- [Ignored](x.md)\n";
        let found = topics(source);
        let labels: Vec<_> = found
            .iter()
            .map(|t| (t.group.as_deref(), t.label.as_str(), t.href.as_str()))
            .collect();
        assert_eq!(
            labels,
            vec![
                (None, "Vision", "vision.md"),
                (Some("The system"), "Viewer", "boxes/viewer/README.md"),
                (
                    Some("The system"),
                    "Engineering",
                    "boxes/engineering/README.md"
                ),
            ]
        );
    }

    #[test]
    fn a_page_listed_twice_is_in_the_tree_only_at_its_shallowest_listing() {
        let dir = std::env::temp_dir().join(format!("devpage-nav-home-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        // Reading order meets `start` under `system` first, one level deeper.
        std::fs::write(
            dir.join("README.md"),
            "# Home\n\n## Topics\n\n- [System](system.md)\n- [Start](start.md)\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("system.md"),
            "# System\n\n## Topics\n\n- [Start](start.md)\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("start.md"),
            "# Start\n\n## Topics\n\n- [First](first.md)\n",
        )
        .unwrap();
        std::fs::write(dir.join("first.md"), "# First\n").unwrap();
        let document = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();

        let tree = tree(&document);
        let [system, start] = &tree[0].entries[..] else {
            panic!("two top-level entries");
        };
        assert_eq!(
            start.label, "Start",
            "the top-level listing is the position"
        );
        assert_eq!(start.children[0].entries[0].label, "First");
        assert!(system.children.is_empty(), "a second listing is left out");
    }

    #[test]
    fn builds_the_tree_and_stops_at_cycles() {
        let dir = std::env::temp_dir().join(format!("devpage-nav-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("guide")).unwrap();
        std::fs::write(
            dir.join("devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("README.md"),
            "# Home\n\n## Topics\n\n- [Guide](guide/README.md)\n- [Missing](nope.md)\n- [Talk](talk.yml)\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("talk.yml"),
            "kind: slides\ntitle: T\nslides: [README.md]\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("guide/README.md"),
            "# Guide\n\n## Topics\n\n- [Back home](../README.md)\n- [Step](step.md)\n",
        )
        .unwrap();
        std::fs::write(dir.join("guide/step.md"), "# Step\n").unwrap();
        let document = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();

        let tree = tree(&document);
        assert_eq!(tree.len(), 1);
        let talk = &tree[0].entries[1];
        assert_eq!(talk.label, "Talk", "a document file is an entry");
        assert!(talk.children.is_empty());
        let guide = &tree[0].entries[0];
        assert_eq!(guide.label, "Guide");
        let under_guide: Vec<_> = guide.children[0]
            .entries
            .iter()
            .map(|e| e.label.as_str())
            .collect();
        assert_eq!(
            under_guide,
            vec!["Step"],
            "a link back to the root is left out"
        );
    }

    #[test]
    fn a_page_outside_the_site_or_a_missing_one_is_a_problem() {
        let dir = std::env::temp_dir().join(format!("devpage-nav-out-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("site")).unwrap();
        let dir = dir.canonicalize().unwrap();
        std::fs::write(dir.join("outside.md"), "# Out\n").unwrap();
        std::fs::write(dir.join("site/README.md"), "# Home\n").unwrap();
        std::fs::write(
            dir.join("site/devpage.yml"),
            "kind: site\ntitle: T\nroot: README.md\n",
        )
        .unwrap();
        let document =
            Document::load(&dir.join("site"), &ServedFolder::new(&dir).unwrap()).unwrap();
        let page = dir.join("site/README.md");
        assert!(matches!(
            resolve(&document, &page, "../outside.md"),
            Target::Problem(message) if message.contains("outside the site's folder")
        ));
        assert!(matches!(
            resolve(&document, &page, "nope.md"),
            Target::Problem(_)
        ));
        assert_eq!(
            resolve(&document, &page, "https://example.com"),
            Target::None
        );
        assert_eq!(resolve(&document, &page, "#top"), Target::None);
    }
}