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