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 live(&self, spec: &LiveSpec) -> Reader {
655        self.cache.acquire(spec)
656    }
657    fn follow(&self, spec: ModuleSpec) -> ModuleLive {
658        self.cache.follow_module(spec)
659    }
660    fn navigate(&self, route: &str) {
661        let f = self.navigate.borrow().clone();
662        if let Some(f) = f {
663            f(route);
664        }
665    }
666    fn live_version(&self) -> String {
667        self.version()
668    }
669    fn bound(&self, layout: &str, slot: &str) -> Option<String> {
670        let st = self.st.borrow();
671        st.sections.iter().filter(|s| s.layout == layout && s.slot == slot).find_map(|s| s.bound.as_ref()).map(|(c, _)| c.clone())
672    }
673}
674
675impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
676    pub fn new(rt: &Runtime, renderer: R, wire: W, clock: C) -> Rc<Self> {
677        let cache = LiveCache::new(rt, wire.clone(), clock);
678        let bus = Bus::new(rt);
679        let app = Rc::new_cyclic(|me| Self {
680            rt: rt.clone(),
681            renderer,
682            wire,
683            cache,
684            bus: bus.clone(),
685            st: RefCell::new(St {
686                version: String::new(),
687                manifest: Manifest::default(),
688                files: Files::default(),
689                modules: BTreeMap::new(),
690                needs: Vec::new(),
691                instances: BTreeMap::new(),
692                next: 0,
693                assignments: Vec::new(),
694                sections: Vec::new(),
695                console: Vec::new(),
696                warned: Default::default(),
697            }),
698            navigate: RefCell::new(None),
699            on_need: RefCell::new(None),
700            attaching: RefCell::new(Vec::new()),
701            trees: RefCell::new(BTreeMap::new()),
702            read_trees: RefCell::new(BTreeMap::new()),
703            sheets: RefCell::new(BTreeMap::new()),
704            keys_off: RefCell::new(None),
705            calls: RefCell::new(BTreeMap::new()),
706            turns: turns::Turns::default(),
707            me: me.clone(),
708        });
709        let host: Weak<dyn BusHost> = Rc::downgrade(&app) as Weak<dyn BusHost>;
710        bus.set_host(host);
711        // FRAME-36: the window's keys, heard before anything of the page.
712        let me = Rc::downgrade(&app);
713        let off = app.renderer.listen_keys(Rc::new(move |p: &crate::keys::Press| me.upgrade().is_some_and(|app| app.press(p))));
714        *app.keys_off.borrow_mut() = Some(off);
715        // FRAME-38: an open overlay follows the registry — redrawn on every
716        // change, closed when the last key goes.
717        let me = Rc::downgrade(&app);
718        bus.keys().on_change(Rc::new(move || {
719            if let Some(app) = me.upgrade() {
720                app.overlay_follows();
721            }
722        }));
723        app
724    }
725
726    /// FRAME-36: a key press — what it matches run, the first chords of a
727    /// sequence held, `?` the overlay; true when the host took it (the
728    /// browser must not have it).
729    pub fn press(&self, p: &crate::keys::Press) -> bool {
730        let keys = self.bus.keys().clone();
731        let heard = keys.press(p);
732        if let crate::keys::Heard::Overlay(open) = heard {
733            self.renderer.keys_overlay(open.then(|| keys.groups()).as_ref());
734        }
735        heard.taken()
736    }
737
738    fn overlay_follows(&self) {
739        let keys = self.bus.keys();
740        if !keys.overlay() {
741            return;
742        }
743        if keys.is_empty() {
744            keys.close_overlay();
745            self.renderer.keys_overlay(None);
746        } else {
747            self.renderer.keys_overlay(Some(&keys.groups()));
748        }
749    }
750
751    /// FRAME-12: the page's bus.
752    pub fn bus(&self) -> Bus {
753        self.bus.clone()
754    }
755
756    /// FRAME-12: version `version`'s module `name`, imported, with its
757    /// manifest entry; every section waiting on it is filled.
758    pub fn provide_module(&self, version: &str, name: &str, entry: ComponentEntry, module: Rc<dyn Module<R>>) {
759        let waiting: Vec<u64> = {
760            let mut st = self.st.borrow_mut();
761            st.modules.insert((version.into(), name.into()), (module, entry));
762            st.needs.retain(|(v, n)| !(v == version && n == name));
763            st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| v == version && n == name)).map(|s| s.sid).collect()
764        };
765        for sid in waiting {
766            self.fill(sid);
767        }
768    }
769
770    /// The `live` subscriptions (the page sweeps and reconnects them).
771    pub fn cache(&self) -> &Rc<LiveCache<W, C>> {
772        &self.cache
773    }
774
775    /// Where a handler's `navigate` goes.
776    pub fn set_navigate(&self, f: Rc<dyn Fn(&str)>) {
777        *self.navigate.borrow_mut() = Some(f);
778    }
779
780    /// FRAME-29: what a walk the page did not start (a module's own DOM
781    /// changing) calls when it left something to fetch.
782    pub fn set_on_need(&self, f: Rc<dyn Fn()>) {
783        *self.on_need.borrow_mut() = Some(f);
784    }
785
786    /// The live version: its hash and manifest. Mounting needs its
787    /// components' files ([`Self::provide`]).
788    pub fn load(&self, version: &str, manifest: Manifest) {
789        let mut st = self.st.borrow_mut();
790        st.version = version.into();
791        st.manifest = manifest;
792    }
793
794    /// The live version's hash.
795    pub fn version(&self) -> String {
796        self.st.borrow().version.clone()
797    }
798
799    /// The live version's manifest.
800    pub fn manifest(&self) -> Manifest {
801        self.st.borrow().manifest.clone()
802    }
803
804    /// Files fetched: kept; every section waiting on them is filled.
805    pub fn provide(&self, files: &Files) {
806        let waiting: Vec<u64> = {
807            let mut st = self.st.borrow_mut();
808            st.files.extend(files);
809            let have = st.files.clone();
810            st.needs.retain(|(v, n)| have.version(v, n).is_none());
811            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()
812        };
813        for sid in waiting {
814            self.fill(sid);
815        }
816    }
817
818    /// What the engine asks to be fetched: `(version, component)`, each once.
819    pub fn needs(&self) -> Vec<(String, String)> {
820        self.st.borrow().needs.clone()
821    }
822
823    fn say(&self, line: &str) {
824        #[cfg(feature = "dom")]
825        web_sys::console::warn_1(&line.into());
826        self.st.borrow_mut().console.push(line.to_string());
827    }
828
829    /// `name` of `version`, checked against what the live manifest names
830    /// (for the live version), its handlers compiled — or its module, when
831    /// it is one.
832    fn prepare(&self, version: &str, name: &str) -> Result<Prepared<R>, SwapError> {
833        let need = |st: &mut St<R>| {
834            let need = (version.to_string(), name.to_string());
835            if !st.needs.contains(&need) {
836                st.needs.push(need);
837            }
838            Err(SwapError::Missing(version.into(), name.into()))
839        };
840        let (files, entry) = {
841            let mut st = self.st.borrow_mut();
842            let entry = (version == st.version).then(|| st.manifest.components.get(name).cloned());
843            if let Some(None) = entry {
844                return Err(SwapError::Unknown(name.into()));
845            }
846            let entry = entry.flatten();
847            let module = st.modules.get(&(version.to_string(), name.to_string())).cloned();
848            match (&entry, module) {
849                // A module of the live version: the one its manifest names.
850                (Some(e), Some((module, got))) if !e.is_rhx() => {
851                    if got.module != e.module {
852                        return Err(SwapError::Failed { component: name.into(), message: "its module is not the one the manifest names (their hashes differ)".into() });
853                    }
854                    return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: e.module.clone(), css: e.css.clone(), uses: e.uses.clone(), module });
855                }
856                (Some(e), None) if !e.is_rhx() => return need(&mut st),
857                // Another version's module.
858                (None, Some((module, got))) if st.files.version(version, name).is_none() => {
859                    return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: got.module.clone(), css: got.css.clone(), uses: got.uses.clone(), module });
860                }
861                _ => {}
862            }
863            match st.files.version(version, name) {
864                Some((t, h)) => ((t.to_string(), h.to_string(), st.files.sheet(version, name)), entry),
865                None => return need(&mut st),
866            }
867        };
868        let failed = |message: String| SwapError::Failed { component: name.into(), message };
869        let (tree_hash, handlers_hash) = (sha256_hex(&files.0), sha256_hex(&files.1));
870        if let Some(e) = &entry {
871            if e.tree != tree_hash || e.handlers != handlers_hash {
872                return Err(failed("its files are not the ones the manifest names (their hashes differ)".into()));
873            }
874        }
875        let tree = self.parsed(&files.0).map_err(failed)?;
876        let slot: MemberSlot = Rc::new(RefCell::new(None));
877        let host: Rc<dyn Host> = Rc::new(AppHost(self.me.clone(), slot.clone()));
878        let folds = Folds::compile(&files.1, &tree.uses, host).map_err(|e| failed(e.to_string()))?;
879        // FRAME-17: a component's handlers compile when it is mounted.
880        crate::marks::mark(&format!("handlers-compiled:{name}"));
881        if tree.css.is_some() && files.2.is_none() {
882            self.say(&format!("{name} ({version}): its tree names a sheet, and none was fetched — drawn without it"));
883        }
884        // FRAME-30: keyed by the compiled sheet's sha256 (the manifest's
885        // `css`), so a sheet compiled anew is a sheet anew.
886        let css = files.2.filter(|_| tree.css.is_some()).map(|text| (format!("{name}@{}", sha256_hex(&text)), text));
887        Ok(Prepared::Rhx { version: version.into(), tree, folds: Rc::new(folds), tree_hash, handlers_hash, slot, css })
888    }
889
890    /// Draws `p` into `element` as instance `id`: an rhx tree with its
891    /// state (`state`, else its initial), its `live` readers and the topics
892    /// it hears; or a module, mounted.
893    fn attach(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
894        // FRAME-29: what is mounting now, outermost first — every section
895        // filled while it mounts is inside it (see [`Self::cycle`]).
896        let name = match &p {
897            Prepared::Module { name, .. } => name.clone(),
898            Prepared::Rhx { tree, .. } => tree.name.clone(),
899        };
900        self.attaching.borrow_mut().push(name);
901        let r = self.attach_now(id, element, p, props, state, pinned);
902        self.attaching.borrow_mut().pop();
903        r
904    }
905
906    /// FRAME-30: its sheet is on the page before it is drawn (and goes again
907    /// when the draw fails); an rhx element carries its sheet's mark.
908    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> {
909        let sheet = p.sheet();
910        self.sheet_up(&sheet);
911        if let Prepared::Rhx { tree, .. } = &p {
912            if let Some(mark) = &tree.css {
913                self.renderer.set_attr(element, "data-css", mark);
914            }
915        }
916        let r = self.draw(id, element, p, props, state, pinned);
917        if r.is_err() {
918            self.sheet_down(&sheet);
919        }
920        r
921    }
922
923    /// FRAME-30: one more instance needs the sheet; the first adopts it.
924    fn sheet_up(&self, sheet: &Sheet) {
925        let Some((key, text)) = sheet else { return };
926        let first = {
927            let mut sheets = self.sheets.borrow_mut();
928            let n = sheets.entry(key.clone()).or_insert(0);
929            *n += 1;
930            *n == 1
931        };
932        if first {
933            self.renderer.sheet(key, text, true);
934        }
935    }
936
937    /// FRAME-30: one fewer; the last drops it.
938    fn sheet_down(&self, sheet: &Sheet) {
939        let Some((href, _)) = sheet else { return };
940        let last = {
941            let mut sheets = self.sheets.borrow_mut();
942            match sheets.get_mut(href) {
943                Some(n) if *n > 1 => {
944                    *n -= 1;
945                    false
946                }
947                Some(_) => {
948                    sheets.remove(href);
949                    true
950                }
951                None => false,
952            }
953        };
954        if last {
955            self.renderer.sheet(href, "", false);
956        }
957    }
958
959    /// FRAME-30: the sheets the page has adopted, by key (`<component>@<its
960    /// sheet's hash or mark>`), each with how many instances hold it.
961    pub fn sheets(&self) -> BTreeMap<String, usize> {
962        self.sheets.borrow().clone()
963    }
964
965    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> {
966        let (version, tree, folds, tree_hash, handlers_hash, slot, css) = match p {
967            Prepared::Module { version, name, hash, css, uses, module } => {
968                let member = self.bus.join(&name, &uses);
969                let mounted = module.mount(element, &props, member.clone()).map_err(|message| {
970                    member.leave();
971                    SwapError::Failed { component: name.clone(), message }
972                })?;
973                // FRAME-18: its marks watched, and walked now.
974                let me = self.me.clone();
975                let observing = self.renderer.observe(
976                    element,
977                    Rc::new(move |targets: Vec<R::Node>| {
978                        if let Some(app) = me.upgrade() {
979                            app.observed(id, &targets);
980                        }
981                    }),
982                );
983                let body = Body::Module { hash, css, uses, module, mounted: Some(mounted), observing: Some(observing) };
984                let inst = Inst { name, version, pinned, element: element.clone(), props, member, body, failed: false };
985                self.st.borrow_mut().instances.insert(id, inst);
986                self.walk(id);
987                return Ok(());
988            }
989            Prepared::Rhx { version, tree, folds, tree_hash, handlers_hash, slot, css } => (version, tree, folds, tree_hash, handlers_hash, slot, css),
990        };
991        // UI-8: a declared prop nobody passed is there, as null (`()` in an
992        // expression) — `#/` gives the layout no `filter`, `#/f/:filter` does.
993        for name in &tree.props {
994            props.entry(name.clone()).or_insert(Value::Null);
995        }
996        let state = State::new(&self.rt, state.as_ref().unwrap_or(&tree.state));
997        let mut readers = Vec::new();
998        let mut live = BTreeMap::new();
999        for (name, d) in &tree.live {
1000            // A bad fold rule is refused at mount, naming it.
1001            for rule in d.on.values() {
1002                rule.parse::<crate::live::FoldRule>().map_err(|message| SwapError::Failed { component: tree.name.clone(), message })?;
1003            }
1004            // UI-10: the params follow the scope — a state key they read
1005            // changing runs the snapshot again (after debounce_ms).
1006            let query = LiveQuery {
1007                snapshot: d.snapshot.clone(),
1008                changes: d.changes.clone(),
1009                key: d.key.clone(),
1010                on: d.on.iter().map(|(a, b)| (a.clone(), b.clone())).collect(),
1011                debounce_ms: d.debounce_ms,
1012            };
1013            // FRAME-16: `when` false holds it: nothing asked.
1014            let (pp, cp, pr, st, when) = (d.params.clone(), d.changes_params.clone(), props.clone(), state.clone(), d.when.clone());
1015            let r = self.cache.follow_held(query, move || {
1016                crate::tree::eval_when(when.as_ref(), &pr, &st).then(|| (crate::tree::eval_params(&pp, &pr, &st), crate::tree::eval_params(&cp, &pr, &st)))
1017            });
1018            live.insert(name.clone(), r.signal());
1019            readers.push(r);
1020        }
1021        let me = self.me.clone();
1022        let on_event: Rc<dyn Fn(&str, Value)> = Rc::new(move |handler: &str, ev: Value| {
1023            if let Some(app) = me.upgrade() {
1024                if let Err(e) = app.dispatch(id, handler, ev) {
1025                    app.say(&e.to_string());
1026                }
1027            }
1028        });
1029        // FRAME-12: its place on the bus — the folds' `emit`, and a fold
1030        // per topic it hears. FRAME-36: joined before its tree is drawn, so
1031        // its keys register before those of the components inside it: the
1032        // deeper, registered later, hears a shared chord first.
1033        let member = self.bus.join(&tree.name, &tree.uses);
1034        *slot.borrow_mut() = Some((member.clone(), id));
1035        let keys = member.keys(
1036            tree.keys
1037                .iter()
1038                .map(|d| {
1039                    let (me, to) = (self.me.clone(), d.to.clone());
1040                    let run: crate::keys::KeyRun = Rc::new(move |ev: Value| {
1041                        if let Some(app) = me.upgrade() {
1042                            if let Err(e) = app.dispatch(id, &to, ev) {
1043                                app.say(&e.to_string());
1044                            }
1045                        }
1046                    });
1047                    (d.clone(), run)
1048                })
1049                .collect(),
1050        );
1051        let scope = Scope { props: props.clone(), state: state.clone(), live: live.clone(), on_event };
1052        let kids: Rc<dyn Children<R>> = Rc::new(Kids(self.me.clone(), pinned.then(|| version.clone()), tree.name.clone()));
1053        let mounted = crate::tree::mount(&self.rt, &self.renderer, &tree, scope, element, kids).map_err(|e| {
1054            member.leave();
1055            SwapError::Failed { component: tree.name.clone(), message: e.to_string() }
1056        })?;
1057        // FRAME-17: an answer that came before its component (asked at
1058        // boot) is drawn by the mount itself.
1059        for (d, r) in tree.live.values().zip(&readers) {
1060            let Some(at) = r.answered_at().filter(|_| r.live().status == crate::live::Status::Live && !r.live().rows.is_empty()) else { continue };
1061            crate::marks::once_at("first-answer", at);
1062            crate::marks::once("first-row");
1063            crate::marks::once_at(&format!("answered:{}", d.snapshot), at);
1064            crate::marks::once(&format!("drawn:{}", d.snapshot));
1065        }
1066        let listening = tree
1067            .bus
1068            .iter()
1069            .map(|(topic, fold)| {
1070                let (me, fold, topic2) = (self.me.clone(), fold.clone(), topic.clone());
1071                member.on(topic, move |data: &Value| {
1072                    if let Some(app) = me.upgrade() {
1073                        app.dispatch_bus(id, &fold, &topic2, data);
1074                    }
1075                })
1076            })
1077            .collect();
1078        let inst = Inst {
1079            name: tree.name.clone(),
1080            version,
1081            pinned,
1082            element: element.clone(),
1083            props,
1084            member,
1085            body: Body::Rhx { tree_hash, handlers_hash, state, live, readers, folds, tree, mounted: Some(mounted), slot, css, _listening: listening, _keys: keys },
1086            failed: false,
1087        };
1088        self.st.borrow_mut().instances.insert(id, inst);
1089        Ok(())
1090    }
1091
1092    fn next_id(&self) -> MountId {
1093        let mut st = self.st.borrow_mut();
1094        st.next += 1;
1095        MountId(st.next)
1096    }
1097
1098    /// An instance of `name` of `version` into `element`; on a failure the
1099    /// element carries `data-failed`.
1100    fn instantiate(&self, element: &R::Node, name: &str, version: &str, pinned: bool, props: Map<String, Value>) -> Result<MountId, SwapError> {
1101        let p = match self.prepare(version, name) {
1102            Ok(p) => p,
1103            Err(e) => {
1104                if !matches!(e, SwapError::Missing(..)) {
1105                    self.renderer.set_attr(element, "data-failed", version);
1106                }
1107                return Err(e);
1108            }
1109        };
1110        let id = self.next_id();
1111        self.attach(id, element, p, props, None, pinned).inspect_err(|_| self.renderer.set_attr(element, "data-failed", version))?;
1112        Ok(id)
1113    }
1114
1115    /// Mounts `name` of the live version into a new element (named for it)
1116    /// appended to `parent`. A component that fails is drawn as failed (its
1117    /// element carries `data-failed`, the version) and the console says why.
1118    pub fn mount(&self, parent: &R::Node, name: &str, props: Map<String, Value>) -> Result<MountId, SwapError> {
1119        let el = self.renderer.create_element(name);
1120        let version = self.version();
1121        let r = self.instantiate(&el, name, &version, false, props);
1122        self.renderer.insert(parent, &el, None);
1123        r.inspect_err(|e| self.say(&format!("{name} ({version}): {e}")))
1124    }
1125
1126    /// Takes instance `id` out: its tree or module, its readers, its place
1127    /// on the bus, the instances in it.
1128    pub fn unmount(&self, id: MountId) {
1129        // FRAME-37: the calls it waits on are closed — their answers fold
1130        // nowhere.
1131        let calls = self.calls.borrow_mut().remove(&id).unwrap_or_default();
1132        for call in calls {
1133            self.wire.close(call);
1134        }
1135        let inst = self.st.borrow_mut().instances.remove(&id);
1136        if let Some(inst) = inst {
1137            self.drop_sections_of(id);
1138            let sheet = inst.prepared().sheet();
1139            inst.teardown();
1140            self.sheet_down(&sheet);
1141        }
1142    }
1143
1144    /// FRAME-12: instance `id` with new props — a route to the component
1145    /// already drawn. A module hears `update(props)`; an rhx component (its
1146    /// props are constants in its scope) is drawn again into its element
1147    /// from its initial state, as a new mount of it was.
1148    pub fn update(&self, id: MountId, props: Map<String, Value>) -> Result<(), SwapError> {
1149        let module = {
1150            let mut st = self.st.borrow_mut();
1151            let Some(inst) = st.instances.get_mut(&id) else { return Err(SwapError::Unknown(format!("instance {}", id.0))) };
1152            inst.props = props.clone();
1153            match &mut inst.body {
1154                Body::Module { mounted, .. } => Some(mounted.take()),
1155                Body::Rhx { .. } => None,
1156            }
1157        };
1158        match module {
1159            Some(mounted) => {
1160                // Called with no borrow held: the module may speak on the bus.
1161                let mut mounted = mounted;
1162                if let Some(m) = mounted.as_mut() {
1163                    m.update(&props);
1164                }
1165                if let Some(Inst { body: Body::Module { mounted: slot, .. }, .. }) = self.st.borrow_mut().instances.get_mut(&id) {
1166                    *slot = mounted;
1167                }
1168                // FRAME-18: what the new props drew, walked.
1169                self.walk(id);
1170                Ok(())
1171            }
1172            None => {
1173                let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
1174                let (p, element, pinned) = (inst.prepared(), inst.element.clone(), inst.pinned);
1175                let held = p.sheet();
1176                inst.teardown();
1177                let r = self.attach(id, &element, p, props, None, pinned);
1178                self.sheet_down(&held);
1179                r
1180            }
1181        }
1182    }
1183
1184    fn unmount_at(&self, at: &R::Node) {
1185        let ids: Vec<MountId> = self.st.borrow().instances.iter().filter(|(_, i)| &i.element == at).map(|(id, _)| *id).collect();
1186        for id in ids {
1187            self.unmount(id);
1188        }
1189        let gone: Vec<Option<MountId>> = {
1190            let mut st = self.st.borrow_mut();
1191            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| &s.div == at);
1192            st.sections = keep;
1193            out.into_iter().map(|s| s.instance).collect()
1194        };
1195        for id in gone.into_iter().flatten() {
1196            self.unmount(id);
1197        }
1198    }
1199
1200    /// Runs `handler` of instance `id` on `event`: its state replaced. The
1201    /// bus is held while it runs: what it emits is heard once it returned.
1202    pub fn dispatch(&self, id: MountId, handler: &str, event: Value) -> Result<(), FoldError> {
1203        let _hold = self.bus.hold();
1204        let (folds, state, props, live) = {
1205            let st = self.st.borrow();
1206            let i = st.instances.get(&id).ok_or_else(|| FoldError::NoHandler(handler.into()))?;
1207            match &i.body {
1208                Body::Rhx { folds, state, live, .. } => (folds.clone(), state.clone(), i.props.clone(), live.clone()),
1209                Body::Module { .. } => return Err(FoldError::NoHandler(handler.into())),
1210            }
1211        };
1212        let rows: Map<String, Value> = live.iter().map(|(k, s)| (k.clone(), s.peek().get("rows").cloned().unwrap_or(Value::Null))).collect();
1213        let next = folds.run(handler, &state.snapshot(), &event, &props, &rows)?;
1214        state.replace(&next);
1215        Ok(())
1216    }
1217
1218    /// FRAME-37: `call` of instance `id` ended: no longer kept to close.
1219    fn forget_call(&self, id: MountId, call: CallId) {
1220        let mut calls = self.calls.borrow_mut();
1221        if let Some(list) = calls.get_mut(&id) {
1222            list.retain(|c| *c != call);
1223            if list.is_empty() {
1224                calls.remove(&id);
1225            }
1226        }
1227    }
1228
1229    /// FRAME-37: how many calls instance `id` waits on (tests).
1230    pub fn calls_of(&self, id: MountId) -> usize {
1231        self.calls.borrow().get(&id).map_or(0, Vec::len)
1232    }
1233
1234    /// FRAME-37: a call's answer, folded once into instance `id` by `fold`
1235    /// with `ev = { method, params, ok, events, message }`. An instance gone
1236    /// meanwhile (unmounted, its section emptied) hears nothing.
1237    fn answered(&self, id: MountId, fold: &str, method: &str, params: &Value, answer: Answer) {
1238        if !self.st.borrow().instances.contains_key(&id) {
1239            return;
1240        }
1241        let mut ev = answer.to_value();
1242        ev["method"] = Value::String(method.into());
1243        ev["params"] = params.clone();
1244        if let Err(e) = self.dispatch(id, fold, ev) {
1245            self.say(&e.to_string());
1246        }
1247    }
1248
1249    /// FRAME-12: `topic` heard on the bus — the fold its tree names, with
1250    /// `ev.bus = { topic, data }`.
1251    fn dispatch_bus(&self, id: MountId, fold: &str, topic: &str, data: &Value) {
1252        let ev = serde_json::json!({ "bus": { "topic": topic, "data": data } });
1253        if let Err(e) = self.dispatch(id, fold, ev) {
1254            self.say(&e.to_string());
1255        }
1256    }
1257
1258    /// A new live version: remounts exactly the instances drawn from the
1259    /// live version whose hashes changed; the files of the changed
1260    /// components must be provided first.
1261    pub fn swap(&self, version: &str, manifest: Manifest) -> SwapReport {
1262        let old = {
1263            let mut st = self.st.borrow_mut();
1264            let old = std::mem::replace(&mut st.version, version.into());
1265            let before = std::mem::replace(&mut st.manifest, manifest.clone());
1266            // STUDIO-9: a component the swap did not change is the same
1267            // files under the new version — kept under it now, so a changed
1268            // component that places an unchanged one draws it at once (the
1269            // page fetches only what changed).
1270            let same: Vec<String> = manifest.components.iter().filter(|(n, e)| before.components.get(*n) == Some(*e)).map(|(n, _)| n.clone()).collect();
1271            for name in same {
1272                if st.files.version(version, &name).is_none() {
1273                    st.files.share(&old, version, &name);
1274                }
1275                let key = (version.to_string(), name.clone());
1276                if !st.modules.contains_key(&key) {
1277                    if let Some(m) = st.modules.get(&(old.clone(), name.clone())).cloned() {
1278                        st.modules.insert(key, m);
1279                    }
1280                }
1281            }
1282            let St { files, modules, needs, .. } = &mut *st;
1283            needs.retain(|(v, n)| files.version(v, n).is_none() && !modules.contains_key(&(v.clone(), n.clone())));
1284            old
1285        };
1286        let candidates: Vec<(MountId, String, (String, String), bool)> = self
1287            .st
1288            .borrow()
1289            .instances
1290            .iter()
1291            .filter(|(_, i)| !i.pinned)
1292            .map(|(id, i)| (*id, i.name.clone(), i.hashes(), matches!(i.body, Body::Rhx { .. })))
1293            .collect();
1294        let mut report = SwapReport::default();
1295        for (id, name, hashes, was_rhx) in candidates {
1296            if !self.st.borrow().instances.contains_key(&id) {
1297                continue;
1298            }
1299            let Some(entry) = manifest.components.get(&name) else {
1300                self.fail(id, version, &old, &name, "not in the new version".into(), &mut report);
1301                continue;
1302            };
1303            if entry.hashes() == hashes {
1304                continue;
1305            }
1306            let p = match self.prepare(version, &name) {
1307                Ok(p) => p,
1308                Err(e) => {
1309                    self.fail(id, version, &old, &name, e.to_string(), &mut report);
1310                    continue;
1311                }
1312            };
1313            let r = if was_rhx && matches!(p, Prepared::Rhx { .. }) { self.remount(id, p) } else { self.replace(id, p) };
1314            match r {
1315                Ok(()) => report.remounted.push(id),
1316                Err(e) => self.fail(id, version, &old, &name, e.to_string(), &mut report),
1317            }
1318        }
1319        // A section whose default moved to another component follows it.
1320        let refill: Vec<u64> = {
1321            let st = self.st.borrow();
1322            st.sections
1323                .iter()
1324                .filter(|s| s.bound.is_none() && !st.assignments.iter().any(|a| a.layout == s.layout && a.slot == s.slot))
1325                .filter(|s| {
1326                    let default = st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot));
1327                    let drawn = s.instance.and_then(|id| st.instances.get(&id)).map(|i| &i.name);
1328                    default != drawn
1329                })
1330                .map(|s| s.sid)
1331                .collect()
1332        };
1333        for sid in refill {
1334            self.fill(sid);
1335        }
1336        report
1337    }
1338
1339    fn fail(&self, id: MountId, version: &str, old: &str, name: &str, why: String, report: &mut SwapReport) {
1340        let drawn = {
1341            let mut st = self.st.borrow_mut();
1342            st.instances.get_mut(&id).map(|i| {
1343                i.failed = true;
1344                (i.element.clone(), i.version.clone())
1345            })
1346        };
1347        let drawn_version = match drawn {
1348            Some((element, v)) => {
1349                self.renderer.set_attr(&element, "data-failed", version);
1350                v
1351            }
1352            None => old.to_string(),
1353        };
1354        self.say(&format!("{name}: {version} failed to mount ({why}); keeping its last good version {drawn_version}"));
1355        report.failed.push((id, why));
1356    }
1357
1358    /// FRAME-12: instance `id` replaced by `p` in its element — the old one
1359    /// destroyed first, then `p` mounted with the same props; when that
1360    /// fails, what was drawn is mounted again (its state too) and the
1361    /// failure answered.
1362    fn replace(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
1363        let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
1364        let (again, state, element, props, pinned, was_failed) = (inst.prepared(), inst.state(), inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
1365        // FRAME-30: the old sheet is held until the new one is adopted.
1366        let held = again.sheet();
1367        self.drop_sections_of(id);
1368        inst.teardown();
1369        let r = self.replace_with(id, &element, p, again, props, state, pinned, was_failed);
1370        self.sheet_down(&held);
1371        r
1372    }
1373
1374    #[allow(clippy::too_many_arguments)]
1375    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> {
1376        let element = element.clone();
1377        match self.attach(id, &element, p, props.clone(), None, pinned) {
1378            Ok(()) => {
1379                if was_failed {
1380                    self.renderer.set_attr(&element, "data-failed", "");
1381                }
1382                Ok(())
1383            }
1384            Err(e) => {
1385                if let Err(again) = self.attach(id, &element, again, props, state, pinned) {
1386                    self.say(&format!("its last good version did not mount again either: {again}"));
1387                }
1388                Err(e)
1389            }
1390        }
1391    }
1392
1393    /// Instance `id` again from `p`, into its element, its props kept and
1394    /// its state too when the shape is the same.
1395    fn remount(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
1396        let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
1397        let state = match (&inst.body, &p) {
1398            (Body::Rhx { state, .. }, Prepared::Rhx { tree, .. }) => {
1399                let shape: Vec<String> = tree.state.keys().cloned().collect();
1400                (state.shape() == shape).then(|| state.snapshot())
1401            }
1402            _ => None,
1403        };
1404        let (element, props, pinned, was_failed) = (inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
1405        let held = inst.prepared().sheet();
1406        self.drop_sections_of(id);
1407        inst.teardown();
1408        let r = self.attach(id, &element, p, props, state, pinned);
1409        self.sheet_down(&held);
1410        if r.is_ok() && was_failed {
1411            self.renderer.set_attr(&element, "data-failed", "");
1412        }
1413        r
1414    }
1415
1416    /// The sections' assignments (`ui.slots.list`); a section with none
1417    /// takes `manifest.slots`' default.
1418    pub fn set_assignments(&self, assignments: Vec<Assignment>) {
1419        self.warn_bound(&assignments);
1420        let changed: Vec<u64> = {
1421            let mut st = self.st.borrow_mut();
1422            let before = std::mem::replace(&mut st.assignments, assignments);
1423            let find = |list: &[Assignment], l: &str, s: &str| list.iter().find(|a| a.layout == l && a.slot == s).cloned();
1424            st.sections
1425                .iter()
1426                .filter(|s| s.bound.is_none() && find(&before, &s.layout, &s.slot) != find(&st.assignments, &s.layout, &s.slot))
1427                .map(|s| s.sid)
1428                .collect()
1429        };
1430        for sid in changed {
1431            self.fill(sid);
1432        }
1433    }
1434
1435    /// `slot_changed` on `ui.watch`: that section remounts with its props,
1436    /// nothing else.
1437    pub fn slot_changed(&self, change: Assignment) {
1438        self.warn_bound(std::slice::from_ref(&change));
1439        let idx = {
1440            let mut st = self.st.borrow_mut();
1441            st.assignments.retain(|a| !(a.layout == change.layout && a.slot == change.slot));
1442            st.assignments.push(change.clone());
1443            st.sections.iter().filter(|s| s.bound.is_none() && s.layout == change.layout && s.slot == change.slot).map(|s| s.sid).collect::<Vec<_>>()
1444        };
1445        for sid in idx {
1446            self.fill(sid);
1447        }
1448    }
1449
1450    /// `slot_changed` back to the default (`ui.slots.clear`).
1451    pub fn slot_reset(&self, layout: &str, slot: &str) {
1452        let idx = {
1453            let mut st = self.st.borrow_mut();
1454            st.assignments.retain(|a| !(a.layout == layout && a.slot == slot));
1455            st.sections.iter().filter(|s| s.bound.is_none() && s.layout == layout && s.slot == slot).map(|s| s.sid).collect::<Vec<_>>()
1456        };
1457        for sid in idx {
1458            self.fill(sid);
1459        }
1460    }
1461
1462    /// Section `i` drawn again: its binding (FRAME-29), else its
1463    /// assignment, else its default. Its files
1464    /// not fetched: it waits ([`Self::needs`]). FRAME-12: the new component
1465    /// is mounted before what the section had is taken out; when it fails,
1466    /// what it had stays drawn, marked `data-failed`.
1467    fn fill(&self, sid: u64) {
1468        // FRAME-50: filled now, so its turn, if it waits one, finds it done.
1469        self.with_section(sid, |s| s.queued = false);
1470        let (div, props, old, want, inline) = {
1471            let st = self.st.borrow();
1472            let Some(s) = st.sections.iter().find(|s| s.sid == sid) else { return };
1473            let want = match (&s.bound, st.assignments.iter().find(|a| a.layout == s.layout && a.slot == s.slot)) {
1474                (Some((c, v)), _) => {
1475                    // STUDIO-11: a module's mark naming no version, in a
1476                    // module pinned to one (a studio's frame), is that
1477                    // version's — a child is its pinned parent's version's.
1478                    let parent = s.owner.and_then(|o| st.instances.get(&o)).filter(|i| i.pinned).map(|i| i.version.clone());
1479                    let v = v.clone().or(parent);
1480                    Some((c.clone(), v.clone().unwrap_or_else(|| st.version.clone()), v.is_some()))
1481                }
1482                (None, Some(a)) => Some((a.component.clone(), a.version.clone(), true)),
1483                (None, None) => st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot)).map(|c| (c.clone(), st.version.clone(), false)),
1484            };
1485            let old = s.instance.and_then(|id| st.instances.get(&id).map(|inst| (id, inst.element.clone(), inst.version.clone())));
1486            (s.div.clone(), s.props.clone(), old, want, s.inline)
1487        };
1488        let Some((component, version, pinned)) = want else {
1489            if let Some((id, el, _)) = old {
1490                self.unmount(id);
1491                self.renderer.remove(&div, &el);
1492            }
1493            self.with_section(sid, |s| s.instance = None);
1494            return;
1495        };
1496        // FRAME-29: a component never fills a section inside an instance of
1497        // itself — a module binding itself, A binding B binding A, a layout
1498        // assigned into its own section would mount without end.
1499        if let Some(chain) = self.cycle(&div, &component) {
1500            self.with_section(sid, |s| s.waiting = None);
1501            self.say(&format!("cycle: {chain} → {component}; the section is left empty"));
1502            return;
1503        }
1504        let p = match self.prepare(&version, &component) {
1505            Ok(p) => p,
1506            Err(SwapError::Missing(..)) => {
1507                self.with_section(sid, |s| s.waiting = Some((version, component, pinned)));
1508                return;
1509            }
1510            Err(e) => {
1511                self.with_section(sid, |s| s.waiting = None);
1512                if let Some((_, el, _)) = &old {
1513                    self.renderer.set_attr(el, "data-failed", &version);
1514                }
1515                self.say(&format!("{component} ({version}): {e}; the section keeps what it shows"));
1516                return;
1517            }
1518        };
1519        // STUDIO-9: an rhx child's section mounts into the child's own
1520        // element, once (its tree says when it goes; a hot-swap remounts
1521        // the instance in place).
1522        if inline {
1523            self.with_section(sid, |s| s.waiting = None);
1524            if old.is_some() {
1525                return;
1526            }
1527            let id = self.next_id();
1528            match self.attach(id, &div, p, props, None, pinned) {
1529                Ok(()) => {
1530                    self.with_section(sid, |s| s.instance = Some(id));
1531                }
1532                Err(e) => {
1533                    self.renderer.set_attr(&div, "data-failed", &version);
1534                    self.say(&format!("{component} ({version}): {e}"));
1535                }
1536            }
1537            return;
1538        }
1539        let el = self.renderer.create_element(&component);
1540        let id = self.next_id();
1541        let drawn_from = p.version().to_string();
1542        match self.attach(id, &el, p, props, None, pinned) {
1543            Ok(()) => {
1544                self.renderer.insert(&div, &el, None);
1545                if let Some((old_id, old_el, _)) = old {
1546                    self.unmount(old_id);
1547                    self.renderer.remove(&div, &old_el);
1548                }
1549                let slot = self.with_section(sid, |s| {
1550                    s.waiting = None;
1551                    s.instance = Some(id);
1552                    s.slot.clone()
1553                });
1554                if let Some(slot) = slot {
1555                    crate::marks::once(&format!("section-mounted:{slot}"));
1556                }
1557            }
1558            Err(e) => {
1559                self.with_section(sid, |s| s.waiting = None);
1560                match old {
1561                    Some((old_id, old_el, old_version)) => {
1562                        self.renderer.set_attr(&old_el, "data-failed", &drawn_from);
1563                        if let Some(i) = self.st.borrow_mut().instances.get_mut(&old_id) {
1564                            i.failed = true;
1565                        }
1566                        self.say(&format!("{component}: {drawn_from} failed to mount ({e}); keeping its last good version {old_version}"));
1567                    }
1568                    None => {
1569                        self.renderer.insert(&div, &el, None);
1570                        self.renderer.set_attr(&el, "data-failed", &version);
1571                        self.with_section(sid, |s| s.instance = None);
1572                        self.say(&format!("{component} ({version}): {e}"));
1573                    }
1574                }
1575            }
1576        }
1577    }
1578
1579    /// FRAME-29: when `component` already draws an instance around `div`,
1580    /// the chain of names from the outermost such instance down, else none.
1581    /// Around is the DOM's holding, and past it the section each outermost
1582    /// instance fills — an instance mounts before its element is placed in
1583    /// its section, so the DOM alone does not reach the layout above it.
1584    fn cycle(&self, div: &R::Node, component: &str) -> Option<String> {
1585        let st = self.st.borrow();
1586        let mut chain: Vec<String> = Vec::new();
1587        let mut at = div.clone();
1588        for _ in 0..st.instances.len() + 1 {
1589            let mut around: Vec<(&MountId, &Inst<R>)> = st.instances.iter().filter(|(_, i)| i.element != at && self.renderer.contains(&i.element, &at)).collect();
1590            if around.is_empty() {
1591                break;
1592            }
1593            // Innermost last: the more of them hold it, the further in.
1594            around.sort_by_key(|(_, i)| around_count(&self.renderer, &st, &i.element));
1595            for (_, i) in around.iter().rev() {
1596                chain.push(i.name.clone());
1597            }
1598            let outer = *around[0].0;
1599            match st.sections.iter().find(|s| s.instance == Some(outer)) {
1600                Some(s) => at = s.div.clone(),
1601                None => break,
1602            }
1603        }
1604        chain.reverse();
1605        // What is mounting now holds `div` too: its element is not placed
1606        // (nor, for rhx, registered) until its mount returns.
1607        let outer: Vec<String> = self.attaching.borrow().iter().filter(|n| !chain.contains(n)).cloned().collect();
1608        let chain: Vec<String> = outer.into_iter().chain(chain).collect();
1609        chain.iter().any(|n| n == component).then(|| chain.join(" → "))
1610    }
1611
1612    /// FRAME-29: an assignment for a slot a mark binds is stored and does
1613    /// nothing; said once per (layout, slot).
1614    fn warn_bound(&self, assignments: &[Assignment]) {
1615        let lines: Vec<String> = {
1616            let mut st = self.st.borrow_mut();
1617            let mut lines = Vec::new();
1618            for a in assignments {
1619                let Some((c, _)) = st.sections.iter().filter(|s| s.layout == a.layout && s.slot == a.slot).find_map(|s| s.bound.clone()) else { continue };
1620                if st.warned.insert((a.layout.clone(), a.slot.clone())) {
1621                    lines.push(format!("{} · {}: assignment {}@{} stored, but the mark binds {c}; it does nothing", a.layout, a.slot, a.component, a.version));
1622                }
1623            }
1624            lines
1625        };
1626        for l in lines {
1627            self.say(&l);
1628        }
1629    }
1630
1631    /// FRAME-18: **the walk** — module instance `id`'s element searched for
1632    /// `[data-slot]` marks. A section of its whose mark is no longer in the
1633    /// element (or whose `data-slot` now names another slot) goes, and what
1634    /// filled it is destroyed — a mark moved within the element stays its
1635    /// section. A filled mark whose other `data-*` attributes changed hands
1636    /// them to what fills it as `update(props)`, never a refill. A mark
1637    /// that is no section yet, and is not inside another section within the
1638    /// element (a mark in a section is the filling component's), becomes one of the layout `id`
1639    /// draws — its slot the attribute's value, its props the mark's other
1640    /// `data-*` attributes (strings), `data-layout` written on it — and is
1641    /// filled as an rhx `<slot>` is ([`Self::fill`]). FRAME-29: a mark
1642    /// carrying `data-component` is bound to it (`data-version` too, when
1643    /// given) — neither is a prop — and a mark whose binding changed is a
1644    /// new section, as one whose slot changed.
1645    pub fn walk(&self, id: MountId) {
1646        let (target, layout) = {
1647            let st = self.st.borrow();
1648            match st.instances.get(&id) {
1649                Some(i) if matches!(i.body, Body::Module { .. }) => (i.element.clone(), i.name.clone()),
1650                _ => return,
1651            }
1652        };
1653        crate::marks::mark(&format!("walk:{layout}"));
1654        let gone: Vec<Option<MountId>> = {
1655            let mut st = self.st.borrow_mut();
1656            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| {
1657                s.owner == Some(id) && (!self.renderer.contains(&target, &s.div) || {
1658                    let (slot, bound, _) = mark_of(&self.renderer, &s.div);
1659                    slot != s.slot || bound != s.bound
1660                })
1661            });
1662            st.sections = keep;
1663            out.into_iter().map(|s| s.instance).collect()
1664        };
1665        for i in gone.into_iter().flatten() {
1666            self.unmount(i);
1667        }
1668        // The props of the marks already sections, read again.
1669        let moved: Vec<(MountId, Map<String, Value>)> = {
1670            let mut st = self.st.borrow_mut();
1671            st.sections
1672                .iter_mut()
1673                .filter(|s| s.owner == Some(id))
1674                .filter_map(|s| {
1675                    let (_, _, props) = mark_of(&self.renderer, &s.div);
1676                    if props == s.props {
1677                        return None;
1678                    }
1679                    s.props = props.clone();
1680                    s.instance.map(|i| (i, props))
1681                })
1682                .collect()
1683        };
1684        for (i, props) in moved {
1685            if let Err(e) = self.update(i, props) {
1686                self.say(&format!("{layout}: a section's props: {e}"));
1687            }
1688        }
1689        // A mark is another section's when that section is inside this
1690        // module's element and holds it — never because this module itself
1691        // fills a section of the page (SURFACE-10: its later marks are its own),
1692        // nor because that section's mark is the module's element itself (a
1693        // module filled inline, STUDIO-9: `contains` counts the element).
1694        let fresh: Vec<R::Node> = {
1695            let st = self.st.borrow();
1696            self.renderer
1697                .marks(&target)
1698                .into_iter()
1699                .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))))
1700                .collect()
1701        };
1702        for mark in fresh {
1703            let (slot, bound, props) = mark_of(&self.renderer, &mark);
1704            self.renderer.set_attr(&mark, "data-layout", &layout);
1705            let sid = self.next_id().0;
1706            let s = Section { sid, owner: Some(id), layout: layout.clone(), slot, div: mark, props, instance: None, waiting: None, bound, inline: false, queued: false };
1707            self.st.borrow_mut().sections.push(s);
1708            self.fill_soon(sid);
1709        }
1710    }
1711
1712    /// FRAME-18: the observer's batch for module instance `id`: walked
1713    /// unless every change was made inside one of its filled sections —
1714    /// under the mark, not on it (a section's own drawing, its rows, is none
1715    /// of the layout's; the mark's attributes are).
1716    pub fn observed(&self, id: MountId, targets: &[R::Node]) {
1717        let inside = {
1718            let st = self.st.borrow();
1719            let filled: Vec<&R::Node> = st.sections.iter().filter(|s| s.owner == Some(id) && s.instance.is_some()).map(|s| &s.div).collect();
1720            targets.iter().all(|t| filled.iter().any(|d| d != &t && self.renderer.contains(d, t)))
1721        };
1722        if !inside {
1723            self.walk(id);
1724            // FRAME-29: a mark drawn by the module's own state may bind a
1725            // component not fetched yet: the page is told to fetch it.
1726            self.told_needs();
1727        }
1728    }
1729
1730    /// FRAME-29, STUDIO-9: the page told to fetch what a mount left
1731    /// waiting (a mark the module's state drew, a child drawn after its
1732    /// parent's first draw: in an `{#each}` fed by `live()`, an `{#if}`).
1733    fn told_needs(&self) {
1734        let on_need = self.on_need.borrow().clone();
1735        if let Some(f) = on_need.filter(|_| !self.st.borrow().needs.is_empty()) {
1736            f();
1737        }
1738    }
1739
1740    /// FRAME-18: the sections module instance `id`'s walk found, gone with
1741    /// it — each one's instance destroyed — before it is.
1742    fn drop_sections_of(&self, id: MountId) {
1743        let gone: Vec<Option<MountId>> = {
1744            let mut st = self.st.borrow_mut();
1745            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| s.owner == Some(id));
1746            st.sections = keep;
1747            out.into_iter().map(|s| s.instance).collect()
1748        };
1749        for i in gone.into_iter().flatten() {
1750            self.unmount(i);
1751        }
1752    }
1753
1754    fn with_section<T>(&self, sid: u64, f: impl FnOnce(&mut Section<R>) -> T) -> Option<T> {
1755        self.st.borrow_mut().sections.iter_mut().find(|s| s.sid == sid).map(f)
1756    }
1757
1758    /// FRAME-17: whether `name` of the live version is here to mount: its
1759    /// files, or its module (a name the manifest lacks is, to be refused).
1760    pub fn here(&self, name: &str) -> bool {
1761        let st = self.st.borrow();
1762        match st.manifest.components.get(name) {
1763            None => true,
1764            Some(e) if e.is_rhx() => st.files.version(&st.version, name).is_some(),
1765            Some(_) => st.modules.contains_key(&(st.version.clone(), name.to_string())),
1766        }
1767    }
1768
1769    /// FRAME-17: whether `name` of the live version is here to mount (its
1770    /// files, or its module); when it is not, it is asked for
1771    /// ([`Self::needs`]).
1772    pub fn ensure(&self, name: &str) -> bool {
1773        let here = self.here(name);
1774        let mut st = self.st.borrow_mut();
1775        let need = (st.version.clone(), name.to_string());
1776        if !here && !st.needs.contains(&need) {
1777            st.needs.push(need);
1778        }
1779        here
1780    }
1781
1782    /// The instance filling `layout`'s section `slot`.
1783    pub fn section(&self, layout: &str, slot: &str) -> Option<MountId> {
1784        self.st.borrow().sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance)
1785    }
1786
1787    /// The sections drawn: `(layout, slot)` each.
1788    pub fn sections(&self) -> Vec<(String, String)> {
1789        self.st.borrow().sections.iter().map(|s| (s.layout.clone(), s.slot.clone())).collect()
1790    }
1791
1792    /// The section menu for `layout`'s `slot`, given every stored version
1793    /// (newest first) with its manifest's entry for the section's component.
1794    pub fn menu(&self, layout: &str, slot: &str, versions: &[(String, Option<ComponentEntry>)]) -> Menu {
1795        let st = self.st.borrow();
1796        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));
1797        let component = drawn
1798            .map(|i| i.name.clone())
1799            .or_else(|| st.manifest.slots.get(layout).and_then(|m| m.get(slot)).cloned())
1800            .unwrap_or_default();
1801        let live = st.manifest.components.get(&component).map(ComponentEntry::hashes);
1802        let versions = versions
1803            .iter()
1804            .filter(|(v, _)| *v != st.version)
1805            .filter_map(|(v, e)| {
1806                let e = e.as_ref()?;
1807                (Some(e.hashes()) != live).then(|| v.clone())
1808            })
1809            .collect();
1810        Menu { component, components: st.manifest.components.keys().cloned().collect(), versions }
1811    }
1812
1813    /// Every instance mounted: `(id, name)`.
1814    pub fn instances(&self) -> Vec<(MountId, String)> {
1815        self.st.borrow().instances.iter().map(|(id, i)| (*id, i.name.clone())).collect()
1816    }
1817
1818    /// Instance `id`'s element.
1819    pub fn element_of(&self, id: MountId) -> R::Node {
1820        self.st.borrow().instances[&id].element.clone()
1821    }
1822
1823    /// Instance `id`'s props.
1824    pub fn props_of(&self, id: MountId) -> Map<String, Value> {
1825        self.st.borrow().instances[&id].props.clone()
1826    }
1827
1828    /// Instance `id`'s state now (a module's: none).
1829    pub fn state_of(&self, id: MountId) -> Map<String, Value> {
1830        self.st.borrow().instances[&id].state().unwrap_or_default()
1831    }
1832
1833    /// Instance `id`'s drawn version: `(version, tree hash, handlers hash)`
1834    /// — a module's `(version, module hash, "")`.
1835    pub fn drawn_from(&self, id: MountId) -> (String, String, String) {
1836        let st = self.st.borrow();
1837        let i = &st.instances[&id];
1838        let (a, b) = i.hashes();
1839        (i.version.clone(), a, b)
1840    }
1841
1842    /// FRAME-12: the name instance `id` draws, while it is mounted.
1843    pub fn name_of(&self, id: MountId) -> Option<String> {
1844        self.st.borrow().instances.get(&id).map(|i| i.name.clone())
1845    }
1846
1847    /// What the engine said on the console, in order.
1848    pub fn console(&self) -> Vec<String> {
1849        self.st.borrow().console.clone()
1850    }
1851}
1852
1853/// How many instances' elements hold `e`.
1854fn around_count<R: Renderer>(r: &R, st: &St<R>, e: &R::Node) -> usize {
1855    st.instances.values().filter(|i| r.contains(&i.element, e)).count()
1856}
1857
1858/// FRAME-18: a mark's slot (its `data-slot`) and its props (its other
1859/// `data-*` attributes, `data-layout` aside, the `data-` taken off).
1860/// FRAME-29: and its binding — `data-component`, with `data-version` when
1861/// it names one — neither of them a prop.
1862/// STUDIO-6: what a mark never hands its component as a prop — the
1863/// section's own names and the engine's (`data-failed` and `data-css` on a
1864/// component's element, `data-refused` in its menu): one list, which
1865/// CONTRACT.md's "A bound mark" names. (An unbound mark's `data-version`
1866/// stays its prop, FRAME-18: a version binds only beside a component.)
1867// FRAME-50: `plexus-held` is the boot's hold (swap/turns.rs), never a prop.
1868pub const MARK_NAMES: [&str; 8] = ["slot", "component", "version", "layout", "failed", "css", "refused", "plexus-held"];
1869
1870fn mark_of<R: Renderer>(r: &R, mark: &R::Node) -> (String, Option<Binding>, Map<String, Value>) {
1871    let mut slot = String::new();
1872    let (mut component, mut version) = (None, None);
1873    let mut props = Map::new();
1874    for (k, v) in r.attrs(mark) {
1875        match k.as_str() {
1876            "data-slot" => slot = v,
1877            "data-component" => component = Some(v),
1878            "data-version" => version = Some(v),
1879            "data-layout" => {}
1880            _ => {
1881                if let Some(name) = k.strip_prefix("data-").filter(|n| !MARK_NAMES.contains(n)) {
1882                    props.insert(name.to_string(), Value::String(v));
1883                }
1884            }
1885        }
1886    }
1887    // `data-version` binds only beside `data-component`; on an unbound
1888    // mark it is a prop like any (FRAME-18).
1889    let bound = match component.filter(|c| !c.is_empty()) {
1890        Some(c) => Some((c, version.filter(|v| !v.is_empty()))),
1891        None => {
1892            if let Some(v) = version {
1893                props.insert("version".into(), Value::String(v));
1894            }
1895            None
1896        }
1897    };
1898    (slot, bound, props)
1899}
1900
1901#[cfg(test)]
1902mod tests;