plexus-ui-engine 0.2.3

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
//! UI-6: **the module registry, hot-swap and the sections**.
//!
//! The registry is the live version's `manifest.json`: each component's
//! name → the hashes of its tree and handlers. A mounted component is an
//! instance: its element (named for the component), its props, its state,
//! its folds and the version it was drawn from.
//!
//! - **Hot-swap** ([`App::swap`]): a new manifest; each mounted instance
//!   whose `tree` or `handlers` hash changed is remounted into the same
//!   element with the same props — its state carried over when the declared
//!   state's shape (its keys) is unchanged, else the new initial state;
//!   every other instance is untouched. One that fails to mount (a
//!   malformed tree, handlers refused) keeps its last good version drawn,
//!   and the console says so.
//! - **Sections**: a layout's `slot` node draws as a `div` carrying
//!   `data-layout` and `data-slot`, filled by its assignment — from
//!   `ui.slots.list` ([`App::set_assignments`]), else `manifest.slots`'
//!   default — with the slot's attributes as props. A component of another
//!   version is drawn from that version's files ([`Files::put_version`],
//!   fetched by the engine from `/app/<hash>/components/<name>.json` and
//!   `.rhai`). `slot_changed` ([`App::slot_changed`]) remounts that section
//!   alone, its props kept.
//!
//! What the engine fetches is handed in as [`Files`] (content-addressed by
//! sha256), so everything here is synchronous: the browser fetches first,
//! then swaps.
//!
//! FRAME-12: a component of any profile but `rhx/1` is a module
//! ([`crate::module`]) the page imports and hands in with
//! [`App::provide_module`]; it is mounted, swapped and filled by the same
//! rules, with these: a module whose hash changed is destroyed, then
//! mounted from the new version into the same element with the same props
//! — and when that `mount` throws, the last good version is mounted again
//! and the element marked; a section whose assignment changes mounts the
//! new component before the old one is taken out, and when the new one
//! fails the old stays drawn, marked; a route to the component already
//! drawn is an `update(props)`. Every mounted instance is a member of the
//! page's [`Bus`] ([`App::bus`]); an rhx fold hears the topics its tree's
//! `bus` names and runs with the bus held.
//!
//! FRAME-29: **a bound mark** — a `[data-slot]` mark that also carries
//! `data-component` (and, optionally, `data-version`) — is a section bound
//! early: its code chose what fills it. The walk fills it with that
//! component (of that version, else the live one) with the mark's other
//! `data-*` as props, whatever the assignments and `slots.json` say; no
//! assignment, `slot_changed` or default reaches it, and `slots_set` on it
//! is refused `bound` ([`crate::bus::BusRefusal::Bound`]). Its props follow
//! the mark as an unbound section's do; a mark whose binding changes is a
//! new section; a swap remounts it when its component's hash changed, as
//! any instance (a `data-version` pins it); it goes when its mark does.

mod boot;
mod turns;

pub use turns::{Yield, HELD};

use crate::bus::{answer_sink, Answer, Bus, BusHost, Listening, Member};
use crate::folds::{FoldError, Folds, Host};
use crate::live::{Clock, Follow, LiveCache, LiveQuery, LiveSpec, ModuleLive, ModuleSpec, Reader};
use crate::module::{Module, ModuleInstance, RHX};
use crate::transport::{CallId, Sink};
use crate::signals::{Runtime, Signal};
use crate::transport::Wire;
use crate::tree::{Children, ComponentTree, Mounted, Renderer, Scope, State};
use serde_json::{Map, Value};
use sha2::Digest;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::{Rc, Weak};

/// One component of a manifest.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ComponentEntry {
    /// The sha256 of `components/<name>.json` (`rhx/1`).
    pub tree: String,
    /// The sha256 of `components/<name>.rhai` (`rhx/1`).
    pub handlers: String,
    pub uses: Vec<String>,
    /// FRAME-12: the profile that draws it; empty (a manifest written
    /// before profiles) is `rhx/1`.
    pub profile: String,
    /// FRAME-12: a module's sha256 (`components/<name>.js`), for every
    /// profile but `rhx/1`.
    pub module: String,
    /// FRAME-30: its sheet's sha256 (`components/<name>.css`); empty when it
    /// has none.
    pub css: String,
}

impl ComponentEntry {
    /// Drawn by the rhx runtime.
    pub fn is_rhx(&self) -> bool {
        self.profile.is_empty() || self.profile == RHX
    }

    /// What names its code: the tree's and the handlers' hashes, or the
    /// module's and (FRAME-30) its sheet's. An rhx sheet is named by its
    /// tree (the mark), so a sheet changed is a tree changed.
    pub fn hashes(&self) -> (String, String) {
        if self.is_rhx() {
            (self.tree.clone(), self.handlers.clone())
        } else {
            (self.module.clone(), self.css.clone())
        }
    }
}

/// A bundle's `manifest.json`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Manifest {
    pub abi: String,
    pub contract: String,
    pub commit: String,
    /// A route pattern (`#/ticket/:id`) → the component (or layout) drawn.
    pub routes: BTreeMap<String, String>,
    pub components: BTreeMap<String, ComponentEntry>,
    /// A layout → its slot → the component filling it by default.
    pub slots: BTreeMap<String, BTreeMap<String, String>>,
}

impl Manifest {
    /// From `manifest.json`'s text.
    pub fn parse(json: &str) -> Result<Self, String> {
        let v: Value = serde_json::from_str(json).map_err(|e| format!("manifest.json: {e}"))?;
        let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
        let map = |k: &str| -> BTreeMap<String, String> {
            v.get(k).and_then(Value::as_object).map(|o| o.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect()).unwrap_or_default()
        };
        let components = v
            .get("components")
            .and_then(Value::as_object)
            .ok_or("manifest.json names no components")?
            .iter()
            .map(|(name, e)| {
                let f = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_string).ok_or(format!("manifest.json: {name} has no {k}"));
                let uses = e.get("uses").and_then(Value::as_array).map(|a| a.iter().filter_map(|u| u.as_str().map(str::to_string)).collect()).unwrap_or_default();
                let profile = e.get("profile").and_then(Value::as_str).unwrap_or(RHX).to_string();
                let css = e.get("css").and_then(Value::as_str).unwrap_or_default().to_string();
                let entry = if profile == RHX {
                    ComponentEntry { tree: f("tree")?, handlers: f("handlers")?, uses, profile, module: String::new(), css }
                } else {
                    ComponentEntry { module: f("module")?, uses, profile, css, ..ComponentEntry::default() }
                };
                Ok((name.clone(), entry))
            })
            .collect::<Result<_, String>>()?;
        let slots = v
            .get("slots")
            .and_then(Value::as_object)
            .map(|o| {
                o.iter()
                    .map(|(layout, m)| {
                        let m = m.as_object().map(|m| m.iter().filter_map(|(a, b)| Some((a.clone(), b.as_str()?.to_string()))).collect()).unwrap_or_default();
                        (layout.clone(), m)
                    })
                    .collect()
            })
            .unwrap_or_default();
        Ok(Self { abi: s("abi"), contract: s("contract"), commit: s("commit"), routes: map("routes"), components, slots })
    }
}

/// What the engine has fetched: each version's component by
/// `(version, name)` — `/app/<version>/components/<name>.json` and `.rhai`.
#[derive(Debug, Clone, Default)]
pub struct Files {
    /// STUDIO-9: shared text — a version that keeps another's unchanged
    /// component (a swap) holds the same allocation, not a copy.
    by_version: BTreeMap<(String, String), (Rc<str>, Rc<str>)>,
    /// FRAME-30: an rhx component's sheet's text — components.json's `css`,
    /// or `components/<name>.css`.
    sheets: BTreeMap<(String, String), Rc<str>>,
}

/// The sha256 of `text`, hex — what a manifest names a file by.
pub fn sha256_hex(text: &str) -> String {
    sha2::Sha256::digest(text.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
}

impl Files {
    /// Keeps version `version`'s component `name`: its tree and handlers.
    pub fn put_version(&mut self, version: &str, name: &str, tree: &str, handlers: &str) {
        self.by_version.insert((version.into(), name.into()), (Rc::from(tree), Rc::from(handlers)));
    }

    /// FRAME-30: keeps version `version`'s component `name`'s sheet's text.
    pub fn put_sheet(&mut self, version: &str, name: &str, css: &str) {
        self.sheets.insert((version.into(), name.into()), Rc::from(css));
    }

    /// FRAME-30: version `version`'s component `name`'s sheet, when fetched.
    pub fn sheet(&self, version: &str, name: &str) -> Option<Rc<str>> {
        self.sheets.get(&(version.to_string(), name.to_string())).cloned()
    }

    /// Version `version`'s component `name`: `(tree, handlers)`.
    pub fn version(&self, version: &str, name: &str) -> Option<(&str, &str)> {
        self.by_version.get(&(version.to_string(), name.to_string())).map(|(t, h)| (&**t, &**h))
    }

    /// STUDIO-9: version `from`'s component `name` kept under `to` as well —
    /// its tree, handlers and sheet shared, not copied. False when `from`
    /// has none.
    pub fn share(&mut self, from: &str, to: &str, name: &str) -> bool {
        let Some(files) = self.by_version.get(&(from.to_string(), name.to_string())).cloned() else { return false };
        self.by_version.insert((to.into(), name.into()), files);
        if let Some(css) = self.sheet(from, name) {
            self.sheets.insert((to.into(), name.into()), css);
        }
        true
    }

    /// STUDIO-9: the bytes kept, each text counted once however many
    /// versions share it.
    pub fn kept_bytes(&self) -> usize {
        let mut seen = std::collections::BTreeSet::new();
        let texts = self.by_version.values().flat_map(|(t, h)| [t, h]).chain(self.sheets.values());
        texts.filter(|x| seen.insert(Rc::as_ptr(x) as *const u8 as usize)).map(|x| x.len()).sum()
    }

    /// Everything `other` holds, kept too.
    pub fn extend(&mut self, other: &Files) {
        self.by_version.extend(other.by_version.iter().map(|(k, v)| (k.clone(), v.clone())));
        self.sheets.extend(other.sheets.iter().map(|(k, v)| (k.clone(), v.clone())));
    }
}

/// What fills a section: `(layout, slot) → (component, version)` — kept
/// by the ui service (`ui.slots.*`), said on `ui.watch` as `slot_changed`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Assignment {
    pub layout: String,
    pub slot: String,
    pub component: String,
    /// The version's hash (the live one's, for a component of the live bundle).
    pub version: String,
}

