plexus-ui-engine 0.2.0

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
//! UI-6: **the view tree** — UI-4's compiled `components/<name>.json`, and
//! its interpreter over a [`Renderer`].
//!
//! Node kinds (the contract's): `el` (attrs each a string or `{ "expr" }`,
//! `on` event → handler, children), `text` (a string or `{ "expr" }`),
//! `if` / `then` / `else`, `each` (`as`, `key`, body), `component` (props),
//! and `slot` (a section: its name and the props of what fills it).
//!
//! Mounting draws the tree once and makes one binding per dynamic place
//! (an attribute, a text, an `if`, an `each`): a fold that changes a state
//! key re-runs only the bindings that read it. An `if` and an `each` hold
//! their place with an empty text node (their anchor) and insert before
//! it; an `each` is keyed — a row whose key stays keeps its nodes.
//!
//! A `component` node draws as an element named for the component
//! (`<ticket-row>`), filled by the engine through [`Children`]; a `slot`
//! as a `div` carrying `data-slot` (and `data-layout`), filled the same way.
//! FRAME-29: a `component` node naming a component the rhx runtime does not
//! draw (another profile: [`Children::binds`]) draws as a **bound mark** — a
//! `div` carrying `data-slot` and `data-component` (both the component's
//! name) and `data-layout` — filled as a section bound to it
//! ([`Children::mount_bound`]), its props the node's, as values.

use crate::signals::{BindingId, Runtime, Signal};
use serde_json::{Map, Value};
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;

pub mod expr;
use expr::Expr;

pub mod recording;
pub use recording::{Call, Recording};

#[cfg(feature = "dom")]
pub mod dom;

/// A value in the tree: a literal string, or a Rhai expression over the
/// scope.
#[derive(Debug, Clone, PartialEq)]
pub enum Attr {
    Lit(String),
    Expr(String),
}

/// One node of a compiled tree.
#[derive(Debug, Clone, PartialEq)]
pub enum Node {
    El { el: String, attrs: BTreeMap<String, Attr>, on: BTreeMap<String, String>, children: Vec<Node> },
    Text(Attr),
    If { cond: String, then: Vec<Node>, otherwise: Vec<Node> },
    Each { expr: String, as_: String, key: String, body: Vec<Node> },
    Component { name: String, props: BTreeMap<String, Attr> },
    Slot { name: String, props: BTreeMap<String, Attr> },
    /// UI-10: `{@html expr}` — the expression's text as HTML, through the
    /// sanitizer ([`crate::html`]).
    Html(String),
}

/// A `live` declaration: the snapshot method and its params, the changes
/// method and its own params (`changes_params`), the key, and the folds by
/// event type (`upsert:ticket`, …). A param is a JSON value or `{ "expr" }`.
#[derive(Debug, Clone, PartialEq)]
pub struct LiveDecl {
    pub snapshot: String,
    pub params: BTreeMap<String, Value>,
    /// UI-10: none — a one-shot read.
    pub changes: Option<String>,
    pub changes_params: BTreeMap<String, Value>,
    pub key: String,
    pub on: BTreeMap<String, String>,
    /// UI-10: how long the params must be quiet before it runs again.
    pub debounce_ms: Option<u64>,
    /// FRAME-16: while this is false, null, empty or 0 the collection asks
    /// nothing — a boolean, or `{ "expr" }` read from the scope. None: always.
    pub when: Option<Value>,
}

/// A component's compiled tree — `components/<name>.json`.
#[derive(Debug, Clone, PartialEq)]
pub struct ComponentTree {
    pub name: String,
    pub abi: String,
    pub props: Vec<String>,
    /// The declared state: its initial value (a map).
    pub state: Map<String, Value>,
    pub live: BTreeMap<String, LiveDecl>,
    pub uses: Vec<String>,
    /// FRAME-12: what it hears on the bus — topic → fold (`on("topic",
    /// "fold")`); none when the tree has no `bus`.
    pub bus: BTreeMap<String, String>,
    /// The sha256 of `components/<name>.rhai`.
    pub handlers: String,
    pub tree: Vec<Node>,
    /// FRAME-30: its sheet's mark (`components/<name>.css` scoped under
    /// `<name>[data-css="<mark>"]`); none when it has no sheet.
    pub css: Option<String>,
    /// FRAME-36: its shortcuts (`keys(#{ … })`, the tree's `keys`), by
    /// chord; none when the tree has no `keys`.
    pub keys: Vec<crate::keys::KeyDecl>,
}

/// Why a tree did not parse or mount.
#[derive(Debug, Clone, PartialEq)]
pub enum TreeError {
    /// Not the contract's schema: where, and what.
    Malformed(String),
    /// An expression did not compile or evaluate: the expression and why.
    Expr { expr: String, message: String },
}

impl std::fmt::Display for TreeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TreeError::Malformed(m) => write!(f, "a malformed tree: {m}"),
            TreeError::Expr { expr, message } => write!(f, "the expression `{expr}`: {message}"),
        }
    }
}

fn bad(at: &str, what: &str) -> TreeError {
    TreeError::Malformed(format!("{at}: {what}"))
}

fn attr(v: &Value, at: &str) -> Result<Attr, TreeError> {
    match v {
        Value::String(s) => Ok(Attr::Lit(s.clone())),
        Value::Object(o) => match o.get("expr") {
            Some(Value::String(e)) if o.len() == 1 => Ok(Attr::Expr(e.clone())),
            _ => Err(bad(at, "a value is a string or { \"expr\": … }")),
        },
        Value::Number(_) | Value::Bool(_) => Ok(Attr::Lit(v.to_string())),
        _ => Err(bad(at, "a value is a string or { \"expr\": … }")),
    }
}

