Skip to main content

plexus_ui_engine/tree/
mod.rs

1//! UI-6: **the view tree** — UI-4's compiled `components/<name>.json`, and
2//! its interpreter over a [`Renderer`].
3//!
4//! Node kinds (the contract's): `el` (attrs each a string or `{ "expr" }`,
5//! `on` event → handler, children), `text` (a string or `{ "expr" }`),
6//! `if` / `then` / `else`, `each` (`as`, `key`, body), `component` (props),
7//! and `slot` (a section: its name and the props of what fills it).
8//!
9//! Mounting draws the tree once and makes one binding per dynamic place
10//! (an attribute, a text, an `if`, an `each`): a fold that changes a state
11//! key re-runs only the bindings that read it. An `if` and an `each` hold
12//! their place with an empty text node (their anchor) and insert before
13//! it; an `each` is keyed — a row whose key stays keeps its nodes.
14//!
15//! A `component` node draws as an element named for the component
16//! (`<ticket-row>`), filled by the engine through [`Children`]; a `slot`
17//! as a `div` carrying `data-slot` (and `data-layout`), filled the same way.
18//! FRAME-29: a `component` node naming a component the rhx runtime does not
19//! draw (another profile: [`Children::binds`]) draws as a **bound mark** — a
20//! `div` carrying `data-slot` and `data-component` (both the component's
21//! name) and `data-layout` — filled as a section bound to it
22//! ([`Children::mount_bound`]), its props the node's, as values.
23
24use crate::signals::{BindingId, Runtime, Signal};
25use serde_json::{Map, Value};
26use std::cell::RefCell;
27use std::collections::BTreeMap;
28use std::rc::Rc;
29
30pub mod expr;
31use expr::Expr;
32
33pub mod recording;
34pub use recording::{Call, Recording};
35
36#[cfg(feature = "dom")]
37pub mod dom;
38
39/// A value in the tree: a literal string, or a Rhai expression over the
40/// scope.
41#[derive(Debug, Clone, PartialEq)]
42pub enum Attr {
43    Lit(String),
44    Expr(String),
45}
46
47/// One node of a compiled tree.
48#[derive(Debug, Clone, PartialEq)]
49pub enum Node {
50    El { el: String, attrs: BTreeMap<String, Attr>, on: BTreeMap<String, String>, children: Vec<Node> },
51    Text(Attr),
52    If { cond: String, then: Vec<Node>, otherwise: Vec<Node> },
53    Each { expr: String, as_: String, key: String, body: Vec<Node> },
54    Component { name: String, props: BTreeMap<String, Attr> },
55    Slot { name: String, props: BTreeMap<String, Attr> },
56    /// UI-10: `{@html expr}` — the expression's text as HTML, through the
57    /// sanitizer ([`crate::html`]).
58    Html(String),
59}
60
61/// A `live` declaration: the snapshot method and its params, the changes
62/// method and its own params (`changes_params`), the key, and the folds by
63/// event type (`upsert:ticket`, …). A param is a JSON value or `{ "expr" }`.
64#[derive(Debug, Clone, PartialEq)]
65pub struct LiveDecl {
66    pub snapshot: String,
67    pub params: BTreeMap<String, Value>,
68    /// UI-10: none — a one-shot read.
69    pub changes: Option<String>,
70    pub changes_params: BTreeMap<String, Value>,
71    pub key: String,
72    pub on: BTreeMap<String, String>,
73    /// UI-10: how long the params must be quiet before it runs again.
74    pub debounce_ms: Option<u64>,
75    /// FRAME-16: while this is false, null, empty or 0 the collection asks
76    /// nothing — a boolean, or `{ "expr" }` read from the scope. None: always.
77    pub when: Option<Value>,
78}
79
80/// A component's compiled tree — `components/<name>.json`.
81#[derive(Debug, Clone, PartialEq)]
82pub struct ComponentTree {
83    pub name: String,
84    pub abi: String,
85    pub props: Vec<String>,
86    /// The declared state: its initial value (a map).
87    pub state: Map<String, Value>,
88    pub live: BTreeMap<String, LiveDecl>,
89    pub uses: Vec<String>,
90    /// FRAME-12: what it hears on the bus — topic → fold (`on("topic",
91    /// "fold")`); none when the tree has no `bus`.
92    pub bus: BTreeMap<String, String>,
93    /// The sha256 of `components/<name>.rhai`.
94    pub handlers: String,
95    pub tree: Vec<Node>,
96    /// FRAME-30: its sheet's mark (`components/<name>.css` scoped under
97    /// `<name>[data-css="<mark>"]`); none when it has no sheet.
98    pub css: Option<String>,
99    /// FRAME-36: its shortcuts (`keys(#{ … })`, the tree's `keys`), by
100    /// chord; none when the tree has no `keys`.
101    pub keys: Vec<crate::keys::KeyDecl>,
102}
103
104/// Why a tree did not parse or mount.
105#[derive(Debug, Clone, PartialEq)]
106pub enum TreeError {
107    /// Not the contract's schema: where, and what.
108    Malformed(String),
109    /// An expression did not compile or evaluate: the expression and why.
110    Expr { expr: String, message: String },
111}
112
113impl std::fmt::Display for TreeError {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            TreeError::Malformed(m) => write!(f, "a malformed tree: {m}"),
117            TreeError::Expr { expr, message } => write!(f, "the expression `{expr}`: {message}"),
118        }
119    }
120}
121
122fn bad(at: &str, what: &str) -> TreeError {
123    TreeError::Malformed(format!("{at}: {what}"))
124}
125
126fn attr(v: &Value, at: &str) -> Result<Attr, TreeError> {
127    match v {
128        Value::String(s) => Ok(Attr::Lit(s.clone())),
129        Value::Object(o) => match o.get("expr") {
130            Some(Value::String(e)) if o.len() == 1 => Ok(Attr::Expr(e.clone())),
131            _ => Err(bad(at, "a value is a string or { \"expr\": … }")),
132        },
133        Value::Number(_) | Value::Bool(_) => Ok(Attr::Lit(v.to_string())),
134        _ => Err(bad(at, "a value is a string or { \"expr\": … }")),
135    }
136}
137
138fn expr_of(v: Option<&Value>, at: &str) -> Result<String, TreeError> {
139    match v {
140        Some(Value::String(s)) => Ok(s.clone()),
141        Some(Value::Object(o)) => match o.get("expr") {
142            Some(Value::String(e)) => Ok(e.clone()),
143            _ => Err(bad(at, "an { \"expr\": … }")),
144        },
145        _ => Err(bad(at, "an { \"expr\": … }")),
146    }
147}
148
149fn attrs(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, Attr>, TreeError> {
150    match v {
151        None => Ok(BTreeMap::new()),
152        Some(Value::Object(o)) => o.iter().map(|(k, v)| Ok((k.clone(), attr(v, &format!("{at}.{k}"))?))).collect(),
153        Some(_) => Err(bad(at, "a map")),
154    }
155}
156
157fn strings(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, String>, TreeError> {
158    match v {
159        None => Ok(BTreeMap::new()),
160        Some(Value::Object(o)) => o
161            .iter()
162            .map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())).ok_or_else(|| bad(&format!("{at}.{k}"), "a string")))
163            .collect(),
164        Some(_) => Err(bad(at, "a map of strings")),
165    }
166}
167
168fn nodes(v: Option<&Value>, at: &str) -> Result<Vec<Node>, TreeError> {
169    match v {
170        None => Ok(Vec::new()),
171        Some(Value::Array(a)) => a.iter().enumerate().map(|(i, n)| node(n, &format!("{at}[{i}]"))).collect(),
172        Some(_) => Err(bad(at, "a list of nodes")),
173    }
174}
175
176fn node(v: &Value, at: &str) -> Result<Node, TreeError> {
177    let o = v.as_object().ok_or_else(|| bad(at, "a node is a map"))?;
178    if let Some(el) = o.get("el") {
179        let el = el.as_str().ok_or_else(|| bad(at, "el is a tag"))?;
180        return Ok(Node::El {
181            el: el.to_string(),
182            attrs: attrs(o.get("attrs"), &format!("{at}.attrs"))?,
183            on: strings(o.get("on"), &format!("{at}.on"))?,
184            children: nodes(o.get("children"), &format!("{at}.children"))?,
185        });
186    }
187    if let Some(t) = o.get("text") {
188        return Ok(Node::Text(attr(t, &format!("{at}.text"))?));
189    }
190    if o.contains_key("if") {
191        return Ok(Node::If {
192            cond: expr_of(o.get("if"), &format!("{at}.if"))?,
193            then: nodes(o.get("then"), &format!("{at}.then"))?,
194            otherwise: nodes(o.get("else"), &format!("{at}.else"))?,
195        });
196    }
197    if let Some(each) = o.get("each") {
198        let e = each.as_object().ok_or_else(|| bad(at, "each is a map"))?;
199        let s = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad(&format!("{at}.each"), &format!("each has a {k}")));
200        return Ok(Node::Each { expr: s("expr")?, as_: s("as")?, key: s("key")?, body: nodes(o.get("body"), &format!("{at}.body"))? });
201    }
202    if let Some(c) = o.get("component") {
203        let name = c.as_str().ok_or_else(|| bad(at, "component is a name"))?;
204        return Ok(Node::Component { name: name.to_string(), props: attrs(o.get("props"), &format!("{at}.props"))? });
205    }
206    if o.contains_key("html") {
207        return Ok(Node::Html(expr_of(o.get("html"), &format!("{at}.html"))?));
208    }
209    if let Some(sl) = o.get("slot") {
210        let name = sl.as_str().ok_or_else(|| bad(at, "slot is a name"))?;
211        return Ok(Node::Slot { name: name.to_string(), props: attrs(o.get("props"), &format!("{at}.props"))? });
212    }
213    Err(bad(at, "a node is el, text, if, each, component or slot"))
214}
215
216/// FRAME-36: the tree's `keys` — chord → `{ to, label?, in_inputs?, only?,
217/// in_controls? }` (FRAME-38).
218fn keys(v: Option<&Value>) -> Result<Vec<crate::keys::KeyDecl>, TreeError> {
219    let Some(v) = v else { return Ok(Vec::new()) };
220    let o = v.as_object().ok_or_else(|| bad("keys", "a map of chord → { to, label, in_inputs, only }"))?;
221    let mut out = Vec::new();
222    for (chord, e) in o {
223        let at = format!("keys.{chord}");
224        let e = e.as_object().ok_or_else(|| bad(&at, "a map"))?;
225        let to = e.get("to").and_then(Value::as_str).ok_or_else(|| bad(&at, "to is a string"))?;
226        let label = match e.get("label") {
227            None => None,
228            Some(Value::String(l)) => Some(l.clone()),
229            Some(_) => return Err(bad(&at, "label is a string")),
230        };
231        let flag = |k: &str| match e.get(k) {
232            None => Ok(false),
233            Some(Value::Bool(b)) => Ok(*b),
234            Some(_) => Err(bad(&at, &format!("{k} is true or false"))),
235        };
236        out.push(crate::keys::KeyDecl::new(chord, to, label, flag("in_inputs")?, flag("only")?).map_err(|m| bad(&at, &m))?.controls(flag("in_controls")?));
237    }
238    Ok(out)
239}
240
241fn params(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, Value>, TreeError> {
242    match v {
243        None | Some(Value::Null) => Ok(BTreeMap::new()),
244        Some(Value::Object(o)) => Ok(o.iter().map(|(k, v)| (k.clone(), v.clone())).collect()),
245        Some(_) => Err(bad(at, "params are a map")),
246    }
247}
248
249impl ComponentTree {
250    /// From `components/<name>.json`'s text; refused, naming where, when it
251    /// is not the contract's schema or an expression does not compile.
252    pub fn parse(json: &str) -> Result<Self, TreeError> {
253        let tree = Self::read(json)?;
254        tree.check()?;
255        Ok(tree)
256    }
257
258    /// FRAME-17: [`Self::parse`] without compiling its expressions — what
259    /// the boot reads of a tree (its props, state, `live`, sections and
260    /// components) before anything is mounted.
261    pub fn read(json: &str) -> Result<Self, TreeError> {
262        let v: Value = serde_json::from_str(json).map_err(|e| TreeError::Malformed(e.to_string()))?;
263        let o = v.as_object().ok_or_else(|| bad("the tree", "a map"))?;
264        let s = |k: &str| o.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad("the tree", &format!("{k} is a string")));
265        let list = |k: &str| -> Result<Vec<String>, TreeError> {
266            match o.get(k) {
267                None => Ok(Vec::new()),
268                Some(Value::Array(a)) => a.iter().map(|x| x.as_str().map(str::to_string).ok_or_else(|| bad(k, "a list of strings"))).collect(),
269                Some(_) => Err(bad(k, "a list of strings")),
270            }
271        };
272        let mut live = BTreeMap::new();
273        if let Some(l) = o.get("live") {
274            for (name, d) in l.as_object().ok_or_else(|| bad("live", "a map"))? {
275                let at = format!("live.{name}");
276                let d = d.as_object().ok_or_else(|| bad(&at, "a map"))?;
277                let ds = |k: &str| d.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad(&at, &format!("{k} is a string")));
278                live.insert(
279                    name.clone(),
280                    LiveDecl {
281                        snapshot: ds("snapshot")?,
282                        params: params(d.get("params"), &at)?,
283                        changes: d.get("changes").and_then(Value::as_str).map(str::to_string),
284                        changes_params: params(d.get("changes_params"), &at)?,
285                        key: ds("key")?,
286                        on: strings(d.get("on"), &format!("{at}.on"))?,
287                        debounce_ms: d.get("debounce_ms").and_then(Value::as_u64),
288                        when: d.get("when").cloned(),
289                    },
290                );
291            }
292        }
293        let state = match o.get("state") {
294            None => Map::new(),
295            Some(Value::Object(m)) => m.clone(),
296            Some(_) => return Err(bad("state", "a map")),
297        };
298        let tree = Self {
299            name: s("name")?,
300            abi: s("abi")?,
301            props: list("props")?,
302            state,
303            live,
304            uses: list("uses")?,
305            bus: strings(o.get("bus"), "bus")?,
306            handlers: o.get("handlers").and_then(Value::as_str).unwrap_or_default().to_string(),
307            tree: nodes(Some(o.get("tree").ok_or_else(|| bad("the tree", "tree is a list"))?), "tree")?,
308            css: o.get("css").and_then(Value::as_str).map(str::to_string),
309            keys: keys(o.get("keys"))?,
310        };
311        Ok(tree)
312    }
313
314    /// Every expression in it compiles.
315    pub fn check(&self) -> Result<(), TreeError> {
316        fn walk(nodes: &[Node], out: &mut Vec<String>) {
317            for n in nodes {
318                match n {
319                    Node::El { attrs, children, .. } => {
320                        out.extend(attrs.values().filter_map(|a| if let Attr::Expr(e) = a { Some(e.clone()) } else { None }));
321                        walk(children, out);
322                    }
323                    Node::Text(Attr::Expr(e)) => out.push(e.clone()),
324                    Node::Text(_) => {}
325                    Node::If { cond, then, otherwise } => {
326                        out.push(cond.clone());
327                        walk(then, out);
328                        walk(otherwise, out);
329                    }
330                    Node::Each { expr, key, body, .. } => {
331                        out.push(expr.clone());
332                        out.push(key.clone());
333                        walk(body, out);
334                    }
335                    Node::Component { props, .. } | Node::Slot { props, .. } => {
336                        out.extend(props.values().filter_map(|a| if let Attr::Expr(e) = a { Some(e.clone()) } else { None }));
337                    }
338                    Node::Html(e) => out.push(e.clone()),
339                }
340            }
341        }
342        let mut all = Vec::new();
343        walk(&self.tree, &mut all);
344        for e in all {
345            Expr::compile(&e).map_err(|message| TreeError::Expr { expr: e.clone(), message })?;
346        }
347        Ok(())
348    }
349}
350
351/// What draws: the DOM in the browser, [`Recording`] in the tests. Every
352/// method takes `&self` (a handle), as `web_sys`'s do.
353pub trait Renderer: Clone + 'static {
354    type Node: Clone + PartialEq + std::fmt::Debug + 'static;
355    fn create_element(&self, tag: &str) -> Self::Node;
356    /// A text node holding `text` (an `if`'s or `each`'s anchor is an empty one).
357    fn create_text(&self, text: &str) -> Self::Node;
358    fn set_attr(&self, node: &Self::Node, name: &str, value: &str);
359    /// FRAME-50: the attribute `name` taken off `node`.
360    fn remove_attr(&self, node: &Self::Node, name: &str);
361    fn set_text(&self, node: &Self::Node, text: &str);
362    /// `child` into `parent`, before `before` (none: last).
363    fn insert(&self, parent: &Self::Node, child: &Self::Node, before: Option<&Self::Node>);
364    fn remove(&self, parent: &Self::Node, child: &Self::Node);
365    /// Calls `handler` with the event's payload whenever `event` fires on
366    /// `node` (`window-<event>`: on the window, while `node` is mounted).
367    /// UI-10: the answer takes the listener away again — the tree calls it
368    /// when the node's block goes, so no closure outlives its component.
369    fn listen(&self, node: &Self::Node, event: &str, handler: Rc<dyn Fn(Value)>) -> Unlisten;
370    /// FRAME-18: the elements under `root` (itself left out) carrying
371    /// `data-slot` — a layout's section marks — in document order.
372    fn marks(&self, root: &Self::Node) -> Vec<Self::Node>;
373    /// FRAME-18: an element's attributes, `(name, value)` each.
374    fn attrs(&self, node: &Self::Node) -> Vec<(String, String)>;
375    /// FRAME-18: whether `node` is `ancestor` or under it.
376    fn contains(&self, ancestor: &Self::Node, node: &Self::Node) -> bool;
377    /// FRAME-18: calls `f` after each batch of changes under `root` that
378    /// touch a mark — a node added or removed that is or holds a
379    /// `[data-slot]`, an attribute set on a mark, at any depth — with the
380    /// node each such change was made in; the answer stops it. The recording
381    /// renderer observes nothing (the host also walks after `mount` and
382    /// `update`); the DOM's is a `MutationObserver`.
383    fn observe(&self, root: &Self::Node, f: Rc<dyn Fn(Vec<Self::Node>)>) -> Unlisten;
384    /// FRAME-30: the sheet `key` (its text `css`) adopted by the page
385    /// (`on`), synchronously, or dropped — `document.adoptedStyleSheets`, no
386    /// `<link>`. The engine calls it once per key each way (it counts the
387    /// instances).
388    fn sheet(&self, key: &str, css: &str, on: bool) {
389        let _ = (key, css, on);
390    }
391    /// FRAME-36: calls `f` with every key press the window hears, in the
392    /// capture phase, before anything of the page; when `f` answers true
393    /// the press is the host's — `preventDefault()`, `stopPropagation()`,
394    /// `stopImmediatePropagation()`. The answer stops it. The recording
395    /// renderer hears nothing (the tests press through `App::press`).
396    fn listen_keys(&self, f: Rc<dyn Fn(&crate::keys::Press) -> bool>) -> Unlisten {
397        let _ = f;
398        Box::new(|| {})
399    }
400    /// FRAME-36: the host's keys overlay, `[data-engine-keys]`, drawn with
401    /// `groups` (every mounted component's keys), or taken away (none).
402    fn keys_overlay(&self, groups: Option<&crate::keys::KeyGroups>) {
403        let _ = groups;
404    }
405}
406
407/// What [`Renderer::listen`] answers: called once, it removes the listener.
408pub type Unlisten = Box<dyn FnOnce()>;
409
410/// The engine's side of a mount: fills a `component` or `slot` node's
411/// element, and empties it when the node goes.
412pub trait Children<R: Renderer> {
413    /// `name`'s instance into `at` (its element), with `props`.
414    fn mount_component(&self, at: &R::Node, name: &str, props: Map<String, Value>);
415    /// The section `slot` of `layout` into `at` (its `div`), with `props`.
416    fn mount_slot(&self, at: &R::Node, layout: &str, slot: &str, props: Map<String, Value>);
417    /// What was mounted into `at` goes (its element is being removed).
418    fn unmount(&self, at: &R::Node);
419    /// FRAME-29: whether a `component` node naming `name` is a bound mark —
420    /// `name` of another profile than this runtime's.
421    fn binds(&self, _name: &str) -> bool {
422        false
423    }
424    /// FRAME-29: the section of `layout` that `at`, a bound mark, holds:
425    /// `name` with `props`, no assignment reaching it.
426    fn mount_bound(&self, at: &R::Node, _layout: &str, name: &str, props: Map<String, Value>) {
427        self.mount_component(at, name, props)
428    }
429}
430
431/// A component's state as signals, one per top-level key: replacing it
432/// sets only the keys whose value changed.
433#[derive(Clone, Debug)]
434pub struct State {
435    rt: Runtime,
436    keys: Rc<RefCell<BTreeMap<String, Signal<Value>>>>,
437}
438
439impl State {
440    /// The state `initial` in `rt`.
441    pub fn new(rt: &Runtime, initial: &Map<String, Value>) -> Self {
442        let keys = initial.iter().map(|(k, v)| (k.clone(), rt.signal(v.clone()))).collect();
443        Self { rt: rt.clone(), keys: Rc::new(RefCell::new(keys)) }
444    }
445
446    /// The whole state, untracked.
447    pub fn snapshot(&self) -> Map<String, Value> {
448        self.keys.borrow().iter().map(|(k, s)| (k.clone(), s.peek())).collect()
449    }
450
451    /// Its keys, in order: the state's shape.
452    pub fn shape(&self) -> Vec<String> {
453        self.keys.borrow().keys().cloned().collect()
454    }
455
456    /// A fold's return: each key set (only a changed value moves its signal),
457    /// as one batch.
458    pub fn replace(&self, next: &Map<String, Value>) {
459        self.rt.batch(|| {
460            for (k, v) in next {
461                let existing = self.keys.borrow().get(k).cloned();
462                match existing {
463                    Some(sig) => sig.set(v.clone()),
464                    None => {
465                        let sig = self.rt.signal(v.clone());
466                        self.keys.borrow_mut().insert(k.clone(), sig);
467                    }
468                }
469            }
470        });
471    }
472
473    /// The keys read (all of them for `None`), tracked, as a map.
474    fn read(&self, keys: Option<&std::collections::BTreeSet<String>>) -> Map<String, Value> {
475        let all = self.keys.borrow();
476        match keys {
477            None => all.iter().map(|(k, s)| (k.clone(), s.get())).collect(),
478            Some(keys) => keys.iter().filter_map(|k| all.get(k).map(|s| (k.clone(), s.get()))).collect(),
479        }
480    }
481}
482
483/// UI-10: a `live`'s params evaluated over the scope — a `{ "expr" }`
484/// value a Rhai expression over the props and `state` (its reads of state
485/// tracked, so a binding around this re-runs when they change), any other
486/// value as written.
487/// FRAME-16: whether a `live`'s `when` lets it ask — none, or a value
488/// (read from the scope when it is `{ "expr" }`) that is not false, null,
489/// empty or 0.
490pub fn eval_when(when: Option<&Value>, props: &Map<String, Value>, state: &State) -> bool {
491    let Some(w) = when else { return true };
492    let mut one = BTreeMap::new();
493    one.insert("when".to_string(), w.clone());
494    match eval_params(&one, props, state).get("when") {
495        None | Some(Value::Null) | Some(Value::Bool(false)) => false,
496        Some(Value::String(s)) => !s.is_empty(),
497        Some(Value::Number(n)) => n.as_f64() != Some(0.0),
498        Some(_) => true,
499    }
500}
501
502pub fn eval_params(params: &BTreeMap<String, Value>, props: &Map<String, Value>, state: &State) -> Value {
503    let mut out = Map::new();
504    for (k, v) in params {
505        let text = v.as_object().and_then(|o| o.get("expr")).and_then(Value::as_str);
506        // FRAME-17: a name or a path (what the compiler admits) read
507        // straight from the props or the state — no Rhai at boot.
508        if let Some(path) = text.and_then(expr::path_of) {
509            let fields = &path[1..];
510            let found = if path[0] == "state" {
511                let keys: Option<std::collections::BTreeSet<String>> = fields.first().map(|k| [k.clone()].into());
512                Some(expr::walk(&Value::Object(state.read(keys.as_ref())), fields).cloned().unwrap_or(Value::Null))
513            } else {
514                props.get(&path[0]).map(|p| expr::walk(p, fields).cloned().unwrap_or(Value::Null))
515            };
516            if let Some(found) = found {
517                out.insert(k.clone(), found);
518                continue;
519            }
520        }
521        let value = match text {
522            None => v.clone(),
523            Some(text) => match Expr::compile(text) {
524                Err(m) => {
525                    warn(&format!("the param {k}: `{text}`: {m}"));
526                    Value::Null
527                }
528                Ok(e) => {
529                    let mut scope = rhai::Scope::new();
530                    for (pk, pv) in props {
531                        if e.reads.names.contains(pk) {
532                            scope.push_constant_dynamic(pk.clone(), expr::to_dynamic(pv));
533                        }
534                    }
535                    if e.reads.names.contains("state") {
536                        scope.push_dynamic("state", expr::to_dynamic(&Value::Object(state.read(e.reads.state_keys.as_ref()))));
537                    }
538                    e.eval(&mut scope).map(|d| expr::to_value(&d)).unwrap_or_else(|m| {
539                        warn(&format!("the param {k}: `{text}`: {m}"));
540                        Value::Null
541                    })
542                }
543            },
544        };
545        out.insert(k.clone(), value);
546    }
547    Value::Object(out)
548}
549
550/// What a tree is mounted with: the props by name, the state, the `live`
551/// collections by name (each `{ rows, status }`), and where its events go.
552pub struct Scope {
553    pub props: Map<String, Value>,
554    pub state: State,
555    pub live: BTreeMap<String, Signal<Value>>,
556    /// `(handler, event payload)` for each `on:` that fires.
557    pub on_event: Rc<dyn Fn(&str, Value)>,
558}
559
560/// Everything one mount draws with.
561struct Ctx<R: Renderer> {
562    rt: Runtime,
563    renderer: R,
564    layout: String,
565    scope: Scope,
566    children: Rc<dyn Children<R>>,
567}
568
569/// FRAME-17: what a signal's value was made into, and the value it was
570/// made of (its `Rc`: stale once the signal is set again) — kept from the
571/// second expression that needs it on (a value one expression reads is
572/// made, used and let go, so the wasm's memory holds no copy of it).
573type Memo = Rc<RefCell<Memoed>>;
574
575#[derive(Default)]
576enum Memoed {
577    #[default]
578    Empty,
579    Seen(std::rc::Weak<dyn std::any::Any>),
580    Kept(std::rc::Weak<dyn std::any::Any>, rhai::Dynamic),
581}
582
583/// An `{#each}` variable: its name, its row, and the row as Rhai's value
584/// once an expression needed it (FRAME-17: once per row, not per
585/// expression).
586#[derive(Clone)]
587struct Var {
588    name: String,
589    sig: Signal<Value>,
590    memo: Memo,
591}
592
593/// The `{#each}` variables in scope, innermost last.
594type Env = Rc<Vec<Var>>;
595
596/// `sig`'s value as Rhai's, made once per value.
597fn memoized(sig: &Signal<Value>, memo: &Memo) -> rhai::Dynamic {
598    let held = sig.shared();
599    let again = match &*memo.borrow() {
600        Memoed::Kept(was, d) if std::rc::Weak::ptr_eq(was, &Rc::downgrade(&held)) => return d.clone(),
601        Memoed::Seen(was) => std::rc::Weak::ptr_eq(was, &Rc::downgrade(&held)),
602        _ => false,
603    };
604    let d = expr::to_dynamic(held.downcast_ref::<Value>().expect("a value"));
605    let was = Rc::downgrade(&held);
606    *memo.borrow_mut() = if again { Memoed::Kept(was, d.clone()) } else { Memoed::Seen(was) };
607    d
608}
609
610/// What one stretch of a tree drew: the nodes it put into its parent, the
611/// bindings it made, the elements it handed to the engine, and the
612/// `if` / `each` blocks inside it.
613struct Block<R: Renderer> {
614    top: Vec<R::Node>,
615    bindings: Vec<BindingId>,
616    /// The listeners its elements hold, taken away with it.
617    unlisten: Vec<Unlisten>,
618    hosts: Vec<R::Node>,
619    dyns: Vec<Rc<RefCell<Dyn<R>>>>,
620}
621
622impl<R: Renderer> Default for Block<R> {
623    fn default() -> Self {
624        Self { top: Vec::new(), bindings: Vec::new(), unlisten: Vec::new(), hosts: Vec::new(), dyns: Vec::new() }
625    }
626}
627
628/// An `if`'s or `each`'s current blocks, by key, in order.
629struct Dyn<R: Renderer> {
630    parent: R::Node,
631    /// Whether its nodes sit in its block's own parent (then removing the
632    /// block removes them one by one).
633    top: bool,
634    rows: Vec<(String, Block<R>, Option<Signal<Value>>)>,
635}
636
637impl<R: Renderer> Ctx<R> {
638    fn expr(&self, text: &str) -> Option<Expr> {
639        // FRAME-17: compiled once a page (expr's own cache).
640        match Expr::compile(text) {
641            Ok(e) => Some(e),
642            Err(m) => {
643                warn(&format!("{}: the expression `{text}`: {m}", self.layout));
644                None
645            }
646        }
647    }
648
649    /// Evaluates `text` in the scope with `env`, reading (tracked) only
650    /// what it names.
651    fn eval(&self, env: &Env, text: &str) -> rhai::Dynamic {
652        self.eval_with(env, None, text)
653    }
654
655    /// [`Self::eval`] with one more constant in scope, innermost.
656    fn eval_with(&self, env: &Env, extra: Option<(&str, &Value)>, text: &str) -> rhai::Dynamic {
657        let Some(e) = self.expr(text) else { return rhai::Dynamic::UNIT };
658        if let Some(v) = e.path.as_ref().and_then(|p| self.path_value(env, extra, &e, p)) {
659            return expr::to_dynamic(&v);
660        }
661        let mut scope = rhai::Scope::new();
662        for (k, v) in &self.scope.props {
663            if e.reads.names.contains(k) {
664                scope.push_constant_dynamic(k.clone(), expr::to_dynamic(v));
665            }
666        }
667        if e.reads.names.contains("state") {
668            let state = self.scope.state.read(e.reads.state_keys.as_ref());
669            scope.push_dynamic("state", expr::to_dynamic(&Value::Object(state)));
670        }
671        for (k, sig) in &self.scope.live {
672            if e.reads.names.contains(k) {
673                // FRAME-17: a collection is converted for the expression
674                // that reads it whole and let go — kept, at a million the
675                // extents and counts held 384 KiB more of the wasm's memory
676                // (over UI-8's 10 MB); a path into it (`rows.status`,
677                // `things.rows`) is read without converting it at all.
678                scope.push_dynamic(k.clone(), sig.with(expr::to_dynamic));
679            }
680        }
681        for v in env.iter() {
682            if e.reads.names.contains(&v.name) {
683                scope.push_dynamic(v.name.clone(), memoized(&v.sig, &v.memo));
684            }
685        }
686        if let Some((k, v)) = extra {
687            scope.push_constant_dynamic(k.to_string(), expr::to_dynamic(v));
688        }
689        match e.eval(&mut scope) {
690            Ok(d) => d,
691            Err(m) => {
692                warn(&format!("{}: `{text}`: {m}", self.layout));
693                rhai::Dynamic::UNIT
694            }
695        }
696    }
697
698    /// FRAME-17: a path (`r.id`, `things.rows`, `state.q`, `filter`) read
699    /// straight from the scope's values, the innermost name first, as Rhai's
700    /// scope would find it — or none when the name is in no scope (Rhai
701    /// says why).
702    fn path_value(&self, env: &Env, extra: Option<(&str, &Value)>, e: &Expr, path: &[String]) -> Option<Value> {
703        let (name, fields) = (&path[0], &path[1..]);
704        let null = || Value::Null;
705        if let Some((k, v)) = extra {
706            if k == name {
707                return Some(expr::walk(v, fields).cloned().unwrap_or_else(null));
708            }
709        }
710        if let Some(v) = env.iter().rev().find(|v| &v.name == name) {
711            return Some(v.sig.with(|row| expr::walk(row, fields).cloned().unwrap_or_else(null)));
712        }
713        if let Some(sig) = self.scope.live.get(name) {
714            return Some(sig.with(|l| expr::walk(l, fields).cloned().unwrap_or_else(null)));
715        }
716        if name == "state" {
717            let state = Value::Object(self.scope.state.read(e.reads.state_keys.as_ref()));
718            return Some(expr::walk(&state, fields).cloned().unwrap_or_else(null));
719        }
720        self.scope.props.get(name).map(|v| expr::walk(v, fields).cloned().unwrap_or_else(null))
721    }
722
723    /// [`Self::eval_with`] as JSON — a path read without passing through Rhai.
724    fn eval_value(&self, env: &Env, extra: Option<(&str, &Value)>, text: &str) -> Value {
725        if let Some(e) = self.expr(text) {
726            if let Some(v) = e.path.as_ref().and_then(|p| self.path_value(env, extra, &e, p)) {
727                return v;
728            }
729        }
730        expr::to_value(&self.eval_with(env, extra, text))
731    }
732
733    fn props(&self, env: &Env, props: &BTreeMap<String, Attr>) -> Map<String, Value> {
734        self.rt.untracked(|| {
735            props
736                .iter()
737                .map(|(k, a)| {
738                    let v = match a {
739                        Attr::Lit(s) => Value::String(s.clone()),
740                        Attr::Expr(e) => expr::to_value(&self.eval(env, e)),
741                    };
742                    (k.clone(), v)
743                })
744                .collect()
745        })
746    }
747}
748
749fn warn(msg: &str) {
750    #[cfg(feature = "dom")]
751    web_sys::console::warn_1(&msg.into());
752    #[cfg(not(feature = "dom"))]
753    let _ = msg;
754}
755
756/// A binding over `compute`: its first value returned, `changed` called
757/// (untracked) with each later value that differs.
758fn watch<T: PartialEq + Clone + 'static>(rt: &Runtime, mut compute: impl FnMut() -> T + 'static, mut changed: impl FnMut(T) + 'static) -> (BindingId, T) {
759    let last: Rc<RefCell<Option<T>>> = Rc::default();
760    let (l, r) = (last.clone(), rt.clone());
761    let id = rt.bind(move || {
762        let v = compute();
763        let mut held = l.borrow_mut();
764        match held.as_ref() {
765            None => *held = Some(v),
766            Some(old) if *old == v => {}
767            Some(_) => {
768                *held = Some(v.clone());
769                drop(held);
770                r.untracked(|| changed(v));
771            }
772        }
773    });
774    let first = last.borrow().clone().expect("a binding runs when made");
775    (id, first)
776}
777
778fn build<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, nodes: &[Node], parent: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
779    for n in nodes {
780        build_node(ctx, env, n, parent, before, block, top);
781    }
782}
783
784fn place<R: Renderer>(ctx: &Ctx<R>, parent: &R::Node, node: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
785    ctx.renderer.insert(parent, node, before);
786    if top {
787        block.top.push(node.clone());
788    }
789}
790
791fn build_node<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, node: &Node, parent: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
792    let r = &ctx.renderer;
793    match node {
794        Node::El { el, attrs, on, children } => {
795            let e = r.create_element(el);
796            for (name, a) in attrs {
797                match a {
798                    Attr::Lit(v) => r.set_attr(&e, name, v),
799                    Attr::Expr(x) => {
800                        let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
801                        let (c2, e2, name2) = (ctx.clone(), e.clone(), name.clone());
802                        let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |v: String| c2.renderer.set_attr(&e2, &name2, &v));
803                        r.set_attr(&e, name, &first);
804                        block.bindings.push(id);
805                    }
806                }
807            }
808            for (event, handler) in on {
809                let (on_event, handler) = (ctx.scope.on_event.clone(), handler.clone());
810                block.unlisten.push(r.listen(&e, event, Rc::new(move |payload: Value| on_event(&handler, payload))));
811            }
812            build(ctx, env, children, &e, None, block, false);
813            place(ctx, parent, &e, before, block, top);
814        }
815        Node::Text(Attr::Lit(t)) => {
816            let t = r.create_text(t);
817            place(ctx, parent, &t, before, block, top);
818        }
819        Node::Text(Attr::Expr(x)) => {
820            let cell: Rc<RefCell<Option<R::Node>>> = Rc::default();
821            let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
822            let (c2, cell2) = (ctx.clone(), cell.clone());
823            let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |v: String| {
824                if let Some(n) = cell2.borrow().as_ref() {
825                    c2.renderer.set_text(n, &v);
826                }
827            });
828            let t = r.create_text(&first);
829            *cell.borrow_mut() = Some(t.clone());
830            block.bindings.push(id);
831            place(ctx, parent, &t, before, block, top);
832        }
833        Node::If { cond, then, otherwise } => {
834            let anchor = r.create_text("");
835            place(ctx, parent, &anchor, before, block, top);
836            let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
837            let branches = Rc::new((then.clone(), otherwise.clone()));
838            let (c, env2, cond2) = (ctx.clone(), env.clone(), cond.clone());
839            let (c2, env3, d2, a2, b2) = (ctx.clone(), env.clone(), d.clone(), anchor.clone(), branches.clone());
840            let (id, first) = watch(&ctx.rt, move || expr::truthy(&c.eval(&env2, &cond2)), move |v: bool| {
841                fill_if(&c2, &env3, &d2, &a2, &b2, v);
842            });
843            block.bindings.push(id);
844            ctx.rt.untracked(|| fill_if(ctx, env, &d, &anchor, &branches, first));
845            block.dyns.push(d);
846        }
847        Node::Each { expr: list, as_, key, body } => {
848            let anchor = r.create_text("");
849            place(ctx, parent, &anchor, before, block, top);
850            let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
851            let spec = Rc::new((as_.clone(), body.clone()));
852            let (c, env2, list2, as2, key2) = (ctx.clone(), env.clone(), list.clone(), as_.clone(), key.clone());
853            let (c2, env3, d2, a2, s2) = (ctx.clone(), env.clone(), d.clone(), anchor.clone(), spec.clone());
854            let (id, first) = watch(
855                &ctx.rt,
856                move || keyed(&c, &env2, &list2, &as2, &key2),
857                move |rows: Vec<(String, Value)>| reconcile(&c2, &env3, &d2, &a2, &s2, rows),
858            );
859            block.bindings.push(id);
860            ctx.rt.untracked(|| reconcile(ctx, env, &d, &anchor, &spec, first));
861            block.dyns.push(d);
862        }
863        Node::Component { name, props } => {
864            let props = ctx.props(env, props);
865            let e = if ctx.children.binds(name) {
866                let e = r.create_element("div");
867                r.set_attr(&e, "data-layout", &ctx.layout);
868                r.set_attr(&e, "data-slot", name);
869                r.set_attr(&e, "data-component", name);
870                ctx.children.mount_bound(&e, &ctx.layout, name, props);
871                e
872            } else {
873                let e = r.create_element(name);
874                ctx.children.mount_component(&e, name, props);
875                e
876            };
877            block.hosts.push(e.clone());
878            place(ctx, parent, &e, before, block, top);
879        }
880        Node::Html(x) => {
881            let anchor = r.create_text("");
882            place(ctx, parent, &anchor, before, block, top);
883            let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
884            let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
885            let (c2, d2, a2) = (ctx.clone(), d.clone(), anchor.clone());
886            let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |html: String| fill_html(&c2, &d2, &a2, &html));
887            block.bindings.push(id);
888            ctx.rt.untracked(|| fill_html(ctx, &d, &anchor, &first));
889            block.dyns.push(d);
890        }
891        Node::Slot { name, props } => {
892            let e = r.create_element("div");
893            r.set_attr(&e, "data-layout", &ctx.layout);
894            r.set_attr(&e, "data-slot", name);
895            let props = ctx.props(env, props);
896            ctx.children.mount_slot(&e, &ctx.layout, name, props);
897            block.hosts.push(e.clone());
898            place(ctx, parent, &e, before, block, top);
899        }
900    }
901}
902
903/// UI-10: an `{@html}`'s nodes: the old ones out, the sanitized tree drawn
904/// before the anchor through the renderer (no HTML string reaches it).
905fn fill_html<R: Renderer>(ctx: &Rc<Ctx<R>>, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, html: &str) {
906    let (old, parent) = {
907        let mut d = d.borrow_mut();
908        (std::mem::take(&mut d.rows), d.parent.clone())
909    };
910    for (_, b, _) in old {
911        dispose(ctx, b, Some(&parent));
912    }
913    fn draw<R: Renderer>(r: &R, nodes: &[crate::html::HNode], parent: &R::Node, before: Option<&R::Node>, top: &mut Vec<R::Node>) {
914        for n in nodes {
915            let node = match n {
916                crate::html::HNode::Text(t) => r.create_text(t),
917                crate::html::HNode::Element { tag, attrs, children } => {
918                    let e = r.create_element(tag);
919                    for (k, v) in attrs {
920                        r.set_attr(&e, k, v);
921                    }
922                    draw(r, children, &e, None, &mut Vec::new());
923                    e
924                }
925            };
926            r.insert(parent, &node, before);
927            top.push(node);
928        }
929    }
930    let mut b = Block::default();
931    draw(&ctx.renderer, &crate::html::sanitize(html), &parent, Some(anchor), &mut b.top);
932    d.borrow_mut().rows.push((String::new(), b, None));
933}
934
935fn fill_if<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, branches: &(Vec<Node>, Vec<Node>), on: bool) {
936    let (old, parent) = {
937        let mut d = d.borrow_mut();
938        (std::mem::take(&mut d.rows), d.parent.clone())
939    };
940    for (_, b, _) in old {
941        dispose(ctx, b, Some(&parent));
942    }
943    let nodes = if on { &branches.0 } else { &branches.1 };
944    if nodes.is_empty() {
945        return;
946    }
947    let mut b = Block::default();
948    build(ctx, env, nodes, &parent, Some(anchor), &mut b, true);
949    d.borrow_mut().rows.push((String::new(), b, None));
950}
951
952/// The list `list` names, each item with its key (a key seen twice gets
953/// its index after it).
954fn keyed<R: Renderer>(ctx: &Ctx<R>, env: &Env, list: &str, as_: &str, key: &str) -> Vec<(String, Value)> {
955    let items = match ctx.eval_value(env, None, list) {
956        Value::Array(a) => a,
957        _ => Vec::new(),
958    };
959    ctx.rt.untracked(|| {
960        let mut seen = std::collections::BTreeSet::new();
961        items
962            .into_iter()
963            .enumerate()
964            .map(|(i, item)| {
965                let mut k = match ctx.eval_value(env, Some((as_, &item)), key) {
966                    Value::String(s) => s,
967                    other => expr::as_text(&expr::to_dynamic(&other)),
968                };
969                if !seen.insert(k.clone()) {
970                    k = format!("{k}#{i}");
971                }
972                (k, item)
973            })
974            .collect()
975    })
976}
977
978fn reconcile<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, spec: &(String, Vec<Node>), rows: Vec<(String, Value)>) {
979    let (mut old, parent) = {
980        let mut d = d.borrow_mut();
981        (std::mem::take(&mut d.rows), d.parent.clone())
982    };
983    // The rows that go.
984    let wanted: std::collections::BTreeSet<&String> = rows.iter().map(|(k, _)| k).collect();
985    let mut kept = Vec::new();
986    for (k, b, s) in old.drain(..) {
987        if wanted.contains(&k) {
988            kept.push((k, b, s));
989        } else {
990            dispose(ctx, b, Some(&parent));
991        }
992    }
993    // Whether the rows that stay keep their order.
994    let kept_order: Vec<&String> = kept.iter().map(|(k, _, _)| k).collect();
995    let new_order: Vec<&String> = rows.iter().map(|(k, _)| k).filter(|k| kept_order.contains(k)).collect();
996    let moved = kept_order != new_order;
997    let mut by_key: BTreeMap<String, (Block<R>, Option<Signal<Value>>)> = kept.into_iter().map(|(k, b, s)| (k, (b, s))).collect();
998    let mut next: Vec<(String, Block<R>, Option<Signal<Value>>)> = Vec::with_capacity(rows.len());
999    let mut before = anchor.clone();
1000    for (k, item) in rows.into_iter().rev() {
1001        match by_key.remove(&k) {
1002            Some((b, s)) => {
1003                if let Some(s) = &s {
1004                    s.set(item);
1005                }
1006                if moved {
1007                    for n in &b.top {
1008                        ctx.renderer.insert(&parent, n, Some(&before));
1009                    }
1010                }
1011                if let Some(first) = b.top.first() {
1012                    before = first.clone();
1013                }
1014                next.push((k, b, s));
1015            }
1016            None => {
1017                let sig = ctx.rt.signal(item);
1018                let mut inner = (**env).clone();
1019                inner.push(Var { name: spec.0.clone(), sig: sig.clone(), memo: Memo::default() });
1020                let mut b = Block::default();
1021                build(ctx, &Rc::new(inner), &spec.1, &parent, Some(&before), &mut b, true);
1022                if let Some(first) = b.top.first() {
1023                    before = first.clone();
1024                }
1025                next.push((k, b, Some(sig)));
1026            }
1027        }
1028    }
1029    next.reverse();
1030    d.borrow_mut().rows = next;
1031}
1032
1033/// Stops `block`'s bindings, empties the engine's elements in it, and —
1034/// given its parent — takes its nodes out.
1035fn dispose<R: Renderer>(ctx: &Ctx<R>, block: Block<R>, parent: Option<&R::Node>) {
1036    for id in block.bindings {
1037        ctx.rt.dispose(id);
1038    }
1039    for off in block.unlisten {
1040        off();
1041    }
1042    for d in block.dyns {
1043        let (rows, dparent, top) = {
1044            let mut d = d.borrow_mut();
1045            (std::mem::take(&mut d.rows), d.parent.clone(), d.top)
1046        };
1047        for (_, b, _) in rows {
1048            dispose(ctx, b, if top && parent.is_some() { Some(&dparent) } else { None });
1049        }
1050    }
1051    for h in &block.hosts {
1052        ctx.children.unmount(h);
1053    }
1054    if let Some(p) = parent {
1055        for n in &block.top {
1056            ctx.renderer.remove(p, n);
1057        }
1058    }
1059}
1060
1061/// A mounted tree: its nodes under the parent and its bindings.
1062pub struct Mounted<R: Renderer> {
1063    pub parent: R::Node,
1064    ctx: Rc<Ctx<R>>,
1065    block: Block<R>,
1066}
1067
1068impl<R: Renderer> Mounted<R> {
1069    /// Takes every node it inserted out of the parent and stops its
1070    /// bindings; [`Children::unmount`] for each component and slot in it.
1071    pub fn unmount(self) {
1072        dispose(&self.ctx, self.block, Some(&self.parent));
1073    }
1074
1075    /// The nodes it put into the parent, in order.
1076    pub fn top(&self) -> Vec<R::Node> {
1077        self.block.top.clone()
1078    }
1079}
1080
1081/// Draws `tree` into `parent` (appended) with `scope`, through `renderer`;
1082/// `children` fills its components and slots.
1083pub fn mount<R: Renderer>(
1084    rt: &Runtime,
1085    renderer: &R,
1086    tree: &ComponentTree,
1087    scope: Scope,
1088    parent: &R::Node,
1089    children: Rc<dyn Children<R>>,
1090) -> Result<Mounted<R>, TreeError> {
1091    tree.check()?;
1092    let ctx = Rc::new(Ctx { rt: rt.clone(), renderer: renderer.clone(), layout: tree.name.clone(), scope, children });
1093    let mut block = Block::default();
1094    rt.untracked(|| build(&ctx, &Rc::new(Vec::new()), &tree.tree, parent, None, &mut block, true));
1095    Ok(Mounted { parent: parent.clone(), ctx, block })
1096}
1097
1098#[cfg(test)]
1099mod tests;