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_with(&augmented, widgets.names(), &mut tags, &|name| {
123        widgets.written(file, name)
124    });
125    let grammars: Vec<_> = extensions.iter().filter_map(|b| b.grammar()).collect();
126    let mut extension_embeds = Vec::new();
127    let mut html = crate::highlight::with_grammars(&grammars, || markdown(&expanded));
128    for (identity, target) in crate::html::values(&html, "src").into_iter().enumerate() {
129        let path = target.split('#').next().unwrap_or(&target);
130        if let Some(binding) = extensions.iter().find(|b| b.owns(Path::new(path))) {
131            extension_embeds.push(target.clone());
132            match binding.embed(file, &target, "", identity) {
133                Ok(embed) => {
134                    let needle = format!("src=\"{}\"", crate::html::escape(&target));
135                    while let Some(at) = html.find(&needle) {
136                        let Some(start) = html[..at].rfind("<img ") else {
137                            break;
138                        };
139                        let Some(end) = html[at..].find('>') else {
140                            break;
141                        };
142                        html.replace_range(start..at + end + 1, &embed);
143                    }
144                }
145                Err(error) => tags.push(format!("Extension embed: {error:#}")),
146            }
147        }
148    }
149    let mut targets = html::values(&html, "href");
150    let mut embeds = html::values(&html, "src");
151    embeds.extend(extension_embeds);
152    targets.extend(embeds.iter().cloned());
153    // A design embedded with `![…](x.design)`, read from the Markdown itself,
154    // whatever HTML the page renders it as.
155    for design in embedded_designs(&source) {
156        if !embeds.contains(&design) {
157            embeds.push(design.clone());
158        }
159        if !targets.contains(&design) {
160            targets.push(design);
161        }
162    }
163    let links = targets
164        .into_iter()
165        .map(|target| Link {
166            file: file.to_path_buf(),
167            line: source
168                .find(&target)
169                .map(|at| source[..at].lines().count().max(1)),
170            target,
171        })
172        .collect();
173    Rendered {
174        file: file.to_path_buf(),
175        source,
176        expanded,
177        html,
178        links,
179        embeds,
180        tags,
181    }
182}
183
184/// `file`'s content as read from the disk now; a file that can't be read
185/// has none.
186pub fn read(widgets: &Widgets, file: &Path) -> Rendered {
187    content(
188        widgets,
189        file,
190        std::fs::read_to_string(file).unwrap_or_default(),
191    )
192}
193
194/// The document a Markdown file is shown in at its own address: its nearest
195/// site; in no site, the file alone, as a doc of one chapter. `None` when
196/// its site can't be read: its page then shows why, and none of the file.
197pub fn shown_in(file: &Path, folder: &Folder) -> Option<Document> {
198    Document::load(&shown_by(file, folder), folder.served()).ok()
199}
200
201/// The file of the document a Markdown file is [shown in](shown_in),
202/// unloaded: its nearest site's document file, or in no site the file
203/// itself.
204pub fn shown_by(file: &Path, folder: &Folder) -> PathBuf {
205    folder.site(file).unwrap_or_else(|| file.to_path_buf())
206}
207
208/// Every id a link's `#fragment` into `file` can land on, as its page
209/// renders them: the ids of the content phase, the tags of its document's
210/// widgets expanded, read through `modules` — without building the frame.
211/// A Markdown file's are its content's, as the document it is
212/// [shown in](shown_in) renders it; a doc's are its chapters', each
213/// prefixed with its chapter's name when there is more than one, and the
214/// chapters' own names. Anything else has none.
215pub fn ids(file: &Path, folder: &Folder, modules: &Modules) -> BTreeSet<String> {
216    if file.extension().is_some_and(|ext| ext == "md") {
217        return shown_in(file, folder)
218            .map(|document| read(&Widgets::of(&document, modules), file).ids())
219            .unwrap_or_default();
220    }
221    let served = folder.served();
222    let Ok(document) = Document::load(file, served) else {
223        return BTreeSet::new();
224    };
225    let Kind::Doc { chapters, .. } = &document.kind else {
226        return BTreeSet::new();
227    };
228    let widgets = Widgets::of(&document, modules);
229    let own_ids = |chapter: &Path| read(&widgets, chapter).ids();
230    if chapters.len() == 1 {
231        return own_ids(&chapters[0]);
232    }
233    let names = chapter_names(chapters, served);
234    let mut ids = BTreeSet::new();
235    for (chapter, (_, name)) in chapters.iter().zip(&names) {
236        ids.extend(
237            own_ids(chapter)
238                .into_iter()
239                .map(|id| format!("{name}--{id}")),
240        );
241        ids.insert(name.clone());
242    }
243    ids
244}
245
246/// The `.design` files a page's Markdown embeds or links to, read from its
247/// syntax tree — never from code, where `![…](x.design)` is only an example.
248fn embedded_designs(source: &str) -> Vec<String> {
249    use comrak::nodes::NodeValue;
250    let arena = comrak::Arena::new();
251    let root = comrak::parse_document(&arena, source, &comrak::Options::default());
252    root.descendants()
253        .filter_map(|node| match &node.data.borrow().value {
254            NodeValue::Image(link) | NodeValue::Link(link) => Some(link.url.clone()),
255            _ => None,
256        })
257        .filter(|url| {
258            url.split('#')
259                .next()
260                .is_some_and(|path| path.ends_with(".design"))
261        })
262        .collect()
263}