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;
15pub use compile::relative_imports as extension_imports;
16mod modules;
17mod request;
18mod tags;
19
20use std::collections::BTreeMap;
21use std::path::{Path, PathBuf};
22use std::sync::LazyLock;
23
24use anyhow::{Result, anyhow};
25use sha2::{Digest, Sha256};
26
27pub use modules::{Modules, Snapshot};
28pub use request::{Compiled, project_module, system_module};
29pub use tags::{expand, expand_with};
30
31use crate::addresses::{Owned, address};
32use crate::document::Document;
33use crate::folder::ServedFolder;
34
35/// The widgets devpage ships, compiled into the binary.
36pub const SYSTEM: &[(&str, &str)] = &[
37    ("Callout", include_str!("../../assets/widgets/Callout.tsx")),
38    (
39        SIDEBAR,
40        include_str!("../../assets/widgets/DevpageSidebar.tsx"),
41    ),
42    ("Cards", include_str!("../../assets/widgets/Cards.tsx")),
43    (
44        LIVE_CANVAS,
45        include_str!("../../assets/widgets/DevpageLiveCanvas.tsx"),
46    ),
47    (
48        LIVE_ORB,
49        include_str!("../../assets/widgets/DevpageLiveOrb.tsx"),
50    ),
51    (
52        LIVE_TASKS,
53        include_str!("../../assets/widgets/DevpageLiveTasks.tsx"),
54    ),
55    (
56        LIVE_TASKS_BUTTON,
57        include_str!("../../assets/widgets/DevpageLiveTasksButton.tsx"),
58    ),
59    ("Example", include_str!("../../assets/widgets/Example.tsx")),
60    (
61        "FileTree",
62        include_str!("../../assets/widgets/FileTree.tsx"),
63    ),
64    ("Keys", include_str!("../../assets/widgets/Keys.tsx")),
65    (
66        REQUIREMENTS,
67        include_str!("../../assets/widgets/Requirements.tsx"),
68    ),
69    ("Soon", include_str!("../../assets/widgets/Soon.tsx")),
70    ("Steps", include_str!("../../assets/widgets/Steps.tsx")),
71    ("Tab", include_str!("../../assets/widgets/Tab.tsx")),
72    ("Tabs", include_str!("../../assets/widgets/Tabs.tsx")),
73    (
74        "Terminal",
75        include_str!("../../assets/widgets/Terminal.tsx"),
76    ),
77];
78
79/// The modules system widgets share, by file name: what a system widget
80/// imports by a relative specifier (`./live`) beside the other system
81/// widgets. None is a widget: a page can't name one.
82pub const SHARED: &[(&str, &str)] = &[
83    (
84        "live-agent-orb.tsx",
85        include_str!("../../assets/widgets/live-agent-orb.tsx"),
86    ),
87    (
88        "live-orb.ts",
89        include_str!("../../assets/widgets/live-orb.ts"),
90    ),
91    ("live.ts", include_str!("../../assets/widgets/live.ts")),
92];
93
94/// The live session's orb, which starts and stops it: devpage's own chrome,
95/// [placed](crate::document::Places) by devpage where the session is on.
96pub const LIVE_ORB: &str = "DevpageLiveOrb";
97
98/// The live session's side panel: its agents and their tasks.
99pub const LIVE_TASKS: &str = "DevpageLiveTasks";
100
101/// The navbar's button that opens the live session's side panel.
102pub const LIVE_TASKS_BUTTON: &str = "DevpageLiveTasksButton";
103
104/// The live session's canvas: a scratch pad over the page.
105pub const LIVE_CANVAS: &str = "DevpageLiveCanvas";
106
107/// The widget that is a site's sidebar: devpage's own chrome, mounted by the
108/// page script on the sidebar the server rendered, never written in a page.
109/// Its `Devpage` prefix keeps it clear of a project's names: a project may
110/// have its own `Sidebar`.
111pub const SIDEBAR: &str = "DevpageSidebar";
112
113/// The system widget that lists a part's requirements: the server writes
114/// its content.
115pub const REQUIREMENTS: &str = "Requirements";
116
117pub use crate::markup::NOTES;
118
119#[cfg(test)]
120thread_local! {
121    /// The document file of every widget set read on this thread, for the
122    /// tests: how often a pass reads each.
123    pub(crate) static READ: std::cell::RefCell<Vec<PathBuf>> = Default::default();
124}
125
126/// The widgets a document's pages can use: name → the address its module is
127/// served at.
128#[derive(Debug, Default)]
129pub struct Widgets {
130    /// The extensions bound to the document, whose widgets are among `modules`.
131    pub(crate) extensions: Vec<crate::extensions::Binding>,
132    /// Every widget by name — system, extension and project alike — with the
133    /// address its module is served at.
134    pub modules: BTreeMap<String, String>,
135    /// Where its modules are read and compiled.
136    cache: Modules,
137    /// The served folder, and each project widget's file, by name.
138    served: ServedFolder,
139    /// Each project widget's file, by name.
140    files: BTreeMap<String, PathBuf>,
141    /// Every name in `modules`: what a project widget can render by name.
142    known: Vec<String>,
143    /// What can't be shown: a widget file with a lowercase name or a system
144    /// widget's name, and a place that names no widget.
145    pub problems: Vec<String>,
146    /// The widgets the document shows outside its pages' text.
147    places: crate::document::Places,
148    /// The document's folder, and the document file's name in the served
149    /// folder: what the `Requirements` widget's list is read by.
150    document: (PathBuf, String),
151}
152
153impl Widgets {
154    /// The system widgets plus the document's own, from its `widgets` folder,
155    /// each at its [content address](crate::addresses), read and compiled
156    /// through `cache`; and the document's places, each naming widgets among
157    /// them.
158    pub fn of(document: &Document, cache: &Modules) -> Self {
159        let mut widgets = Self::read(document, cache);
160        widgets.places = document.places.clone();
161        for (place, names) in document.places.named() {
162            for name in names {
163                if !widgets.modules.contains_key(name) {
164                    widgets.problems.push(format!(
165                        "{} — places: {place}: no widget is named {name}",
166                        document.name(&document.path()).unwrap_or_default()
167                    ));
168                }
169            }
170        }
171        widgets
172    }
173
174    /// The system and extension widgets plus those in the document's
175    /// `widgets` folder.
176    fn read(document: &Document, cache: &Modules) -> Self {
177        #[cfg(test)]
178        READ.with_borrow_mut(|read| read.push(document.path()));
179        let mut widgets = Self {
180            cache: cache.clone(),
181            ..Self::default()
182        };
183        for (name, _) in SYSTEM {
184            let mount = document.served.mount();
185            widgets.modules.insert(
186                name.to_string(),
187                system_address(&format!("{name}.tsx"), mount),
188            );
189        }
190        widgets.served = document.served.clone();
191        widgets.document = (
192            document.base.clone(),
193            document.name(&document.path()).unwrap_or_default(),
194        );
195        widgets.extensions = document.extensions.clone();
196        for binding in &widgets.extensions {
197            for (name, url) in binding.widget_urls() {
198                if widgets.modules.insert(name.clone(), url).is_some() {
199                    widgets
200                        .problems
201                        .push(format!("Extension widget {name} is already registered"));
202                }
203            }
204        }
205        widgets.known = widgets.modules.keys().cloned().collect();
206        let Some(folder) = &document.widgets else {
207            return widgets;
208        };
209        let Ok(entries) = std::fs::read_dir(folder) else {
210            return widgets;
211        };
212        let mut files: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();
213        files.sort();
214        let mut own = Vec::new();
215        for file in files {
216            // A file that resolves outside the served folder is never read,
217            // or named.
218            if file.extension().is_none_or(|ext| ext != "tsx")
219                || document.served.file(&file).is_none()
220            {
221                continue;
222            }
223            let Some(label) = document.name(&file) else {
224                continue;
225            };
226            let name = file
227                .file_stem()
228                .unwrap_or_default()
229                .to_string_lossy()
230                .into_owned();
231            if !name.starts_with(|c: char| c.is_ascii_uppercase()) {
232                // A lowercase .tsx is a helper a widget imports, not a widget.
233                continue;
234            }
235            if widgets.modules.contains_key(&name) {
236                widgets
237                    .problems
238                    .push(format!("{} — {name} is a system widget's name", label));
239                continue;
240            }
241            if name == NOTES {
242                widgets.problems.push(format!(
243                    "{} — {NOTES} is devpage's tag for a slide's notes",
244                    label
245                ));
246                continue;
247            }
248            own.push((name, file));
249        }
250        // A widget's address covers the names it can render, so every name is
251        // known before any address is made.
252        let known: Vec<String> = widgets
253            .modules
254            .keys()
255            .cloned()
256            .chain(own.iter().map(|(name, _)| name.clone()))
257            .collect::<std::collections::BTreeSet<_>>()
258            .into_iter()
259            .collect();
260        for (name, file) in own {
261            let url = cache
262                .snapshot(&document.served, &file)
263                .address(&file, &known);
264            widgets.modules.insert(name.clone(), url);
265            widgets.files.insert(name, file);
266        }
267        widgets.known = known;
268        widgets
269    }
270
271    /// The cache its modules are read and compiled through.
272    pub fn cache(&self) -> &Modules {
273        &self.cache
274    }
275
276    /// Every name a page can use as a widget tag, sorted.
277    pub fn names(&self) -> &[String] {
278        &self.known
279    }
280
281    /// The content the server writes for the widget `name` on the page
282    /// `file`, in place of what its tag holds: the `Requirements` widget's
283    /// list. `None` for every other widget.
284    pub(crate) fn written(&self, file: &Path, name: &str) -> Option<String> {
285        let (base, document) = &self.document;
286        (name == REQUIREMENTS)
287            .then(|| crate::requirements::listing(&self.served, base, document, file))
288    }
289
290    /// A project widget or helper `file` of this set, compiled now as its
291    /// address serves it.
292    pub fn compile(&self, file: &Path) -> Result<String> {
293        self.cache
294            .snapshot(&self.served, file)
295            .compile(file, &self.known)
296    }
297
298    /// What the `<head>` of a page whose rendered content is `content`, in a
299    /// frame that mounts the widgets `chrome`, needs: the import map naming
300    /// React and the [page module](crate::addresses), the widgets the page
301    /// script loads, the document's places and its extensions' addresses
302    /// when it has any, and the page's [load set](Self::load_set), its
303    /// places' widgets included — each module as a `modulepreload` at the
304    /// very address its import asks for, and the design engine's wasm as a
305    /// low-priority fetch — so the browser asks for all of it at once, as
306    /// soon as it reads the head.
307    pub fn head(&self, content: &str, chrome: &[&str]) -> String {
308        let modules = serde_json::to_string(&self.modules).unwrap_or_default();
309        let react = address(Owned::Asset("react.js"));
310        let page = address(Owned::Asset("page.js"));
311        let placed = self.places.named();
312        let mut setup = format!("window.devpageWidgets = {modules};");
313        if !placed.is_empty() {
314            let places: BTreeMap<&str, &[String]> = placed.iter().copied().collect();
315            setup.push_str(&format!(
316                "window.devpagePlaces = {};",
317                serde_json::to_string(&places).unwrap_or_default()
318            ));
319        }
320        if !self.extensions.is_empty() {
321            let extensions: BTreeMap<String, String> = self
322                .extensions
323                .iter()
324                .map(crate::extensions::Binding::address)
325                .collect();
326            setup.push_str(&format!(
327                "window.devpageExtensions = {};",
328                serde_json::to_string(&extensions).unwrap_or_default()
329            ));
330        }
331        // A place's widgets load after the content's and the frame's.
332        let chrome: Vec<&str> = chrome
333            .iter()
334            .copied()
335            .chain(
336                placed
337                    .iter()
338                    .flat_map(|(_, names)| names.iter().map(String::as_str)),
339            )
340            .collect();
341        let (preloads, fetches) = self.load_set(content, &chrome);
342        let mut links = String::new();
343        for module in preloads {
344            links.push_str(&format!("\n<link rel=\"modulepreload\" href=\"{module}\">"));
345        }
346        for fetch in fetches {
347            links.push_str(&format!(
348                "\n<link rel=\"preload\" href=\"{fetch}\" as=\"fetch\" crossorigin fetchpriority=\"low\">"
349            ));
350        }
351        for binding in &self.extensions {
352            for style in binding.style_urls() {
353                links.push_str(&format!(
354                    "\n<link rel=\"stylesheet\" href=\"{}\">",
355                    crate::html::escape(&style)
356                ));
357            }
358        }
359        format!(
360            r#"<script type="importmap">{{"imports":{{"react":"{react}","react/jsx-runtime":"{react}","react-dom/client":"{react}","devpage":"{page}"}}}}</script>
361<script>{setup}</script>{links}"#
362        )
363    }
364
365    /// Everything a page whose rendered content is `content`, in a frame that
366    /// mounts the widgets `chrome` — a site's sidebar, [`SIDEBAR`] — loads
367    /// from devpage beyond its stylesheet and page script: the modules —
368    /// React if it has a widget; each widget it names, then the frame's; the
369    /// widgets each of those renders by name (its `__devpageUses`), and so
370    /// on; every module a widget's imports reach; the design script
371    /// and engine with an
372    /// embedded design — and what is fetched, not imported: the engine's
373    /// wasm. Each is the address [`address`] makes, so it is the one the
374    /// import asks for.
375    pub fn load_set(&self, content: &str, chrome: &[&str]) -> (Vec<String>, Vec<String>) {
376        let mut queue: Vec<String> = content
377            .split("data-widget=\"")
378            .skip(1)
379            .filter_map(|rest| rest.split('"').next())
380            .map(str::to_string)
381            .collect();
382        // The frame's own come after the content's: the server drew them
383        // already, so the reader waits on the content's first.
384        queue.extend(chrome.iter().map(|name| name.to_string()));
385        let mut seen = std::collections::BTreeSet::new();
386        let mut widgets = Vec::new();
387        let mut helpers = Vec::new();
388        // In the order the page names them: the first are wanted first.
389        let mut next = 0;
390        while let Some(name) = queue.get(next).cloned() {
391            next += 1;
392            if !self.modules.contains_key(&name) || !seen.insert(name.clone()) {
393                continue;
394            }
395            widgets.push(self.modules[&name].clone());
396            let compiled = match self.files.get(&name) {
397                Some(file) => {
398                    let snapshot = self.cache.snapshot(&self.served, file);
399                    for (helper, _) in snapshot.closure(file).into_iter().skip(1) {
400                        helpers.push(snapshot.address(&helper, &self.known));
401                    }
402                    snapshot.compile(file, &self.known)
403                }
404                None => {
405                    let file = format!("{name}.tsx");
406                    for helper in system_closure(&file).into_iter().skip(1) {
407                        helpers.push(system_address(helper, self.served.mount()));
408                    }
409                    self.cache
410                        .system(&file)
411                        .unwrap_or_else(|| Err(anyhow!("no {name}")))
412                }
413            };
414            queue.extend(compiled.map(|js| compile::uses(&js)).unwrap_or_default());
415        }
416        let mut modules = Vec::new();
417        if !seen.is_empty() {
418            modules.push(address(Owned::Asset("react.js")));
419        }
420        modules.extend(widgets);
421        for helper in helpers {
422            if !modules.contains(&helper) {
423                modules.push(helper);
424            }
425        }
426        let mut fetches = Vec::new();
427        if content.contains("<canvas class=\"design\"") {
428            // The design script and the modules it imports, the engine's
429            // bindings last.
430            for module in [
431                "design.js",
432                "design-stream.js",
433                "design-canvas.js",
434                "design-tiles.js",
435                "design-engine.js",
436            ] {
437                modules.push(address(Owned::Asset(module)));
438            }
439            fetches.push(address(Owned::Asset("design-engine.wasm")));
440        }
441        (modules, fetches)
442    }
443}
444
445/// Whether `path` is a widget or helper file: a `.ts` or `.tsx` directly in a
446/// widgets folder.
447pub fn is_widget_file(path: &Path, folder: &Path) -> bool {
448    path.parent() == Some(folder)
449        && path
450            .extension()
451            .is_some_and(|ext| ext == "ts" || ext == "tsx")
452}
453
454/// A system module: a system widget's file or one of the [`SHARED`] modules.
455struct SystemModule {
456    /// Its file name, as its address has it: `Tabs.tsx`, `live.ts`.
457    file: String,
458    /// Its source.
459    source: &'static str,
460    /// Each relative specifier it imports and the system module's file the
461    /// specifier names.
462    imports: Vec<(String, String)>,
463    /// Its [version](system_hash).
464    hash: String,
465}
466
467/// Every system module: the system widgets, each as `<name>.tsx`, and the
468/// shared modules.
469static SYSTEM_MODULES: LazyLock<Vec<SystemModule>> = LazyLock::new(|| {
470    let sources: Vec<(String, &'static str)> = SYSTEM
471        .iter()
472        .map(|(name, source)| (format!("{name}.tsx"), *source))
473        .chain(
474            SHARED
475                .iter()
476                .map(|(file, source)| (file.to_string(), *source)),
477        )
478        .collect();
479    let names: Vec<&str> = SYSTEM.iter().map(|(n, _)| *n).collect();
480    let imports: BTreeMap<&str, Vec<(String, String)>> = sources
481        .iter()
482        .map(|(file, source)| {
483            let found = compile::relative_imports(Path::new(file), source)
484                .into_iter()
485                .filter_map(|specifier| {
486                    let stem = specifier.strip_prefix("./")?;
487                    modules::IMPORT_EXTENSIONS
488                        .iter()
489                        .map(|ext| format!("{stem}{ext}"))
490                        .find(|named| sources.iter().any(|(file, _)| file == named))
491                        .map(|named| (specifier, named))
492                })
493                .collect();
494            (file.as_str(), found)
495        })
496        .collect();
497    sources
498        .iter()
499        .map(|(file, source)| {
500            let mut hash = Sha256::new();
501            hash.update(crate::addresses::BUILD);
502            hash.update(names.join("\0"));
503            for reached in closure(file, &imports) {
504                let (_, source) = sources
505                    .iter()
506                    .find(|(file, _)| *file == reached)
507                    .expect("an import names a system module");
508                hash.update([0]);
509                hash.update(reached);
510                hash.update([0]);
511                hash.update(source);
512            }
513            SystemModule {
514                file: file.clone(),
515                source,
516                imports: imports[file.as_str()].clone(),
517                hash: crate::addresses::short(&hash.finalize()),
518            }
519        })
520        .collect()
521});
522
523/// `file` and every system module its relative imports reach: `file` first,
524/// then the rest in name order.
525fn closure<'a>(file: &'a str, imports: &'a BTreeMap<&str, Vec<(String, String)>>) -> Vec<&'a str> {
526    let mut found = std::collections::BTreeSet::new();
527    let mut queue = vec![file];
528    while let Some(next) = queue.pop() {
529        for (_, imported) in imports.get(next).into_iter().flatten() {
530            if imported != file && found.insert(imported.as_str()) {
531                queue.push(imported);
532            }
533        }
534    }
535    std::iter::once(file).chain(found).collect()
536}
537
538/// The system module in `file` — `Tabs.tsx`, `live.ts`.
539fn system_module_named(file: &str) -> Option<&'static SystemModule> {
540    SYSTEM_MODULES.iter().find(|module| module.file == file)
541}
542
543/// The source of the system module in `file`, and each relative specifier
544/// it imports with the address that import asks for: the imported module's
545/// own, beside the importer's. `None` for a file that isn't a system module.
546pub(crate) fn system(file: &str) -> Option<(&'static str, BTreeMap<String, String>)> {
547    let module = system_module_named(file)?;
548    let imports = module
549        .imports
550        .iter()
551        .map(|(specifier, imported)| {
552            let hash = system_hash(imported).unwrap_or_default();
553            (specifier.clone(), format!("./{imported}?v={hash}"))
554        })
555        .collect();
556    Some((module.source, imports))
557}
558
559/// The system module in `file` and every system module its relative imports
560/// reach: `file` first, then the rest in name order. Empty for a file that
561/// isn't a system module.
562pub(crate) fn system_closure(file: &str) -> Vec<&'static str> {
563    let Some(module) = system_module_named(file) else {
564        return Vec::new();
565    };
566    let imports: BTreeMap<&str, Vec<(String, String)>> = SYSTEM_MODULES
567        .iter()
568        .map(|module| (module.file.as_str(), module.imports.clone()))
569        .collect();
570    closure(&module.file, &imports)
571        .into_iter()
572        .filter_map(|file| system_module_named(file).map(|module| module.file.as_str()))
573        .collect()
574}
575
576/// A system module's version: its source, the sources of every system
577/// module its relative imports reach, the names a system widget can render
578/// and the build — everything its compiled bytes are made from. `None` for
579/// a file that isn't a system module.
580pub fn system_hash(file: &str) -> Option<&'static str> {
581    system_module_named(file).map(|module| module.hash.as_str())
582}
583
584/// The address the system module in `file` is served at for the document
585/// served under `mount`, carrying its [version](system_hash).
586pub fn system_address(file: &str, mount: &str) -> String {
587    address(Owned::SystemModule {
588        file,
589        mount,
590        hash: system_hash(file).unwrap_or_default(),
591    })
592}
593
594#[cfg(test)]
595mod tests {
596    use super::*;
597    use codespec_rust_macro::spec;
598
599    #[test]
600    fn a_system_widget_address_carries_its_own_version() {
601        assert_eq!(
602            system_address("Callout.tsx", ""),
603            format!(
604                "/__devpage/system-widgets/Callout.tsx?v={}",
605                system_hash("Callout.tsx").unwrap()
606            )
607        );
608        assert_ne!(
609            system_hash("Callout.tsx"),
610            system_hash("Tabs.tsx"),
611            "each system widget has its own version"
612        );
613        assert_eq!(system_hash("Nope"), None);
614    }
615
616    #[test]
617    fn every_system_module_compiles_and_imports_system_modules_at_their_addresses() {
618        let modules = Modules::default();
619        let files = SYSTEM
620            .iter()
621            .map(|(name, _)| format!("{name}.tsx"))
622            .chain(SHARED.iter().map(|(file, _)| file.to_string()));
623        for file in files {
624            let (source, imports) = system(&file).unwrap();
625            assert_eq!(
626                compile::relative_imports(Path::new(&file), source)
627                    .into_iter()
628                    .collect::<std::collections::BTreeSet<_>>(),
629                imports.keys().cloned().collect(),
630                "{file}: every relative import names a system module"
631            );
632            let js = modules.system(&file).unwrap().unwrap();
633            for address in imports.values() {
634                assert!(js.contains(&format!("{address:?}")), "{file}: {js}");
635            }
636        }
637        // An import asks for the very address the imported module has: the
638        // importer's own folder, the module's file and its version.
639        let (_, imports) = system("DevpageLiveOrb.tsx").unwrap();
640        assert_eq!(
641            imports["./live"],
642            format!("./live.ts?v={}", system_hash("live.ts").unwrap())
643        );
644        assert_eq!(
645            system_address("live.ts", "/d"),
646            format!(
647                "/d/__devpage/system-widgets/live.ts?v={}",
648                system_hash("live.ts").unwrap()
649            )
650        );
651        assert_eq!(system("live"), None, "a module is named by its file");
652    }
653
654    #[test]
655    fn a_system_widget_loads_with_every_module_its_imports_reach() {
656        assert_eq!(
657            system_closure("DevpageLiveCanvas.tsx"),
658            [
659                "DevpageLiveCanvas.tsx",
660                "DevpageLiveTasks.tsx",
661                "live-agent-orb.tsx",
662                "live.ts"
663            ]
664        );
665        assert_eq!(system_closure("Callout.tsx"), ["Callout.tsx"]);
666        let widgets = Widgets {
667            modules: BTreeMap::from([(
668                LIVE_CANVAS.to_string(),
669                system_address("DevpageLiveCanvas.tsx", ""),
670            )]),
671            ..Widgets::default()
672        };
673        let (modules, _) = widgets.load_set("", &[LIVE_CANVAS]);
674        assert_eq!(
675            modules,
676            [
677                address(Owned::Asset("react.js")),
678                system_address("DevpageLiveCanvas.tsx", ""),
679                system_address("DevpageLiveTasks.tsx", ""),
680                system_address("live-agent-orb.tsx", ""),
681                system_address("live.ts", ""),
682            ]
683        );
684    }
685
686    #[test]
687    fn lowercase_files_are_helpers_and_a_system_name_is_a_problem() {
688        let dir = std::env::temp_dir().join(format!("devpage-wset-{}", std::process::id()));
689        let _ = std::fs::remove_dir_all(&dir);
690        std::fs::create_dir_all(dir.join("widgets")).unwrap();
691        std::fs::write(
692            dir.join("devpage.yml"),
693            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
694        )
695        .unwrap();
696        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
697        std::fs::write(dir.join("widgets/Card.tsx"), "export default () => null;").unwrap();
698        std::fs::write(dir.join("widgets/cards.tsx"), "export const x = 1;").unwrap();
699        std::fs::write(
700            dir.join("widgets/Callout.tsx"),
701            "export default () => null;",
702        )
703        .unwrap();
704        let dir = dir.canonicalize().unwrap();
705        let document = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
706        let widgets = Widgets::of(&document, &Modules::default());
707        assert!(widgets.modules.contains_key("Card"));
708        assert!(!widgets.modules.contains_key("cards"));
709        assert!(widgets.modules["Callout"].starts_with("/__devpage/system-widgets/"));
710        assert_eq!(
711            widgets.problems,
712            vec!["widgets/Callout.tsx — Callout is a system widget's name".to_string()]
713        );
714        let known: Vec<String> = widgets.modules.keys().cloned().collect();
715        assert_eq!(
716            widgets.modules["Card"],
717            Modules::default()
718                .snapshot(
719                    &ServedFolder::new(&dir).unwrap(),
720                    &dir.join("widgets/Card.tsx")
721                )
722                .address(&dir.join("widgets/Card.tsx"), &known)
723        );
724    }
725
726    #[test]
727    fn devpage_sidebar_is_reserved_and_a_project_sidebar_is_not() {
728        let dir = std::env::temp_dir().join(format!("devpage-wsidebar-{}", std::process::id()));
729        let _ = std::fs::remove_dir_all(&dir);
730        std::fs::create_dir_all(dir.join("widgets")).unwrap();
731        std::fs::write(
732            dir.join("devpage.yml"),
733            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
734        )
735        .unwrap();
736        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
737        for name in ["DevpageSidebar", "Sidebar"] {
738            std::fs::write(
739                dir.join(format!("widgets/{name}.tsx")),
740                "export default () => null;",
741            )
742            .unwrap();
743        }
744        let dir = dir.canonicalize().unwrap();
745        let widgets = Widgets::of(
746            &Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap(),
747            &Modules::default(),
748        );
749        assert_eq!(
750            widgets.problems,
751            vec![
752                "widgets/DevpageSidebar.tsx — DevpageSidebar is a system widget's name".to_string()
753            ]
754        );
755        assert!(widgets.modules["DevpageSidebar"].starts_with("/__devpage/system-widgets/"));
756        assert!(widgets.modules["Sidebar"].starts_with("/__devpage/widgets/"));
757    }
758
759    #[test]
760    #[spec("widget-names-are-unique")]
761    fn a_project_widget_named_notes_clashes() {
762        let dir = std::env::temp_dir().join(format!("devpage-wnotes-{}", std::process::id()));
763        let _ = std::fs::remove_dir_all(&dir);
764        std::fs::create_dir_all(dir.join("widgets")).unwrap();
765        std::fs::write(
766            dir.join("devpage.yml"),
767            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
768        )
769        .unwrap();
770        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
771        std::fs::write(dir.join("widgets/Notes.tsx"), "export default () => null;").unwrap();
772        let dir = dir.canonicalize().unwrap();
773        let widgets = Widgets::of(
774            &Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap(),
775            &Modules::default(),
776        );
777        assert!(!widgets.modules.contains_key("Notes"));
778        assert_eq!(
779            widgets.problems,
780            vec!["widgets/Notes.tsx — Notes is devpage's tag for a slide's notes".to_string()]
781        );
782    }
783    #[test]
784    fn a_place_names_widgets_the_head_lists_and_loads() {
785        let dir = std::env::temp_dir().join(format!("devpage-wplaces-{}", std::process::id()));
786        let _ = std::fs::remove_dir_all(&dir);
787        std::fs::create_dir_all(dir.join("widgets")).unwrap();
788        std::fs::write(
789            dir.join("devpage.yml"),
790            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\nplaces:\n  navbar: [Dot]\n  panel: [Dot, Gone]\n",
791        )
792        .unwrap();
793        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
794        std::fs::write(dir.join("widgets/Dot.tsx"), "export default () => null;").unwrap();
795        let dir = dir.canonicalize().unwrap();
796        let document = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
797        let widgets = Widgets::of(&document, &Modules::default());
798        assert_eq!(
799            widgets.problems,
800            vec!["devpage.yml — places: panel: no widget is named Gone".to_string()]
801        );
802        let head = widgets.head("<p>no widget</p>", &[]);
803        assert!(
804            head.contains(r#"window.devpagePlaces = {"navbar":["Dot"],"panel":["Dot","Gone"]};"#),
805            "{head}"
806        );
807        assert!(
808            head.contains(&format!(
809                "<link rel=\"modulepreload\" href=\"{}\">",
810                widgets.modules["Dot"]
811            )),
812            "a place's widget is in the load set: {head}"
813        );
814        assert!(
815            head.contains(&format!(
816                r#""devpage":"{}""#,
817                address(Owned::Asset("page.js"))
818            )),
819            "{head}"
820        );
821        // A document with no places says nothing of them.
822        std::fs::write(
823            dir.join("devpage.yml"),
824            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\n",
825        )
826        .unwrap();
827        let document = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
828        let head = Widgets::of(&document, &Modules::default()).head("", &[]);
829        assert!(!head.contains("devpagePlaces"), "{head}");
830        // A place devpage doesn't have is refused.
831        std::fs::write(
832            dir.join("devpage.yml"),
833            "kind: site\ntitle: T\nroot: README.md\nplaces:\n  footer: [Dot]\n",
834        )
835        .unwrap();
836        assert!(Document::load(&dir, &ServedFolder::new(&dir).unwrap()).is_err());
837    }
838}