/// A mounted instance.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MountId(pub u64);

/// What a swap did.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SwapReport {
    /// Remounted on their new hashes.
    pub remounted: Vec<MountId>,
    /// Kept on their last good version: each with why.
    pub failed: Vec<(MountId, String)>,
}

/// Why a mount or a load did not happen.
#[derive(Debug, Clone, PartialEq)]
pub enum SwapError {
    /// No component of that name in the version.
    Unknown(String),
    /// A component's files were not fetched yet: `(version, name)`
    /// ([`App::needs`] lists it).
    Missing(String, String),
    /// The tree did not parse or mount, or the handlers were refused: why.
    Failed { component: String, message: String },
}

impl std::fmt::Display for SwapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SwapError::Unknown(c) => write!(f, "no component {c} in this version"),
            SwapError::Missing(v, n) => write!(f, "{n} of {v} is not fetched yet"),
            SwapError::Failed { component, message } => write!(f, "{component} failed to mount: {message}"),
        }
    }
}

/// The section menu (a right-click on a section): the live bundle's
/// components by name, and the section's component's other stored
/// versions — those whose hash for it differs from the live one's —
/// newest first, the live one excluded.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Menu {
    /// The section's component, as drawn.
    pub component: String,
    pub components: Vec<String>,
    pub versions: Vec<String>,
}

/// The member an rhx component's folds speak through, and the instance
/// they fold into (FRAME-37: a call's answer folds there), set at each mount.
type MemberSlot = Rc<RefCell<Option<(Member, MountId)>>>;

/// A component ready to mount: an rhx tree and folds, checked; or a module.
enum Prepared<R: Renderer> {
    Rhx { version: String, tree: Rc<ComponentTree>, folds: Rc<Folds>, tree_hash: String, handlers_hash: String, slot: MemberSlot, css: Sheet },
    Module { version: String, name: String, hash: String, css: String, uses: Vec<String>, module: Rc<dyn Module<R>> },
}

/// FRAME-30: a sheet the page adopts — its key (the component and its
/// sheet's hash) and its text.
type Sheet = Option<(String, Rc<str>)>;

impl<R: Renderer> Prepared<R> {
    fn version(&self) -> &str {
        match self {
            Prepared::Rhx { version, .. } | Prepared::Module { version, .. } => version,
        }
    }

    /// FRAME-30: its sheet, when it has one — an rhx tree that names a mark
    /// (the text components.json or its file gave), a module whose entry
    /// names a `css` (the text it exports as `css`) — keyed by the component
    /// and the sheet's sha256: two versions of one sheet are one sheet.
    fn sheet(&self) -> Sheet {
        match self {
            Prepared::Rhx { css, .. } => css.clone(),
            Prepared::Module { name, css, module, .. } => (!css.is_empty()).then(|| module.css()).flatten().map(|text| (format!("{name}@{css}"), Rc::from(text.as_str()))),
        }
    }
}

/// What draws a mounted instance.
enum Body<R: Renderer> {
    Rhx {
        tree_hash: String,
        handlers_hash: String,
        state: State,
        live: BTreeMap<String, Signal<Value>>,
        readers: Vec<Follow>,
        folds: Rc<Folds>,
        tree: Rc<ComponentTree>,
        mounted: Option<Mounted<R>>,
        slot: MemberSlot,
        /// FRAME-30: its sheet, keyed, and its text.
        css: Sheet,
        /// The topics it hears.
        _listening: Vec<Listening>,
        /// FRAME-36: its keys, in the page's registry while it is mounted.
        _keys: crate::keys::KeysHeld,
    },
    Module {
        hash: String,
        /// FRAME-30: its sheet's sha256, empty when none.
        css: String,
        uses: Vec<String>,
        module: Rc<dyn Module<R>>,
        mounted: Option<Box<dyn ModuleInstance>>,
        /// FRAME-18: the observer of its element's marks, stopped with it.
        observing: Option<crate::tree::Unlisten>,
    },
}

/// A mounted instance.
struct Inst<R: Renderer> {
    name: String,
    version: String,
    /// Drawn from an assignment's version: a swap leaves it.
    pinned: bool,
    element: R::Node,
    props: Map<String, Value>,
    member: Member,
    body: Body<R>,
    /// Its last swap failed: it carries `data-failed`.
    failed: bool,
}

impl<R: Renderer> Inst<R> {
    fn hashes(&self) -> (String, String) {
        match &self.body {
            Body::Rhx { tree_hash, handlers_hash, .. } => (tree_hash.clone(), handlers_hash.clone()),
            Body::Module { hash, css, .. } => (hash.clone(), css.clone()),
        }
    }

    /// What it was drawn from, ready to mount again.
    fn prepared(&self) -> Prepared<R> {
        match &self.body {
            Body::Rhx { tree_hash, handlers_hash, folds, tree, slot, css, .. } => Prepared::Rhx {
                version: self.version.clone(),
                tree: tree.clone(),
                folds: folds.clone(),
                tree_hash: tree_hash.clone(),
                handlers_hash: handlers_hash.clone(),
                slot: slot.clone(),
                css: css.clone(),
            },
            Body::Module { hash, css, uses, module, .. } => {
                Prepared::Module { version: self.version.clone(), name: self.name.clone(), hash: hash.clone(), css: css.clone(), uses: uses.clone(), module: module.clone() }
            }
        }
    }

    fn state(&self) -> Option<Map<String, Value>> {
        match &self.body {
            Body::Rhx { state, .. } => Some(state.snapshot()),
            Body::Module { .. } => None,
        }
    }

    /// Takes it out of the page: its tree or its module, its readers, its
    /// place on the bus.
    fn teardown(mut self) {
        match &mut self.body {
            Body::Rhx { mounted, readers, .. } => {
                if let Some(m) = mounted.take() {
                    m.unmount();
                }
                drop(std::mem::take(readers));
            }
            Body::Module { mounted, observing, .. } => {
                if let Some(off) = observing.take() {
                    off();
                }
                if let Some(m) = mounted.take() {
                    m.destroy();
                }
            }
        }
        self.member.leave();
    }
}

/// A section drawn: its `div`, its props and what fills it.
struct Section<R: Renderer> {
    sid: u64,
    /// FRAME-18: the module layout whose mark it is (the walk found it);
    /// none for an rhx `<slot>` (its tree says when it goes).
    owner: Option<MountId>,
    layout: String,
    slot: String,
    div: R::Node,
    props: Map<String, Value>,
    instance: Option<MountId>,
    /// What it waits on, when its files are not fetched yet.
    waiting: Option<(String, String, bool)>,
    /// FRAME-29: what its mark binds it to — `(component, version)`, the
    /// version none for the live one; none for a late-bound section.
    bound: Option<Binding>,
    /// STUDIO-9: an rhx child's own element (`<tag-chip>`), filled in
    /// place — its component mounts into `div` itself, never a new element
    /// inside it.
    inline: bool,
    /// FRAME-50: drawn while the mount yields, and waiting its turn
    /// ([`App::fill_soon`]); a fill before the turn takes it off.
    queued: bool,
}

/// FRAME-29: a mark's `data-component` and `data-version`.
type Binding = (String, Option<String>);

/// A module handed in: its code and its version's manifest entry.
type Provided<R> = (Rc<dyn Module<R>>, ComponentEntry);

struct St<R: Renderer> {
    version: String,
    manifest: Manifest,
    files: Files,
    /// FRAME-12: the modules imported, by `(version, name)`.
    modules: BTreeMap<(String, String), Provided<R>>,
    needs: Vec<(String, String)>,
    instances: BTreeMap<MountId, Inst<R>>,
    next: u64,
    assignments: Vec<Assignment>,
    sections: Vec<Section<R>>,
    console: Vec<String>,
    /// FRAME-29: the (layout, slot)s whose stored assignment a mark's
    /// binding overrides, said once each.
    warned: std::collections::BTreeSet<(String, String)>,
}

/// The engine: the registry, the instances, the sections — over a
/// renderer, the wire (for `call` and `live`) and a clock.
pub struct App<R: Renderer, W: Wire, C: Clock> {
    rt: Runtime,
    renderer: R,
    wire: W,
    cache: Rc<LiveCache<W, C>>,
    bus: Bus,
    st: RefCell<St<R>>,
    navigate: RefCell<Option<Rc<dyn Fn(&str)>>>,
    /// FRAME-29: told when a walk the module's own DOM set off left
    /// something to fetch ([`Self::needs`]).
    on_need: RefCell<Option<Rc<dyn Fn()>>>,
    /// FRAME-29: the components mounting now, outermost first.
    attaching: RefCell<Vec<String>>,
    /// FRAME-17: every tree parsed, by its sha256 — once a page.
    trees: RefCell<BTreeMap<String, Rc<ComponentTree>>>,
    /// FRAME-17: trees the boot read without compiling, by sha256.
    read_trees: RefCell<BTreeMap<String, Rc<ComponentTree>>>,
    /// FRAME-30: each sheet on the page by its address, and how many
    /// mounted instances hold it.
    sheets: RefCell<BTreeMap<String, usize>>,
    /// FRAME-36: the window's key listener, stopped with the engine.
    keys_off: RefCell<Option<crate::tree::Unlisten>>,
    /// FRAME-37: each instance's calls whose answer it waits on, closed when
    /// it is unmounted.
    calls: RefCell<BTreeMap<MountId, Vec<CallId>>>,
    /// FRAME-50: the mount's turns ([`turns`]).
    turns: turns::Turns<R::Node>,
    me: Weak<Self>,
}