fn expr_of(v: Option<&Value>, at: &str) -> Result<String, TreeError> {
    match v {
        Some(Value::String(s)) => Ok(s.clone()),
        Some(Value::Object(o)) => match o.get("expr") {
            Some(Value::String(e)) => Ok(e.clone()),
            _ => Err(bad(at, "an { \"expr\": … }")),
        },
        _ => Err(bad(at, "an { \"expr\": … }")),
    }
}

fn attrs(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, Attr>, TreeError> {
    match v {
        None => Ok(BTreeMap::new()),
        Some(Value::Object(o)) => o.iter().map(|(k, v)| Ok((k.clone(), attr(v, &format!("{at}.{k}"))?))).collect(),
        Some(_) => Err(bad(at, "a map")),
    }
}

fn strings(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, String>, TreeError> {
    match v {
        None => Ok(BTreeMap::new()),
        Some(Value::Object(o)) => o
            .iter()
            .map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())).ok_or_else(|| bad(&format!("{at}.{k}"), "a string")))
            .collect(),
        Some(_) => Err(bad(at, "a map of strings")),
    }
}

fn nodes(v: Option<&Value>, at: &str) -> Result<Vec<Node>, TreeError> {
    match v {
        None => Ok(Vec::new()),
        Some(Value::Array(a)) => a.iter().enumerate().map(|(i, n)| node(n, &format!("{at}[{i}]"))).collect(),
        Some(_) => Err(bad(at, "a list of nodes")),
    }
}

fn node(v: &Value, at: &str) -> Result<Node, TreeError> {
    let o = v.as_object().ok_or_else(|| bad(at, "a node is a map"))?;
    if let Some(el) = o.get("el") {
        let el = el.as_str().ok_or_else(|| bad(at, "el is a tag"))?;
        return Ok(Node::El {
            el: el.to_string(),
            attrs: attrs(o.get("attrs"), &format!("{at}.attrs"))?,
            on: strings(o.get("on"), &format!("{at}.on"))?,
            children: nodes(o.get("children"), &format!("{at}.children"))?,
        });
    }
    if let Some(t) = o.get("text") {
        return Ok(Node::Text(attr(t, &format!("{at}.text"))?));
    }
    if o.contains_key("if") {
        return Ok(Node::If {
            cond: expr_of(o.get("if"), &format!("{at}.if"))?,
            then: nodes(o.get("then"), &format!("{at}.then"))?,
            otherwise: nodes(o.get("else"), &format!("{at}.else"))?,
        });
    }
    if let Some(each) = o.get("each") {
        let e = each.as_object().ok_or_else(|| bad(at, "each is a map"))?;
        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}")));
        return Ok(Node::Each { expr: s("expr")?, as_: s("as")?, key: s("key")?, body: nodes(o.get("body"), &format!("{at}.body"))? });
    }
    if let Some(c) = o.get("component") {
        let name = c.as_str().ok_or_else(|| bad(at, "component is a name"))?;
        return Ok(Node::Component { name: name.to_string(), props: attrs(o.get("props"), &format!("{at}.props"))? });
    }
    if o.contains_key("html") {
        return Ok(Node::Html(expr_of(o.get("html"), &format!("{at}.html"))?));
    }
    if let Some(sl) = o.get("slot") {
        let name = sl.as_str().ok_or_else(|| bad(at, "slot is a name"))?;
        return Ok(Node::Slot { name: name.to_string(), props: attrs(o.get("props"), &format!("{at}.props"))? });
    }
    Err(bad(at, "a node is el, text, if, each, component or slot"))
}

/// FRAME-36: the tree's `keys` — chord → `{ to, label?, in_inputs?, only?,
/// in_controls? }` (FRAME-38).
fn keys(v: Option<&Value>) -> Result<Vec<crate::keys::KeyDecl>, TreeError> {
    let Some(v) = v else { return Ok(Vec::new()) };
    let o = v.as_object().ok_or_else(|| bad("keys", "a map of chord → { to, label, in_inputs, only }"))?;
    let mut out = Vec::new();
    for (chord, e) in o {
        let at = format!("keys.{chord}");
        let e = e.as_object().ok_or_else(|| bad(&at, "a map"))?;
        let to = e.get("to").and_then(Value::as_str).ok_or_else(|| bad(&at, "to is a string"))?;
        let label = match e.get("label") {
            None => None,
            Some(Value::String(l)) => Some(l.clone()),
            Some(_) => return Err(bad(&at, "label is a string")),
        };
        let flag = |k: &str| match e.get(k) {
            None => Ok(false),
            Some(Value::Bool(b)) => Ok(*b),
            Some(_) => Err(bad(&at, &format!("{k} is true or false"))),
        };
        out.push(crate::keys::KeyDecl::new(chord, to, label, flag("in_inputs")?, flag("only")?).map_err(|m| bad(&at, &m))?.controls(flag("in_controls")?));
    }
    Ok(out)
}

fn params(v: Option<&Value>, at: &str) -> Result<BTreeMap<String, Value>, TreeError> {
    match v {
        None | Some(Value::Null) => Ok(BTreeMap::new()),
        Some(Value::Object(o)) => Ok(o.iter().map(|(k, v)| (k.clone(), v.clone())).collect()),
        Some(_) => Err(bad(at, "params are a map")),
    }
}

impl ComponentTree {
    /// From `components/<name>.json`'s text; refused, naming where, when it
    /// is not the contract's schema or an expression does not compile.
    pub fn parse(json: &str) -> Result<Self, TreeError> {
        let tree = Self::read(json)?;
        tree.check()?;
        Ok(tree)
    }

