plexus-ui-engine 0.2.3

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! UI-6: **the wasm entry** — what `index.html` calls once `engine.js` has
//! loaded `engine.wasm`: `boot(version)`, the hash the page was served for.
//!
//! It reads the service and the socket's port the page names (FRAME-6:
//! `<meta name="plexus-service">` and `<meta name="plexus-ws-port">`, as a
//! binary stamps them; a page naming only `menger-ws-port` — every bundle
//! built before — speaks `menger.call` on that port, as it did), opens the
//! page's one WebSocket (signed in by the session's cookie; a
//! reconnect loop of 1 s), reads `/app/<version>/manifest.json`, fetches
//! the version's components, asks `ui.slots.list`, opens `ui.watch`
//! (UI-9: `live { version }` swaps, `slot_changed` remounts a section),
//! mounts the route's component into the body, follows the hash, and
//! draws the section menu on a right-click. Behind the `dom` feature, on
//! wasm32.
//!
//! FRAME-16: `host.js`'s `start(version)` boots it in parallel — the
//! socket made, `manifest.json` and `components.json` asked, all before the
//! wasm is instantiated — and hands them over with [`boot_started`]: the
//! socket adopted (plexus-client's `WsTransport::adopt`), the manifest and
//! every rhx component's tree and handlers read from what was fetched (a
//! component missing from `components.json`, or a bundle without one, from
//! its own files). `boot(version)` stays for an entrypoint that calls it;
//! it opens its socket and reads the manifest at once, side by side.
//!
//! FRAME-12: a component whose profile is not `rhx/1` is imported from its
//! version's `components/<name>.js` (through `host.js`) and handed in as a
//! module — the live version's at boot, a changed one before a swap, and
//! another version's when a section asks for it (its manifest read first,
//! for the profile); a route to the component already drawn updates its
//! props.
//!
//! STUDIO-3: the routes are the manifest's with the service's rows merged
//! over them ([`Router::merged`]) — the rows the page was served with
//! (`<meta name="plexus-routes">`, so the first draw and FRAME-17's early
//! send read them with no round trip), then `ui.routes.list` once the
//! watch is open (and after a reconnect or a `lagged`), and every
//! `route_changed` on `ui.watch`, each redrawing the route when what it
//! names changed — never a reload.

use crate::live::Clock;
use crate::router::Router;
use crate::signals::Runtime;
use crate::host_js;
use crate::swap::{App, Assignment, ComponentEntry, Files, Manifest, MountId};
use crate::transport::ws::{sleep, WsWire};
use crate::transport::{Wire, WireItem};
use crate::tree::dom::Dom;
use crate::tree::Renderer;
use serde_json::{json, Value};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;

/// The page's clock: milliseconds since the epoch.
#[derive(Clone, Copy, Debug)]
pub struct PageClock;

impl Clock for PageClock {
    fn now_ms(&self) -> u64 {
        js_sys::Date::now() as u64
    }
    fn schedule(&self, after_ms: u64, f: Box<dyn FnOnce()>) {
        // Freed once it has run.
        let c = Closure::once_into_js(move || f());
        let _ = window().set_timeout_with_callback_and_timeout_and_arguments_0(c.unchecked_ref(), after_ms.min(i32::MAX as u64) as i32);
    }
    /// STUDIO-16: the next animation frame — or, when the page draws none
    /// (hidden: the browser holds its frames), [`FRAME_LATE_MS`] from now,
    /// whichever comes first; `f` runs once. Every `f` asked before that
    /// frame runs in it, in order; the two callbacks are made once a page
    /// (no closure crosses to JavaScript per frame).
    fn frame(&self, f: Box<dyn FnOnce()>) {
        FRAME_DUE.with(|due| due.borrow_mut().push(f));
        if FRAME_ASKED.with(|a| a.replace(true)) {
            return;
        }
        let w = window();
        FRAME_CALLBACKS.with(|(drawn, late)| {
            let _ = w.request_animation_frame(drawn.as_ref().unchecked_ref());
            let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(late.as_ref().unchecked_ref(), FRAME_LATE_MS);
        });
    }
}

/// STUDIO-16: the frame — what was due for it, in order (whichever of the
/// page's frame and the late timer comes first; the other finds nothing,
/// or runs a frame asked since a little early).
fn run_frame() {
    FRAME_ASKED.with(|a| a.set(false));
    let due = FRAME_DUE.with(|due| std::mem::take(&mut *due.borrow_mut()));
    for f in due {
        f();
    }
}

thread_local! {
    /// STUDIO-16: what waits for the next frame, and whether it is asked.
    static FRAME_DUE: RefCell<Vec<Box<dyn FnOnce()>>> = const { RefCell::new(Vec::new()) };
    static FRAME_ASKED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// The frame's callback and the late timer's, made once a page.
    static FRAME_CALLBACKS: (Closure<dyn FnMut()>, Closure<dyn FnMut()>) = (Closure::new(run_frame), Closure::new(run_frame));
}

