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