    /// FRAME-17: [`Self::parse`] without compiling its expressions — what
    /// the boot reads of a tree (its props, state, `live`, sections and
    /// components) before anything is mounted.
    pub fn read(json: &str) -> Result<Self, TreeError> {
        let v: Value = serde_json::from_str(json).map_err(|e| TreeError::Malformed(e.to_string()))?;
        let o = v.as_object().ok_or_else(|| bad("the tree", "a map"))?;
        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")));
        let list = |k: &str| -> Result<Vec<String>, TreeError> {
            match o.get(k) {
                None => Ok(Vec::new()),
                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(),
                Some(_) => Err(bad(k, "a list of strings")),
            }
        };
        let mut live = BTreeMap::new();
        if let Some(l) = o.get("live") {
            for (name, d) in l.as_object().ok_or_else(|| bad("live", "a map"))? {
                let at = format!("live.{name}");
                let d = d.as_object().ok_or_else(|| bad(&at, "a map"))?;
                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")));
                live.insert(
                    name.clone(),
                    LiveDecl {
                        snapshot: ds("snapshot")?,
                        params: params(d.get("params"), &at)?,
                        changes: d.get("changes").and_then(Value::as_str).map(str::to_string),
                        changes_params: params(d.get("changes_params"), &at)?,
                        key: ds("key")?,
                        on: strings(d.get("on"), &format!("{at}.on"))?,
                        debounce_ms: d.get("debounce_ms").and_then(Value::as_u64),
                        when: d.get("when").cloned(),
                    },
                );
            }
        }
        let state = match o.get("state") {
            None => Map::new(),
            Some(Value::Object(m)) => m.clone(),
            Some(_) => return Err(bad("state", "a map")),
        };
        let tree = Self {
            name: s("name")?,
            abi: s("abi")?,
            props: list("props")?,
            state,
            live,
            uses: list("uses")?,
            bus: strings(o.get("bus"), "bus")?,
            handlers: o.get("handlers").and_then(Value::as_str).unwrap_or_default().to_string(),
            tree: nodes(Some(o.get("tree").ok_or_else(|| bad("the tree", "tree is a list"))?), "tree")?,
            css: o.get("css").and_then(Value::as_str).map(str::to_string),
            keys: keys(o.get("keys"))?,
        };
        Ok(tree)
    }

    /// Every expression in it compiles.
    pub fn check(&self) -> Result<(), TreeError> {
        fn walk(nodes: &[Node], out: &mut Vec<String>) {
            for n in nodes {
                match n {
                    Node::El { attrs, children, .. } => {
                        out.extend(attrs.values().filter_map(|a| if let Attr::Expr(e) = a { Some(e.clone()) } else { None }));
                        walk(children, out);
                    }
                    Node::Text(Attr::Expr(e)) => out.push(e.clone()),
                    Node::Text(_) => {}
                    Node::If { cond, then, otherwise } => {
                        out.push(cond.clone());
                        walk(then, out);
                        walk(otherwise, out);
                    }
                    Node::Each { expr, key, body, .. } => {
                        out.push(expr.clone());
                        out.push(key.clone());
                        walk(body, out);
                    }
                    Node::Component { props, .. } | Node::Slot { props, .. } => {
                        out.extend(props.values().filter_map(|a| if let Attr::Expr(e) = a { Some(e.clone()) } else { None }));
                    }
                    Node::Html(e) => out.push(e.clone()),
                }
            }
        }
        let mut all = Vec::new();
        walk(&self.tree, &mut all);
        for e in all {
            Expr::compile(&e).map_err(|message| TreeError::Expr { expr: e.clone(), message })?;
        }
        Ok(())
    }
}

/// What draws: the DOM in the browser, [`Recording`] in the tests. Every
/// method takes `&self` (a handle), as `web_sys`'s do.
pub trait Renderer: Clone + 'static {
    type Node: Clone + PartialEq + std::fmt::Debug + 'static;
    fn create_element(&self, tag: &str) -> Self::Node;
    /// A text node holding `text` (an `if`'s or `each`'s anchor is an empty one).
    fn create_text(&self, text: &str) -> Self::Node;
    fn set_attr(&self, node: &Self::Node, name: &str, value: &str);
    /// FRAME-50: the attribute `name` taken off `node`.
    fn remove_attr(&self, node: &Self::Node, name: &str);
    fn set_text(&self, node: &Self::Node, text: &str);
    /// `child` into `parent`, before `before` (none: last).
    fn insert(&self, parent: &Self::Node, child: &Self::Node, before: Option<&Self::Node>);
    fn remove(&self, parent: &Self::Node, child: &Self::Node);
    /// Calls `handler` with the event's payload whenever `event` fires on
    /// `node` (`window-<event>`: on the window, while `node` is mounted).
    /// UI-10: the answer takes the listener away again — the tree calls it
    /// when the node's block goes, so no closure outlives its component.
    fn listen(&self, node: &Self::Node, event: &str, handler: Rc<dyn Fn(Value)>) -> Unlisten;
    /// FRAME-18: the elements under `root` (itself left out) carrying
    /// `data-slot` — a layout's section marks — in document order.
    fn marks(&self, root: &Self::Node) -> Vec<Self::Node>;
    /// FRAME-18: an element's attributes, `(name, value)` each.
    fn attrs(&self, node: &Self::Node) -> Vec<(String, String)>;
    /// FRAME-18: whether `node` is `ancestor` or under it.
    fn contains(&self, ancestor: &Self::Node, node: &Self::Node) -> bool;
    /// FRAME-18: calls `f` after each batch of changes under `root` that
    /// touch a mark — a node added or removed that is or holds a
    /// `[data-slot]`, an attribute set on a mark, at any depth — with the
    /// node each such change was made in; the answer stops it. The recording
    /// renderer observes nothing (the host also walks after `mount` and
    /// `update`); the DOM's is a `MutationObserver`.
    fn observe(&self, root: &Self::Node, f: Rc<dyn Fn(Vec<Self::Node>)>) -> Unlisten;
    /// FRAME-30: the sheet `key` (its text `css`) adopted by the page
    /// (`on`), synchronously, or dropped — `document.adoptedStyleSheets`, no
    /// `<link>`. The engine calls it once per key each way (it counts the
    /// instances).
    fn sheet(&self, key: &str, css: &str, on: bool) {
        let _ = (key, css, on);
    }
    /// FRAME-36: calls `f` with every key press the window hears, in the
    /// capture phase, before anything of the page; when `f` answers true
    /// the press is the host's — `preventDefault()`, `stopPropagation()`,
    /// `stopImmediatePropagation()`. The answer stops it. The recording
    /// renderer hears nothing (the tests press through `App::press`).
    fn listen_keys(&self, f: Rc<dyn Fn(&crate::keys::Press) -> bool>) -> Unlisten {
        let _ = f;
        Box::new(|| {})
    }
    /// FRAME-36: the host's keys overlay, `[data-engine-keys]`, drawn with
    /// `groups` (every mounted component's keys), or taken away (none).
    fn keys_overlay(&self, groups: Option<&crate::keys::KeyGroups>) {
        let _ = groups;
    }
}