/// STUDIO-16: how long a change waits for a frame the page does not draw.
const FRAME_LATE_MS: i32 = 100;

type PageApp = App<Dom, WsWire, PageClock>;

/// FRAME-50: how long the boot's sections stay held, at most, once the
/// mount settled, for the snapshots it asked.
const HOLD_MS: u64 = 100;

/// FRAME-50: said on the bus once the boot's mount and its hold are over.
const BOOTED: &str = "plexus.booted";
/// STUDIO-32: the page's session ended (sticky): `{ sent }`.
const SIGNED_OUT: &str = "plexus.signed_out";

/// Everything the page holds.
struct Page {
    app: Rc<PageApp>,
    wire: WsWire,
    dom: Dom,
    root: web_sys::Node,
    current: RefCell<Option<MountId>>,
    manifests: RefCell<HashMap<String, Manifest>>,
    fetching: RefCell<BTreeSet<(String, String)>>,
    /// FRAME-17: the hash whose component is being fetched.
    waiting: RefCell<Option<String>>,
    /// STUDIO-3: the service's route rows (`ui.routes`), pattern → component
    /// — none on a page of its own bundle (`own`: the studio's routes are
    /// its manifest's).
    route_rows: RefCell<BTreeMap<String, String>>,
    /// STUDIO-2: the named bundle the page is drawn from and stays on
    /// (`<meta name="plexus-ui-bundle">`, the studio's): the live pointer is
    /// another bundle's, so its moves swap nothing here.
    own: Option<String>,
    /// STUDIO-6: on a page of its own bundle, the app's live version as
    /// `ui.watch` last said it — what a section's change naming no version
    /// means there (the app's components, never the studio's own).
    app_live: RefCell<Option<String>>,
}

fn window() -> web_sys::Window {
    web_sys::window().expect("a window")
}

fn say(line: &str) {
    web_sys::console::log_1(&line.into());
}