impl<R: Renderer, W: Wire, C: Clock> Drop for App<R, W, C> {
    fn drop(&mut self) {
        if let Some(off) = self.keys_off.borrow_mut().take() {
            off();
        }
    }
}

/// The engine's side of every mount ([`Children`]): the engine, the version
/// the instance whose tree is drawing is pinned to (none: it follows the
/// page's), and its name.
struct Kids<R: Renderer, W: Wire, C: Clock>(Weak<App<R, W, C>>, Option<String>, String);

impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> Children<R> for Kids<R, W, C> {
    fn mount_component(&self, at: &R::Node, name: &str, props: Map<String, Value>) {
        let Some(app) = self.0.upgrade() else { return };
        let version = app.st.borrow().version.clone();
        let pin = self.1.clone();
        if pin.as_deref().is_none_or(|v| v == version) {
            match app.instantiate(at, name, &version, pin.is_some(), props.clone()) {
                Ok(_) => return,
                // STUDIO-9: not fetched yet: it waits, below, as a
                // section's component does.
                Err(SwapError::Missing(..)) => {}
                Err(e) => return app.say(&format!("{name} ({version}): {e}")),
            }
        }
        // STUDIO-9: a section bound to the child, filled in the child's own
        // element — of the version its parent is pinned to (a section
        // assigned a stored version, a mark's data-version, a studio's
        // frame: its children are that version's), or the page's — and
        // fetched as any section's component is.
        let sid = app.next_id().0;
        let s = Section { sid, owner: None, layout: self.2.clone(), slot: name.into(), div: at.clone(), props, instance: None, waiting: None, bound: Some((name.to_string(), pin)), inline: true, queued: false };
        app.st.borrow_mut().sections.push(s);
        app.fill(sid);
        app.told_needs();
    }

    fn mount_slot(&self, at: &R::Node, layout: &str, slot: &str, props: Map<String, Value>) {
        if let Some(app) = self.0.upgrade() {
            let sid = app.next_id().0;
            let s = Section { sid, owner: None, layout: layout.into(), slot: slot.into(), div: at.clone(), props, instance: None, waiting: None, bound: None, inline: false, queued: false };
            app.st.borrow_mut().sections.push(s);
            app.fill_soon(sid);
        }
    }

    fn unmount(&self, at: &R::Node) {
        if let Some(app) = self.0.upgrade() {
            app.unmount_at(at);
        }
    }

    /// FRAME-29: a child of another profile is a bound mark.
    fn binds(&self, name: &str) -> bool {
        let Some(app) = self.0.upgrade() else { return false };
        let st = app.st.borrow();
        // STUDIO-9: a pinned parent's child is of its version: a module
        // there when that version's module is here, rhx when its files are.
        if let Some(v) = self.1.as_deref().filter(|v| *v != st.version) {
            if st.modules.contains_key(&(v.to_string(), name.to_string())) {
                return true;
            }
            if st.files.version(v, name).is_some() {
                return false;
            }
        }
        st.manifest.components.get(name).is_some_and(|e| !e.is_rhx())
    }

    fn mount_bound(&self, at: &R::Node, layout: &str, name: &str, props: Map<String, Value>) {
        if let Some(app) = self.0.upgrade() {
            let sid = app.next_id().0;
            // STUDIO-9: of the version the parent is pinned to.
            let bound = Some((name.to_string(), self.1.clone()));
            let s = Section { sid, owner: None, layout: layout.into(), slot: name.into(), div: at.clone(), props, instance: None, waiting: None, bound, inline: false, queued: false };
            app.st.borrow_mut().sections.push(s);
            app.fill_soon(sid);
            app.told_needs();
        }
    }
}

/// The folds' host: `call` through the wire, `navigate` to the router,
/// `emit` and `slots_set` through the instance's member of the bus;
/// FRAME-37: `call_then` folds the answer into the instance that called.
struct AppHost<R: Renderer, W: Wire, C: Clock>(Weak<App<R, W, C>>, MemberSlot);

impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> Host for AppHost<R, W, C> {
    fn call(&self, method: &str, params: Value) {
        if let Some(app) = self.0.upgrade() {
            app.wire.open(method, params, Box::new(|_| {}));
        }
    }
    /// FRAME-37: sent once, as `call` is — nothing keeps it to be asked
    /// again on a reconnect (the live cache keeps only its collections) —
    /// and its answer folded in the bus's turn: after the fold that called
    /// has returned its state, even when the wire answers at once.
    fn call_then(&self, method: &str, params: Value, fold: &str) {
        let Some(app) = self.0.upgrade() else { return };
        let Some(id) = self.1.borrow().as_ref().map(|(_, id)| *id) else { return };
        let (me, fold, m, p) = (self.0.clone(), fold.to_string(), method.to_string(), params.clone());
        // Kept while it is open, so an unmount closes it; an answer at once
        // (inside `open`) is never kept.
        let open: Rc<std::cell::Cell<Option<CallId>>> = Rc::new(std::cell::Cell::new(None));
        let ended = Rc::new(std::cell::Cell::new(false));
        let (o, e) = (open.clone(), ended.clone());
        let call = app.wire.open(
            method,
            params,
            answer_sink(move |answer| {
                e.set(true);
                let Some(app) = me.upgrade() else { return };
                if let Some(call) = o.get() {
                    app.forget_call(id, call);
                }
                app.bus.defer(move || {
                    if let Some(app) = me.upgrade() {
                        app.answered(id, &fold, &m, &p, answer);
                    }
                });
            }),
        );
        if !ended.get() {
            open.set(Some(call));
            app.calls.borrow_mut().entry(id).or_default().push(call);
        }
    }
    fn navigate(&self, route: &str) {
        let f = self.0.upgrade().and_then(|app| app.navigate.borrow().clone());
        if let Some(f) = f {
            f(route);
        }
    }
    fn emit(&self, topic: &str, data: Value) -> Result<(), String> {
        let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
        member.ok_or("not mounted")?.emit(topic, data).map_err(|r| r.to_string())
    }
    fn last(&self, topic: &str) -> Value {
        let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
        member.and_then(|m| m.last(topic)).unwrap_or(Value::Null)
    }
    fn slots_set(&self, layout: &str, slot: &str, component: &str, version: Option<&str>) -> Result<(), String> {
        let member = self.1.borrow().as_ref().map(|(m, _)| m.clone());
        member.ok_or("not mounted")?.slots_set(layout, slot, component, version, Box::new(|_| {})).map(|_| ()).map_err(|r| r.to_string())
    }
}

/// FRAME-12: what the bus asks of the host.
impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> BusHost for App<R, W, C> {
    fn open(&self, method: &str, params: Value, sink: Sink) -> CallId {
        self.wire.open(method, params, sink)
    }
    fn live(&self, spec: &LiveSpec) -> Reader {
        self.cache.acquire(spec)
    }
    fn follow(&self, spec: ModuleSpec) -> ModuleLive {
        self.cache.follow_module(spec)
    }
    fn navigate(&self, route: &str) {
        let f = self.navigate.borrow().clone();
        if let Some(f) = f {
            f(route);
        }
    }
    fn live_version(&self) -> String {
        self.version()
    }
    fn bound(&self, layout: &str, slot: &str) -> Option<String> {
        let st = self.st.borrow();
        st.sections.iter().filter(|s| s.layout == layout && s.slot == slot).find_map(|s| s.bound.as_ref()).map(|(c, _)| c.clone())
    }
}

impl<R: Renderer, W: Wire + Clone + 'static, C: Clock + Clone + 'static> App<R, W, C> {
    pub fn new(rt: &Runtime, renderer: R, wire: W, clock: C) -> Rc<Self> {
        let cache = LiveCache::new(rt, wire.clone(), clock);
        let bus = Bus::new(rt);
        let app = Rc::new_cyclic(|me| Self {
            rt: rt.clone(),
            renderer,
            wire,
            cache,
            bus: bus.clone(),
            st: RefCell::new(St {
                version: String::new(),
                manifest: Manifest::default(),
                files: Files::default(),
                modules: BTreeMap::new(),
                needs: Vec::new(),
                instances: BTreeMap::new(),
                next: 0,
                assignments: Vec::new(),
                sections: Vec::new(),
                console: Vec::new(),
                warned: Default::default(),
            }),
            navigate: RefCell::new(None),
            on_need: RefCell::new(None),
            attaching: RefCell::new(Vec::new()),
            trees: RefCell::new(BTreeMap::new()),
            read_trees: RefCell::new(BTreeMap::new()),
            sheets: RefCell::new(BTreeMap::new()),
            keys_off: RefCell::new(None),
            calls: RefCell::new(BTreeMap::new()),
            turns: turns::Turns::default(),
            me: me.clone(),
        });
        let host: Weak<dyn BusHost> = Rc::downgrade(&app) as Weak<dyn BusHost>;
        bus.set_host(host);
        // FRAME-36: the window's keys, heard before anything of the page.
        let me = Rc::downgrade(&app);
        let off = app.renderer.listen_keys(Rc::new(move |p: &crate::keys::Press| me.upgrade().is_some_and(|app| app.press(p))));
        *app.keys_off.borrow_mut() = Some(off);
        // FRAME-38: an open overlay follows the registry — redrawn on every
        // change, closed when the last key goes.
        let me = Rc::downgrade(&app);
        bus.keys().on_change(Rc::new(move || {
            if let Some(app) = me.upgrade() {
                app.overlay_follows();
            }
        }));
        app
    }