/// What [`Renderer::listen`] answers: called once, it removes the listener.
pub type Unlisten = Box<dyn FnOnce()>;

/// The engine's side of a mount: fills a `component` or `slot` node's
/// element, and empties it when the node goes.
pub trait Children<R: Renderer> {
    /// `name`'s instance into `at` (its element), with `props`.
    fn mount_component(&self, at: &R::Node, name: &str, props: Map<String, Value>);
    /// The section `slot` of `layout` into `at` (its `div`), with `props`.
    fn mount_slot(&self, at: &R::Node, layout: &str, slot: &str, props: Map<String, Value>);
    /// What was mounted into `at` goes (its element is being removed).
    fn unmount(&self, at: &R::Node);
    /// FRAME-29: whether a `component` node naming `name` is a bound mark —
    /// `name` of another profile than this runtime's.
    fn binds(&self, _name: &str) -> bool {
        false
    }
    /// FRAME-29: the section of `layout` that `at`, a bound mark, holds:
    /// `name` with `props`, no assignment reaching it.
    fn mount_bound(&self, at: &R::Node, _layout: &str, name: &str, props: Map<String, Value>) {
        self.mount_component(at, name, props)
    }
}

/// A component's state as signals, one per top-level key: replacing it
/// sets only the keys whose value changed.
#[derive(Clone, Debug)]
pub struct State {
    rt: Runtime,
    keys: Rc<RefCell<BTreeMap<String, Signal<Value>>>>,
}

impl State {
    /// The state `initial` in `rt`.
    pub fn new(rt: &Runtime, initial: &Map<String, Value>) -> Self {
        let keys = initial.iter().map(|(k, v)| (k.clone(), rt.signal(v.clone()))).collect();
        Self { rt: rt.clone(), keys: Rc::new(RefCell::new(keys)) }
    }

    /// The whole state, untracked.
    pub fn snapshot(&self) -> Map<String, Value> {
        self.keys.borrow().iter().map(|(k, s)| (k.clone(), s.peek())).collect()
    }

    /// Its keys, in order: the state's shape.
    pub fn shape(&self) -> Vec<String> {
        self.keys.borrow().keys().cloned().collect()
    }

    /// A fold's return: each key set (only a changed value moves its signal),
    /// as one batch.
    pub fn replace(&self, next: &Map<String, Value>) {
        self.rt.batch(|| {
            for (k, v) in next {
                let existing = self.keys.borrow().get(k).cloned();
                match existing {
                    Some(sig) => sig.set(v.clone()),
                    None => {
                        let sig = self.rt.signal(v.clone());
                        self.keys.borrow_mut().insert(k.clone(), sig);
                    }
                }
            }
        });
    }

    /// The keys read (all of them for `None`), tracked, as a map.
    fn read(&self, keys: Option<&std::collections::BTreeSet<String>>) -> Map<String, Value> {
        let all = self.keys.borrow();
        match keys {
            None => all.iter().map(|(k, s)| (k.clone(), s.get())).collect(),
            Some(keys) => keys.iter().filter_map(|k| all.get(k).map(|s| (k.clone(), s.get()))).collect(),
        }
    }
}

/// UI-10: a `live`'s params evaluated over the scope — a `{ "expr" }`
/// value a Rhai expression over the props and `state` (its reads of state
/// tracked, so a binding around this re-runs when they change), any other
/// value as written.
/// FRAME-16: whether a `live`'s `when` lets it ask — none, or a value
/// (read from the scope when it is `{ "expr" }`) that is not false, null,
/// empty or 0.
pub fn eval_when(when: Option<&Value>, props: &Map<String, Value>, state: &State) -> bool {
    let Some(w) = when else { return true };
    let mut one = BTreeMap::new();
    one.insert("when".to_string(), w.clone());
    match eval_params(&one, props, state).get("when") {
        None | Some(Value::Null) | Some(Value::Bool(false)) => false,
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Number(n)) => n.as_f64() != Some(0.0),
        Some(_) => true,
    }
}