/// The `content` of `<meta name="NAME">`, when the page has one.
fn meta(document: &web_sys::Document, name: &str) -> Option<String> {
    document.query_selector(&format!(r#"meta[name="{name}"]"#)).ok().flatten().and_then(|m| m.get_attribute("content"))
}

/// The service the page speaks to: its `plexus-service` (a name a stamp
/// filled — letters, digits, `.`, `_` and `-`), else
/// [`crate::transport::ws::FALLBACK_SERVICE`].
fn service_name(document: &web_sys::Document) -> String {
    meta(document, "plexus-service")
        .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')))
        .unwrap_or_else(|| crate::transport::ws::FALLBACK_SERVICE.to_string())
}

/// The socket's URL: over https the origin's `/ws`, else the stamped port
/// (`plexus-ws-port`, else `menger-ws-port`) on the page's host.
fn socket_url(document: &web_sys::Document) -> String {
    let loc = window().location();
    let host = loc.hostname().unwrap_or_else(|_| "127.0.0.1".into());
    if loc.protocol().ok().as_deref() == Some("https:") {
        return format!("wss://{}/ws", loc.host().unwrap_or(host));
    }
    let digits = |p: &String| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
    let port = meta(document, "plexus-ws-port")
        .filter(digits)
        .or_else(|| meta(document, "menger-ws-port").filter(digits))
        .unwrap_or_else(|| "4455".into());
    format!("ws://{host}:{port}")
}

/// `url`'s body as text — UI-19: asked at its content URL when the page
/// has one for it.
async fn fetch_text(url: &str) -> Result<String, String> {
    // UI-19: the page's own version's files by their content.
    let url = &host_js::file_url(url);
    let resp = wasm_bindgen_futures::JsFuture::from(window().fetch_with_str(url)).await.map_err(|e| format!("{url}: {e:?}"))?;
    let resp: web_sys::Response = resp.dyn_into().map_err(|_| format!("{url}: no response"))?;
    if !resp.ok() {
        return Err(format!("{url}: {}", resp.status()));
    }
    let text = wasm_bindgen_futures::JsFuture::from(resp.text().map_err(|e| format!("{e:?}"))?).await.map_err(|e| format!("{e:?}"))?;
    text.as_string().ok_or_else(|| format!("{url}: no text"))
}

/// STUDIO-3: the route rows the page was served with — `<meta
/// name="plexus-routes" content="{ pattern: component }">` — or none.
fn served_rows(document: &web_sys::Document) -> BTreeMap<String, String> {
    meta(document, "plexus-routes").and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}

/// STUDIO-3: `manifest`'s routes with `rows` merged over them.
fn merged(manifest: &Manifest, rows: &BTreeMap<String, String>) -> Router {
    Router::merged(&manifest.routes, rows, |c| manifest.components.contains_key(c))
}

impl Page {
    /// STUDIO-2: whether the page is drawn from a named bundle of its own
    /// (`<meta name="plexus-ui-bundle">`, the studio's) and not the app's:
    /// every event of the app's live pointer — `live`, `route_changed`, the
    /// route rows — belongs to the app, and is none of this page's.
    fn is_own(&self) -> bool {
        self.own.is_some()
    }

    /// STUDIO-3: the live manifest's routes with the rows merged in.
    fn router(&self) -> Router {
        merged(&self.app.manifest(), &self.route_rows.borrow())
    }

    /// STUDIO-3: `ui.routes.list` — the rows as they stand; the route
    /// redrawn when they changed.
    async fn routes_listed(self: &Rc<Self>) {
        if self.is_own() {
            return;
        }
        match self.wire.ask("ui.routes.list", json!({})).await {
            Ok(items) => {
                let rows: BTreeMap<String, String> = items
                    .iter()
                    .filter(|i| i["type"] == "route")
                    .filter_map(|i| Some((i["pattern"].as_str()?.to_string(), i["component"].as_str()?.to_string())))
                    .collect();
                if *self.route_rows.borrow() != rows {
                    *self.route_rows.borrow_mut() = rows;
                    self.route();
                }
            }
            Err(e) => say(&format!("ui.routes.list: {e}")),
        }
    }

    /// Version `version`'s manifest (kept: a version's files never change).
    async fn manifest(&self, version: &str) -> Result<Manifest, String> {
        if let Some(m) = self.manifests.borrow().get(version) {
            return Ok(m.clone());
        }
        let m = Manifest::parse(&fetch_text(&format!("/app/{version}/manifest.json")).await?)?;
        self.manifests.borrow_mut().insert(version.into(), m.clone());
        Ok(m)
    }

    /// Version `version`'s components `names`, fetched.
    async fn components(&self, version: &str, names: &[String]) -> Files {
        // UI-8: every file asked at once, not one after another (eleven
        // components were 22 round trips before the first mount).
        let mut files = Files::default();
        let fetched = futures::future::join_all(names.iter().map(|name| async move {
            let (t, h) = (format!("/app/{version}/components/{name}.json"), format!("/app/{version}/components/{name}.rhai"));
            let (tree, rhai) = futures::future::join(fetch_text(&t), fetch_text(&h)).await;
            // FRAME-30: a tree that names a mark has a sheet beside it.
            let marked = tree.as_ref().ok().and_then(|t| serde_json::from_str::<Value>(t).ok()).is_some_and(|t| t.get("css").is_some());
            let css = if marked { fetch_text(&format!("/app/{version}/components/{name}.css")).await.ok() } else { None };
            (tree, rhai, css)
        }))
        .await;
        for (name, (tree, rhai, css)) in names.iter().zip(fetched) {
            match (tree, rhai) {
                (Ok(t), Ok(h)) => {
                    files.put_version(version, name, &t, &h);
                    if let Some(css) = css {
                        files.put_sheet(version, name, &css);
                    }
                }
                (Err(e), _) | (_, Err(e)) => say(&format!("{name} of {version}: {e}")),
            }
        }
        files
    }

    /// FRAME-16: version `version`'s rhx components `names` from
    /// `components.json`'s text (`one`), those it lacks from their files.
    async fn components_from(&self, version: &str, names: &[String], one: Option<&str>) -> Files {
        let doc: Option<serde_json::Map<String, Value>> = one.and_then(|t| serde_json::from_str::<Value>(t).ok()).and_then(|v| v.as_object().cloned());
        let mut files = Files::default();
        let mut rest = Vec::new();
        for name in names {
            let entry = doc.as_ref().and_then(|d| d.get(name));
            match (entry.and_then(|e| e["tree"].as_str()), entry.and_then(|e| e["handlers"].as_str())) {
                (Some(t), Some(h)) => {
                    files.put_version(version, name, t, h);
                    // FRAME-30: its sheet's text, beside its tree.
                    if let Some(css) = entry.and_then(|e| e["css"].as_str()) {
                        files.put_sheet(version, name, css);
                    }
                }
                _ => rest.push(name.clone()),
            }
        }
        if !rest.is_empty() {
            files.extend(&self.components(version, &rest).await);
        }
        files
    }

    /// FRAME-12: version `version`'s modules `names` (their entries in
    /// `manifest`), imported and handed over.
    async fn modules(&self, version: &str, manifest: &Manifest, names: &[String]) {
        let imported = futures::future::join_all(names.iter().map(|name| host_js::import(version, name))).await;
        for (name, m) in names.iter().zip(imported) {
            match (m, manifest.components.get(name)) {
                (Ok(m), Some(entry)) => self.app.provide_module(version, name, entry.clone(), Rc::new(m)),
                (Err(e), _) => say(&format!("{name} of {version}: {e}")),
                (Ok(_), None) => say(&format!("{name} of {version}: not in its manifest")),
            }
        }
    }

    /// Version `version`'s components `names`: the rhx ones' files fetched,
    /// the modules imported, all handed over.
    async fn fetch(&self, version: &str, manifest: &Manifest, names: &[String]) {
        self.fetch_from(version, manifest, names, None).await
    }

    /// [`Self::fetch`], the rhx ones from `components.json`'s text when given.
    async fn fetch_from(&self, version: &str, manifest: &Manifest, names: &[String], one: Option<&str>) {
        let (rhx, modules): (Vec<String>, Vec<String>) = names.iter().cloned().partition(|n| manifest.components.get(n).is_none_or(ComponentEntry::is_rhx));
        let (files, ()) = futures::future::join(self.components_from(version, &rhx, one), self.modules(version, manifest, &modules)).await;
        self.app.provide(&files);
    }

    /// Fetches whatever the engine asks for, and hands it over — another
    /// version's manifest read first, for each component's profile.
    fn pump(self: &Rc<Self>) {
        for (v, n) in self.app.needs() {
            if !self.fetching.borrow_mut().insert((v.clone(), n.clone())) {
                continue;
            }
            let me = self.clone();
            wasm_bindgen_futures::spawn_local(async move {
                match me.manifest(&v).await {
                    Ok(m) => me.fetch(&v, &m, std::slice::from_ref(&n)).await,
                    Err(e) => say(&format!("{n} of {v}: {e}")),
                }
                me.fetching.borrow_mut().remove(&(v, n));
                me.pump();
                // FRAME-17: the route that waited on it, drawn now — once.
                let waited = me.waiting.borrow().clone();
                let now = window().location().hash().unwrap_or_default();
                let component = waited.filter(|h| *h == now).and_then(|h| me.router().resolve(&h)).map(|r| r.component);
                if component.is_some_and(|c| me.app.here(&c)) {
                    me.waiting.borrow_mut().take();
                    me.route();
                }
            });
        }
    }

    /// The route the hash names, mounted in place of the last — or, when
    /// it names the component already drawn, that one's props updated.
    fn route(self: &Rc<Self>) {
        let hash = window().location().hash().unwrap_or_default();
        let resolved = self.router().resolve(&hash);
        let current = *self.current.borrow();
        if let (Some(id), Some(route)) = (current, &resolved) {
            if self.app.name_of(id).as_deref() == Some(route.component.as_str()) {
                if let Err(e) = self.app.update(id, route.props.clone()) {
                    say(&format!("{}: {e}", route.component));
                }
                self.pump();
                return;
            }
        }
        // FRAME-17: a component not here yet (a module the boot did not
        // import) is asked for, and the route drawn once it is — what is
        // drawn stays until then (FRAME-12: the new before the old goes).
        if let Some(route) = &resolved {
            if !self.app.ensure(&route.component) {
                *self.waiting.borrow_mut() = Some(hash);
                self.pump();
                return;
            }
        }
        if let Some(old) = self.current.borrow_mut().take() {
            let el = self.app.element_of(old);
            self.app.unmount(old);
            self.dom.remove(&self.root, &el);
        }
        let Some(route) = resolved else {
            say(&format!("no route for {hash}"));
            return;
        };
        match self.app.mount(&self.root, &route.component, route.props) {
            Ok(id) => *self.current.borrow_mut() = Some(id),
            Err(e) => say(&format!("{}: {e}", route.component)),
        }
        self.pump();
    }

    /// `ui.slots.list`: the assignments.
    async fn assignments(self: &Rc<Self>) {
        match self.wire.ask("ui.slots.list", json!({})).await {
            Ok(items) => {
                let list = items
                    .iter()
                    .filter(|i| i["type"] == "assignment")
                    .filter_map(|i| {
                        Some(Assignment {
                            layout: i["layout"].as_str()?.into(),
                            slot: i["slot"].as_str()?.into(),
                            component: i["component"].as_str()?.into(),
                            version: i["version"].as_str()?.into(),
                        })
                    })
                    .collect();
                self.app.set_assignments(list);
                self.pump();
            }
            Err(e) => say(&format!("ui.slots.list: {e}")),
        }
    }

    /// `ui.watch`, opened (again after a reconnect).
    fn watch(self: &Rc<Self>) {
        let me = Rc::downgrade(self);
        self.wire.open("ui.watch", json!({}), Box::new(move |item| {
            let Some(page) = me.upgrade() else { return };
            match item {
                WireItem::Data(ev) => page.heard(ev),
                WireItem::Refused(m) => say(&format!("ui.watch: {m}")),
                _ => {}
            }
        }));
    }

    fn heard(self: &Rc<Self>, ev: Value) {
        match ev["type"].as_str() {
            // STUDIO-2: the app's pointer, none of a page of its own bundle's.
            Some("live") if self.is_own() => {
                *self.app_live.borrow_mut() = ev["version"].as_str().map(str::to_string);
            }
            Some("route_changed") if self.is_own() => {}
            Some("live") => {
                let Some(version) = ev["version"].as_str().map(str::to_string) else { return };
                if version == self.app.version() {
                    return;
                }
                let me = self.clone();
                wasm_bindgen_futures::spawn_local(async move { me.swap_to(&version).await });
            }
            Some("slot_changed") => {
                let (layout, slot) = (ev["layout"].as_str().unwrap_or_default().to_string(), ev["slot"].as_str().unwrap_or_default().to_string());
                match (ev["component"].as_str(), ev["version"].as_str()) {
                    (Some(c), v) => {
                        // A section's change naming no version is the app's live one: on a
                        // page of its own bundle, the version ui.watch said, not the page's.
                        let fallback = || if self.is_own() { self.app_live.borrow().clone().unwrap_or_else(|| self.app.version()) } else { self.app.version() };
                        self.app.slot_changed(Assignment { layout, slot, component: c.into(), version: v.map(str::to_string).unwrap_or_else(fallback) })
                    }
                    (None, _) => self.app.slot_reset(&layout, &slot),
                }
                self.pump();
            }
            Some("route_changed") => {
                let Some(pattern) = ev["pattern"].as_str().map(str::to_string) else { return };
                let before = self.router().resolve(&window().location().hash().unwrap_or_default());
                match ev["component"].as_str() {
                    Some(c) => self.route_rows.borrow_mut().insert(pattern, c.to_string()),
                    None => self.route_rows.borrow_mut().remove(&pattern),
                };
                if self.router().resolve(&window().location().hash().unwrap_or_default()) != before {
                    self.route();
                }
            }
            Some("lagged") => {
                let me = self.clone();
                wasm_bindgen_futures::spawn_local(async move {
                    me.assignments().await;
                    me.routes_listed().await;
                });
            }
            _ => {}
        }
    }

    /// A push: the new manifest, the components whose hashes changed
    /// fetched, then the swap.
    async fn swap_to(self: &Rc<Self>, version: &str) {
        let m = match self.manifest(version).await {
            Ok(m) => m,
            Err(e) => return say(&format!("the version {version}: {e}")),
        };
        let old = self.app.manifest();
        let changed: Vec<String> = m.components.iter().filter(|(n, e)| old.components.get(*n) != Some(*e)).map(|(n, _)| n.clone()).collect();
        // The changed ones now; the rest when something mounts them (pump).
        self.fetch(version, &m, &changed).await;
        let report = self.app.swap(version, m);
        say(&format!("ui: {version} live — {} remounted, {} kept on their last good version", report.remounted.len(), report.failed.len()));
        self.pump();
    }
}

thread_local! {
    static PAGE: RefCell<Option<Rc<Page>>> = const { RefCell::new(None) };
}

/// Boots the engine on the page for the version `version` (its hash, as
/// `index.html` was served for it).
#[wasm_bindgen]
pub fn boot(version: String) {
    wasm_bindgen_futures::spawn_local(async move {
        if let Err(e) = run(version, None).await {
            web_sys::console::error_1(&format!("ui: {e}").into());
        }
    });
}

/// FRAME-16: what host.js's `start` began before the wasm was instantiated.
struct Started {
    socket: web_sys::WebSocket,
    /// Promises of `manifest.json`'s and `components.json`'s text (`null`
    /// when it could not be had).
    manifest: js_sys::Promise,
    components: js_sys::Promise,
}

/// FRAME-16: boots the engine for `version` on what host.js's
/// `start(version)` began — its `socket`, adopted, and the promises of the
/// version's `manifest.json` and `components.json` text.
#[wasm_bindgen]
pub fn boot_started(version: String, socket: web_sys::WebSocket, manifest: js_sys::Promise, components: js_sys::Promise) {
    wasm_bindgen_futures::spawn_local(async move {
        if let Err(e) = run(version, Some(Started { socket, manifest, components })).await {
            web_sys::console::error_1(&format!("ui: {e}").into());
        }
    });
}

/// A promise of text: its string, or `None` (null, a failure).
async fn text_of(p: js_sys::Promise) -> Option<String> {
    wasm_bindgen_futures::JsFuture::from(p).await.ok().and_then(|v| v.as_string())
}

async fn run(version: String, started: Option<Started>) -> Result<(), String> {
    let document = window().document().ok_or("no document")?;
    let root: web_sys::Node = document.body().ok_or("no body")?.into();
    let wire = WsWire::new(&socket_url(&document), &service_name(&document));
    // The socket, the manifest and the components side by side.
    let (socket, manifest_text, components_text) = match started {
        Some(s) => (Some(s.socket), Some(s.manifest), Some(s.components)),
        None => (None, None, None),
    };
    let opened = async {
        match socket {
            Some(s) => wire.run_adopting(s).await,
            None => wire.run().await,
        }
    };
    let read = async {
        let given = match manifest_text {
            Some(p) => text_of(p).await,
            None => None,
        };
        let text = match given {
            Some(t) => Ok(t),
            None => fetch_text(&format!("/app/{version}/manifest.json")).await,
        };
        let one = match components_text {
            Some(p) => text_of(p).await,
            None => None,
        };
        (text, one)
    };
    let ((), (manifest_read, one)) = futures::future::join(opened, read).await;
    let dom = Dom::new(document.clone());
    let app = App::new(&Runtime::new(), dom.clone(), wire.clone(), PageClock);
    let page = Rc::new(Page {
        app: app.clone(),
        wire: wire.clone(),
        dom,
        root,
        current: RefCell::new(None),
        manifests: RefCell::new(HashMap::new()),
        fetching: RefCell::new(BTreeSet::new()),
        waiting: RefCell::new(None),
        own: meta(&document, "plexus-ui-bundle").filter(|n| !n.is_empty()),
        app_live: RefCell::new(None),
        // STUDIO-3: the rows are the tenant's routes, never the studio's own.
        route_rows: RefCell::new(match meta(&document, "plexus-ui-bundle").filter(|n| !n.is_empty()) {
            Some(_) => BTreeMap::new(),
            None => served_rows(&document),
        }),
    });
    PAGE.with(|p| *p.borrow_mut() = Some(page.clone()));
    // STUDIO-32: a session that ended, said on the bus, kept — `sent` the
    // page on its way to the sign-in it names, else back from it still
    // signed out (a component may say so; the console has).
    let weak = Rc::downgrade(&page.app);
    wire.on_signed_out(Rc::new(move |how| {
        if let Some(app) = weak.upgrade() {
            app.bus().say_sticky(SIGNED_OUT, json!({ "sent": how == host_js::SignedOut::Sent }));
        }
    }));


    let manifest = Manifest::parse(&manifest_read?)?;
    page.manifests.borrow_mut().insert(version.clone(), manifest.clone());
    app.load(&version, manifest.clone());
    // FRAME-17: every rhx component's text is in components.json (one
    // request, already made); a module is imported only when the route
    // mounts it — the route's component, its sections' and theirs — and
    // the rest when a section is swapped or the route changes.
    let rhx: Vec<String> = manifest.components.iter().filter(|(_, e)| e.is_rhx()).map(|(n, _)| n.clone()).collect();
    // STUDIO-3: the rows the page was served with, merged.
    let routed = merged(&manifest, &page.route_rows.borrow()).resolve(&window().location().hash().unwrap_or_default());
    if one.is_some() {
        page.fetch_from(&version, &manifest, &rhx, one.as_deref()).await;
    }
    let names: Vec<String> = match &routed {
        Some(r) => app.reachable(&r.component),
        None => Vec::new(),
    };
    let rest: Vec<String> = names.into_iter().filter(|n| one.is_none() || !rhx.contains(n)).collect();
    // FRAME-50: Rhai's engine (its first making, the packages registered,
    // 6–11 ms, was the longest piece of the mount's first task) is made
    // while the route's modules are on the wire — only when the route asks
    // nothing before its mount: a warm reload's imports resolve at once, and
    // a making there would hold back the early sends. Else the mount makes
    // it, as before (measured on a warm reload of the rhx board: a turn of
    // its own after the early sends cost 9 ms on the first row).
    let on_the_wire = rest.iter().any(|n| manifest.components.get(n).is_some_and(|e| !e.is_rhx()));
    let nothing_early = one.is_some() && routed.as_ref().is_none_or(|r| app.boot_specs(&r.component, r.props.clone()).is_empty());
    let overlap = on_the_wire && nothing_early;
    let warm = async {
        if overlap {
            crate::tree::expr::engine();
        }
    };
    futures::future::join(page.fetch_from(&version, &manifest, &rest, one.as_deref()), warm).await;
    if one.is_none() {
        // A bundle without components.json: the route's trees told what it
        // reaches only once they were here.
        if let Some(r) = &routed {
            let more: Vec<String> = app.reachable(&r.component).into_iter().filter(|n| !rest.contains(n)).collect();
            page.fetch_from(&version, &manifest, &more, None).await;
        }
    }
    crate::marks::once("components-parsed");
    // UI-19: the page's files kept across versions by the service worker.
    host_js::keep_files(&version);
    app.set_navigate(Rc::new(|route: &str| {
        let _ = window().location().set_hash(route);
    }));
    // FRAME-29: a bound mark a module's own state drew may name a component
    // not here yet — fetched as any section's.
    let p = Rc::downgrade(&page);
    app.set_on_need(Rc::new(move || {
        if let Some(page) = p.upgrade() {
            page.pump();
        }
    }));

    // FRAME-17: the route's snapshots asked now, before the mount — the
    // registry keeps each answer for the component that reads it.
    let early: Vec<_> = match &routed {
        Some(r) => app.boot_specs(&r.component, r.props.clone()).iter().map(|spec| app.cache().acquire(spec)).collect(),
        None => Vec::new(),
    };
    // The watch, so nothing said while the rest is asked is missed.
    page.watch();
    // UI-8: the route is drawn with the bundle's defaults at once; the
    // assignments, when they come, refill only the sections they change
    // (`set_assignments`) — the first rows wait on no `ui.slots.list`.
    // FRAME-50: the layout drawn now, each section in a task of its own —
    // an answer that arrived while one mounted is handled before the next.
    app.set_yield(Some(Rc::new(host_js::yield_then)));
    page.route();
    let pg = page.clone();
    app.when_settled(Box::new(move || {
        pg.app.set_yield(None);
        crate::marks::once("layout-mounted");
        drop(early);
        // FRAME-50: the sections drawn together once what the mount asked
        // is answered — the page's first real layout has the rows — or
        // HOLD_MS after, whichever is first.
        // Then `plexus.booted` on the bus, once and sticky (FRAME-53): the
        // page is up — what a component that waits for it hears, mounted
        // before or after, instead of guessing from a tick.
        let app = Rc::downgrade(&pg.app);
        let booted = std::cell::Cell::new(false);
        let release: Rc<dyn Fn()> = Rc::new(move || {
            if let Some(app) = app.upgrade().filter(|_| !booted.replace(true)) {
                app.release();
                app.bus().say_sticky(BOOTED, json!({}));
            }
        });
        let r = release.clone();
        pg.app.cache().when_answered(Box::new(move || r()));
        PageClock.schedule(HOLD_MS, Box::new(move || release()));
        let p = pg.clone();
        wasm_bindgen_futures::spawn_local(async move { p.assignments().await });
        // STUDIO-3: the rows as they stand now the watch is open — a change
        // between the page's serving and the watch is not missed.
        wasm_bindgen_futures::spawn_local(async move { pg.routes_listed().await });
    }));

    // The hash.
    let p = page.clone();
    let on_hash = Closure::<dyn FnMut()>::new(move || p.route());
    window().add_event_listener_with_callback("hashchange", on_hash.as_ref().unchecked_ref()).map_err(|e| format!("{e:?}"))?;
    on_hash.forget();

    // A reconnect: every `live` asked again, the watch and the assignments.
    let p = Rc::downgrade(&page);
    wire.on_reconnect(Rc::new(move || {
        if let Some(page) = p.upgrade() {
            page.app.cache().reconnected();
            page.watch();
            let pg = page.clone();
            wasm_bindgen_futures::spawn_local(async move {
                pg.assignments().await;
                pg.routes_listed().await;
            });
        }
    }));

    // The menu.
    let p = page.clone();
    let on_menu = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |e: web_sys::MouseEvent| menu_event(&p, e));
    document.add_event_listener_with_callback("contextmenu", on_menu.as_ref().unchecked_ref()).map_err(|e| format!("{e:?}"))?;
    on_menu.forget();

    // The cache's keep: swept every second.
    let p = Rc::downgrade(&page);
    wasm_bindgen_futures::spawn_local(async move {
        while let Some(page) = p.upgrade() {
            page.app.cache().sweep();
            drop(page);
            sleep(1_000).await;
        }
    });
    Ok(())
}

// ── the section menu ──────────────────────────────────────────────────────

const MENU_STYLE: &str = "position:fixed;z-index:2147483647;min-width:14rem;max-width:24rem;padding:.25rem 0;\
background:Canvas;color:CanvasText;border:1px solid GrayText;border-radius:6px;box-shadow:0 6px 24px rgba(0,0,0,.25);\
font:13px/1.4 system-ui,sans-serif";
const HEAD_STYLE: &str = "padding:.25rem .75rem;font-size:11px;opacity:.7;text-transform:uppercase;letter-spacing:.04em";
const ITEM_STYLE: &str = "display:block;width:100%;text-align:left;padding:.3rem .75rem;border:0;background:none;color:inherit;font:inherit;cursor:pointer";

fn close_menu(document: &web_sys::Document) {
    if let Ok(Some(m)) = document.query_selector("[data-engine-menu]") {
        m.remove();
    }
}

fn menu_event(page: &Rc<Page>, e: web_sys::MouseEvent) {
    let Some(target) = e.target().and_then(|t| t.dyn_into::<web_sys::Element>().ok()) else { return };
    if target.closest("[data-engine-menu]").ok().flatten().is_some() {
        return;
    }
    // FRAME-29: a bound mark (`data-component`) is no section to swap: the
    // menu is the late-bound section around it, if any.
    let Some(section) = target.closest("[data-slot]:not([data-component])").ok().flatten() else { return };
    e.prevent_default();
    let layout = section.get_attribute("data-layout").unwrap_or_default();
    let slot = section.get_attribute("data-slot").unwrap_or_default();
    let (x, y) = (e.client_x(), e.client_y());
    let page = page.clone();
    wasm_bindgen_futures::spawn_local(async move { open_menu(&page, &layout, &slot, x, y).await });
}

/// Every stored version (newest first) with its manifest's entry for
/// `component`.
async fn versions_of(page: &Rc<Page>, component: &str) -> Vec<(String, Option<ComponentEntry>, String)> {
    let items = page.wire.ask("ui.versions", json!({})).await.unwrap_or_default();
    let mut out = Vec::new();
    for v in items.iter().filter(|i| i["type"] == "version") {
        let Some(hash) = v["hash"].as_str() else { continue };
        let entry = page.manifest(hash).await.ok().and_then(|m| m.components.get(component).cloned());
        let label = format!("{} · {}", &hash[..hash.len().min(10)], v["commit"].as_str().unwrap_or(""));
        out.push((hash.to_string(), entry, label));
    }
    out
}

async fn open_menu(page: &Rc<Page>, layout: &str, slot: &str, x: i32, y: i32) {
    let document = page.dom.document.clone();
    close_menu(&document);
    let component = page.app.menu(layout, slot, &[]).component;
    let stored = versions_of(page, &component).await;
    let listed: Vec<(String, Option<ComponentEntry>)> = stored.iter().map(|(h, e, _)| (h.clone(), e.clone())).collect();
    let menu = page.app.menu(layout, slot, &listed);
    let Ok(m) = document.create_element("div") else { return };
    let _ = m.set_attribute("data-engine-menu", "");
    let _ = m.set_attribute("role", "menu");
    let _ = m.set_attribute("style", &format!("{MENU_STYLE};left:{x}px;top:{y}px"));
    let add = |parent: &web_sys::Element, tag: &str, attrs: &[(&str, &str)], text: &str| -> Option<web_sys::Element> {
        let el = document.create_element(tag).ok()?;
        for (k, v) in attrs {
            let _ = el.set_attribute(k, v);
        }
        el.set_text_content(Some(text));
        let _ = parent.append_child(&el);
        Some(el)
    };
    add(&m, "div", &[("style", HEAD_STYLE)], &format!("{layout} · {slot}: components"));
    for name in &menu.components {
        if let Some(b) = add(&m, "button", &[("data-component", name), ("style", ITEM_STYLE), ("role", "menuitem")], name) {
            let (page, layout, slot, name, live) = (page.clone(), layout.to_string(), slot.to_string(), name.clone(), page.app.version());
            on_click(&b, move || pick(&page, &layout, &slot, &name, &live));
        }
    }
    if !menu.versions.is_empty() {
        add(&m, "div", &[("style", HEAD_STYLE)], &format!("{}: other versions", menu.component));
    }
    for v in &menu.versions {
        let label = stored.iter().find(|(h, _, _)| h == v).map(|(_, _, l)| l.clone()).unwrap_or_else(|| v.clone());
        if let Some(b) = add(&m, "button", &[("data-version", v), ("style", ITEM_STYLE), ("role", "menuitem")], &label) {
            let (page, layout, slot, name, v) = (page.clone(), layout.to_string(), slot.to_string(), menu.component.clone(), v.clone());
            on_click(&b, move || pick(&page, &layout, &slot, &name, &v));
        }
    }
    if let Some(body) = document.body() {
        let _ = body.append_child(&m);
    }
    // A click elsewhere, or Escape, closes it.
    let doc = document.clone();
    let away = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
        let inside = e.target().and_then(|t| t.dyn_into::<web_sys::Element>().ok()).and_then(|t| t.closest("[data-engine-menu]").ok().flatten()).is_some();
        let escape = e.dyn_ref::<web_sys::KeyboardEvent>().is_some_and(|k| k.key() == "Escape");
        if (!inside && e.type_() == "mousedown") || escape {
            close_menu(&doc);
        }
    });
    let _ = document.add_event_listener_with_callback("mousedown", away.as_ref().unchecked_ref());
    let _ = document.add_event_listener_with_callback("keydown", away.as_ref().unchecked_ref());
    away.forget();
}