    /// FRAME-36: a key press — what it matches run, the first chords of a
    /// sequence held, `?` the overlay; true when the host took it (the
    /// browser must not have it).
    pub fn press(&self, p: &crate::keys::Press) -> bool {
        let keys = self.bus.keys().clone();
        let heard = keys.press(p);
        if let crate::keys::Heard::Overlay(open) = heard {
            self.renderer.keys_overlay(open.then(|| keys.groups()).as_ref());
        }
        heard.taken()
    }

    fn overlay_follows(&self) {
        let keys = self.bus.keys();
        if !keys.overlay() {
            return;
        }
        if keys.is_empty() {
            keys.close_overlay();
            self.renderer.keys_overlay(None);
        } else {
            self.renderer.keys_overlay(Some(&keys.groups()));
        }
    }

    /// FRAME-12: the page's bus.
    pub fn bus(&self) -> Bus {
        self.bus.clone()
    }

    /// FRAME-12: version `version`'s module `name`, imported, with its
    /// manifest entry; every section waiting on it is filled.
    pub fn provide_module(&self, version: &str, name: &str, entry: ComponentEntry, module: Rc<dyn Module<R>>) {
        let waiting: Vec<u64> = {
            let mut st = self.st.borrow_mut();
            st.modules.insert((version.into(), name.into()), (module, entry));
            st.needs.retain(|(v, n)| !(v == version && n == name));
            st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| v == version && n == name)).map(|s| s.sid).collect()
        };
        for sid in waiting {
            self.fill(sid);
        }
    }

    /// The `live` subscriptions (the page sweeps and reconnects them).
    pub fn cache(&self) -> &Rc<LiveCache<W, C>> {
        &self.cache
    }

    /// Where a handler's `navigate` goes.
    pub fn set_navigate(&self, f: Rc<dyn Fn(&str)>) {
        *self.navigate.borrow_mut() = Some(f);
    }

    /// FRAME-29: what a walk the page did not start (a module's own DOM
    /// changing) calls when it left something to fetch.
    pub fn set_on_need(&self, f: Rc<dyn Fn()>) {
        *self.on_need.borrow_mut() = Some(f);
    }

    /// The live version: its hash and manifest. Mounting needs its
    /// components' files ([`Self::provide`]).
    pub fn load(&self, version: &str, manifest: Manifest) {
        let mut st = self.st.borrow_mut();
        st.version = version.into();
        st.manifest = manifest;
    }

    /// The live version's hash.
    pub fn version(&self) -> String {
        self.st.borrow().version.clone()
    }

    /// The live version's manifest.
    pub fn manifest(&self) -> Manifest {
        self.st.borrow().manifest.clone()
    }

    /// Files fetched: kept; every section waiting on them is filled.
    pub fn provide(&self, files: &Files) {
        let waiting: Vec<u64> = {
            let mut st = self.st.borrow_mut();
            st.files.extend(files);
            let have = st.files.clone();
            st.needs.retain(|(v, n)| have.version(v, n).is_none());
            st.sections.iter().filter(|s| s.waiting.as_ref().is_some_and(|(v, n, _)| have.version(v, n).is_some())).map(|s| s.sid).collect()
        };
        for sid in waiting {
            self.fill(sid);
        }
    }

    /// What the engine asks to be fetched: `(version, component)`, each once.
    pub fn needs(&self) -> Vec<(String, String)> {
        self.st.borrow().needs.clone()
    }

    fn say(&self, line: &str) {
        #[cfg(feature = "dom")]
        web_sys::console::warn_1(&line.into());
        self.st.borrow_mut().console.push(line.to_string());
    }

    /// `name` of `version`, checked against what the live manifest names
    /// (for the live version), its handlers compiled — or its module, when
    /// it is one.
    fn prepare(&self, version: &str, name: &str) -> Result<Prepared<R>, SwapError> {
        let need = |st: &mut St<R>| {
            let need = (version.to_string(), name.to_string());
            if !st.needs.contains(&need) {
                st.needs.push(need);
            }
            Err(SwapError::Missing(version.into(), name.into()))
        };
        let (files, entry) = {
            let mut st = self.st.borrow_mut();
            let entry = (version == st.version).then(|| st.manifest.components.get(name).cloned());
            if let Some(None) = entry {
                return Err(SwapError::Unknown(name.into()));
            }
            let entry = entry.flatten();
            let module = st.modules.get(&(version.to_string(), name.to_string())).cloned();
            match (&entry, module) {
                // A module of the live version: the one its manifest names.
                (Some(e), Some((module, got))) if !e.is_rhx() => {
                    if got.module != e.module {
                        return Err(SwapError::Failed { component: name.into(), message: "its module is not the one the manifest names (their hashes differ)".into() });
                    }
                    return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: e.module.clone(), css: e.css.clone(), uses: e.uses.clone(), module });
                }
                (Some(e), None) if !e.is_rhx() => return need(&mut st),
                // Another version's module.
                (None, Some((module, got))) if st.files.version(version, name).is_none() => {
                    return Ok(Prepared::Module { version: version.into(), name: name.into(), hash: got.module.clone(), css: got.css.clone(), uses: got.uses.clone(), module });
                }
                _ => {}
            }
            match st.files.version(version, name) {
                Some((t, h)) => ((t.to_string(), h.to_string(), st.files.sheet(version, name)), entry),
                None => return need(&mut st),
            }
        };
        let failed = |message: String| SwapError::Failed { component: name.into(), message };
        let (tree_hash, handlers_hash) = (sha256_hex(&files.0), sha256_hex(&files.1));
        if let Some(e) = &entry {
            if e.tree != tree_hash || e.handlers != handlers_hash {
                return Err(failed("its files are not the ones the manifest names (their hashes differ)".into()));
            }
        }
        let tree = self.parsed(&files.0).map_err(failed)?;
        let slot: MemberSlot = Rc::new(RefCell::new(None));
        let host: Rc<dyn Host> = Rc::new(AppHost(self.me.clone(), slot.clone()));
        let folds = Folds::compile(&files.1, &tree.uses, host).map_err(|e| failed(e.to_string()))?;
        // FRAME-17: a component's handlers compile when it is mounted.
        crate::marks::mark(&format!("handlers-compiled:{name}"));
        if tree.css.is_some() && files.2.is_none() {
            self.say(&format!("{name} ({version}): its tree names a sheet, and none was fetched — drawn without it"));
        }
        // FRAME-30: keyed by the compiled sheet's sha256 (the manifest's
        // `css`), so a sheet compiled anew is a sheet anew.
        let css = files.2.filter(|_| tree.css.is_some()).map(|text| (format!("{name}@{}", sha256_hex(&text)), text));
        Ok(Prepared::Rhx { version: version.into(), tree, folds: Rc::new(folds), tree_hash, handlers_hash, slot, css })
    }

    /// Draws `p` into `element` as instance `id`: an rhx tree with its
    /// state (`state`, else its initial), its `live` readers and the topics
    /// it hears; or a module, mounted.
    fn attach(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
        // FRAME-29: what is mounting now, outermost first — every section
        // filled while it mounts is inside it (see [`Self::cycle`]).
        let name = match &p {
            Prepared::Module { name, .. } => name.clone(),
            Prepared::Rhx { tree, .. } => tree.name.clone(),
        };
        self.attaching.borrow_mut().push(name);
        let r = self.attach_now(id, element, p, props, state, pinned);
        self.attaching.borrow_mut().pop();
        r
    }

    /// FRAME-30: its sheet is on the page before it is drawn (and goes again
    /// when the draw fails); an rhx element carries its sheet's mark.
    fn attach_now(&self, id: MountId, element: &R::Node, p: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
        let sheet = p.sheet();
        self.sheet_up(&sheet);
        if let Prepared::Rhx { tree, .. } = &p {
            if let Some(mark) = &tree.css {
                self.renderer.set_attr(element, "data-css", mark);
            }
        }
        let r = self.draw(id, element, p, props, state, pinned);
        if r.is_err() {
            self.sheet_down(&sheet);
        }
        r
    }

    /// FRAME-30: one more instance needs the sheet; the first adopts it.
    fn sheet_up(&self, sheet: &Sheet) {
        let Some((key, text)) = sheet else { return };
        let first = {
            let mut sheets = self.sheets.borrow_mut();
            let n = sheets.entry(key.clone()).or_insert(0);
            *n += 1;
            *n == 1
        };
        if first {
            self.renderer.sheet(key, text, true);
        }
    }

    /// FRAME-30: one fewer; the last drops it.
    fn sheet_down(&self, sheet: &Sheet) {
        let Some((href, _)) = sheet else { return };
        let last = {
            let mut sheets = self.sheets.borrow_mut();
            match sheets.get_mut(href) {
                Some(n) if *n > 1 => {
                    *n -= 1;
                    false
                }
                Some(_) => {
                    sheets.remove(href);
                    true
                }
                None => false,
            }
        };
        if last {
            self.renderer.sheet(href, "", false);
        }
    }

    /// FRAME-30: the sheets the page has adopted, by key (`<component>@<its
    /// sheet's hash or mark>`), each with how many instances hold it.
    pub fn sheets(&self) -> BTreeMap<String, usize> {
        self.sheets.borrow().clone()
    }

    fn draw(&self, id: MountId, element: &R::Node, p: Prepared<R>, mut props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool) -> Result<(), SwapError> {
        let (version, tree, folds, tree_hash, handlers_hash, slot, css) = match p {
            Prepared::Module { version, name, hash, css, uses, module } => {
                let member = self.bus.join(&name, &uses);
                let mounted = module.mount(element, &props, member.clone()).map_err(|message| {
                    member.leave();
                    SwapError::Failed { component: name.clone(), message }
                })?;
                // FRAME-18: its marks watched, and walked now.
                let me = self.me.clone();
                let observing = self.renderer.observe(
                    element,
                    Rc::new(move |targets: Vec<R::Node>| {
                        if let Some(app) = me.upgrade() {
                            app.observed(id, &targets);
                        }
                    }),
                );
                let body = Body::Module { hash, css, uses, module, mounted: Some(mounted), observing: Some(observing) };
                let inst = Inst { name, version, pinned, element: element.clone(), props, member, body, failed: false };
                self.st.borrow_mut().instances.insert(id, inst);
                self.walk(id);
                return Ok(());
            }
            Prepared::Rhx { version, tree, folds, tree_hash, handlers_hash, slot, css } => (version, tree, folds, tree_hash, handlers_hash, slot, css),
        };
        // UI-8: a declared prop nobody passed is there, as null (`()` in an
        // expression) — `#/` gives the layout no `filter`, `#/f/:filter` does.
        for name in &tree.props {
            props.entry(name.clone()).or_insert(Value::Null);
        }
        let state = State::new(&self.rt, state.as_ref().unwrap_or(&tree.state));
        let mut readers = Vec::new();
        let mut live = BTreeMap::new();
        for (name, d) in &tree.live {
            // A bad fold rule is refused at mount, naming it.
            for rule in d.on.values() {
                rule.parse::<crate::live::FoldRule>().map_err(|message| SwapError::Failed { component: tree.name.clone(), message })?;
            }
            // UI-10: the params follow the scope — a state key they read
            // changing runs the snapshot again (after debounce_ms).
            let query = LiveQuery {
                snapshot: d.snapshot.clone(),
                changes: d.changes.clone(),
                key: d.key.clone(),
                on: d.on.iter().map(|(a, b)| (a.clone(), b.clone())).collect(),
                debounce_ms: d.debounce_ms,
            };
            // FRAME-16: `when` false holds it: nothing asked.
            let (pp, cp, pr, st, when) = (d.params.clone(), d.changes_params.clone(), props.clone(), state.clone(), d.when.clone());
            let r = self.cache.follow_held(query, move || {
                crate::tree::eval_when(when.as_ref(), &pr, &st).then(|| (crate::tree::eval_params(&pp, &pr, &st), crate::tree::eval_params(&cp, &pr, &st)))
            });
            live.insert(name.clone(), r.signal());
            readers.push(r);
        }
        let me = self.me.clone();
        let on_event: Rc<dyn Fn(&str, Value)> = Rc::new(move |handler: &str, ev: Value| {
            if let Some(app) = me.upgrade() {
                if let Err(e) = app.dispatch(id, handler, ev) {
                    app.say(&e.to_string());
                }
            }
        });
        // FRAME-12: its place on the bus — the folds' `emit`, and a fold
        // per topic it hears. FRAME-36: joined before its tree is drawn, so
        // its keys register before those of the components inside it: the
        // deeper, registered later, hears a shared chord first.
        let member = self.bus.join(&tree.name, &tree.uses);
        *slot.borrow_mut() = Some((member.clone(), id));
        let keys = member.keys(
            tree.keys
                .iter()
                .map(|d| {
                    let (me, to) = (self.me.clone(), d.to.clone());
                    let run: crate::keys::KeyRun = Rc::new(move |ev: Value| {
                        if let Some(app) = me.upgrade() {
                            if let Err(e) = app.dispatch(id, &to, ev) {
                                app.say(&e.to_string());
                            }
                        }
                    });
                    (d.clone(), run)
                })
                .collect(),
        );
        let scope = Scope { props: props.clone(), state: state.clone(), live: live.clone(), on_event };
        let kids: Rc<dyn Children<R>> = Rc::new(Kids(self.me.clone(), pinned.then(|| version.clone()), tree.name.clone()));
        let mounted = crate::tree::mount(&self.rt, &self.renderer, &tree, scope, element, kids).map_err(|e| {
            member.leave();
            SwapError::Failed { component: tree.name.clone(), message: e.to_string() }
        })?;
        // FRAME-17: an answer that came before its component (asked at
        // boot) is drawn by the mount itself.
        for (d, r) in tree.live.values().zip(&readers) {
            let Some(at) = r.answered_at().filter(|_| r.live().status == crate::live::Status::Live && !r.live().rows.is_empty()) else { continue };
            crate::marks::once_at("first-answer", at);
            crate::marks::once("first-row");
            crate::marks::once_at(&format!("answered:{}", d.snapshot), at);
            crate::marks::once(&format!("drawn:{}", d.snapshot));
        }
        let listening = tree
            .bus
            .iter()
            .map(|(topic, fold)| {
                let (me, fold, topic2) = (self.me.clone(), fold.clone(), topic.clone());
                member.on(topic, move |data: &Value| {
                    if let Some(app) = me.upgrade() {
                        app.dispatch_bus(id, &fold, &topic2, data);
                    }
                })
            })
            .collect();
        let inst = Inst {
            name: tree.name.clone(),
            version,
            pinned,
            element: element.clone(),
            props,
            member,
            body: Body::Rhx { tree_hash, handlers_hash, state, live, readers, folds, tree, mounted: Some(mounted), slot, css, _listening: listening, _keys: keys },
            failed: false,
        };
        self.st.borrow_mut().instances.insert(id, inst);
        Ok(())
    }

    fn next_id(&self) -> MountId {
        let mut st = self.st.borrow_mut();
        st.next += 1;
        MountId(st.next)
    }

    /// An instance of `name` of `version` into `element`; on a failure the
    /// element carries `data-failed`.
    fn instantiate(&self, element: &R::Node, name: &str, version: &str, pinned: bool, props: Map<String, Value>) -> Result<MountId, SwapError> {
        let p = match self.prepare(version, name) {
            Ok(p) => p,
            Err(e) => {
                if !matches!(e, SwapError::Missing(..)) {
                    self.renderer.set_attr(element, "data-failed", version);
                }
                return Err(e);
            }
        };
        let id = self.next_id();
        self.attach(id, element, p, props, None, pinned).inspect_err(|_| self.renderer.set_attr(element, "data-failed", version))?;
        Ok(id)
    }

    /// Mounts `name` of the live version into a new element (named for it)
    /// appended to `parent`. A component that fails is drawn as failed (its
    /// element carries `data-failed`, the version) and the console says why.
    pub fn mount(&self, parent: &R::Node, name: &str, props: Map<String, Value>) -> Result<MountId, SwapError> {
        let el = self.renderer.create_element(name);
        let version = self.version();
        let r = self.instantiate(&el, name, &version, false, props);
        self.renderer.insert(parent, &el, None);
        r.inspect_err(|e| self.say(&format!("{name} ({version}): {e}")))
    }

    /// Takes instance `id` out: its tree or module, its readers, its place
    /// on the bus, the instances in it.
    pub fn unmount(&self, id: MountId) {
        // FRAME-37: the calls it waits on are closed — their answers fold
        // nowhere.
        let calls = self.calls.borrow_mut().remove(&id).unwrap_or_default();
        for call in calls {
            self.wire.close(call);
        }
        let inst = self.st.borrow_mut().instances.remove(&id);
        if let Some(inst) = inst {
            self.drop_sections_of(id);
            let sheet = inst.prepared().sheet();
            inst.teardown();
            self.sheet_down(&sheet);
        }
    }

    /// FRAME-12: instance `id` with new props — a route to the component
    /// already drawn. A module hears `update(props)`; an rhx component (its
    /// props are constants in its scope) is drawn again into its element
    /// from its initial state, as a new mount of it was.
    pub fn update(&self, id: MountId, props: Map<String, Value>) -> Result<(), SwapError> {
        let module = {
            let mut st = self.st.borrow_mut();
            let Some(inst) = st.instances.get_mut(&id) else { return Err(SwapError::Unknown(format!("instance {}", id.0))) };
            inst.props = props.clone();
            match &mut inst.body {
                Body::Module { mounted, .. } => Some(mounted.take()),
                Body::Rhx { .. } => None,
            }
        };
        match module {
            Some(mounted) => {
                // Called with no borrow held: the module may speak on the bus.
                let mut mounted = mounted;
                if let Some(m) = mounted.as_mut() {
                    m.update(&props);
                }
                if let Some(Inst { body: Body::Module { mounted: slot, .. }, .. }) = self.st.borrow_mut().instances.get_mut(&id) {
                    *slot = mounted;
                }
                // FRAME-18: what the new props drew, walked.
                self.walk(id);
                Ok(())
            }
            None => {
                let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
                let (p, element, pinned) = (inst.prepared(), inst.element.clone(), inst.pinned);
                let held = p.sheet();
                inst.teardown();
                let r = self.attach(id, &element, p, props, None, pinned);
                self.sheet_down(&held);
                r
            }
        }
    }

    fn unmount_at(&self, at: &R::Node) {
        let ids: Vec<MountId> = self.st.borrow().instances.iter().filter(|(_, i)| &i.element == at).map(|(id, _)| *id).collect();
        for id in ids {
            self.unmount(id);
        }
        let gone: Vec<Option<MountId>> = {
            let mut st = self.st.borrow_mut();
            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| &s.div == at);
            st.sections = keep;
            out.into_iter().map(|s| s.instance).collect()
        };
        for id in gone.into_iter().flatten() {
            self.unmount(id);
        }
    }

    /// Runs `handler` of instance `id` on `event`: its state replaced. The
    /// bus is held while it runs: what it emits is heard once it returned.
    pub fn dispatch(&self, id: MountId, handler: &str, event: Value) -> Result<(), FoldError> {
        let _hold = self.bus.hold();
        let (folds, state, props, live) = {
            let st = self.st.borrow();
            let i = st.instances.get(&id).ok_or_else(|| FoldError::NoHandler(handler.into()))?;
            match &i.body {
                Body::Rhx { folds, state, live, .. } => (folds.clone(), state.clone(), i.props.clone(), live.clone()),
                Body::Module { .. } => return Err(FoldError::NoHandler(handler.into())),
            }
        };
        let rows: Map<String, Value> = live.iter().map(|(k, s)| (k.clone(), s.peek().get("rows").cloned().unwrap_or(Value::Null))).collect();
        let next = folds.run(handler, &state.snapshot(), &event, &props, &rows)?;
        state.replace(&next);
        Ok(())
    }

    /// FRAME-37: `call` of instance `id` ended: no longer kept to close.
    fn forget_call(&self, id: MountId, call: CallId) {
        let mut calls = self.calls.borrow_mut();
        if let Some(list) = calls.get_mut(&id) {
            list.retain(|c| *c != call);
            if list.is_empty() {
                calls.remove(&id);
            }
        }
    }

    /// FRAME-37: how many calls instance `id` waits on (tests).
    pub fn calls_of(&self, id: MountId) -> usize {
        self.calls.borrow().get(&id).map_or(0, Vec::len)
    }

    /// FRAME-37: a call's answer, folded once into instance `id` by `fold`
    /// with `ev = { method, params, ok, events, message }`. An instance gone
    /// meanwhile (unmounted, its section emptied) hears nothing.
    fn answered(&self, id: MountId, fold: &str, method: &str, params: &Value, answer: Answer) {
        if !self.st.borrow().instances.contains_key(&id) {
            return;
        }
        let mut ev = answer.to_value();
        ev["method"] = Value::String(method.into());
        ev["params"] = params.clone();
        if let Err(e) = self.dispatch(id, fold, ev) {
            self.say(&e.to_string());
        }
    }

    /// FRAME-12: `topic` heard on the bus — the fold its tree names, with
    /// `ev.bus = { topic, data }`.
    fn dispatch_bus(&self, id: MountId, fold: &str, topic: &str, data: &Value) {
        let ev = serde_json::json!({ "bus": { "topic": topic, "data": data } });
        if let Err(e) = self.dispatch(id, fold, ev) {
            self.say(&e.to_string());
        }
    }

    /// A new live version: remounts exactly the instances drawn from the
    /// live version whose hashes changed; the files of the changed
    /// components must be provided first.
    pub fn swap(&self, version: &str, manifest: Manifest) -> SwapReport {
        let old = {
            let mut st = self.st.borrow_mut();
            let old = std::mem::replace(&mut st.version, version.into());
            let before = std::mem::replace(&mut st.manifest, manifest.clone());
            // STUDIO-9: a component the swap did not change is the same
            // files under the new version — kept under it now, so a changed
            // component that places an unchanged one draws it at once (the
            // page fetches only what changed).
            let same: Vec<String> = manifest.components.iter().filter(|(n, e)| before.components.get(*n) == Some(*e)).map(|(n, _)| n.clone()).collect();
            for name in same {
                if st.files.version(version, &name).is_none() {
                    st.files.share(&old, version, &name);
                }
                let key = (version.to_string(), name.clone());
                if !st.modules.contains_key(&key) {
                    if let Some(m) = st.modules.get(&(old.clone(), name.clone())).cloned() {
                        st.modules.insert(key, m);
                    }
                }
            }
            let St { files, modules, needs, .. } = &mut *st;
            needs.retain(|(v, n)| files.version(v, n).is_none() && !modules.contains_key(&(v.clone(), n.clone())));
            old
        };
        let candidates: Vec<(MountId, String, (String, String), bool)> = self
            .st
            .borrow()
            .instances
            .iter()
            .filter(|(_, i)| !i.pinned)
            .map(|(id, i)| (*id, i.name.clone(), i.hashes(), matches!(i.body, Body::Rhx { .. })))
            .collect();
        let mut report = SwapReport::default();
        for (id, name, hashes, was_rhx) in candidates {
            if !self.st.borrow().instances.contains_key(&id) {
                continue;
            }
            let Some(entry) = manifest.components.get(&name) else {
                self.fail(id, version, &old, &name, "not in the new version".into(), &mut report);
                continue;
            };
            if entry.hashes() == hashes {
                continue;
            }
            let p = match self.prepare(version, &name) {
                Ok(p) => p,
                Err(e) => {
                    self.fail(id, version, &old, &name, e.to_string(), &mut report);
                    continue;
                }
            };
            let r = if was_rhx && matches!(p, Prepared::Rhx { .. }) { self.remount(id, p) } else { self.replace(id, p) };
            match r {
                Ok(()) => report.remounted.push(id),
                Err(e) => self.fail(id, version, &old, &name, e.to_string(), &mut report),
            }
        }
        // A section whose default moved to another component follows it.
        let refill: Vec<u64> = {
            let st = self.st.borrow();
            st.sections
                .iter()
                .filter(|s| s.bound.is_none() && !st.assignments.iter().any(|a| a.layout == s.layout && a.slot == s.slot))
                .filter(|s| {
                    let default = st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot));
                    let drawn = s.instance.and_then(|id| st.instances.get(&id)).map(|i| &i.name);
                    default != drawn
                })
                .map(|s| s.sid)
                .collect()
        };
        for sid in refill {
            self.fill(sid);
        }
        report
    }

    fn fail(&self, id: MountId, version: &str, old: &str, name: &str, why: String, report: &mut SwapReport) {
        let drawn = {
            let mut st = self.st.borrow_mut();
            st.instances.get_mut(&id).map(|i| {
                i.failed = true;
                (i.element.clone(), i.version.clone())
            })
        };
        let drawn_version = match drawn {
            Some((element, v)) => {
                self.renderer.set_attr(&element, "data-failed", version);
                v
            }
            None => old.to_string(),
        };
        self.say(&format!("{name}: {version} failed to mount ({why}); keeping its last good version {drawn_version}"));
        report.failed.push((id, why));
    }

    /// FRAME-12: instance `id` replaced by `p` in its element — the old one
    /// destroyed first, then `p` mounted with the same props; when that
    /// fails, what was drawn is mounted again (its state too) and the
    /// failure answered.
    fn replace(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
        let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
        let (again, state, element, props, pinned, was_failed) = (inst.prepared(), inst.state(), inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
        // FRAME-30: the old sheet is held until the new one is adopted.
        let held = again.sheet();
        self.drop_sections_of(id);
        inst.teardown();
        let r = self.replace_with(id, &element, p, again, props, state, pinned, was_failed);
        self.sheet_down(&held);
        r
    }

    #[allow(clippy::too_many_arguments)]
    fn replace_with(&self, id: MountId, element: &R::Node, p: Prepared<R>, again: Prepared<R>, props: Map<String, Value>, state: Option<Map<String, Value>>, pinned: bool, was_failed: bool) -> Result<(), SwapError> {
        let element = element.clone();
        match self.attach(id, &element, p, props.clone(), None, pinned) {
            Ok(()) => {
                if was_failed {
                    self.renderer.set_attr(&element, "data-failed", "");
                }
                Ok(())
            }
            Err(e) => {
                if let Err(again) = self.attach(id, &element, again, props, state, pinned) {
                    self.say(&format!("its last good version did not mount again either: {again}"));
                }
                Err(e)
            }
        }
    }

    /// Instance `id` again from `p`, into its element, its props kept and
    /// its state too when the shape is the same.
    fn remount(&self, id: MountId, p: Prepared<R>) -> Result<(), SwapError> {
        let inst = self.st.borrow_mut().instances.remove(&id).expect("an instance");
        let state = match (&inst.body, &p) {
            (Body::Rhx { state, .. }, Prepared::Rhx { tree, .. }) => {
                let shape: Vec<String> = tree.state.keys().cloned().collect();
                (state.shape() == shape).then(|| state.snapshot())
            }
            _ => None,
        };
        let (element, props, pinned, was_failed) = (inst.element.clone(), inst.props.clone(), inst.pinned, inst.failed);
        let held = inst.prepared().sheet();
        self.drop_sections_of(id);
        inst.teardown();
        let r = self.attach(id, &element, p, props, state, pinned);
        self.sheet_down(&held);
        if r.is_ok() && was_failed {
            self.renderer.set_attr(&element, "data-failed", "");
        }
        r
    }

    /// The sections' assignments (`ui.slots.list`); a section with none
    /// takes `manifest.slots`' default.
    pub fn set_assignments(&self, assignments: Vec<Assignment>) {
        self.warn_bound(&assignments);
        let changed: Vec<u64> = {
            let mut st = self.st.borrow_mut();
            let before = std::mem::replace(&mut st.assignments, assignments);
            let find = |list: &[Assignment], l: &str, s: &str| list.iter().find(|a| a.layout == l && a.slot == s).cloned();
            st.sections
                .iter()
                .filter(|s| s.bound.is_none() && find(&before, &s.layout, &s.slot) != find(&st.assignments, &s.layout, &s.slot))
                .map(|s| s.sid)
                .collect()
        };
        for sid in changed {
            self.fill(sid);
        }
    }

    /// `slot_changed` on `ui.watch`: that section remounts with its props,
    /// nothing else.
    pub fn slot_changed(&self, change: Assignment) {
        self.warn_bound(std::slice::from_ref(&change));
        let idx = {
            let mut st = self.st.borrow_mut();
            st.assignments.retain(|a| !(a.layout == change.layout && a.slot == change.slot));
            st.assignments.push(change.clone());
            st.sections.iter().filter(|s| s.bound.is_none() && s.layout == change.layout && s.slot == change.slot).map(|s| s.sid).collect::<Vec<_>>()
        };
        for sid in idx {
            self.fill(sid);
        }
    }

    /// `slot_changed` back to the default (`ui.slots.clear`).
    pub fn slot_reset(&self, layout: &str, slot: &str) {
        let idx = {
            let mut st = self.st.borrow_mut();
            st.assignments.retain(|a| !(a.layout == layout && a.slot == slot));
            st.sections.iter().filter(|s| s.bound.is_none() && s.layout == layout && s.slot == slot).map(|s| s.sid).collect::<Vec<_>>()
        };
        for sid in idx {
            self.fill(sid);
        }
    }

    /// Section `i` drawn again: its binding (FRAME-29), else its
    /// assignment, else its default. Its files
    /// not fetched: it waits ([`Self::needs`]). FRAME-12: the new component
    /// is mounted before what the section had is taken out; when it fails,
    /// what it had stays drawn, marked `data-failed`.
    fn fill(&self, sid: u64) {
        // FRAME-50: filled now, so its turn, if it waits one, finds it done.
        self.with_section(sid, |s| s.queued = false);
        let (div, props, old, want, inline) = {
            let st = self.st.borrow();
            let Some(s) = st.sections.iter().find(|s| s.sid == sid) else { return };
            let want = match (&s.bound, st.assignments.iter().find(|a| a.layout == s.layout && a.slot == s.slot)) {
                (Some((c, v)), _) => {
                    // STUDIO-11: a module's mark naming no version, in a
                    // module pinned to one (a studio's frame), is that
                    // version's — a child is its pinned parent's version's.
                    let parent = s.owner.and_then(|o| st.instances.get(&o)).filter(|i| i.pinned).map(|i| i.version.clone());
                    let v = v.clone().or(parent);
                    Some((c.clone(), v.clone().unwrap_or_else(|| st.version.clone()), v.is_some()))
                }
                (None, Some(a)) => Some((a.component.clone(), a.version.clone(), true)),
                (None, None) => st.manifest.slots.get(&s.layout).and_then(|m| m.get(&s.slot)).map(|c| (c.clone(), st.version.clone(), false)),
            };
            let old = s.instance.and_then(|id| st.instances.get(&id).map(|inst| (id, inst.element.clone(), inst.version.clone())));
            (s.div.clone(), s.props.clone(), old, want, s.inline)
        };
        let Some((component, version, pinned)) = want else {
            if let Some((id, el, _)) = old {
                self.unmount(id);
                self.renderer.remove(&div, &el);
            }
            self.with_section(sid, |s| s.instance = None);
            return;
        };
        // FRAME-29: a component never fills a section inside an instance of
        // itself — a module binding itself, A binding B binding A, a layout
        // assigned into its own section would mount without end.
        if let Some(chain) = self.cycle(&div, &component) {
            self.with_section(sid, |s| s.waiting = None);
            self.say(&format!("cycle: {chain} → {component}; the section is left empty"));
            return;
        }
        let p = match self.prepare(&version, &component) {
            Ok(p) => p,
            Err(SwapError::Missing(..)) => {
                self.with_section(sid, |s| s.waiting = Some((version, component, pinned)));
                return;
            }
            Err(e) => {
                self.with_section(sid, |s| s.waiting = None);
                if let Some((_, el, _)) = &old {
                    self.renderer.set_attr(el, "data-failed", &version);
                }
                self.say(&format!("{component} ({version}): {e}; the section keeps what it shows"));
                return;
            }
        };
        // STUDIO-9: an rhx child's section mounts into the child's own
        // element, once (its tree says when it goes; a hot-swap remounts
        // the instance in place).
        if inline {
            self.with_section(sid, |s| s.waiting = None);
            if old.is_some() {
                return;
            }
            let id = self.next_id();
            match self.attach(id, &div, p, props, None, pinned) {
                Ok(()) => {
                    self.with_section(sid, |s| s.instance = Some(id));
                }
                Err(e) => {
                    self.renderer.set_attr(&div, "data-failed", &version);
                    self.say(&format!("{component} ({version}): {e}"));
                }
            }
            return;
        }
        let el = self.renderer.create_element(&component);
        let id = self.next_id();
        let drawn_from = p.version().to_string();
        match self.attach(id, &el, p, props, None, pinned) {
            Ok(()) => {
                self.renderer.insert(&div, &el, None);
                if let Some((old_id, old_el, _)) = old {
                    self.unmount(old_id);
                    self.renderer.remove(&div, &old_el);
                }
                let slot = self.with_section(sid, |s| {
                    s.waiting = None;
                    s.instance = Some(id);
                    s.slot.clone()
                });
                if let Some(slot) = slot {
                    crate::marks::once(&format!("section-mounted:{slot}"));
                }
            }
            Err(e) => {
                self.with_section(sid, |s| s.waiting = None);
                match old {
                    Some((old_id, old_el, old_version)) => {
                        self.renderer.set_attr(&old_el, "data-failed", &drawn_from);
                        if let Some(i) = self.st.borrow_mut().instances.get_mut(&old_id) {
                            i.failed = true;
                        }
                        self.say(&format!("{component}: {drawn_from} failed to mount ({e}); keeping its last good version {old_version}"));
                    }
                    None => {
                        self.renderer.insert(&div, &el, None);
                        self.renderer.set_attr(&el, "data-failed", &version);
                        self.with_section(sid, |s| s.instance = None);
                        self.say(&format!("{component} ({version}): {e}"));
                    }
                }
            }
        }
    }

    /// FRAME-29: when `component` already draws an instance around `div`,
    /// the chain of names from the outermost such instance down, else none.
    /// Around is the DOM's holding, and past it the section each outermost
    /// instance fills — an instance mounts before its element is placed in
    /// its section, so the DOM alone does not reach the layout above it.
    fn cycle(&self, div: &R::Node, component: &str) -> Option<String> {
        let st = self.st.borrow();
        let mut chain: Vec<String> = Vec::new();
        let mut at = div.clone();
        for _ in 0..st.instances.len() + 1 {
            let mut around: Vec<(&MountId, &Inst<R>)> = st.instances.iter().filter(|(_, i)| i.element != at && self.renderer.contains(&i.element, &at)).collect();
            if around.is_empty() {
                break;
            }
            // Innermost last: the more of them hold it, the further in.
            around.sort_by_key(|(_, i)| around_count(&self.renderer, &st, &i.element));
            for (_, i) in around.iter().rev() {
                chain.push(i.name.clone());
            }
            let outer = *around[0].0;
            match st.sections.iter().find(|s| s.instance == Some(outer)) {
                Some(s) => at = s.div.clone(),
                None => break,
            }
        }
        chain.reverse();
        // What is mounting now holds `div` too: its element is not placed
        // (nor, for rhx, registered) until its mount returns.
        let outer: Vec<String> = self.attaching.borrow().iter().filter(|n| !chain.contains(n)).cloned().collect();
        let chain: Vec<String> = outer.into_iter().chain(chain).collect();
        chain.iter().any(|n| n == component).then(|| chain.join(" → "))
    }

    /// FRAME-29: an assignment for a slot a mark binds is stored and does
    /// nothing; said once per (layout, slot).
    fn warn_bound(&self, assignments: &[Assignment]) {
        let lines: Vec<String> = {
            let mut st = self.st.borrow_mut();
            let mut lines = Vec::new();
            for a in assignments {
                let Some((c, _)) = st.sections.iter().filter(|s| s.layout == a.layout && s.slot == a.slot).find_map(|s| s.bound.clone()) else { continue };
                if st.warned.insert((a.layout.clone(), a.slot.clone())) {
                    lines.push(format!("{} · {}: assignment {}@{} stored, but the mark binds {c}; it does nothing", a.layout, a.slot, a.component, a.version));
                }
            }
            lines
        };
        for l in lines {
            self.say(&l);
        }
    }

    /// FRAME-18: **the walk** — module instance `id`'s element searched for
    /// `[data-slot]` marks. A section of its whose mark is no longer in the
    /// element (or whose `data-slot` now names another slot) goes, and what
    /// filled it is destroyed — a mark moved within the element stays its
    /// section. A filled mark whose other `data-*` attributes changed hands
    /// them to what fills it as `update(props)`, never a refill. A mark
    /// that is no section yet, and is not inside another section within the
    /// element (a mark in a section is the filling component's), becomes one of the layout `id`
    /// draws — its slot the attribute's value, its props the mark's other
    /// `data-*` attributes (strings), `data-layout` written on it — and is
    /// filled as an rhx `<slot>` is ([`Self::fill`]). FRAME-29: a mark
    /// carrying `data-component` is bound to it (`data-version` too, when
    /// given) — neither is a prop — and a mark whose binding changed is a
    /// new section, as one whose slot changed.
    pub fn walk(&self, id: MountId) {
        let (target, layout) = {
            let st = self.st.borrow();
            match st.instances.get(&id) {
                Some(i) if matches!(i.body, Body::Module { .. }) => (i.element.clone(), i.name.clone()),
                _ => return,
            }
        };
        crate::marks::mark(&format!("walk:{layout}"));
        let gone: Vec<Option<MountId>> = {
            let mut st = self.st.borrow_mut();
            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| {
                s.owner == Some(id) && (!self.renderer.contains(&target, &s.div) || {
                    let (slot, bound, _) = mark_of(&self.renderer, &s.div);
                    slot != s.slot || bound != s.bound
                })
            });
            st.sections = keep;
            out.into_iter().map(|s| s.instance).collect()
        };
        for i in gone.into_iter().flatten() {
            self.unmount(i);
        }
        // The props of the marks already sections, read again.
        let moved: Vec<(MountId, Map<String, Value>)> = {
            let mut st = self.st.borrow_mut();
            st.sections
                .iter_mut()
                .filter(|s| s.owner == Some(id))
                .filter_map(|s| {
                    let (_, _, props) = mark_of(&self.renderer, &s.div);
                    if props == s.props {
                        return None;
                    }
                    s.props = props.clone();
                    s.instance.map(|i| (i, props))
                })
                .collect()
        };
        for (i, props) in moved {
            if let Err(e) = self.update(i, props) {
                self.say(&format!("{layout}: a section's props: {e}"));
            }
        }
        // A mark is another section's when that section is inside this
        // module's element and holds it — never because this module itself
        // fills a section of the page (SURFACE-10: its later marks are its own),
        // nor because that section's mark is the module's element itself (a
        // module filled inline, STUDIO-9: `contains` counts the element).
        let fresh: Vec<R::Node> = {
            let st = self.st.borrow();
            self.renderer
                .marks(&target)
                .into_iter()
                .filter(|m| !st.sections.iter().any(|s| &s.div == m || (s.div != target && self.renderer.contains(&target, &s.div) && self.renderer.contains(&s.div, m))))
                .collect()
        };
        for mark in fresh {
            let (slot, bound, props) = mark_of(&self.renderer, &mark);
            self.renderer.set_attr(&mark, "data-layout", &layout);
            let sid = self.next_id().0;
            let s = Section { sid, owner: Some(id), layout: layout.clone(), slot, div: mark, props, instance: None, waiting: None, bound, inline: false, queued: false };
            self.st.borrow_mut().sections.push(s);
            self.fill_soon(sid);
        }
    }

    /// FRAME-18: the observer's batch for module instance `id`: walked
    /// unless every change was made inside one of its filled sections —
    /// under the mark, not on it (a section's own drawing, its rows, is none
    /// of the layout's; the mark's attributes are).
    pub fn observed(&self, id: MountId, targets: &[R::Node]) {
        let inside = {
            let st = self.st.borrow();
            let filled: Vec<&R::Node> = st.sections.iter().filter(|s| s.owner == Some(id) && s.instance.is_some()).map(|s| &s.div).collect();
            targets.iter().all(|t| filled.iter().any(|d| d != &t && self.renderer.contains(d, t)))
        };
        if !inside {
            self.walk(id);
            // FRAME-29: a mark drawn by the module's own state may bind a
            // component not fetched yet: the page is told to fetch it.
            self.told_needs();
        }
    }

    /// FRAME-29, STUDIO-9: the page told to fetch what a mount left
    /// waiting (a mark the module's state drew, a child drawn after its
    /// parent's first draw: in an `{#each}` fed by `live()`, an `{#if}`).
    fn told_needs(&self) {
        let on_need = self.on_need.borrow().clone();
        if let Some(f) = on_need.filter(|_| !self.st.borrow().needs.is_empty()) {
            f();
        }
    }

    /// FRAME-18: the sections module instance `id`'s walk found, gone with
    /// it — each one's instance destroyed — before it is.
    fn drop_sections_of(&self, id: MountId) {
        let gone: Vec<Option<MountId>> = {
            let mut st = self.st.borrow_mut();
            let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut st.sections).into_iter().partition(|s| s.owner == Some(id));
            st.sections = keep;
            out.into_iter().map(|s| s.instance).collect()
        };
        for i in gone.into_iter().flatten() {
            self.unmount(i);
        }
    }

    fn with_section<T>(&self, sid: u64, f: impl FnOnce(&mut Section<R>) -> T) -> Option<T> {
        self.st.borrow_mut().sections.iter_mut().find(|s| s.sid == sid).map(f)
    }

    /// FRAME-17: whether `name` of the live version is here to mount: its
    /// files, or its module (a name the manifest lacks is, to be refused).
    pub fn here(&self, name: &str) -> bool {
        let st = self.st.borrow();
        match st.manifest.components.get(name) {
            None => true,
            Some(e) if e.is_rhx() => st.files.version(&st.version, name).is_some(),
            Some(_) => st.modules.contains_key(&(st.version.clone(), name.to_string())),
        }
    }

    /// FRAME-17: whether `name` of the live version is here to mount (its
    /// files, or its module); when it is not, it is asked for
    /// ([`Self::needs`]).
    pub fn ensure(&self, name: &str) -> bool {
        let here = self.here(name);
        let mut st = self.st.borrow_mut();
        let need = (st.version.clone(), name.to_string());
        if !here && !st.needs.contains(&need) {
            st.needs.push(need);
        }
        here
    }

    /// The instance filling `layout`'s section `slot`.
    pub fn section(&self, layout: &str, slot: &str) -> Option<MountId> {
        self.st.borrow().sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance)
    }

    /// The sections drawn: `(layout, slot)` each.
    pub fn sections(&self) -> Vec<(String, String)> {
        self.st.borrow().sections.iter().map(|s| (s.layout.clone(), s.slot.clone())).collect()
    }

    /// The section menu for `layout`'s `slot`, given every stored version
    /// (newest first) with its manifest's entry for the section's component.
    pub fn menu(&self, layout: &str, slot: &str, versions: &[(String, Option<ComponentEntry>)]) -> Menu {
        let st = self.st.borrow();
        let drawn = st.sections.iter().find(|s| s.layout == layout && s.slot == slot).and_then(|s| s.instance).and_then(|id| st.instances.get(&id));
        let component = drawn
            .map(|i| i.name.clone())
            .or_else(|| st.manifest.slots.get(layout).and_then(|m| m.get(slot)).cloned())
            .unwrap_or_default();
        let live = st.manifest.components.get(&component).map(ComponentEntry::hashes);
        let versions = versions
            .iter()
            .filter(|(v, _)| *v != st.version)
            .filter_map(|(v, e)| {
                let e = e.as_ref()?;
                (Some(e.hashes()) != live).then(|| v.clone())
            })
            .collect();
        Menu { component, components: st.manifest.components.keys().cloned().collect(), versions }
    }

    /// Every instance mounted: `(id, name)`.
    pub fn instances(&self) -> Vec<(MountId, String)> {
        self.st.borrow().instances.iter().map(|(id, i)| (*id, i.name.clone())).collect()
    }

    /// Instance `id`'s element.
    pub fn element_of(&self, id: MountId) -> R::Node {
        self.st.borrow().instances[&id].element.clone()
    }

    /// Instance `id`'s props.
    pub fn props_of(&self, id: MountId) -> Map<String, Value> {
        self.st.borrow().instances[&id].props.clone()
    }

    /// Instance `id`'s state now (a module's: none).
    pub fn state_of(&self, id: MountId) -> Map<String, Value> {
        self.st.borrow().instances[&id].state().unwrap_or_default()
    }

    /// Instance `id`'s drawn version: `(version, tree hash, handlers hash)`
    /// — a module's `(version, module hash, "")`.
    pub fn drawn_from(&self, id: MountId) -> (String, String, String) {
        let st = self.st.borrow();
        let i = &st.instances[&id];
        let (a, b) = i.hashes();
        (i.version.clone(), a, b)
    }

    /// FRAME-12: the name instance `id` draws, while it is mounted.
    pub fn name_of(&self, id: MountId) -> Option<String> {
        self.st.borrow().instances.get(&id).map(|i| i.name.clone())
    }

    /// What the engine said on the console, in order.
    pub fn console(&self) -> Vec<String> {
        self.st.borrow().console.clone()
    }
}