pub fn eval_params(params: &BTreeMap<String, Value>, props: &Map<String, Value>, state: &State) -> Value {
    let mut out = Map::new();
    for (k, v) in params {
        let text = v.as_object().and_then(|o| o.get("expr")).and_then(Value::as_str);
        // FRAME-17: a name or a path (what the compiler admits) read
        // straight from the props or the state — no Rhai at boot.
        if let Some(path) = text.and_then(expr::path_of) {
            let fields = &path[1..];
            let found = if path[0] == "state" {
                let keys: Option<std::collections::BTreeSet<String>> = fields.first().map(|k| [k.clone()].into());
                Some(expr::walk(&Value::Object(state.read(keys.as_ref())), fields).cloned().unwrap_or(Value::Null))
            } else {
                props.get(&path[0]).map(|p| expr::walk(p, fields).cloned().unwrap_or(Value::Null))
            };
            if let Some(found) = found {
                out.insert(k.clone(), found);
                continue;
            }
        }
        let value = match text {
            None => v.clone(),
            Some(text) => match Expr::compile(text) {
                Err(m) => {
                    warn(&format!("the param {k}: `{text}`: {m}"));
                    Value::Null
                }
                Ok(e) => {
                    let mut scope = rhai::Scope::new();
                    for (pk, pv) in props {
                        if e.reads.names.contains(pk) {
                            scope.push_constant_dynamic(pk.clone(), expr::to_dynamic(pv));
                        }
                    }
                    if e.reads.names.contains("state") {
                        scope.push_dynamic("state", expr::to_dynamic(&Value::Object(state.read(e.reads.state_keys.as_ref()))));
                    }
                    e.eval(&mut scope).map(|d| expr::to_value(&d)).unwrap_or_else(|m| {
                        warn(&format!("the param {k}: `{text}`: {m}"));
                        Value::Null
                    })
                }
            },
        };
        out.insert(k.clone(), value);
    }
    Value::Object(out)
}

/// What a tree is mounted with: the props by name, the state, the `live`
/// collections by name (each `{ rows, status }`), and where its events go.
pub struct Scope {
    pub props: Map<String, Value>,
    pub state: State,
    pub live: BTreeMap<String, Signal<Value>>,
    /// `(handler, event payload)` for each `on:` that fires.
    pub on_event: Rc<dyn Fn(&str, Value)>,
}

/// Everything one mount draws with.
struct Ctx<R: Renderer> {
    rt: Runtime,
    renderer: R,
    layout: String,
    scope: Scope,
    children: Rc<dyn Children<R>>,
}

/// FRAME-17: what a signal's value was made into, and the value it was
/// made of (its `Rc`: stale once the signal is set again) — kept from the
/// second expression that needs it on (a value one expression reads is
/// made, used and let go, so the wasm's memory holds no copy of it).
type Memo = Rc<RefCell<Memoed>>;

#[derive(Default)]
enum Memoed {
    #[default]
    Empty,
    Seen(std::rc::Weak<dyn std::any::Any>),
    Kept(std::rc::Weak<dyn std::any::Any>, rhai::Dynamic),
}

/// An `{#each}` variable: its name, its row, and the row as Rhai's value
/// once an expression needed it (FRAME-17: once per row, not per
/// expression).
#[derive(Clone)]
struct Var {
    name: String,
    sig: Signal<Value>,
    memo: Memo,
}

/// The `{#each}` variables in scope, innermost last.
type Env = Rc<Vec<Var>>;

/// `sig`'s value as Rhai's, made once per value.
fn memoized(sig: &Signal<Value>, memo: &Memo) -> rhai::Dynamic {
    let held = sig.shared();
    let again = match &*memo.borrow() {
        Memoed::Kept(was, d) if std::rc::Weak::ptr_eq(was, &Rc::downgrade(&held)) => return d.clone(),
        Memoed::Seen(was) => std::rc::Weak::ptr_eq(was, &Rc::downgrade(&held)),
        _ => false,
    };
    let d = expr::to_dynamic(held.downcast_ref::<Value>().expect("a value"));
    let was = Rc::downgrade(&held);
    *memo.borrow_mut() = if again { Memoed::Kept(was, d.clone()) } else { Memoed::Seen(was) };
    d
}

/// What one stretch of a tree drew: the nodes it put into its parent, the
/// bindings it made, the elements it handed to the engine, and the
/// `if` / `each` blocks inside it.
struct Block<R: Renderer> {
    top: Vec<R::Node>,
    bindings: Vec<BindingId>,
    /// The listeners its elements hold, taken away with it.
    unlisten: Vec<Unlisten>,
    hosts: Vec<R::Node>,
    dyns: Vec<Rc<RefCell<Dyn<R>>>>,
}

impl<R: Renderer> Default for Block<R> {
    fn default() -> Self {
        Self { top: Vec::new(), bindings: Vec::new(), unlisten: Vec::new(), hosts: Vec::new(), dyns: Vec::new() }
    }
}

/// An `if`'s or `each`'s current blocks, by key, in order.
struct Dyn<R: Renderer> {
    parent: R::Node,
    /// Whether its nodes sit in its block's own parent (then removing the
    /// block removes them one by one).
    top: bool,
    rows: Vec<(String, Block<R>, Option<Signal<Value>>)>,
}

impl<R: Renderer> Ctx<R> {
    fn expr(&self, text: &str) -> Option<Expr> {
        // FRAME-17: compiled once a page (expr's own cache).
        match Expr::compile(text) {
            Ok(e) => Some(e),
            Err(m) => {
                warn(&format!("{}: the expression `{text}`: {m}", self.layout));
                None
            }
        }
    }

    /// Evaluates `text` in the scope with `env`, reading (tracked) only
    /// what it names.
    fn eval(&self, env: &Env, text: &str) -> rhai::Dynamic {
        self.eval_with(env, None, text)
    }

