Skip to main content

devpage_core/page/
content.rs

1//! The content phase: one file's Markdown, its widgets' tags expanded, as
2//! the HTML its page shows — with every link that content holds, by file and
3//! line. The frame is put round it afterwards, so no link of the frame's —
4//! the navbar's, the sidebar's — is among them. What the preview and
5//! `devpage check` judge a page by is this, the content its page shows.
6
7use std::collections::BTreeSet;
8use std::path::{Path, PathBuf};
9
10use crate::document::{Document, Kind};
11use crate::folder::Folder;
12use crate::html;
13use crate::widgets::{Modules, Widgets};
14
15use super::frame::chapter_names;
16use super::markdown::markdown;
17
18/// One file's content as its page shows it.
19pub struct Rendered {
20    file: PathBuf,
21    source: String,
22    expanded: String,
23    html: String,
24    links: Vec<Link>,
25    embeds: Vec<String>,
26    tags: Vec<String>,
27}
28
29/// A link the content holds: what it names as written — an `href`, a
30/// `src`, or a design the Markdown embeds — the file it is written in, and
31/// the line, when its text is found in the file.
32#[derive(Debug, Clone, PartialEq)]
33pub struct Link {
34    pub file: PathBuf,
35    pub line: Option<usize>,
36    pub target: String,
37}
38
39impl Rendered {
40    /// The file the content is read from.
41    pub fn file(&self) -> &Path {
42        &self.file
43    }
44
45    /// The Markdown as written.
46    pub fn source(&self) -> &str {
47        &self.source
48    }
49
50    /// The Markdown its HTML is made from: the source with its widgets'
51    /// tags expanded, `<Notes>` taken out and an unknown tag replaced by
52    /// its error — what search reads a page by.
53    pub fn expanded(&self) -> &str {
54        &self.expanded
55    }
56
57    /// The content's HTML, links as written.
58    pub fn html(&self) -> &str {
59        &self.html
60    }
61
62    /// Every id the content's HTML holds — its headings', a footnote's, a
63    /// raw element's — a link's `#fragment` can land on.
64    pub fn ids(&self) -> BTreeSet<String> {
65        html::values(&self.html, "id").into_iter().collect()
66    }
67
68    /// The id of each Markdown heading the content shows, in order — a
69    /// heading inside a widget among them, one inside an unknown tag not,
70    /// since its page doesn't show it.
71    pub fn heading_ids(&self) -> Vec<String> {
72        super::markdown::heading_ids(&self.html)
73    }
74
75    /// Every link the content holds, in the order its HTML holds them.
76    pub fn links(&self) -> &[Link] {
77        &self.links
78    }
79
80    /// What the content draws from other files, as written: every `src` —
81    /// an image, a design's canvas, a frame — and every design the Markdown
82    /// embeds. A link only to be followed is not among them.
83    pub fn embeds(&self) -> &[String] {
84        &self.embeds
85    }
86
87    /// What expanding the widgets' tags found wrong — a tag that is no
88    /// widget, a misplaced one — each as `line: message`.
89    pub(crate) fn tag_problems(&self) -> &[String] {
90        &self.tags
91    }
92}
93
94/// `file`'s content from `source`, the tags of `widgets` expanded first.
95pub fn content(widgets: &Widgets, file: &Path, source: String) -> Rendered {
96    let _render = tracing::info_span!("render").entered();
97    let mut tags = Vec::new();
98    let expanded = crate::widgets::expand(&source, widgets.names(), &mut tags);
99    let html = markdown(&expanded);
100    let mut targets = html::values(&html, "href");
101    let mut embeds = html::values(&html, "src");
102    targets.extend(embeds.iter().cloned());
103    // A design embedded with `![…](x.design)`, read from the Markdown itself,
104    // whatever HTML the page renders it as.
105    for design in embedded_designs(&source) {
106        if !embeds.contains(&design) {
107            embeds.push(design.clone());
108        }
109        if !targets.contains(&design) {
110            targets.push(design);
111        }
112    }
113    let links = targets
114        .into_iter()
115        .map(|target| Link {
116            file: file.to_path_buf(),
117            line: source
118                .find(&target)
119                .map(|at| source[..at].lines().count().max(1)),
120            target,
121        })
122        .collect();
123    Rendered {
124        file: file.to_path_buf(),
125        source,
126        expanded,
127        html,
128        links,
129        embeds,
130        tags,
131    }
132}
133
134/// `file`'s content as read from the disk now; a file that can't be read
135/// has none.
136pub fn read(widgets: &Widgets, file: &Path) -> Rendered {
137    content(
138        widgets,
139        file,
140        std::fs::read_to_string(file).unwrap_or_default(),
141    )
142}
143
144/// The document a Markdown file is shown in at its own address: its nearest
145/// site; in no site, the file alone, as a doc of one chapter. `None` when
146/// its site can't be read: its page then shows why, and none of the file.
147pub fn shown_in(file: &Path, folder: &Folder) -> Option<Document> {
148    Document::load(&shown_by(file, folder), folder.served()).ok()
149}
150
151/// The file of the document a Markdown file is [shown in](shown_in),
152/// unloaded: its nearest site's document file, or in no site the file
153/// itself.
154pub fn shown_by(file: &Path, folder: &Folder) -> PathBuf {
155    folder.site(file).unwrap_or_else(|| file.to_path_buf())
156}
157
158/// Every id a link's `#fragment` into `file` can land on, as its page
159/// renders them: the ids of the content phase, the tags of its document's
160/// widgets expanded, read through `modules` — without building the frame.
161/// A Markdown file's are its content's, as the document it is
162/// [shown in](shown_in) renders it; a doc's are its chapters', each
163/// prefixed with its chapter's name when there is more than one, and the
164/// chapters' own names. Anything else has none.
165pub fn ids(file: &Path, folder: &Folder, modules: &Modules) -> BTreeSet<String> {
166    if file.extension().is_some_and(|ext| ext == "md") {
167        return shown_in(file, folder)
168            .map(|document| read(&Widgets::of(&document, modules), file).ids())
169            .unwrap_or_default();
170    }
171    let served = folder.served();
172    let Ok(document) = Document::load(file, served) else {
173        return BTreeSet::new();
174    };
175    let Kind::Doc { chapters, .. } = &document.kind else {
176        return BTreeSet::new();
177    };
178    let widgets = Widgets::of(&document, modules);
179    let own_ids = |chapter: &Path| read(&widgets, chapter).ids();
180    if chapters.len() == 1 {
181        return own_ids(&chapters[0]);
182    }
183    let names = chapter_names(chapters, served);
184    let mut ids = BTreeSet::new();
185    for (chapter, (_, name)) in chapters.iter().zip(&names) {
186        ids.extend(
187            own_ids(chapter)
188                .into_iter()
189                .map(|id| format!("{name}--{id}")),
190        );
191        ids.insert(name.clone());
192    }
193    ids
194}
195
196/// The `.design` files a page's Markdown embeds or links to, read from its
197/// syntax tree — never from code, where `![…](x.design)` is only an example.
198fn embedded_designs(source: &str) -> Vec<String> {
199    use comrak::nodes::NodeValue;
200    let arena = comrak::Arena::new();
201    let root = comrak::parse_document(&arena, source, &comrak::Options::default());
202    root.descendants()
203        .filter_map(|node| match &node.data.borrow().value {
204            NodeValue::Image(link) | NodeValue::Link(link) => Some(link.url.clone()),
205            _ => None,
206        })
207        .filter(|url| {
208            url.split('#')
209                .next()
210                .is_some_and(|path| path.ends_with(".design"))
211        })
212        .collect()
213}