/// How many instances' elements hold `e`.
fn around_count<R: Renderer>(r: &R, st: &St<R>, e: &R::Node) -> usize {
    st.instances.values().filter(|i| r.contains(&i.element, e)).count()
}

/// FRAME-18: a mark's slot (its `data-slot`) and its props (its other
/// `data-*` attributes, `data-layout` aside, the `data-` taken off).
/// FRAME-29: and its binding — `data-component`, with `data-version` when
/// it names one — neither of them a prop.
/// STUDIO-6: what a mark never hands its component as a prop — the
/// section's own names and the engine's (`data-failed` and `data-css` on a
/// component's element, `data-refused` in its menu): one list, which
/// CONTRACT.md's "A bound mark" names. (An unbound mark's `data-version`
/// stays its prop, FRAME-18: a version binds only beside a component.)
// FRAME-50: `plexus-held` is the boot's hold (swap/turns.rs), never a prop.
pub const MARK_NAMES: [&str; 8] = ["slot", "component", "version", "layout", "failed", "css", "refused", "plexus-held"];

fn mark_of<R: Renderer>(r: &R, mark: &R::Node) -> (String, Option<Binding>, Map<String, Value>) {
    let mut slot = String::new();
    let (mut component, mut version) = (None, None);
    let mut props = Map::new();
    for (k, v) in r.attrs(mark) {
        match k.as_str() {
            "data-slot" => slot = v,
            "data-component" => component = Some(v),
            "data-version" => version = Some(v),
            "data-layout" => {}
            _ => {
                if let Some(name) = k.strip_prefix("data-").filter(|n| !MARK_NAMES.contains(n)) {
                    props.insert(name.to_string(), Value::String(v));
                }
            }
        }
    }
    // `data-version` binds only beside `data-component`; on an unbound
    // mark it is a prop like any (FRAME-18).
    let bound = match component.filter(|c| !c.is_empty()) {
        Some(c) => Some((c, version.filter(|v| !v.is_empty()))),
        None => {
            if let Some(v) = version {
                props.insert("version".into(), Value::String(v));
            }
            None
        }
    };
    (slot, bound, props)
}

#[cfg(test)]
mod tests;