    /// [`Self::eval`] with one more constant in scope, innermost.
    fn eval_with(&self, env: &Env, extra: Option<(&str, &Value)>, text: &str) -> rhai::Dynamic {
        let Some(e) = self.expr(text) else { return rhai::Dynamic::UNIT };
        if let Some(v) = e.path.as_ref().and_then(|p| self.path_value(env, extra, &e, p)) {
            return expr::to_dynamic(&v);
        }
        let mut scope = rhai::Scope::new();
        for (k, v) in &self.scope.props {
            if e.reads.names.contains(k) {
                scope.push_constant_dynamic(k.clone(), expr::to_dynamic(v));
            }
        }
        if e.reads.names.contains("state") {
            let state = self.scope.state.read(e.reads.state_keys.as_ref());
            scope.push_dynamic("state", expr::to_dynamic(&Value::Object(state)));
        }
        for (k, sig) in &self.scope.live {
            if e.reads.names.contains(k) {
                // FRAME-17: a collection is converted for the expression
                // that reads it whole and let go — kept, at a million the
                // extents and counts held 384 KiB more of the wasm's memory
                // (over UI-8's 10 MB); a path into it (`rows.status`,
                // `things.rows`) is read without converting it at all.
                scope.push_dynamic(k.clone(), sig.with(expr::to_dynamic));
            }
        }
        for v in env.iter() {
            if e.reads.names.contains(&v.name) {
                scope.push_dynamic(v.name.clone(), memoized(&v.sig, &v.memo));
            }
        }
        if let Some((k, v)) = extra {
            scope.push_constant_dynamic(k.to_string(), expr::to_dynamic(v));
        }
        match e.eval(&mut scope) {
            Ok(d) => d,
            Err(m) => {
                warn(&format!("{}: `{text}`: {m}", self.layout));
                rhai::Dynamic::UNIT
            }
        }
    }

    /// FRAME-17: a path (`r.id`, `things.rows`, `state.q`, `filter`) read
    /// straight from the scope's values, the innermost name first, as Rhai's
    /// scope would find it — or none when the name is in no scope (Rhai
    /// says why).
    fn path_value(&self, env: &Env, extra: Option<(&str, &Value)>, e: &Expr, path: &[String]) -> Option<Value> {
        let (name, fields) = (&path[0], &path[1..]);
        let null = || Value::Null;
        if let Some((k, v)) = extra {
            if k == name {
                return Some(expr::walk(v, fields).cloned().unwrap_or_else(null));
            }
        }
        if let Some(v) = env.iter().rev().find(|v| &v.name == name) {
            return Some(v.sig.with(|row| expr::walk(row, fields).cloned().unwrap_or_else(null)));
        }
        if let Some(sig) = self.scope.live.get(name) {
            return Some(sig.with(|l| expr::walk(l, fields).cloned().unwrap_or_else(null)));
        }
        if name == "state" {
            let state = Value::Object(self.scope.state.read(e.reads.state_keys.as_ref()));
            return Some(expr::walk(&state, fields).cloned().unwrap_or_else(null));
        }
        self.scope.props.get(name).map(|v| expr::walk(v, fields).cloned().unwrap_or_else(null))
    }

    /// [`Self::eval_with`] as JSON — a path read without passing through Rhai.
    fn eval_value(&self, env: &Env, extra: Option<(&str, &Value)>, text: &str) -> Value {
        if let Some(e) = self.expr(text) {
            if let Some(v) = e.path.as_ref().and_then(|p| self.path_value(env, extra, &e, p)) {
                return v;
            }
        }
        expr::to_value(&self.eval_with(env, extra, text))
    }

    fn props(&self, env: &Env, props: &BTreeMap<String, Attr>) -> Map<String, Value> {
        self.rt.untracked(|| {
            props
                .iter()
                .map(|(k, a)| {
                    let v = match a {
                        Attr::Lit(s) => Value::String(s.clone()),
                        Attr::Expr(e) => expr::to_value(&self.eval(env, e)),
                    };
                    (k.clone(), v)
                })
                .collect()
        })
    }
}

fn warn(msg: &str) {
    #[cfg(feature = "dom")]
    web_sys::console::warn_1(&msg.into());
    #[cfg(not(feature = "dom"))]
    let _ = msg;
}

/// A binding over `compute`: its first value returned, `changed` called
/// (untracked) with each later value that differs.
fn watch<T: PartialEq + Clone + 'static>(rt: &Runtime, mut compute: impl FnMut() -> T + 'static, mut changed: impl FnMut(T) + 'static) -> (BindingId, T) {
    let last: Rc<RefCell<Option<T>>> = Rc::default();
    let (l, r) = (last.clone(), rt.clone());
    let id = rt.bind(move || {
        let v = compute();
        let mut held = l.borrow_mut();
        match held.as_ref() {
            None => *held = Some(v),
            Some(old) if *old == v => {}
            Some(_) => {
                *held = Some(v.clone());
                drop(held);
                r.untracked(|| changed(v));
            }
        }
    });
    let first = last.borrow().clone().expect("a binding runs when made");
    (id, first)
}

fn build<R: Renderer>(ctx: &Rc<Ctx<R>>, env: &Env, nodes: &[Node], parent: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
    for n in nodes {
        build_node(ctx, env, n, parent, before, block, top);
    }
}

fn place<R: Renderer>(ctx: &Ctx<R>, parent: &R::Node, node: &R::Node, before: Option<&R::Node>, block: &mut Block<R>, top: bool) {
    ctx.renderer.insert(parent, node, before);
    if top {
        block.top.push(node.clone());
    }
}

