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