Skip to main content

plexus_ui_engine/swap/
mod.rs

1//! UI-6: **the module registry, hot-swap and the sections**.
2//!
3//! The registry is the live version's `manifest.json`: each component's
4//! name → the hashes of its tree and handlers. A mounted component is an
5//! instance: its element (named for the component), its props, its state,
6//! its folds and the version it was drawn from.
7//!
8//! - **Hot-swap** ([`App::swap`]): a new manifest; each mounted instance
9//!   whose `tree` or `handlers` hash changed is remounted into the same
10//!   element with the same props — its state carried over when the declared
11//!   state's shape (its keys) is unchanged, else the new initial state;
12//!   every other instance is untouched. One that fails to mount (a
13//!   malformed tree, handlers refused) keeps its last good version drawn,
14//!   and the console says so.
15//! - **Sections**: a layout's `slot` node draws as a `div` carrying
16//!   `data-layout` and `data-slot`, filled by its assignment — from
17//!   `ui.slots.list` ([`App::set_assignments`]), else `manifest.slots`'
18//!   default — with the slot's attributes as props. A component of another
19//!   version is drawn from that version's files ([`Files::put_version`],
20//!   fetched by the engine from `/app/<hash>/components/<name>.json` and
21//!   `.rhai`). `slot_changed` ([`App::slot_changed`]) remounts that section
22//!   alone, its props kept.
23//!
24//! What the engine fetches is handed in as [`Files`] (content-addressed by
25//! sha256), so everything here is synchronous: the browser fetches first,
26//! then swaps.
27//!
28//! FRAME-12: a component of any profile but `rhx/1` is a module
29//! ([`crate::module`]) the page imports and hands in with
30//! [`App::provide_module`]; it is mounted, swapped and filled by the same
31//! rules, with these: a module whose hash changed is destroyed, then
32//! mounted from the new version into the same element with the same props
33//! — and when that `mount` throws, the last good version is mounted again
34//! and the element marked; a section whose assignment changes mounts the
35//! new component before the old one is taken out, and when the new one
36//! fails the old stays drawn, marked; a route to the component already
37//! drawn is an `update(props)`. Every mounted instance is a member of the
38//! page's [`Bus`] ([`App::bus`]); an rhx fold hears the topics its tree's
39//! `bus` names and runs with the bus held.
40//!
41//! FRAME-29: **a bound mark** — a `[data-slot]` mark that also carries
42//! `data-component` (and, optionally, `data-version`) — is a section bound
43//! early: its code chose what fills it. The walk fills it with that
44//! component (of that version, else the live one) with the mark's other
45//! `data-*` as props, whatever the assignments and `slots.json` say; no
46//! assignment, `slot_changed` or default reaches it, and `slots_set` on it
47//! is refused `bound` ([`crate::bus::BusRefusal::Bound`]). Its props follow
48//! the mark as an unbound section's do; a mark whose binding changes is a
49//! new section; a swap remounts it when its component's hash changed, as
50//! any instance (a `data-version` pins it); it goes when its mark does.
51
52mod boot;
53mod turns;
54
55pub use turns::{Yield, HELD};
56
57use crate::bus::{answer_sink, Answer, Bus, BusHost, Listening, Member};
58use crate::folds::{FoldError, Folds, Host};
59use crate::live::{Clock, Follow, LiveCache, LiveQuery, LiveSpec, ModuleLive, ModuleSpec, Reader};
60use crate::module::{Module, ModuleInstance, RHX};
61use crate::transport::{CallId, Sink};
62use crate::signals::{Runtime, Signal};
63use crate::transport::Wire;
64use crate::tree::{Children, ComponentTree, Mounted, Renderer, Scope, State};
65use serde_json::{Map, Value};
66use sha2::Digest;
67use std::cell::RefCell;
68use std::collections::BTreeMap;
69use std::rc::{Rc, Weak};
70
71/// One component of a manifest.
72#[derive(Debug, Clone, PartialEq, Eq, Default)]
73pub struct ComponentEntry {
74    /// The sha256 of `components/<name>.json` (`rhx/1`).
75    pub tree: String,
76    /// The sha256 of `components/<name>.rhai` (`rhx/1`).
77    pub handlers: String,
78    pub uses: Vec<String>,
79    /// FRAME-12: the profile that draws it; empty (a manifest written
80    /// before profiles) is `rhx/1`.
81    pub profile: String,
82    /// FRAME-12: a module's sha256 (`components/<name>.js`), for every
83    /// profile but `rhx/1`.
84    pub module: String,
85    /// FRAME-30: its sheet's sha256 (`components/<name>.css`); empty when it
86    /// has none.
87    pub css: String,
88}
89
90impl ComponentEntry {
91    /// Drawn by the rhx runtime.
92    pub fn is_rhx(&self) -> bool {
93        self.profile.is_empty() || self.profile == RHX
94    }
95
96    /// What names its code: the tree's and the handlers' hashes, or the
97    /// module's and (FRAME-30) its sheet's. An rhx sheet is named by its
98    /// tree (the mark), so a sheet changed is a tree changed.
99    pub fn hashes(&self) -> (String, String) {
100        if self.is_rhx() {
101            (self.tree.clone(), self.handlers.clone())
102        } else {
103            (self.module.clone(), self.css.clone())
104        }
105    }
106}
107
108/// A bundle's `manifest.json`.
109#[derive(Debug, Clone, PartialEq, Eq, Default)]
110pub struct Manifest {
111    pub abi: String,
112    pub contract: String,
113    pub commit: String,
114    /// A route pattern (`#/ticket/:id`) → the component (or layout) drawn.
115    pub routes: BTreeMap<String, String>,
116    pub components: BTreeMap<String, ComponentEntry>,
117    /// A layout → its slot → the component filling it by default.
118    pub slots: BTreeMap<String, BTreeMap<String, String>>,
119}
120
121impl Manifest {
122    /// From `manifest.json`'s text.
123    pub fn parse(json: &str) -> Result<Self, String> {
124        let v: Value = serde_json::from_str(json).map_err(|e| format!("manifest.json: {e}"))?;
125        let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
126        let map = |k: &str| -> BTreeMap<String, String> {
127            v.get(k).and_then(Value::as_object).map(|o| o.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect()).unwrap_or_default()
128        };
129        let components = v
130            .get("components")
131            .and_then(Value::as_object)
132            .ok_or("manifest.json names no components")?
133            .iter()
134            .map(|(name, e)| {
135                let f = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_string).ok_or(format!("manifest.json: {name} has no {k}"));
136                let uses = e.get("uses").and_then(Value::as_array).map(|a| a.iter().filter_map(|u| u.as_str().map(str::to_string)).collect()).unwrap_or_default();
137                let profile = e.get("profile").and_then(Value::as_str).unwrap_or(RHX).to_string();
138                let css = e.get("css").and_then(Value::as_str).unwrap_or_default().to_string();
139                let entry = if profile == RHX {
140                    ComponentEntry { tree: f("tree")?, handlers: f("handlers")?, uses, profile, module: String::new(), css }
141                } else {
142                    ComponentEntry { module: f("module")?, uses, profile, css, ..ComponentEntry::default() }
143                };
144                Ok((name.clone(), entry))
145            })
146            .collect::<Result<_, String>>()?;
147        let slots = v
148            .get("slots")
149            .and_then(Value::as_object)
150            .map(|o| {
151                o.iter()
152                    .map(|(layout, m)| {
153                        let m = m.as_object().map(|m| m.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect()).unwrap_or_default();
154                        (layout.clone(), m)
155                    })
156                    .collect()
157            })
158            .unwrap_or_default();
159        Ok(Self { abi: s("abi"), contract: s("contract"), commit: s("commit"), routes: map("routes"), components, slots })
160    }
161}
162
163/// What the engine has fetched: each version's component by
164/// `(version, name)` — `/app/<version>/components/<name>.json` and `.rhai`.
165#[derive(Debug, Clone, Default)]
166pub struct Files {
167    /// STUDIO-9: shared text — a version that keeps another's unchanged
168    /// component (a swap) holds the same allocation, not a copy.
169    by_version: BTreeMap<(String, String), (Rc<str>, Rc<str>)>,
170    /// FRAME-30: an rhx component's sheet's text — components.json's `css`,
171    /// or `components/<name>.css`.
172    sheets: BTreeMap<(String, String), Rc<str>>,
173}
174
175/// The sha256 of `text`, hex — what a manifest names a file by.
176pub fn sha256_hex(text: &str) -> String {
177    sha2::Sha256::digest(text.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
178}
179
180impl Files {
181    /// Keeps version `version`'s component `name`: its tree and handlers.
182    pub fn put_version(&mut self, version: &str, name: &str, tree: &str, handlers: &str) {
183        self.by_version.insert((version.into(), name.into()), (Rc::from(tree), Rc::from(handlers)));
184    }
185
186    /// FRAME-30: keeps version `version`'s component `name`'s sheet's text.
187    pub fn put_sheet(&mut self, version: &str, name: &str, css: &str) {
188        self.sheets.insert((version.into(), name.into()), Rc::from(css));
189    }
190
191    /// FRAME-30: version `version`'s component `name`'s sheet, when fetched.
192    pub fn sheet(&self, version: &str, name: &str) -> Option<Rc<str>> {
193        self.sheets.get(&(version.to_string(), name.to_string())).cloned()
194    }
195
196    /// Version `version`'s component `name`: `(tree, handlers)`.
197    pub fn version(&self, version: &str, name: &str) -> Option<(&str, &str)> {
198        self.by_version.get(&(version.to_string(), name.to_string())).map(|(t, h)| (&**t, &**h))
199    }
200
201    /// STUDIO-9: version `from`'s component `name` kept under `to` as well —
202    /// its tree, handlers and sheet shared, not copied. False when `from`
203    /// has none.
204    pub fn share(&mut self, from: &str, to: &str, name: &str) -> bool {
205        let Some(files) = self.by_version.get(&(from.to_string(), name.to_string())).cloned() else { return false };
206        self.by_version.insert((to.into(), name.into()), files);
207        if let Some(css) = self.sheet(from, name) {
208            self.sheets.insert((to.into(), name.into()), css);
209        }
210        true
211    }
212
213    /// STUDIO-9: the bytes kept, each text counted once however many
214    /// versions share it.
215    pub fn kept_bytes(&self) -> usize {
216        let mut seen = std::collections::BTreeSet::new();
217        let texts = self.by_version.values().flat_map(|(t, h)| [t, h]).chain(self.sheets.values());
218        texts.filter(|x| seen.insert(Rc::as_ptr(x) as *const u8 as usize)).map(|x| x.len()).sum()
219    }
220
221    /// Everything `other` holds, kept too.
222    pub fn extend(&mut self, other: &Files) {
223        self.by_version.extend(other.by_version.iter().map(|(k, v)| (k.clone(), v.clone())));
224        self.sheets.extend(other.sheets.iter().map(|(k, v)| (k.clone(), v.clone())));
225    }
226}
227
228/// What fills a section: `(layout, slot) → (component, version)` — kept
229/// by the ui service (`ui.slots.*`), said on `ui.watch` as `slot_changed`.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct Assignment {
232    pub layout: String,
233    pub slot: String,
234    pub component: String,
235    /// The version's hash (the live one's, for a component of the live bundle).
236    pub version: String,
237}
238
239/// A mounted instance.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
241pub struct MountId(pub u64);
242
243/// What a swap did.
244#[derive(Debug, Clone, PartialEq, Default)]
245pub struct SwapReport {
246    /// Remounted on their new hashes.
247    pub remounted: Vec<MountId>,
248    /// Kept on their last good version: each with why.
249    pub failed: Vec<(MountId, String)>,
250}
251
252/// Why a mount or a load did not happen.
253#[derive(Debug, Clone, PartialEq)]
254pub enum SwapError {
255    /// No component of that name in the version.
256    Unknown(String),
257    /// A component's files were not fetched yet: `(version, name)`
258    /// ([`App::needs`] lists it).
259    Missing(String, String),
260    /// The tree did not parse or mount, or the handlers were refused: why.
261    Failed { component: String, message: String },
262}
263
264impl std::fmt::Display for SwapError {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        match self {
267            SwapError::Unknown(c) => write!(f, "no component {c} in this version"),
268            SwapError::Missing(v, n) => write!(f, "{n} of {v} is not fetched yet"),
269            SwapError::Failed { component, message } => write!(f, "{component} failed to mount: {message}"),
270        }
271    }
272}
273
274/// The section menu (a right-click on a section): the live bundle's
275/// components by name, and the section's component's other stored
276/// versions — those whose hash for it differs from the live one's —
277/// newest first, the live one excluded.
278#[derive(Debug, Clone, PartialEq, Default)]
279pub struct Menu {
280    /// The section's component, as drawn.
281    pub component: String,
282    pub components: Vec<String>,
283    pub versions: Vec<String>,
284}
285
286/// The member an rhx component's folds speak through, and the instance
287/// they fold into (FRAME-37: a call's answer folds there), set at each mount.
288type MemberSlot = Rc<RefCell<Option<(Member, MountId)>>>;
289
290/// A component ready to mount: an rhx tree and folds, checked; or a module.
291enum Prepared<R: Renderer> {
292    Rhx { version: String, tree: Rc<ComponentTree>, folds: Rc<Folds>, tree_hash: String, handlers_hash: String, slot: MemberSlot, css: Sheet },
293    Module { version: String, name: String, hash: String, css: String, uses: Vec<String>, module: Rc<dyn Module<R>> },
294}
295
296/// FRAME-30: a sheet the page adopts — its key (the component and its
297/// sheet's hash) and its text.
298type Sheet = Option<(String, Rc<str>)>;
299
300impl<R: Renderer> Prepared<R> {
301    fn version(&self) -> &str {
302        match self {
303            Prepared::Rhx { version, .. } | Prepared::Module { version, .. } => version,
304        }
305    }
306
307    /// FRAME-30: its sheet, when it has one — an rhx tree that names a mark
308    /// (the text components.json or its file gave), a module whose entry
309    /// names a `css` (the text it exports as `css`) — keyed by the component
310    /// and the sheet's sha256: two versions of one sheet are one sheet.
311    fn sheet(&self) -> Sheet {
312        match self {
313            Prepared::Rhx { css, .. } => css.clone(),
314            Prepared::Module { name, css, module, .. } => (!css.is_empty()).then(|| module.css()).flatten().map(|text| (format!("{name}@{css}"), Rc::from(text.as_str()))),
315        }
316    }
317}
318
319/// What draws a mounted instance.
320enum Body<R: Renderer> {
321    Rhx {
322        tree_hash: String,
323        handlers_hash: String,
324        state: State,
325        live: BTreeMap<String, Signal<Value>>,
326        readers: Vec<Follow>,
327        folds: Rc<Folds>,
328        tree: Rc<ComponentTree>,
329        mounted: Option<Mounted<R>>,
330        slot: MemberSlot,
331        /// FRAME-30: its sheet, keyed, and its text.
332        css: Sheet,
333        /// The topics it hears.
334        _listening: Vec<Listening>,
335        /// FRAME-36: its keys, in the page's registry while it is mounted.
336        _keys: crate::keys::KeysHeld,
337    },
338    Module {
339        hash: String,
340        /// FRAME-30: its sheet's sha256, empty when none.
341        css: String,
342        uses: Vec<String>,
343        module: Rc<dyn Module<R>>,
344        mounted: Option<Box<dyn ModuleInstance>>,
345        /// FRAME-18: the observer of its element's marks, stopped with it.
346        observing: Option<crate::tree::Unlisten>,
347    },
348}
349
350/// A mounted instance.
351struct Inst<R: Renderer> {
352    name: String,
353    version: String,
354    /// Drawn from an assignment's version: a swap leaves it.
355    pinned: bool,
356    element: R::Node,
357    props: Map<String, Value>,
358    member: Member,
359    body: Body<R>,
360    /// Its last swap failed: it carries `data-failed`.
361    failed: bool,
362}
363
364impl<R: Renderer> Inst<R> {
365    fn hashes(&self) -> (String, String) {
366        match &self.body {
367            Body::Rhx { tree_hash, handlers_hash, .. } => (tree_hash.clone(), handlers_hash.clone()),
368            Body::Module { hash, css, .. } => (hash.clone(), css.clone()),
369        }
370    }
371
372    /// What it was drawn from, ready to mount again.
373    fn prepared(&self) -> Prepared<R> {
374        match &self.body {
375            Body::Rhx { tree_hash, handlers_hash, folds, tree, slot, css, .. } => Prepared::Rhx {
376                version: self.version.clone(),
377                tree: tree.clone(),
378                folds: folds.clone(),
379                tree_hash: tree_hash.clone(),
380                handlers_hash: handlers_hash.clone(),
381                slot: slot.clone(),
382                css: css.clone(),
383            },
384            Body::Module { hash, css, uses, module, .. } => {
385                Prepared::Module { version: self.version.clone(), name: self.name.clone(), hash: hash.clone(), css: css.clone(), uses: uses.clone(), module: module.clone() }
386            }
387        }
388    }
389
390    fn state(&self) -> Option<Map<String, Value>> {
391        match &self.body {
392            Body::Rhx { state, .. } => Some(state.snapshot()),
393            Body::Module { .. } => None,
394        }
395    }
396
397    /// Takes it out of the page: its tree or its module, its readers, its
398    /// place on the bus.
399    fn teardown(mut self) {
400        match &mut self.body {
401            Body::Rhx { mounted, readers, .. } => {
402                if let Some(m) = mounted.take() {
403                    m.unmount();
404                }
405                drop(std::mem::take(readers));
406            }
407            Body::Module { mounted, observing, .. } => {
408                if let Some(off) = observing.take() {
409                    off();
410                }
411                if let Some(m) = mounted.take() {
412                    m.destroy();
413                }
414            }
415        }
416        self.member.leave();
417    }
418}
419
420/// A section drawn: its `div`, its props and what fills it.
421struct Section<R: Renderer> {
422    sid: u64,
423    /// FRAME-18: the module layout whose mark it is (the walk found it);
424    /// none for an rhx `<slot>` (its tree says when it goes).
425    owner: Option<MountId>,
426    layout: String,
427    slot: String,
428    div: R::Node,
429    props: Map<String, Value>,
430    instance: Option<MountId>,
431    /// What it waits on, when its files are not fetched yet.
432    waiting: Option<(String, String, bool)>,
433    /// FRAME-29: what its mark binds it to — `(component, version)`, the
434    /// version none for the live one; none for a late-bound section.
435    bound: Option<Binding>,
436    /// STUDIO-9: an rhx child's own element (`<tag-chip>`), filled in
437    /// place — its component mounts into `div` itself, never a new element
438    /// inside it.
439    inline: bool,
440    /// FRAME-50: drawn while the mount yields, and waiting its turn
441    /// ([`App::fill_soon`]); a fill before the turn takes it off.
442    queued: bool,
443}
444
445/// FRAME-29: a mark's `data-component` and `data-version`.
446type Binding = (String, Option<String>);
447
448/// A module handed in: its code and its version's manifest entry.
449type Provided<R> = (Rc<dyn Module<R>>, ComponentEntry);
450
451struct St<R: Renderer> {
452    version: String,
453    manifest: Manifest,
454    files: Files,
455    /// FRAME-12: the modules imported, by `(version, name)`.
456    modules: BTreeMap<(String, String), Provided<R>>,
457    needs: Vec<(String, String)>,
458    instances: BTreeMap<MountId, Inst<R>>,
459    next: u64,
460    assignments: Vec<Assignment>,
461    sections: Vec<Section<R>>,
462    console: Vec<String>,
463    /// FRAME-29: the (layout, slot)s whose stored assignment a mark's
464    /// binding overrides, said once each.
465    warned: std::collections::BTreeSet<(String, String)>,
466}
467
468/// The engine: the registry, the instances, the sections — over a
469/// renderer, the wire (for `call` and `live`) and a clock.
470pub struct App<R: Renderer, W: Wire, C: Clock> {
471    rt: Runtime,
472    renderer: R,
473    wire: W,
474    cache: Rc<LiveCache<W, C>>,
475    bus: Bus,
476    st: RefCell<St<R>>,
477    navigate: RefCell<Option<Rc<dyn Fn(&str)>>>,
478    /// FRAME-29: told when a walk the module's own DOM set off left
479    /// something to fetch ([`Self::needs`]).
480    on_need: RefCell<Option<Rc<dyn Fn()>>>,
481    /// FRAME-29: the components mounting now, outermost first.
482    attaching: RefCell<Vec<String>>,
483    /// FRAME-17: every tree parsed, by its sha256 — once a page.
484    trees: RefCell<BTreeMap<String, Rc<ComponentTree>>>,
485    /// FRAME-17: trees the boot read without compiling, by sha256.
486    read_trees: RefCell<BTreeMap<String, Rc<ComponentTree>>>,
487    /// FRAME-30: each sheet on the page by its address, and how many
488    /// mounted instances hold it.
489    sheets: RefCell<BTreeMap<String, usize>>,
490    /// FRAME-36: the window's key listener, stopped with the engine.
491    keys_off: RefCell<Option<crate::tree::Unlisten>>,
492    /// FRAME-37: each instance's calls whose answer it waits on, closed when
493    /// it is unmounted.
494    calls: RefCell<BTreeMap<MountId, Vec<CallId>>>,
495    /// FRAME-50: the mount's turns ([`turns`]).
496    turns: turns::Turns<R::Node>,
497    me: Weak<Self>,
498}
499
500impl<R: Renderer, W: Wire, C: Clock> Drop for App<R, W, C> {
501    fn drop(&mut self) {
502        if let Some(off) = self.keys_off.borrow_mut().take() {
503            off();
504        }
505    }
506}
507
508/// The engine's side of every mount ([`Children`]): the engine, the version
509/// the instance whose tree is drawing is pinned to (none: it follows the
510/// page's), and its name.
511struct Kids<R: Renderer, W: Wire, C: Clock>(Weak<App<R, W, C>>, Option<String>, String);
512
513impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> Children<R> for Kids<R, W, C> {
514    fn mount_component(&self, at: &R::Node, name: &str, props: Map<String, Value>) {
515        let Some(app) = self.0.upgrade() else { return };
516        let version = app.st.borrow().version.clone();
517        let pin = self.1.clone();
518        if pin.as_deref().is_none_or(|v| v == version) {
519            match app.instantiate(at, name, &version, pin.is_some(), props.clone()) {
520                Ok(_) => return,
521                // STUDIO-9: not fetched yet: it waits, below, as a
522                // section's component does.
523                Err(SwapError::Missing(..)) => {}
524                Err(e) => return app.say(&format!("{name} ({version}): {e}")),
525            }
526        }
527        // STUDIO-9: a section bound to the child, filled in the child's own
528        // element — of the version its parent is pinned to (a section
529        // assigned a stored version, a mark's data-version, a studio's
530        // frame: its children are that version's), or the page's — and
531        // fetched as any section's component is.
532        let sid = app.next_id().0;
533        let s = Section { sid, owner: None, layout: self.2.clone(), slot: name.into(), div: at.clone(), props, instance: None, waiting: None, bound: Some((name.to_string(), pin)), inline: true, queued: false };
534        app.st.borrow_mut().sections.push(s);
535        app.fill(sid);
536        app.told_needs();
537    }
538
539    fn mount_slot(&self, at: &R::Node, layout: &str, slot: &str, props: Map<String, Value>) {
540        if let Some(app) = self.0.upgrade() {
541            let sid = app.next_id().0;
542            let s = Section { sid, owner: None, layout: layout.into(), slot: slot.into(), div: at.clone(), props, instance: None, waiting: None, bound: None, inline: false, queued: false };
543            app.st.borrow_mut().sections.push(s);
544            app.fill_soon(sid);
545        }
546    }
547
548    fn unmount(&self, at: &R::Node) {
549        if let Some(app) = self.0.upgrade() {
550            app.unmount_at(at);
551        }
552    }
553
554    /// FRAME-29: a child of another profile is a bound mark.
555    fn binds(&self, name: &str) -> bool {
556        let Some(app) = self.0.upgrade() else { return false };
557        let st = app.st.borrow();
558        // STUDIO-9: a pinned parent's child is of its version: a module
559        // there when that version's module is here, rhx when its files are.
560        if let Some(v) = self.1.as_deref().filter(|v| *v != st.version) {
561            if st.modules.contains_key(&(v.to_string(), name.to_string())) {
562                return true;
563            }
564            if st.files.version(v, name).is_some() {
565                return false;
566            }
567        }
568        st.manifest.components.get(name).is_some_and(|e| !e.is_rhx())
569    }
570
571    fn mount_bound(&self, at: &R::Node, layout: &str, name: &str, props: Map<String, Value>) {
572        if let Some(app) = self.0.upgrade() {
573            let sid = app.next_id().0;
574            // STUDIO-9: of the version the parent is pinned to.
575            let bound = Some((name.to_string(), self.1.clone()));
576            let s = Section { sid, owner: None, layout: layout.into(), slot: name.into(), div: at.clone(), props, instance: None, waiting: None, bound, inline: false, queued: false };
577            app.st.borrow_mut().sections.push(s);
578            app.fill_soon(sid);
579            app.told_needs();
580        }
581    }
582}
583
584/// The folds' host: `call` through the wire, `navigate` to the router,
585/// `emit` and `slots_set` through the instance's member of the bus;
586/// FRAME-37: `call_then` folds the answer into the instance that called.
587struct AppHost<R: Renderer, W: Wire, C: Clock>(Weak<App<R, W, C>>, MemberSlot);
588
589impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> Host for AppHost<R, W, C> {
590    fn call(&self, method: &str, params: Value) {
591        if let Some(app) = self.0.upgrade() {
592            app.wire.open(method, params, Box::new(|_| {}));
593        }
594    }
595    /// FRAME-37: sent once, as `call` is — nothing keeps it to be asked
596    /// again on a reconnect (the live cache keeps only its collections) —
597    /// and its answer folded in the bus's turn: after the fold that called
598    /// has returned its state, even when the wire answers at once.
599    fn call_then(&self, method: &str, params: Value, fold: &str) {
600        let Some(app) = self.0.upgrade() else { return };
601        let Some(id) = self.1.borrow().as_ref().map(|(_, id)| *id) else { return };
602        let (me, fold, m, p) = (self.0.clone(), fold.to_string(), method.to_string(), params.clone());
603        // Kept while it is open, so an unmount closes it; an answer at once
604        // (inside `open`) is never kept.
605        let open: Rc<std::cell::Cell<Option<CallId>>> = Rc::new(std::cell::Cell::new(None));
606        let ended = Rc::new(std::cell::Cell::new(false));
607        let (o, e) = (open.clone(), ended.clone());
608        let call = app.wire.open(
609            method,
610            params,
611            answer_sink(move |answer| {
612                e.set(true);
613                let Some(app) = me.upgrade() else { return };
614                if let Some(call) = o.get() {
615                    app.forget_call(id, call);
616                }
617                app.bus.defer(move || {
618                    if let Some(app) = me.upgrade() {
619                        app.answered(id, &fold, &m, &p, answer);
620                    }
621                });
622            }),
623        );
624        if !ended.get() {
625            open.set(Some(call));
626            app.calls.borrow_mut().entry(id).or_default().push(call);
627        }
628    }
629    fn navigate(&self, route: &str) {
630        let f = self.0.upgrade().and_then(|app| app.navigate.borrow().clone());
631        if let Some(f) = f {
632            f(route);
633        }
634    }
635    fn emit(&self, topic: &str, data: Value) -> Result<(), String> {
636        let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
637        member.ok_or("not mounted")?.emit(topic, data).map_err(|r| r.to_string())
638    }
639    fn last(&self, topic: &str) -> Value {
640        let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
641        member.and_then(|m| m.last(topic)).unwrap_or(Value::Null)
642    }
643    fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>) -> Result<(), String> {
644        let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
645        member.ok_or("not mounted")?.slots_set(layout, slot, component, version, Box::new(|_| {})).map(|_| ()).map_err(|r| r.to_string())
646    }
647}
648
649/// FRAME-12: what the bus asks of the host.
650impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> BusHost for App<R, W, C> {
651    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
652        self.wire.open(method, params, sink)
653    }
654    fn close(&self, call: CallId) {
655        self.wire.close(call)
656    }
657    fn live(&self, spec: &LiveSpec) -> Reader {
658        self.cache.acquire(spec)
659    }
660    fn follow(&self, spec: ModuleSpec) -> ModuleLive {
661        self.cache.follow_module(spec)
662    }
663    fn navigate(&self, route: &str) {
664        let f = self.navigate.borrow().clone();
665        if let Some(f) = f {
666            f(route);
667        }
668    }
669    fn live_version(&self) -> String {
670        self.version()
671    }
672    fn bound(&self, layout: &str, slot: &str) -> Option<String> {
673        let st = self.st.borrow();
674        st.sections.iter().filter(|s| s.layout == layout && s.slot == slot).find_map(|s| s.bound.as_ref()).map(|(c, _)| c.clone())
675    }
676}
677
678impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
679    pub fn new(rt: &Runtime, renderer: R, wire: W, clock: C) -> Rc<Self> {
680        let cache = LiveCache::new(rt, wire.clone(), clock);
681        let bus = Bus::new(rt);
682        let app = Rc::new_cyclic(|me| Self {
683            rt: rt.clone(),
684            renderer,
685            wire,
686            cache,
687            bus: bus.clone(),
688            st: RefCell::new(St {
689                version: String::new(),
690                manifest: Manifest::default(),
691                files: Files::default(),
692                modules: BTreeMap::new(),
693                needs: Vec::new(),
694                instances: BTreeMap::new(),
695                next: 0,
696                assignments: Vec::new(),
697                sections: Vec::new(),
698                console: Vec::new(),
699                warned: Default::default(),
700            }),
701            navigate: RefCell::new(None),
702            on_need: RefCell::new(None),
703            attaching: RefCell::new(Vec::new()),
704            trees: RefCell::new(BTreeMap::new()),
705            read_trees: RefCell::new(BTreeMap::new()),
706            sheets: RefCell::new(BTreeMap::new()),
707            keys_off: RefCell::new(None),
708            calls: RefCell::new(BTreeMap::new()),
709            turns: turns::Turns::default(),
710            me: me.clone(),
711        });
712        let host: Weak<dyn BusHost> = Rc::downgrade(&app) as Weak<dyn BusHost>;
713        bus.set_host(host);
714        // FRAME-36: the window's keys, heard before anything of the page.
715        let me = Rc::downgrade(&app);
716        let off = app.renderer.listen_keys(Rc::new(move |p: &crate::keys::Press| me.upgrade().is_some_and(|app| app.press(p))));
717        *app.keys_off.borrow_mut() = Some(off);
718        // FRAME-38: an open overlay follows the registry — redrawn on every
719        // change, closed when the last key goes.
720        let me = Rc::downgrade(&app);
721        bus.keys().on_change(Rc::new(move || {
722            if let Some(app) = me.upgrade() {
723                app.overlay_follows();
724            }
725        }));
726        app
727    }
728
729    /// FRAME-36: a key press — what it matches run, the first chords of a
730    /// sequence held, `?` the overlay; true when the host took it (the
731    /// browser must not have it).
732    pub fn press(&self, p: &crate::keys::Press) -> bool {
733        let keys = self.bus.keys().clone();
734        let heard = keys.press(p);
735        if let crate::keys::Heard::Overlay(open) = heard {
736            self.renderer.keys_overlay(open.then(|| keys.groups()).as_ref());
737        }
738        heard.taken()
739    }
740
741    fn overlay_follows(&self) {
742        let keys = self.bus.keys();
743        if !keys.overlay() {
744            return;
745        }
746        if keys.is_empty() {
747            keys.close_overlay();
748            self.renderer.keys_overlay(None);
749        } else {
750            self.renderer.keys_overlay(Some(&keys.groups()));
751        }
752    }
753
754    /// FRAME-12: the page's bus.
755    pub fn bus(&self) -> Bus {
756        self.bus.clone()
757    }
758
759    /// FRAME-12: version `version`'s module `name`, imported, with its
760    /// manifest entry; every section waiting on it is filled.
761    pub fn provide_module(&self, version: &str, name: &str, entry: ComponentEntry, module: Rc<dyn Module<R>>) {
762        let waiting: Vec<u64> = {
763            let mut st = self.st.borrow_mut();
764            st.modules.insert((version.into(), name.into()), (module, entry));
765            st.needs.retain(|(v, n)| !(v == version && n == name));
766            st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| v == version && n == name)).map(|s| s.sid).collect()
767        };
768        for sid in waiting {
769            self.fill(sid);
770        }
771    }
772
773    /// The `live` subscriptions (the page sweeps and reconnects them).
774    pub fn cache(&self) -> &Rc<LiveCache<W, C>> {
775        &self.cache
776    }
777
778    /// Where a handler's `navigate` goes.
779    pub fn set_navigate(&self, f: Rc<dyn Fn(&str)>) {
780        *self.navigate.borrow_mut() = Some(f);
781    }
782
783    /// FRAME-29: what a walk the page did not start (a module's own DOM
784    /// changing) calls when it left something to fetch.
785    pub fn set_on_need(&self, f: Rc<dyn Fn()>) {
786        *self.on_need.borrow_mut() = Some(f);
787    }
788
789    /// The live version: its hash and manifest. Mounting needs its
790    /// components' files ([`Self::provide`]).
791    pub fn load(&self, version: &str, manifest: Manifest) {
792        let mut st = self.st.borrow_mut();
793        st.version = version.into();
794        st.manifest = manifest;
795    }
796
797    /// The live version's hash.
798    pub fn version(&self) -> String {
799        self.st.borrow().version.clone()
800    }
801
802    /// The live version's manifest.
803    pub fn manifest(&self) -> Manifest {
804        self.st.borrow().manifest.clone()
805    }
806
807    /// Files fetched: kept; every section waiting on them is filled.
808    pub fn provide(&self, files: &Files) {
809        let waiting: Vec<u64> = {
810            let mut st = self.st.borrow_mut();
811            st.files.extend(files);
812            let have = st.files.clone();
813            st.needs.retain(|(v, n)| have.version(v, n).is_none());
814            st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| have.version(v, n).is_some())).map(|s| s.sid).collect()
815        };
816        for sid in waiting {
817            self.fill(sid);
818        }
819    }
820
821    /// What the engine asks to be fetched: `(version, component)`, each once.
822    pub fn needs(&self) -> Vec<(String, String)> {
823        self.st.borrow().needs.clone()
824    }
825
826    fn say(&self, line: &str) {
827        #[cfg(feature = "dom")]
828        web_sys::console::warn_1(&line.into());
829        self.st.borrow_mut().console.push(line.to_string());
830    }
831
832    /// `name` of `version`, checked against what the live manifest names
833    /// (for the live version), its handlers compiled — or its module, when
834    /// it is one.
835    fn prepare(&self, version: &str, name: &str) -> Result<Prepared<R>, SwapError> {
836        let need = |st: &mut St<R>| {
837            let need = (version.to_string(), name.to_string());
838            if !st.needs.contains(&need) {
839                st.needs.push(need);
840            }
841            Err(SwapError::Missing(version.into(), name.into()))
842        };
843        let (files, entry) = {
844            let mut st = self.st.borrow_mut();
845            let entry = (version == st.version).then(|| st.manifest.components.get(name).cloned());
846            if let Some(None) = entry {
847                return Err(SwapError::Unknown(name.into()));
848            }
849            let entry = entry.flatten();
850            let module = st.modules.get(&(version.to_string(), name.to_string())).cloned();
851            match (&entry, module) {
852                // A module of the live version: the one its manifest names.
853                (Some(e), Some((module, got))) if !e.is_rhx() => {
854                    if got.module != e.module {
855                        return Err(SwapError::Failed { component: name.into(), message: "its module is not the one the manifest names (their hashes differ)".into() });
856                    }
857                    return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: e.module.clone(), css: e.css.clone(), uses: e.uses.clone(), module });
858                }
859                (Some(e), None) if !e.is_rhx() => return need(&mut st),
860                // Another version's module.
861                (None, Some((module, got))) if st.files.version(version, name).is_none() => {
862                    return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: got.module.clone(), css: got.css.clone(), uses: got.uses.clone(), module });
863                }
864                _ => {}
865            }
866            match st.files.version(version, name) {
867                Some((t, h)) => ((t.to_string(), h.to_string(), st.files.sheet(version, name)), entry),
868                None => return need(&mut st),
869            }
870        };
871        let failed = |message: String| SwapError::Failed { component: name.into(), message };
872        let (tree_hash, handlers_hash) = (sha256_hex(&files.0), sha256_hex(&files.1));
873        if let Some(e) = &entry {
874            if e.tree != tree_hash || e.handlers != handlers_hash {
875                return Err(failed("its files are not the ones the manifest names (their hashes differ)".into()));
876            }
877        }
878        let tree = self.parsed(&files.0).map_err(failed)?;
879        let slot: MemberSlot = Rc::new(RefCell::new(None));
880        let host: Rc<dyn Host> = Rc::new(AppHost(self.me.clone(), slot.clone()));
881        let folds = Folds::compile(&files.1, &tree.uses, host).map_err(|e| failed(e.to_string()))?;
882        // FRAME-17: a component's handlers compile when it is mounted.
883        crate::marks::mark(&format!("handlers-compiled:{name}"));
884        if tree.css.is_some() && files.2.is_none() {
885            self.say(&format!("{name} ({version}): its tree names a sheet, and none was fetched — drawn without it"));
886        }
887        // FRAME-30: keyed by the compiled sheet's sha256 (the manifest's
888        // `css`), so a sheet compiled anew is a sheet anew.
889        let css = files.2.filter(|_| tree.css.is_some()).map(|text| (format!("{name}@{}", sha256_hex(&text)), text));
890        Ok(Prepared::Rhx { version: version.into(), tree, folds: Rc::new(folds), tree_hash, handlers_hash, slot, css })
891    }
892
893    /// Draws `p` into `element` as instance `id`: an rhx tree with its
894    /// state (`state`, else its initial), its `live` readers and the topics
895    /// it hears; or a module, mounted.
896    fn attach(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
897        // FRAME-29: what is mounting now, outermost first — every section
898        // filled while it mounts is inside it (see [`Self::cycle`]).
899        let name = match &p {
900            Prepared::Module { name, .. } => name.clone(),
901            Prepared::Rhx { tree, .. } => tree.name.clone(),
902        };
903        self.attaching.borrow_mut().push(name);
904        let r = self.attach_now(id, element, p, props, state, pinned);
905        self.attaching.borrow_mut().pop();
906        r
907    }
908
909    /// FRAME-30: its sheet is on the page before it is drawn (and goes again
910    /// when the draw fails); an rhx element carries its sheet's mark.
911    fn attach_now(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
912        let sheet = p.sheet();
913        self.sheet_up(&sheet);
914        if let Prepared::Rhx { tree, .. } = &p {
915            if let Some(mark) = &tree.css {
916                self.renderer.set_attr(element, "data-css", mark);
917            }
918        }
919        let r = self.draw(id, element, p, props, state, pinned);
920        if r.is_err() {
921            self.sheet_down(&sheet);
922        }
923        r
924    }
925
926    /// FRAME-30: one more instance needs the sheet; the first adopts it.
927    fn sheet_up(&self, sheet: &Sheet) {
928        let Some((key, text)) = sheet else { return };
929        let first = {
930            let mut sheets = self.sheets.borrow_mut();
931            let n = sheets.entry(key.clone()).or_insert(0);
932            *n += 1;
933            *n == 1
934        };
935        if first {
936            self.renderer.sheet(key, text, true);
937        }
938    }
939
940    /// FRAME-30: one fewer; the last drops it.
941    fn sheet_down(&self, sheet: &Sheet) {
942        let Some((href, _)) = sheet else { return };
943        let last = {
944            let mut sheets = self.sheets.borrow_mut();
945            match sheets.get_mut(href) {
946                Some(n) if *n > 1 => {
947                    *n -= 1;
948                    false
949                }
950                Some(_) => {
951                    sheets.remove(href);
952                    true
953                }
954                None => false,
955            }
956        };
957        if last {
958            self.renderer.sheet(href, "", false);
959        }
960    }
961
962    /// FRAME-30: the sheets the page has adopted, by key (`<component>@<its
963    /// sheet's hash or mark>`), each with how many instances hold it.
964    pub fn sheets(&self) -> BTreeMap<String, usize> {
965        self.sheets.borrow().clone()
966    }
967
968    fn draw(&self, id: MountId, element: &R::Node, p: Prepared<R>, mut props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
969        let (version, tree, folds, tree_hash, handlers_hash, slot, css) = match p {
970            Prepared::Module { version, name, hash, css, uses, module } => {
971                let member = self.bus.join(&name, &uses);
972                let mounted = module.mount(element, &props, member.clone()).map_err(|message| {
973                    member.leave();
974                    SwapError::Failed { component: name.clone(), message }
975                })?;
976                // FRAME-18: its marks watched, and walked now.
977                let me = self.me.clone();
978                let observing = self.renderer.observe(
979                    element,
980                    Rc::new(move |targets: Vec<R::Node>| {
981                        if let Some(app) = me.upgrade() {
982                            app.observed(id, &targets);
983                        }
984                    }),
985                );
986                let body = Body::Module { hash, css, uses, module, mounted: Some(mounted), observing: Some(observing) };
987                let inst = Inst { name, version, pinned, element: element.clone(), props, member, body, failed: false };
988                self.st.borrow_mut().instances.insert(id, inst);
989                self.walk(id);
990                return Ok(());
991            }
992            Prepared::Rhx { version, tree, folds, tree_hash, handlers_hash, slot, css } => (version, tree, folds, tree_hash, handlers_hash, slot, css),
993        };
994        // UI-8: a declared prop nobody passed is there, as null (`()` in an
995        // expression) — `#/` gives the layout no `filter`, `#/f/:filter` does.
996        for name in &tree.props {
997            props.entry(name.clone()).or_insert(Value::Null);
998        }
999        let state = State::new(&self.rt, state.as_ref().unwrap_or(&tree.state));
1000        let mut readers = Vec::new();
1001        let mut live = BTreeMap::new();
1002        for (name, d) in &tree.live {
1003            // A bad fold rule is refused at mount, naming it.
1004            for rule in d.on.values() {
1005                rule.parse::<crate::live::FoldRule>().map_err(|message| SwapError::Failed { component: tree.name.clone(), message })?;
1006            }
1007            // UI-10: the params follow the scope — a state key they read
1008            // changing runs the snapshot again (after debounce_ms).
1009            let query = LiveQuery {
1010                snapshot: d.snapshot.clone(),
1011                changes: d.changes.clone(),
1012                key: d.key.clone(),
1013                on: d.on.iter().map(|(a, b)| (a.clone(), b.clone())).collect(),
1014                debounce_ms: d.debounce_ms,
1015            };
1016            // FRAME-16: `when` false holds it: nothing asked.
1017            let (pp, cp, pr, st, when) = (d.params.clone(), d.changes_params.clone(), props.clone(), state.clone(), d.when.clone());
1018            let r = self.cache.follow_held(query, move || {
1019                crate::tree::eval_when(when.as_ref(), &pr, &st).then(|| (crate::tree::eval_params(&pp, &pr, &st), crate::tree::eval_params(&cp, &pr, &st)))
1020            });
1021            live.insert(name.clone(), r.signal());
1022            readers.push(r);
1023        }
1024        let me = self.me.clone();
1025        let on_event: Rc<dyn Fn(&str, Value)> = Rc::new(move |handler: &str, ev: Value| {
1026            if let Some(app) = me.upgrade() {
1027                if let Err(e) = app.dispatch(id, handler, ev) {
1028                    app.say(&e.to_string());
1029                }
1030            }
1031        });
1032        // FRAME-12: its place on the bus — the folds' `emit`, and a fold
1033        // per topic it hears. FRAME-36: joined before its tree is drawn, so
1034        // its keys register before those of the components inside it: the
1035        // deeper, registered later, hears a shared chord first.
1036        let member = self.bus.join(&tree.name, &tree.uses);
1037        *slot.borrow_mut() = Some((member.clone(), id));
1038        let keys = member.keys(
1039            tree.keys
1040                .iter()
1041                .map(|d| {
1042                    let (me, to) = (self.me.clone(), d.to.clone());
1043                    let run: crate::keys::KeyRun = Rc::new(move |ev: Value| {
1044                        if let Some(app) = me.upgrade() {
1045                            if let Err(e) = app.dispatch(id, &to, ev) {
1046                                app.say(&e.to_string());
1047                            }
1048                        }
1049                    });
1050                    (d.clone(), run)
1051                })
1052                .collect(),
1053        );
1054        let scope = Scope { props: props.clone(), state: state.clone(), live: live.clone(), on_event };
1055        let kids: Rc<dyn Children<R>> = Rc::new(Kids(self.me.clone(), pinned.then(|| version.clone()), tree.name.clone()));
1056        let mounted = crate::tree::mount(&self.rt, &self.renderer, &tree, scope, element, kids).map_err(|e| {
1057            member.leave();
1058            SwapError::Failed { component: tree.name.clone(), message: e.to_string() }
1059        })?;
1060        // FRAME-17: an answer that came before its component (asked at
1061        // boot) is drawn by the mount itself.
1062        for (d, r) in tree.live.values().zip(&readers) {
1063            let Some(at) = r.answered_at().filter(|_| r.live().status == crate::live::Status::Live && !r.live().rows.is_empty()) else { continue };
1064            crate::marks::once_at("first-answer", at);
1065            crate::marks::once("first-row");
1066            crate::marks::once_at(&format!("answered:{}", d.snapshot), at);
1067            crate::marks::once(&format!("drawn:{}", d.snapshot));
1068        }
1069        let listening = tree
1070            .bus
1071            .iter()
1072            .map(|(topic, fold)| {
1073                let (me, fold, topic2) = (self.me.clone(), fold.clone(), topic.clone());
1074                member.on(topic, move |data: &Value| {
1075                    if let Some(app) = me.upgrade() {
1076                        app.dispatch_bus(id, &fold, &topic2, data);
1077                    }
1078                })
1079            })
1080            .collect();
1081        let inst = Inst {
1082            name: tree.name.clone(),
1083            version,
1084            pinned,
1085            element: element.clone(),
1086            props,
1087            member,
1088            body: Body::Rhx { tree_hash, handlers_hash, state, live, readers, folds, tree, mounted: Some(mounted), slot, css, _listening: listening, _keys: keys },
1089            failed: false,
1090        };
1091        self.st.borrow_mut().instances.insert(id, inst);
1092        Ok(())
1093    }
1094
1095    fn next_id(&self) -> MountId {
1096        let mut st = self.st.borrow_mut();
1097        st.next += 1;
1098        MountId(st.next)
1099    }
1100
1101    /// An instance of `name` of `version` into `element`; on a failure the
1102    /// element carries `data-failed`.
1103    fn instantiate(&self, element: &R::Node, name: &str, version: &str, pinned: bool, props: Map<String, Value>) -> Result<MountId, SwapError> {
1104        let p = match self.prepare(version, name) {
1105            Ok(p) => p,
1106            Err(e) => {
1107                if !matches!(e, SwapError::Missing(..)) {
1108                    self.renderer.set_attr(element, "data-failed", version);
1109                }
1110                return Err(e);
1111            }
1112        };
1113        let id = self.next_id();
1114        self.attach(id, element, p, props, None, pinned).inspect_err(|_| self.renderer.set_attr(element, "data-failed", version))?;
1115        Ok(id)
1116    }
1117
1118    /// Mounts `name` of the live version into a new element (named for it)
1119    /// appended to `parent`. A component that fails is drawn as failed (its
1120    /// element carries `data-failed`, the version) and the console says why.
1121    pub fn mount(&self, parent: &R::Node, name: &str, props: Map<String, Value>) -> Result<MountId, SwapError> {
1122        let el = self.renderer.create_element(name);
1123        let version = self.version();
1124        let r = self.instantiate(&el, name, &version, false, props);
1125        self.renderer.insert(parent, &el, None);
1126        r.inspect_err(|e| self.say(&format!("{name} ({version}): {e}")))
1127    }
1128
1129    /// Takes instance `id` out: its tree or module, its readers, its place
1130    /// on the bus, the instances in it.
1131    pub fn unmount(&self, id: MountId) {
1132        // FRAME-37: the calls it waits on are closed — their answers fold
1133        // nowhere.
1134        let calls = self.calls.borrow_mut().remove(&id).unwrap_or_default();
1135        for call in calls {
1136            self.wire.close(call);
1137        }
1138        let inst = self.st.borrow_mut().instances.remove(&id);
1139        if let Some(inst) = inst {
1140            self.drop_sections_of(id);
1141            let sheet = inst.prepared().sheet();
1142            inst.teardown();
1143            self.sheet_down(&sheet);
1144        }
1145    }
1146
1147    /// FRAME-12: instance `id` with new props — a route to the component
1148    /// already drawn. A module hears `update(props)`; an rhx component (its
1149    /// props are constants in its scope) is drawn again into its element
1150    /// from its initial state, as a new mount of it was.
1151    pub fn update(&self, id: MountId, props: Map<String, Value>) -> Result<(), SwapError> {
1152        let module = {
1153            let mut st = self.st.borrow_mut();
1154            let Some(inst) = st.instances.get_mut(&id) else { return Err(SwapError::Unknown(format!("instance {}", id.0))) };
1155            inst.props = props.clone();
1156            match &mut inst.body {
1157                Body::Module { mounted, .. } => Some(mounted.take()),
1158                Body::Rhx { .. } => None,
1159            }
1160        };
1161        match module {
1162            Some(mounted) => {
1163                // Called with no borrow held: the module may speak on the bus.
1164                let mut mounted = mounted;
1165                if let Some(m) = mounted.as_mut() {
1166                    m.update(&props);
1167                }
1168                if let Some(Inst { body: Body::Module { mounted: slot, .. }, .. }) = self.st.borrow_mut().instances.get_mut(&id) {
1169                    *slot = mounted;
1170                }
1171                // FRAME-18: what the new props drew, walked.
1172                self.walk(id);
1173                Ok(())
1174            }
1175            None => {
1176                let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
1177                let (p, element, pinned) = (inst.prepared(), inst.element.clone(), inst.pinned);
1178                let held = p.sheet();
1179                inst.teardown();
1180                let r = self.attach(id, &element, p, props, None, pinned);
1181                self.sheet_down(&held);
1182                r
1183            }
1184        }
1185    }
1186
1187    fn unmount_at(&self, at: &R::Node) {
1188        let ids: Vec<MountId> = self.st.borrow().instances.iter().filter(|(_, i)| &i.element == at).map(|(id, _)| *id).collect();
1189        for id in ids {
1190            self.unmount(id);
1191        }
1192        let gone: Vec<Option<MountId>> = {
1193            let mut st = self.st.borrow_mut();
1194            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| &s.div == at);
1195            st.sections = keep;
1196            out.into_iter().map(|s| s.instance).collect()
1197        };
1198        for id in gone.into_iter().flatten() {
1199            self.unmount(id);
1200        }
1201    }
1202
1203    /// Runs `handler` of instance `id` on `event`: its state replaced. The
1204    /// bus is held while it runs: what it emits is heard once it returned.
1205    pub fn dispatch(&self, id: MountId, handler: &str, event: Value) -> Result<(), FoldError> {
1206        let _hold = self.bus.hold();
1207        let (folds, state, props, live) = {
1208            let st = self.st.borrow();
1209            let i = st.instances.get(&id).ok_or_else(|| FoldError::NoHandler(handler.into()))?;
1210            match &i.body {
1211                Body::Rhx { folds, state, live, .. } => (folds.clone(), state.clone(), i.props.clone(), live.clone()),
1212                Body::Module { .. } => return Err(FoldError::NoHandler(handler.into())),
1213            }
1214        };
1215        let rows: Map<String, Value> = live.iter().map(|(k, s)| (k.clone(), s.peek().get("rows").cloned().unwrap_or(Value::Null))).collect();
1216        let next = folds.run(handler, &state.snapshot(), &event, &props, &rows)?;
1217        state.replace(&next);
1218        Ok(())
1219    }
1220
1221    /// FRAME-37: `call` of instance `id` ended: no longer kept to close.
1222    fn forget_call(&self, id: MountId, call: CallId) {
1223        let mut calls = self.calls.borrow_mut();
1224        if let Some(list) = calls.get_mut(&id) {
1225            list.retain(|c| *c != call);
1226            if list.is_empty() {
1227                calls.remove(&id);
1228            }
1229        }
1230    }
1231
1232    /// FRAME-37: how many calls instance `id` waits on (tests).
1233    pub fn calls_of(&self, id: MountId) -> usize {
1234        self.calls.borrow().get(&id).map_or(0, Vec::len)
1235    }
1236
1237    /// FRAME-37: a call's answer, folded once into instance `id` by `fold`
1238    /// with `ev = { method, params, ok, events, message }`. An instance gone
1239    /// meanwhile (unmounted, its section emptied) hears nothing.
1240    fn answered(&self, id: MountId, fold: &str, method: &str, params: &Value, answer: Answer) {
1241        if !self.st.borrow().instances.contains_key(&id) {
1242            return;
1243        }
1244        let mut ev = answer.to_value();
1245        ev["method"] = Value::String(method.into());
1246        ev["params"] = params.clone();
1247        if let Err(e) = self.dispatch(id, fold, ev) {
1248            self.say(&e.to_string());
1249        }
1250    }
1251
1252    /// FRAME-12: `topic` heard on the bus — the fold its tree names, with
1253    /// `ev.bus = { topic, data }`.
1254    fn dispatch_bus(&self, id: MountId, fold: &str, topic: &str, data: &Value) {
1255        let ev = serde_json::json!({ "bus": { "topic": topic, "data": data } });
1256        if let Err(e) = self.dispatch(id, fold, ev) {
1257            self.say(&e.to_string());
1258        }
1259    }
1260
1261    /// A new live version: remounts exactly the instances drawn from the
1262    /// live version whose hashes changed; the files of the changed
1263    /// components must be provided first.
1264    pub fn swap(&self, version: &str, manifest: Manifest) -> SwapReport {
1265        let old = {
1266            let mut st = self.st.borrow_mut();
1267            let old = std::mem::replace(&mut st.version, version.into());
1268            let before = std::mem::replace(&mut st.manifest, manifest.clone());
1269            // STUDIO-9: a component the swap did not change is the same
1270            // files under the new version — kept under it now, so a changed
1271            // component that places an unchanged one draws it at once (the
1272            // page fetches only what changed).
1273            let same: Vec<String> = manifest.components.iter().filter(|(n, e)| before.components.get(*n) == Some(*e)).map(|(n, _)| n.clone()).collect();
1274            for name in same {
1275                if st.files.version(version, &name).is_none() {
1276                    st.files.share(&old, version, &name);
1277                }
1278                let key = (version.to_string(), name.clone());
1279                if !st.modules.contains_key(&key) {
1280                    if let Some(m) = st.modules.get(&(old.clone(), name.clone())).cloned() {
1281                        st.modules.insert(key, m);
1282                    }
1283                }
1284            }
1285            let St { files, modules, needs, .. } = &mut *st;
1286            needs.retain(|(v, n)| files.version(v, n).is_none() && !modules.contains_key(&(v.clone(), n.clone())));
1287            old
1288        };
1289        let candidates: Vec<(MountId, String, (String, String), bool)> = self
1290            .st
1291            .borrow()
1292            .instances
1293            .iter()
1294            .filter(|(_, i)| !i.pinned)
1295            .map(|(id, i)| (*id, i.name.clone(), i.hashes(), matches!(i.body, Body::Rhx { .. })))
1296            .collect();
1297        let mut report = SwapReport::default();
1298        for (id, name, hashes, was_rhx) in candidates {
1299            if !self.st.borrow().instances.contains_key(&id) {
1300                continue;
1301            }
1302            let Some(entry) = manifest.components.get(&name) else {
1303                self.fail(id, version, &old, &name, "not in the new version".into(), &mut report);
1304                continue;
1305            };
1306            if entry.hashes() == hashes {
1307                continue;
1308            }
1309            let p = match self.prepare(version, &name) {
1310                Ok(p) => p,
1311                Err(e) => {
1312                    self.fail(id, version, &old, &name, e.to_string(), &mut report);
1313                    continue;
1314                }
1315            };
1316            let r = if was_rhx && matches!(p, Prepared::Rhx { .. }) { self.remount(id, p) } else { self.replace(id, p) };
1317            match r {
1318                Ok(()) => report.remounted.push(id),
1319                Err(e) => self.fail(id, version, &old, &name, e.to_string(), &mut report),
1320            }
1321        }
1322        // A section whose default moved to another component follows it.
1323        let refill: Vec<u64> = {
1324            let st = self.st.borrow();
1325            st.sections
1326                .iter()
1327                .filter(|s| s.bound.is_none() && !st.assignments.iter().any(|a| a.layout == s.layout && a.slot == s.slot))
1328                .filter(|s| {
1329                    let default = st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot));
1330                    let drawn = s.instance.and_then(|id| st.instances.get(&id)).map(|i| &i.name);
1331                    default != drawn
1332                })
1333                .map(|s| s.sid)
1334                .collect()
1335        };
1336        for sid in refill {
1337            self.fill(sid);
1338        }
1339        report
1340    }
1341
1342    fn fail(&self, id: MountId, version: &str, old: &str, name: &str, why: String, report: &mut SwapReport) {
1343        let drawn = {
1344            let mut st = self.st.borrow_mut();
1345            st.instances.get_mut(&id).map(|i| {
1346                i.failed = true;
1347                (i.element.clone(), i.version.clone())
1348            })
1349        };
1350        let drawn_version = match drawn {
1351            Some((element, v)) => {
1352                self.renderer.set_attr(&element, "data-failed", version);
1353                v
1354            }
1355            None => old.to_string(),
1356        };
1357        self.say(&format!("{name}: {version} failed to mount ({why}); keeping its last good version {drawn_version}"));
1358        report.failed.push((id, why));
1359    }
1360
1361    /// FRAME-12: instance `id` replaced by `p` in its element — the old one
1362    /// destroyed first, then `p` mounted with the same props; when that
1363    /// fails, what was drawn is mounted again (its state too) and the
1364    /// failure answered.
1365    fn replace(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
1366        let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
1367        let (again, state, element, props, pinned, was_failed) = (inst.prepared(), inst.state(), inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
1368        // FRAME-30: the old sheet is held until the new one is adopted.
1369        let held = again.sheet();
1370        self.drop_sections_of(id);
1371        inst.teardown();
1372        let r = self.replace_with(id, &element, p, again, props, state, pinned, was_failed);
1373        self.sheet_down(&held);
1374        r
1375    }
1376
1377    #[allow(clippy::too_many_arguments)]
1378    fn replace_with(&self, id: MountId, element: &R::Node, p: Prepared<R>, again: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool, was_failed: bool) -> Result<(), SwapError> {
1379        let element = element.clone();
1380        match self.attach(id, &element, p, props.clone(), None, pinned) {
1381            Ok(()) => {
1382                if was_failed {
1383                    self.renderer.set_attr(&element, "data-failed", "");
1384                }
1385                Ok(())
1386            }
1387            Err(e) => {
1388                if let Err(again) = self.attach(id, &element, again, props, state, pinned) {
1389                    self.say(&format!("its last good version did not mount again either: {again}"));
1390                }
1391                Err(e)
1392            }
1393        }
1394    }
1395
1396    /// Instance `id` again from `p`, into its element, its props kept and
1397    /// its state too when the shape is the same.
1398    fn remount(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
1399        let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
1400        let state = match (&inst.body, &p) {
1401            (Body::Rhx { state, .. }, Prepared::Rhx { tree, .. }) => {
1402                let shape: Vec<String> = tree.state.keys().cloned().collect();
1403                (state.shape() == shape).then(|| state.snapshot())
1404            }
1405            _ => None,
1406        };
1407        let (element, props, pinned, was_failed) = (inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
1408        let held = inst.prepared().sheet();
1409        self.drop_sections_of(id);
1410        inst.teardown();
1411        let r = self.attach(id, &element, p, props, state, pinned);
1412        self.sheet_down(&held);
1413        if r.is_ok() && was_failed {
1414            self.renderer.set_attr(&element, "data-failed", "");
1415        }
1416        r
1417    }
1418
1419    /// The sections' assignments (`ui.slots.list`); a section with none
1420    /// takes `manifest.slots`' default.
1421    pub fn set_assignments(&self, assignments: Vec<Assignment>) {
1422        self.warn_bound(&assignments);
1423        let changed: Vec<u64> = {
1424            let mut st = self.st.borrow_mut();
1425            let before = std::mem::replace(&mut st.assignments, assignments);
1426            let find = |list: &[Assignment], l: &str, s: &str| list.iter().find(|a| a.layout == l && a.slot == s).cloned();
1427            st.sections
1428                .iter()
1429                .filter(|s| s.bound.is_none() && find(&before, &s.layout, &s.slot) != find(&st.assignments, &s.layout, &s.slot))
1430                .map(|s| s.sid)
1431                .collect()
1432        };
1433        for sid in changed {
1434            self.fill(sid);
1435        }
1436    }
1437
1438    /// `slot_changed` on `ui.watch`: that section remounts with its props,
1439    /// nothing else.
1440    pub fn slot_changed(&self, change: Assignment) {
1441        self.warn_bound(std::slice::from_ref(&change));
1442        let idx = {
1443            let mut st = self.st.borrow_mut();
1444            st.assignments.retain(|a| !(a.layout == change.layout && a.slot == change.slot));
1445            st.assignments.push(change.clone());
1446            st.sections.iter().filter(|s| s.bound.is_none() && s.layout == change.layout && s.slot == change.slot).map(|s| s.sid).collect::<Vec<_>>()
1447        };
1448        for sid in idx {
1449            self.fill(sid);
1450        }
1451    }
1452
1453    /// `slot_changed` back to the default (`ui.slots.clear`).
1454    pub fn slot_reset(&self, layout: &str, slot: &str) {
1455        let idx = {
1456            let mut st = self.st.borrow_mut();
1457            st.assignments.retain(|a| !(a.layout == layout && a.slot == slot));
1458            st.sections.iter().filter(|s| s.bound.is_none() && s.layout == layout && s.slot == slot).map(|s| s.sid).collect::<Vec<_>>()
1459        };
1460        for sid in idx {
1461            self.fill(sid);
1462        }
1463    }
1464
1465    /// Section `i` drawn again: its binding (FRAME-29), else its
1466    /// assignment, else its default. Its files
1467    /// not fetched: it waits ([`Self::needs`]). FRAME-12: the new component
1468    /// is mounted before what the section had is taken out; when it fails,
1469    /// what it had stays drawn, marked `data-failed`.
1470    fn fill(&self, sid: u64) {
1471        // FRAME-50: filled now, so its turn, if it waits one, finds it done.
1472        self.with_section(sid, |s| s.queued = false);
1473        let (div, props, old, want, inline) = {
1474            let st = self.st.borrow();
1475            let Some(s) = st.sections.iter().find(|s| s.sid == sid) else { return };
1476            let want = match (&s.bound, st.assignments.iter().find(|a| a.layout == s.layout && a.slot == s.slot)) {
1477                (Some((c, v)), _) => {
1478                    // STUDIO-11: a module's mark naming no version, in a
1479                    // module pinned to one (a studio's frame), is that
1480                    // version's — a child is its pinned parent's version's.
1481                    let parent = s.owner.and_then(|o| st.instances.get(&o)).filter(|i| i.pinned).map(|i| i.version.clone());
1482                    let v = v.clone().or(parent);
1483                    Some((c.clone(), v.clone().unwrap_or_else(|| st.version.clone()), v.is_some()))
1484                }
1485                (None, Some(a)) => Some((a.component.clone(), a.version.clone(), true)),
1486                (None, None) => st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot)).map(|c| (c.clone(), st.version.clone(), false)),
1487            };
1488            let old = s.instance.and_then(|id| st.instances.get(&id).map(|inst| (id, inst.element.clone(), inst.version.clone())));
1489            (s.div.clone(), s.props.clone(), old, want, s.inline)
1490        };
1491        let Some((component, version, pinned)) = want else {
1492            if let Some((id, el, _)) = old {
1493                self.unmount(id);
1494                self.renderer.remove(&div, &el);
1495            }
1496            self.with_section(sid, |s| s.instance = None);
1497            return;
1498        };
1499        // FRAME-29: a component never fills a section inside an instance of
1500        // itself — a module binding itself, A binding B binding A, a layout
1501        // assigned into its own section would mount without end.
1502        if let Some(chain) = self.cycle(&div, &component) {
1503            self.with_section(sid, |s| s.waiting = None);
1504            self.say(&format!("cycle: {chain} → {component}; the section is left empty"));
1505            return;
1506        }
1507        let p = match self.prepare(&version, &component) {
1508            Ok(p) => p,
1509            Err(SwapError::Missing(..)) => {
1510                self.with_section(sid, |s| s.waiting = Some((version, component, pinned)));
1511                return;
1512            }
1513            Err(e) => {
1514                self.with_section(sid, |s| s.waiting = None);
1515                if let Some((_, el, _)) = &old {
1516                    self.renderer.set_attr(el, "data-failed", &version);
1517                }
1518                self.say(&format!("{component} ({version}): {e}; the section keeps what it shows"));
1519                return;
1520            }
1521        };
1522        // STUDIO-9: an rhx child's section mounts into the child's own
1523        // element, once (its tree says when it goes; a hot-swap remounts
1524        // the instance in place).
1525        if inline {
1526            self.with_section(sid, |s| s.waiting = None);
1527            if old.is_some() {
1528                return;
1529            }
1530            let id = self.next_id();
1531            match self.attach(id, &div, p, props, None, pinned) {
1532                Ok(()) => {
1533                    self.with_section(sid, |s| s.instance = Some(id));
1534                }
1535                Err(e) => {
1536                    self.renderer.set_attr(&div, "data-failed", &version);
1537                    self.say(&format!("{component} ({version}): {e}"));
1538                }
1539            }
1540            return;
1541        }
1542        let el = self.renderer.create_element(&component);
1543        let id = self.next_id();
1544        let drawn_from = p.version().to_string();
1545        match self.attach(id, &el, p, props, None, pinned) {
1546            Ok(()) => {
1547                self.renderer.insert(&div, &el, None);
1548                if let Some((old_id, old_el, _)) = old {
1549                    self.unmount(old_id);
1550                    self.renderer.remove(&div, &old_el);
1551                }
1552                let slot = self.with_section(sid, |s| {
1553                    s.waiting = None;
1554                    s.instance = Some(id);
1555                    s.slot.clone()
1556                });
1557                if let Some(slot) = slot {
1558                    crate::marks::once(&format!("section-mounted:{slot}"));
1559                }
1560            }
1561            Err(e) => {
1562                self.with_section(sid, |s| s.waiting = None);
1563                match old {
1564                    Some((old_id, old_el, old_version)) => {
1565                        self.renderer.set_attr(&old_el, "data-failed", &drawn_from);
1566                        if let Some(i) = self.st.borrow_mut().instances.get_mut(&old_id) {
1567                            i.failed = true;
1568                        }
1569                        self.say(&format!("{component}: {drawn_from} failed to mount ({e}); keeping its last good version {old_version}"));
1570                    }
1571                    None => {
1572                        self.renderer.insert(&div, &el, None);
1573                        self.renderer.set_attr(&el, "data-failed", &version);
1574                        self.with_section(sid, |s| s.instance = None);
1575                        self.say(&format!("{component} ({version}): {e}"));
1576                    }
1577                }
1578            }
1579        }
1580    }
1581
1582    /// FRAME-29: when `component` already draws an instance around `div`,
1583    /// the chain of names from the outermost such instance down, else none.
1584    /// Around is the DOM's holding, and past it the section each outermost
1585    /// instance fills — an instance mounts before its element is placed in
1586    /// its section, so the DOM alone does not reach the layout above it.
1587    fn cycle(&self, div: &R::Node, component: &str) -> Option<String> {
1588        let st = self.st.borrow();
1589        let mut chain: Vec<String> = Vec::new();
1590        let mut at = div.clone();
1591        for _ in 0..st.instances.len() + 1 {
1592            let mut around: Vec<(&MountId, &Inst<R>)> = st.instances.iter().filter(|(_, i)| i.element != at && self.renderer.contains(&i.element, &at)).collect();
1593            if around.is_empty() {
1594                break;
1595            }
1596            // Innermost last: the more of them hold it, the further in.
1597            around.sort_by_key(|(_, i)| around_count(&self.renderer, &st, &i.element));
1598            for (_, i) in around.iter().rev() {
1599                chain.push(i.name.clone());
1600            }
1601            let outer = *around[0].0;
1602            match st.sections.iter().find(|s| s.instance == Some(outer)) {
1603                Some(s) => at = s.div.clone(),
1604                None => break,
1605            }
1606        }
1607        chain.reverse();
1608        // What is mounting now holds `div` too: its element is not placed
1609        // (nor, for rhx, registered) until its mount returns.
1610        let outer: Vec<String> = self.attaching.borrow().iter().filter(|n| !chain.contains(n)).cloned().collect();
1611        let chain: Vec<String> = outer.into_iter().chain(chain).collect();
1612        chain.iter().any(|n| n == component).then(|| chain.join(" → "))
1613    }
1614
1615    /// FRAME-29: an assignment for a slot a mark binds is stored and does
1616    /// nothing; said once per (layout, slot).
1617    fn warn_bound(&self, assignments: &[Assignment]) {
1618        let lines: Vec<String> = {
1619            let mut st = self.st.borrow_mut();
1620            let mut lines = Vec::new();
1621            for a in assignments {
1622                let Some((c, _)) = st.sections.iter().filter(|s| s.layout == a.layout && s.slot == a.slot).find_map(|s| s.bound.clone()) else { continue };
1623                if st.warned.insert((a.layout.clone(), a.slot.clone())) {
1624                    lines.push(format!("{} · {}: assignment {}@{} stored, but the mark binds {c}; it does nothing", a.layout, a.slot, a.component, a.version));
1625                }
1626            }
1627            lines
1628        };
1629        for l in lines {
1630            self.say(&l);
1631        }
1632    }
1633
1634    /// FRAME-18: **the walk** — module instance `id`'s element searched for
1635    /// `[data-slot]` marks. A section of its whose mark is no longer in the
1636    /// element (or whose `data-slot` now names another slot) goes, and what
1637    /// filled it is destroyed — a mark moved within the element stays its
1638    /// section. A filled mark whose other `data-*` attributes changed hands
1639    /// them to what fills it as `update(props)`, never a refill. A mark
1640    /// that is no section yet, and is not inside another section within the
1641    /// element (a mark in a section is the filling component's), becomes one of the layout `id`
1642    /// draws — its slot the attribute's value, its props the mark's other
1643    /// `data-*` attributes (strings), `data-layout` written on it — and is
1644    /// filled as an rhx `<slot>` is ([`Self::fill`]). FRAME-29: a mark
1645    /// carrying `data-component` is bound to it (`data-version` too, when
1646    /// given) — neither is a prop — and a mark whose binding changed is a
1647    /// new section, as one whose slot changed.
1648    pub fn walk(&self, id: MountId) {
1649        let (target, layout) = {
1650            let st = self.st.borrow();
1651            match st.instances.get(&id) {
1652                Some(i) if matches!(i.body, Body::Module { .. }) => (i.element.clone(), i.name.clone()),
1653                _ => return,
1654            }
1655        };
1656        crate::marks::mark(&format!("walk:{layout}"));
1657        let gone: Vec<Option<MountId>> = {
1658            let mut st = self.st.borrow_mut();
1659            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| {
1660                s.owner == Some(id) && (!self.renderer.contains(&target, &s.div) || {
1661                    let (slot, bound, _) = mark_of(&self.renderer, &s.div);
1662                    slot != s.slot || bound != s.bound
1663                })
1664            });
1665            st.sections = keep;
1666            out.into_iter().map(|s| s.instance).collect()
1667        };
1668        for i in gone.into_iter().flatten() {
1669            self.unmount(i);
1670        }
1671        // The props of the marks already sections, read again.
1672        let moved: Vec<(MountId, Map<String, Value>)> = {
1673            let mut st = self.st.borrow_mut();
1674            st.sections
1675                .iter_mut()
1676                .filter(|s| s.owner == Some(id))
1677                .filter_map(|s| {
1678                    let (_, _, props) = mark_of(&self.renderer, &s.div);
1679                    if props == s.props {
1680                        return None;
1681                    }
1682                    s.props = props.clone();
1683                    s.instance.map(|i| (i, props))
1684                })
1685                .collect()
1686        };
1687        for (i, props) in moved {
1688            if let Err(e) = self.update(i, props) {
1689                self.say(&format!("{layout}: a section's props: {e}"));
1690            }
1691        }
1692        // A mark is another section's when that section is inside this
1693        // module's element and holds it — never because this module itself
1694        // fills a section of the page (SURFACE-10: its later marks are its own),
1695        // nor because that section's mark is the module's element itself (a
1696        // module filled inline, STUDIO-9: `contains` counts the element).
1697        let fresh: Vec<R::Node> = {
1698            let st = self.st.borrow();
1699            self.renderer
1700                .marks(&target)
1701                .into_iter()
1702                .filter(|m| !st.sections.iter().any(|s| &s.div == m || (s.div != target && self.renderer.contains(&target, &s.div) && self.renderer.contains(&s.div, m))))
1703                .collect()
1704        };
1705        for mark in fresh {
1706            let (slot, bound, props) = mark_of(&self.renderer, &mark);
1707            self.renderer.set_attr(&mark, "data-layout", &layout);
1708            let sid = self.next_id().0;
1709            let s = Section { sid, owner: Some(id), layout: layout.clone(), slot, div: mark, props, instance: None, waiting: None, bound, inline: false, queued: false };
1710            self.st.borrow_mut().sections.push(s);
1711            self.fill_soon(sid);
1712        }
1713    }
1714
1715    /// FRAME-18: the observer's batch for module instance `id`: walked
1716    /// unless every change was made inside one of its filled sections —
1717    /// under the mark, not on it (a section's own drawing, its rows, is none
1718    /// of the layout's; the mark's attributes are).
1719    pub fn observed(&self, id: MountId, targets: &[R::Node]) {
1720        let inside = {
1721            let st = self.st.borrow();
1722            let filled: Vec<&R::Node> = st.sections.iter().filter(|s| s.owner == Some(id) && s.instance.is_some()).map(|s| &s.div).collect();
1723            targets.iter().all(|t| filled.iter().any(|d| d != &t && self.renderer.contains(d, t)))
1724        };
1725        if !inside {
1726            self.walk(id);
1727            // FRAME-29: a mark drawn by the module's own state may bind a
1728            // component not fetched yet: the page is told to fetch it.
1729            self.told_needs();
1730        }
1731    }
1732
1733    /// FRAME-29, STUDIO-9: the page told to fetch what a mount left
1734    /// waiting (a mark the module's state drew, a child drawn after its
1735    /// parent's first draw: in an `{#each}` fed by `live()`, an `{#if}`).
1736    fn told_needs(&self) {
1737        let on_need = self.on_need.borrow().clone();
1738        if let Some(f) = on_need.filter(|_| !self.st.borrow().needs.is_empty()) {
1739            f();
1740        }
1741    }
1742
1743    /// FRAME-18: the sections module instance `id`'s walk found, gone with
1744    /// it — each one's instance destroyed — before it is.
1745    fn drop_sections_of(&self, id: MountId) {
1746        let gone: Vec<Option<MountId>> = {
1747            let mut st = self.st.borrow_mut();
1748            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| s.owner == Some(id));
1749            st.sections = keep;
1750            out.into_iter().map(|s| s.instance).collect()
1751        };
1752        for i in gone.into_iter().flatten() {
1753            self.unmount(i);
1754        }
1755    }
1756
1757    fn with_section<T>(&self, sid: u64, f: impl FnOnce(&mut Section<R>) -> T) -> Option<T> {
1758        self.st.borrow_mut().sections.iter_mut().find(|s| s.sid == sid).map(f)
1759    }
1760
1761    /// FRAME-17: whether `name` of the live version is here to mount: its
1762    /// files, or its module (a name the manifest lacks is, to be refused).
1763    pub fn here(&self, name: &str) -> bool {
1764        let st = self.st.borrow();
1765        match st.manifest.components.get(name) {
1766            None => true,
1767            Some(e) if e.is_rhx() => st.files.version(&st.version, name).is_some(),
1768            Some(_) => st.modules.contains_key(&(st.version.clone(), name.to_string())),
1769        }
1770    }
1771
1772    /// FRAME-17: whether `name` of the live version is here to mount (its
1773    /// files, or its module); when it is not, it is asked for
1774    /// ([`Self::needs`]).
1775    pub fn ensure(&self, name: &str) -> bool {
1776        let here = self.here(name);
1777        let mut st = self.st.borrow_mut();
1778        let need = (st.version.clone(), name.to_string());
1779        if !here && !st.needs.contains(&need) {
1780            st.needs.push(need);
1781        }
1782        here
1783    }
1784
1785    /// The instance filling `layout`'s section `slot`.
1786    pub fn section(&self, layout: &str, slot: &str) -> Option<MountId> {
1787        self.st.borrow().sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance)
1788    }
1789
1790    /// The sections drawn: `(layout, slot)` each.
1791    pub fn sections(&self) -> Vec<(String, String)> {
1792        self.st.borrow().sections.iter().map(|s| (s.layout.clone(), s.slot.clone())).collect()
1793    }
1794
1795    /// The section menu for `layout`'s `slot`, given every stored version
1796    /// (newest first) with its manifest's entry for the section's component.
1797    pub fn menu(&self, layout: &str, slot: &str, versions: &[(String, Option<ComponentEntry>)]) -> Menu {
1798        let st = self.st.borrow();
1799        let drawn = st.sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance).and_then(|id| st.instances.get(&id));
1800        let component = drawn
1801            .map(|i| i.name.clone())
1802            .or_else(|| st.manifest.slots.get(layout).and_then(|m| m.get(slot)).cloned())
1803            .unwrap_or_default();
1804        let live = st.manifest.components.get(&component).map(ComponentEntry::hashes);
1805        let versions = versions
1806            .iter()
1807            .filter(|(v, _)| *v != st.version)
1808            .filter_map(|(v, e)| {
1809                let e = e.as_ref()?;
1810                (Some(e.hashes()) != live).then(|| v.clone())
1811            })
1812            .collect();
1813        Menu { component, components: st.manifest.components.keys().cloned().collect(), versions }
1814    }
1815
1816    /// Every instance mounted: `(id, name)`.
1817    pub fn instances(&self) -> Vec<(MountId, String)> {
1818        self.st.borrow().instances.iter().map(|(id, i)| (*id, i.name.clone())).collect()
1819    }
1820
1821    /// Instance `id`'s element.
1822    pub fn element_of(&self, id: MountId) -> R::Node {
1823        self.st.borrow().instances[&id].element.clone()
1824    }
1825
1826    /// Instance `id`'s props.
1827    pub fn props_of(&self, id: MountId) -> Map<String, Value> {
1828        self.st.borrow().instances[&id].props.clone()
1829    }
1830
1831    /// Instance `id`'s state now (a module's: none).
1832    pub fn state_of(&self, id: MountId) -> Map<String, Value> {
1833        self.st.borrow().instances[&id].state().unwrap_or_default()
1834    }
1835
1836    /// Instance `id`'s drawn version: `(version, tree hash, handlers hash)`
1837    /// — a module's `(version, module hash, "")`.
1838    pub fn drawn_from(&self, id: MountId) -> (String, String, String) {
1839        let st = self.st.borrow();
1840        let i = &st.instances[&id];
1841        let (a, b) = i.hashes();
1842        (i.version.clone(), a, b)
1843    }
1844
1845    /// FRAME-12: the name instance `id` draws, while it is mounted.
1846    pub fn name_of(&self, id: MountId) -> Option<String> {
1847        self.st.borrow().instances.get(&id).map(|i| i.name.clone())
1848    }
1849
1850    /// What the engine said on the console, in order.
1851    pub fn console(&self) -> Vec<String> {
1852        self.st.borrow().console.clone()
1853    }
1854}
1855
1856/// How many instances' elements hold `e`.
1857fn around_count<R: Renderer>(r: &R, st: &St<R>, e: &R::Node) -> usize {
1858    st.instances.values().filter(|i| r.contains(&i.element, e)).count()
1859}
1860
1861/// FRAME-18: a mark's slot (its `data-slot`) and its props (its other
1862/// `data-*` attributes, `data-layout` aside, the `data-` taken off).
1863/// FRAME-29: and its binding — `data-component`, with `data-version` when
1864/// it names one — neither of them a prop.
1865/// STUDIO-6: what a mark never hands its component as a prop — the
1866/// section's own names and the engine's (`data-failed` and `data-css` on a
1867/// component's element, `data-refused` in its menu): one list, which
1868/// CONTRACT.md's "A bound mark" names. (An unbound mark's `data-version`
1869/// stays its prop, FRAME-18: a version binds only beside a component.)
1870// FRAME-50: `plexus-held` is the boot's hold (swap/turns.rs), never a prop.
1871pub const MARK_NAMES: [&str; 8] = ["slot", "component", "version", "layout", "failed", "css", "refused", "plexus-held"];
1872
1873fn mark_of<R: Renderer>(r: &R, mark: &R::Node) -> (String, Option<Binding>, Map<String, Value>) {
1874    let mut slot = String::new();
1875    let (mut component, mut version) = (None, None);
1876    let mut props = Map::new();
1877    for (k, v) in r.attrs(mark) {
1878        match k.as_str() {
1879            "data-slot" => slot = v,
1880            "data-component" => component = Some(v),
1881            "data-version" => version = Some(v),
1882            "data-layout" => {}
1883            _ => {
1884                if let Some(name) = k.strip_prefix("data-").filter(|n| !MARK_NAMES.contains(n)) {
1885                    props.insert(name.to_string(), Value::String(v));
1886                }
1887            }
1888        }
1889    }
1890    // `data-version` binds only beside `data-component`; on an unbound
1891    // mark it is a prop like any (FRAME-18).
1892    let bound = match component.filter(|c| !c.is_empty()) {
1893        Some(c) => Some((c, version.filter(|v| !v.is_empty()))),
1894        None => {
1895            if let Some(v) = version {
1896                props.insert("version".into(), Value::String(v));
1897            }
1898            None
1899        }
1900    };
1901    (slot, bound, props)
1902}
1903
1904#[cfg(test)]
1905mod tests;