fn 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) {
    let r = &ctx.renderer;
    match node {
        Node::El { el, attrs, on, children } => {
            let e = r.create_element(el);
            for (name, a) in attrs {
                match a {
                    Attr::Lit(v) => r.set_attr(&e, name, v),
                    Attr::Expr(x) => {
                        let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
                        let (c2, e2, name2) = (ctx.clone(), e.clone(), name.clone());
                        let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |v: String| c2.renderer.set_attr(&e2, &name2, &v));
                        r.set_attr(&e, name, &first);
                        block.bindings.push(id);
                    }
                }
            }
            for (event, handler) in on {
                let (on_event, handler) = (ctx.scope.on_event.clone(), handler.clone());
                block.unlisten.push(r.listen(&e, event, Rc::new(move |payload: Value| on_event(&handler, payload))));
            }
            build(ctx, env, children, &e, None, block, false);
            place(ctx, parent, &e, before, block, top);
        }
        Node::Text(Attr::Lit(t)) => {
            let t = r.create_text(t);
            place(ctx, parent, &t, before, block, top);
        }
        Node::Text(Attr::Expr(x)) => {
            let cell: Rc<RefCell<Option<R::Node>>> = Rc::default();
            let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
            let (c2, cell2) = (ctx.clone(), cell.clone());
            let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |v: String| {
                if let Some(n) = cell2.borrow().as_ref() {
                    c2.renderer.set_text(n, &v);
                }
            });
            let t = r.create_text(&first);
            *cell.borrow_mut() = Some(t.clone());
            block.bindings.push(id);
            place(ctx, parent, &t, before, block, top);
        }
        Node::If { cond, then, otherwise } => {
            let anchor = r.create_text("");
            place(ctx, parent, &anchor, before, block, top);
            let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
            let branches = Rc::new((then.clone(), otherwise.clone()));
            let (c, env2, cond2) = (ctx.clone(), env.clone(), cond.clone());
            let (c2, env3, d2, a2, b2) = (ctx.clone(), env.clone(), d.clone(), anchor.clone(), branches.clone());
            let (id, first) = watch(&ctx.rt, move || expr::truthy(&c.eval(&env2, &cond2)), move |v: bool| {
                fill_if(&c2, &env3, &d2, &a2, &b2, v);
            });
            block.bindings.push(id);
            ctx.rt.untracked(|| fill_if(ctx, env, &d, &anchor, &branches, first));
            block.dyns.push(d);
        }
        Node::Each { expr: list, as_, key, body } => {
            let anchor = r.create_text("");
            place(ctx, parent, &anchor, before, block, top);
            let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
            let spec = Rc::new((as_.clone(), body.clone()));
            let (c, env2, list2, as2, key2) = (ctx.clone(), env.clone(), list.clone(), as_.clone(), key.clone());
            let (c2, env3, d2, a2, s2) = (ctx.clone(), env.clone(), d.clone(), anchor.clone(), spec.clone());
            let (id, first) = watch(
                &ctx.rt,
                move || keyed(&c, &env2, &list2, &as2, &key2),
                move |rows: Vec<(String, Value)>| reconcile(&c2, &env3, &d2, &a2, &s2, rows),
            );
            block.bindings.push(id);
            ctx.rt.untracked(|| reconcile(ctx, env, &d, &anchor, &spec, first));
            block.dyns.push(d);
        }
        Node::Component { name, props } => {
            let props = ctx.props(env, props);
            let e = if ctx.children.binds(name) {
                let e = r.create_element("div");
                r.set_attr(&e, "data-layout", &ctx.layout);
                r.set_attr(&e, "data-slot", name);
                r.set_attr(&e, "data-component", name);
                ctx.children.mount_bound(&e, &ctx.layout, name, props);
                e
            } else {
                let e = r.create_element(name);
                ctx.children.mount_component(&e, name, props);
                e
            };
            block.hosts.push(e.clone());
            place(ctx, parent, &e, before, block, top);
        }
        Node::Html(x) => {
            let anchor = r.create_text("");
            place(ctx, parent, &anchor, before, block, top);
            let d = Rc::new(RefCell::new(Dyn { parent: parent.clone(), top, rows: Vec::new() }));
            let (c, env2, x2) = (ctx.clone(), env.clone(), x.clone());
            let (c2, d2, a2) = (ctx.clone(), d.clone(), anchor.clone());
            let (id, first) = watch(&ctx.rt, move || expr::as_text(&c.eval(&env2, &x2)), move |html: String| fill_html(&c2, &d2, &a2, &html));
            block.bindings.push(id);
            ctx.rt.untracked(|| fill_html(ctx, &d, &anchor, &first));
            block.dyns.push(d);
        }
        Node::Slot { name, props } => {
            let e = r.create_element("div");
            r.set_attr(&e, "data-layout", &ctx.layout);
            r.set_attr(&e, "data-slot", name);
            let props = ctx.props(env, props);
            ctx.children.mount_slot(&e, &ctx.layout, name, props);
            block.hosts.push(e.clone());
            place(ctx, parent, &e, before, block, top);
        }
    }
}

/// UI-10: an `{@html}`'s nodes: the old ones out, the sanitized tree drawn
/// before the anchor through the renderer (no HTML string reaches it).
fn fill_html<R: Renderer>(ctx: &Rc<Ctx<R>>, d: &Rc<RefCell<Dyn<R>>>, anchor: &R::Node, html: &str) {
    let (old, parent) = {
        let mut d = d.borrow_mut();
        (std::mem::take(&mut d.rows), d.parent.clone())
    };
    for (_, b, _) in old {
        dispose(ctx, b, Some(&parent));
    }
    fn draw<R: Renderer>(r: &R, nodes: &[crate::html::HNode], parent: &R::Node, before: Option<&R::Node>, top: &mut Vec<R::Node>) {
        for n in nodes {
            let node = match n {
                crate::html::HNode::Text(t) => r.create_text(t),
                crate::html::HNode::Element { tag, attrs, children } => {
                    let e = r.create_element(tag);
                    for (k, v) in attrs {
                        r.set_attr(&e, k, v);
                    }
                    draw(r, children, &e, None, &mut Vec::new());
                    e
                }
            };
            r.insert(parent, &node, before);
            top.push(node);
        }
    }
    let mut b = Block::default();
    draw(&ctx.renderer, &crate::html::sanitize(html), &parent, Some(anchor), &mut b.top);
    d.borrow_mut().rows.push((String::new(), b, None));
}