fn on_click(el: &web_sys::Element, f: impl Fn() + 'static) {
    let c = Closure::<dyn FnMut()>::new(f);
    let _ = el.add_event_listener_with_callback("click", c.as_ref().unchecked_ref());
    c.forget();
}

/// A pick: `ui.slots.set`; the section remounts when `ui.watch` says so; a
/// refusal is shown in the menu.
fn pick(page: &Rc<Page>, layout: &str, slot: &str, component: &str, version: &str) {
    let page = page.clone();
    let params = json!({ "layout": layout, "slot": slot, "component": component, "version": version });
    wasm_bindgen_futures::spawn_local(async move {
        let refusal = match page.wire.ask("ui.slots.set", params).await {
            Ok(items) => items.iter().find(|i| i["type"] != "set").map(|i| i["message"].as_str().map(str::to_string).unwrap_or_else(|| i.to_string())),
            Err(m) => Some(m),
        };
        let document = page.dom.document.clone();
        match refusal {
            None => close_menu(&document),
            Some(why) => {
                if let Ok(Some(m)) = document.query_selector("[data-engine-menu]") {
                    if let Ok(Some(old)) = m.query_selector("[data-refused]") {
                        old.remove();
                    }
                    if let Ok(el) = document.create_element("div") {
                        let _ = el.set_attribute("data-refused", "");
                        let _ = el.set_attribute("role", "alert");
                        let _ = el.set_attribute("style", "padding:.4rem .75rem;color:#b3261e;border-top:1px solid GrayText");
                        el.set_text_content(Some(&format!("refused: {why}")));
                        let _ = m.append_child(&el);
                    }
                }
            }
        }
    });
}