Skip to main content

devpage_core/widgets/
mod.rs

1//! Widgets: React components used as capitalized HTML tags in Markdown.
2//!
3//! On the server a page's widget tags become placeholder elements carrying the
4//! widget's name, its props' source and its content ([`tags`]), which comrak
5//! renders as Markdown. In the browser the page script loads React and the
6//! widgets, compiled here from TSX by oxc ([`compile`]), and mounts each
7//! placeholder. What was read and compiled is kept in a [`Modules`] cache.
8//!
9//! This module is the widget set a document has: its names, the address
10//! each is served at, and what a page loads.
11
12mod compile;
13mod modules;
14mod tags;
15
16use std::collections::BTreeMap;
17use std::path::{Path, PathBuf};
18
19use anyhow::{Result, anyhow};
20
21pub use modules::{Modules, Snapshot};
22pub use tags::expand;
23
24use crate::addresses::{Owned, address};
25use crate::document::Document;
26use crate::served::ServedFolder;
27
28/// The widgets devpage ships, compiled into the binary.
29pub const SYSTEM: &[(&str, &str)] = &[
30    ("Callout", include_str!("../../assets/widgets/Callout.tsx")),
31    (
32        SIDEBAR,
33        include_str!("../../assets/widgets/DevpageSidebar.tsx"),
34    ),
35    ("Cards", include_str!("../../assets/widgets/Cards.tsx")),
36    ("Example", include_str!("../../assets/widgets/Example.tsx")),
37    (
38        "FileTree",
39        include_str!("../../assets/widgets/FileTree.tsx"),
40    ),
41    ("Keys", include_str!("../../assets/widgets/Keys.tsx")),
42    ("Steps", include_str!("../../assets/widgets/Steps.tsx")),
43    ("Tab", include_str!("../../assets/widgets/Tab.tsx")),
44    ("Tabs", include_str!("../../assets/widgets/Tabs.tsx")),
45    (
46        "Terminal",
47        include_str!("../../assets/widgets/Terminal.tsx"),
48    ),
49];
50
51/// The widget that is a site's sidebar: devpage's own chrome, mounted by the
52/// page script on the sidebar the server rendered, never written in a page.
53/// Its `Devpage` prefix keeps it clear of a project's names: a project may
54/// have its own `Sidebar`.
55pub const SIDEBAR: &str = "DevpageSidebar";
56
57pub use crate::markup::NOTES;
58
59/// The widgets a document's pages can use: name → the address its module is
60/// served at.
61#[derive(Debug, Default)]
62pub struct Widgets {
63    pub modules: BTreeMap<String, String>,
64    /// Where its modules are read and compiled.
65    cache: Modules,
66    /// The served folder, and each project widget's file, by name.
67    served: ServedFolder,
68    files: BTreeMap<String, PathBuf>,
69    /// Every name in `modules`: what a project widget can render by name.
70    known: Vec<String>,
71    /// Widget files that can't be widgets: a lowercase name, or a system
72    /// widget's name.
73    pub problems: Vec<String>,
74}
75
76impl Widgets {
77    /// The system widgets plus the document's own, from its `widgets` folder,
78    /// each at its [content address](crate::addresses), read and compiled
79    /// through `cache`.
80    pub fn of(document: &Document, cache: &Modules) -> Self {
81        let mut widgets = Self {
82            cache: cache.clone(),
83            ..Self::default()
84        };
85        for (name, _) in SYSTEM {
86            let mount = document.served.mount();
87            widgets.modules.insert(
88                name.to_string(),
89                address(Owned::SystemWidget { name, mount }),
90            );
91        }
92        widgets.served = document.served.clone();
93        widgets.known = widgets.modules.keys().cloned().collect();
94        let Some(folder) = &document.widgets else {
95            return widgets;
96        };
97        let Ok(entries) = std::fs::read_dir(folder) else {
98            return widgets;
99        };
100        let mut files: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();
101        files.sort();
102        let mut own = Vec::new();
103        for file in files {
104            // A file that resolves outside the served folder is never read.
105            if file.extension().is_none_or(|ext| ext != "tsx")
106                || document.served.file(&file).is_none()
107            {
108                continue;
109            }
110            let name = file
111                .file_stem()
112                .unwrap_or_default()
113                .to_string_lossy()
114                .into_owned();
115            let label = document.name(&file);
116            if !name.starts_with(|c: char| c.is_ascii_uppercase()) {
117                // A lowercase .tsx is a helper a widget imports, not a widget.
118                continue;
119            }
120            if SYSTEM.iter().any(|(system, _)| *system == name) {
121                widgets
122                    .problems
123                    .push(format!("{} — {name} is a system widget's name", label));
124                continue;
125            }
126            if name == NOTES {
127                widgets.problems.push(format!(
128                    "{} — {NOTES} is devpage's tag for a slide's notes",
129                    label
130                ));
131                continue;
132            }
133            own.push((name, file));
134        }
135        // A widget's address covers the names it can render, so every name is
136        // known before any address is made.
137        let known: Vec<String> = widgets
138            .modules
139            .keys()
140            .cloned()
141            .chain(own.iter().map(|(name, _)| name.clone()))
142            .collect::<std::collections::BTreeSet<_>>()
143            .into_iter()
144            .collect();
145        for (name, file) in own {
146            let url = address(Owned::Module {
147                snapshot: &cache.snapshot(&document.served, &file),
148                file: &file,
149                known: &known,
150            });
151            widgets.modules.insert(name.clone(), url);
152            widgets.files.insert(name, file);
153        }
154        widgets.known = known;
155        widgets
156    }
157
158    /// The cache its modules are read and compiled through.
159    pub fn cache(&self) -> &Modules {
160        &self.cache
161    }
162
163    /// Every name a page can use as a widget tag, sorted.
164    pub fn names(&self) -> &[String] {
165        &self.known
166    }
167
168    /// A project widget or helper `file` of this set, compiled now as its
169    /// address serves it.
170    pub fn compile(&self, file: &Path) -> Result<String> {
171        self.cache
172            .snapshot(&self.served, file)
173            .compile(file, &self.known)
174    }
175
176    /// What the `<head>` of a page whose rendered content is `content`, in a
177    /// frame that mounts the widgets `chrome`, needs: the import map naming
178    /// React, the widgets the page script loads, and the page's
179    /// [load set](Self::load_set) — each module as a `modulepreload` at the
180    /// very address its import asks for, and the design engine's wasm as a
181    /// low-priority fetch — so the browser asks for all of it at once, as
182    /// soon as it reads the head.
183    pub fn head(&self, content: &str, chrome: &[&str]) -> String {
184        let modules = serde_json::to_string(&self.modules).unwrap_or_default();
185        let react = address(Owned::Asset("react.js"));
186        let (preloads, fetches) = self.load_set(content, chrome);
187        let mut links = String::new();
188        for module in preloads {
189            links.push_str(&format!("\n<link rel=\"modulepreload\" href=\"{module}\">"));
190        }
191        for fetch in fetches {
192            links.push_str(&format!(
193                "\n<link rel=\"preload\" href=\"{fetch}\" as=\"fetch\" crossorigin fetchpriority=\"low\">"
194            ));
195        }
196        format!(
197            r#"<script type="importmap">{{"imports":{{"react":"{react}","react/jsx-runtime":"{react}","react-dom/client":"{react}"}}}}</script>
198<script>window.devpageWidgets = {modules};</script>{links}"#
199        )
200    }
201
202    /// Everything a page whose rendered content is `content`, in a frame that
203    /// mounts the widgets `chrome` — a site's sidebar, [`SIDEBAR`] — loads
204    /// from devpage beyond its stylesheet and page script: the modules —
205    /// React if it has a widget; each widget it names, then the frame's; the
206    /// widgets each of those renders by name (its `__devpageUses`), and so
207    /// on; every helper a project widget's imports reach; the design script
208    /// and engine with an
209    /// embedded design — and what is fetched, not imported: the engine's
210    /// wasm. Each is the address [`address`] makes, so it is the one the
211    /// import asks for.
212    pub fn load_set(&self, content: &str, chrome: &[&str]) -> (Vec<String>, Vec<String>) {
213        let mut queue: Vec<String> = content
214            .split("data-widget=\"")
215            .skip(1)
216            .filter_map(|rest| rest.split('"').next())
217            .map(str::to_string)
218            .collect();
219        // The frame's own come after the content's: the server drew them
220        // already, so the reader waits on the content's first.
221        queue.extend(chrome.iter().map(|name| name.to_string()));
222        let mut seen = std::collections::BTreeSet::new();
223        let mut widgets = Vec::new();
224        let mut helpers = Vec::new();
225        // In the order the page names them: the first are wanted first.
226        let mut next = 0;
227        while let Some(name) = queue.get(next).cloned() {
228            next += 1;
229            if !self.modules.contains_key(&name) || !seen.insert(name.clone()) {
230                continue;
231            }
232            widgets.push(self.modules[&name].clone());
233            let compiled = match self.files.get(&name) {
234                Some(file) => {
235                    let snapshot = self.cache.snapshot(&self.served, file);
236                    for (helper, _) in snapshot.closure(file).into_iter().skip(1) {
237                        helpers.push(address(Owned::Module {
238                            snapshot: &snapshot,
239                            file: &helper,
240                            known: &self.known,
241                        }));
242                    }
243                    snapshot.compile(file, &self.known)
244                }
245                None => self
246                    .cache
247                    .system(&name)
248                    .unwrap_or_else(|| Err(anyhow!("no {name}"))),
249            };
250            queue.extend(compiled.map(|js| compile::uses(&js)).unwrap_or_default());
251        }
252        let mut modules = Vec::new();
253        if !seen.is_empty() {
254            modules.push(address(Owned::Asset("react.js")));
255        }
256        modules.extend(widgets);
257        for helper in helpers {
258            if !modules.contains(&helper) {
259                modules.push(helper);
260            }
261        }
262        let mut fetches = Vec::new();
263        if content.contains("<canvas class=\"design\"") {
264            // The design script and the modules it imports, the engine's
265            // bindings last.
266            for module in [
267                "design.js",
268                "design-stream.js",
269                "design-canvas.js",
270                "design-tiles.js",
271                "design-engine.js",
272            ] {
273                modules.push(address(Owned::Asset(module)));
274            }
275            fetches.push(address(Owned::Asset("design-engine.wasm")));
276        }
277        (modules, fetches)
278    }
279}
280
281/// Whether `path` is a widget or helper file: a `.ts` or `.tsx` directly in a
282/// widgets folder.
283pub fn is_widget_file(path: &Path, folder: &Path) -> bool {
284    path.parent() == Some(folder)
285        && path
286            .extension()
287            .is_some_and(|ext| ext == "ts" || ext == "tsx")
288}
289
290/// The source of a system widget, by name.
291pub fn system(name: &str) -> Option<&'static str> {
292    SYSTEM.iter().find(|(n, _)| *n == name).map(|(_, s)| *s)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn lowercase_files_are_helpers_and_a_system_name_is_a_problem() {
301        let dir = std::env::temp_dir().join(format!("devpage-wset-{}", std::process::id()));
302        let _ = std::fs::remove_dir_all(&dir);
303        std::fs::create_dir_all(dir.join("widgets")).unwrap();
304        std::fs::write(
305            dir.join("devpage.yml"),
306            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
307        )
308        .unwrap();
309        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
310        std::fs::write(dir.join("widgets/Card.tsx"), "export default () => null;").unwrap();
311        std::fs::write(dir.join("widgets/cards.tsx"), "export const x = 1;").unwrap();
312        std::fs::write(
313            dir.join("widgets/Callout.tsx"),
314            "export default () => null;",
315        )
316        .unwrap();
317        let dir = dir.canonicalize().unwrap();
318        let document = Document::load(&dir, &dir).unwrap();
319        let widgets = Widgets::of(&document, &Modules::default());
320        assert!(widgets.modules.contains_key("Card"));
321        assert!(!widgets.modules.contains_key("cards"));
322        assert!(widgets.modules["Callout"].starts_with("/__devpage/system-widgets/"));
323        assert_eq!(
324            widgets.problems,
325            vec!["widgets/Callout.tsx — Callout is a system widget's name".to_string()]
326        );
327        let known: Vec<String> = widgets.modules.keys().cloned().collect();
328        assert_eq!(
329            widgets.modules["Card"],
330            address(Owned::Module {
331                snapshot: &Modules::default().snapshot(&dir, &dir.join("widgets/Card.tsx")),
332                file: &dir.join("widgets/Card.tsx"),
333                known: &known
334            })
335        );
336    }
337
338    #[test]
339    fn devpage_sidebar_is_reserved_and_a_project_sidebar_is_not() {
340        let dir = std::env::temp_dir().join(format!("devpage-wsidebar-{}", std::process::id()));
341        let _ = std::fs::remove_dir_all(&dir);
342        std::fs::create_dir_all(dir.join("widgets")).unwrap();
343        std::fs::write(
344            dir.join("devpage.yml"),
345            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
346        )
347        .unwrap();
348        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
349        for name in ["DevpageSidebar", "Sidebar"] {
350            std::fs::write(
351                dir.join(format!("widgets/{name}.tsx")),
352                "export default () => null;",
353            )
354            .unwrap();
355        }
356        let dir = dir.canonicalize().unwrap();
357        let widgets = Widgets::of(&Document::load(&dir, &dir).unwrap(), &Modules::default());
358        assert_eq!(
359            widgets.problems,
360            vec![
361                "widgets/DevpageSidebar.tsx — DevpageSidebar is a system widget's name".to_string()
362            ]
363        );
364        assert!(widgets.modules["DevpageSidebar"].starts_with("/__devpage/system-widgets/"));
365        assert!(widgets.modules["Sidebar"].starts_with("/__devpage/widgets/"));
366    }
367
368    #[test]
369    fn a_project_widget_named_notes_clashes() {
370        let dir = std::env::temp_dir().join(format!("devpage-wnotes-{}", std::process::id()));
371        let _ = std::fs::remove_dir_all(&dir);
372        std::fs::create_dir_all(dir.join("widgets")).unwrap();
373        std::fs::write(
374            dir.join("devpage.yml"),
375            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
376        )
377        .unwrap();
378        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
379        std::fs::write(dir.join("widgets/Notes.tsx"), "export default () => null;").unwrap();
380        let dir = dir.canonicalize().unwrap();
381        let widgets = Widgets::of(&Document::load(&dir, &dir).unwrap(), &Modules::default());
382        assert!(!widgets.modules.contains_key("Notes"));
383        assert_eq!(
384            widgets.problems,
385            vec!["widgets/Notes.tsx — Notes is devpage's tag for a slide's notes".to_string()]
386        );
387    }
388}