fn 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) {
    let (old, parent) = {
        let mut d = d.borrow_mut();
        (std::mem::take(&mut d.rows), d.parent.clone())
    };
    for (_, b, _) in old {
        dispose(ctx, b, Some(&parent));
    }
    let nodes = if on { &branches.0 } else { &branches.1 };
    if nodes.is_empty() {
        return;
    }
    let mut b = Block::default();
    build(ctx, env, nodes, &parent, Some(anchor), &mut b, true);
    d.borrow_mut().rows.push((String::new(), b, None));
}

/// The list `list` names, each item with its key (a key seen twice gets
/// its index after it).
fn keyed<R: Renderer>(ctx: &Ctx<R>, env: &Env, list: &str, as_: &str, key: &str) -> Vec<(String, Value)> {
    let items = match ctx.eval_value(env, None, list) {
        Value::Array(a) => a,
        _ => Vec::new(),
    };
    ctx.rt.untracked(|| {
        let mut seen = std::collections::BTreeSet::new();
        items
            .into_iter()
            .enumerate()
            .map(|(i, item)| {
                let mut k = match ctx.eval_value(env, Some((as_, &item)), key) {
                    Value::String(s) => s,
                    other => expr::as_text(&expr::to_dynamic(&other)),
                };
                if !seen.insert(k.clone()) {
                    k = format!("{k}#{i}");
                }
                (k, item)
            })
            .collect()
    })
}

fn 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)>) {
    let (mut old, parent) = {
        let mut d = d.borrow_mut();
        (std::mem::take(&mut d.rows), d.parent.clone())
    };
    // The rows that go.
    let wanted: std::collections::BTreeSet<&String> = rows.iter().map(|(k, _)| k).collect();
    let mut kept = Vec::new();
    for (k, b, s) in old.drain(..) {
        if wanted.contains(&k) {
            kept.push((k, b, s));
        } else {
            dispose(ctx, b, Some(&parent));
        }
    }
    // Whether the rows that stay keep their order.
    let kept_order: Vec<&String> = kept.iter().map(|(k, _, _)| k).collect();
    let new_order: Vec<&String> = rows.iter().map(|(k, _)| k).filter(|k| kept_order.contains(k)).collect();
    let moved = kept_order != new_order;
    let mut by_key: BTreeMap<String, (Block<R>, Option<Signal<Value>>)> = kept.into_iter().map(|(k, b, s)| (k, (b, s))).collect();
    let mut next: Vec<(String, Block<R>, Option<Signal<Value>>)> = Vec::with_capacity(rows.len());
    let mut before = anchor.clone();
    for (k, item) in rows.into_iter().rev() {
        match by_key.remove(&k) {
            Some((b, s)) => {
                if let Some(s) = &s {
                    s.set(item);
                }
                if moved {
                    for n in &b.top {
                        ctx.renderer.insert(&parent, n, Some(&before));
                    }
                }
                if let Some(first) = b.top.first() {
                    before = first.clone();
                }
                next.push((k, b, s));
            }
            None => {
                let sig = ctx.rt.signal(item);
                let mut inner = (**env).clone();
                inner.push(Var { name: spec.0.clone(), sig: sig.clone(), memo: Memo::default() });
                let mut b = Block::default();
                build(ctx, &Rc::new(inner), &spec.1, &parent, Some(&before), &mut b, true);
                if let Some(first) = b.top.first() {
                    before = first.clone();
                }
                next.push((k, b, Some(sig)));
            }
        }
    }
    next.reverse();
    d.borrow_mut().rows = next;
}

/// Stops `block`'s bindings, empties the engine's elements in it, and —
/// given its parent — takes its nodes out.
fn dispose<R: Renderer>(ctx: &Ctx<R>, block: Block<R>, parent: Option<&R::Node>) {
    for id in block.bindings {
        ctx.rt.dispose(id);
    }
    for off in block.unlisten {
        off();
    }
    for d in block.dyns {
        let (rows, dparent, top) = {
            let mut d = d.borrow_mut();
            (std::mem::take(&mut d.rows), d.parent.clone(), d.top)
        };
        for (_, b, _) in rows {
            dispose(ctx, b, if top && parent.is_some() { Some(&dparent) } else { None });
        }
    }
    for h in &block.hosts {
        ctx.children.unmount(h);
    }
    if let Some(p) = parent {
        for n in &block.top {
            ctx.renderer.remove(p, n);
        }
    }
}

/// A mounted tree: its nodes under the parent and its bindings.
pub struct Mounted<R: Renderer> {
    pub parent: R::Node,
    ctx: Rc<Ctx<R>>,
    block: Block<R>,
}

impl<R: Renderer> Mounted<R> {
    /// Takes every node it inserted out of the parent and stops its
    /// bindings; [`Children::unmount`] for each component and slot in it.
    pub fn unmount(self) {
        dispose(&self.ctx, self.block, Some(&self.parent));
    }

    /// The nodes it put into the parent, in order.
    pub fn top(&self) -> Vec<R::Node> {
        self.block.top.clone()
    }
}

/// Draws `tree` into `parent` (appended) with `scope`, through `renderer`;
/// `children` fills its components and slots.
pub fn mount<R: Renderer>(
    rt: &Runtime,
    renderer: &R,
    tree: &ComponentTree,
    scope: Scope,
    parent: &R::Node,
    children: Rc<dyn Children<R>>,
) -> Result<Mounted<R>, TreeError> {
    tree.check()?;
    let ctx = Rc::new(Ctx { rt: rt.clone(), renderer: renderer.clone(), layout: tree.name.clone(), scope, children });
    let mut block = Block::default();
    rt.untracked(|| build(&ctx, &Rc::new(Vec::new()), &tree.tree, parent, None, &mut block, true));
    Ok(Mounted { parent: parent.clone(), ctx, block })
}

#[cfg(test)]
mod tests;