nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
//! Components: the [`Component`] trait, its [`Props`] and [`Event`]s
//! (derived), the [`Registry`] a surface renders from, and the JS glue and
//! TypeScript declarations generated from them ([`declarations`]).

use std::{
    any::{Any, TypeId},
    fmt,
    sync::Arc,
};

use rustc_hash::FxHashMap;

use super::{
    Children, IntoElement, PropError, Slot, TsType, TsTypes,
    builder::{ComponentElement, ElNode},
    call::{AnyValue, JsResult, MethodCall},
    class::{Class, ClassDef, ClassSpec, MemberKind, Thrown},
    js::{JsHost, JsIn, JsOwned},
    module::{FunctionSpec, Module, ModuleSpec},
};

/// A component written in Rust: a function that runs once ([`Self::view`])
/// and makes its view, binding what changes to signals. Its props come from
/// JS (or from the component whose view has it), its events go to JS.
/// `#[component]` on a function makes the type and this impl.
///
/// It is registered under its type's full path ([`std::any::type_name`]:
/// its crate, modules and name) and exported to JS as the type's own name
/// (the last segment), so neither is written by hand
/// ([`Registry::register`]).
///
/// ```ignore
/// #[component]
/// pub fn Button(props: ButtonProps, cx: Scope<ButtonEvent>) -> impl IntoElement {
///     view()
///         .px_4()
///         .py_3()
///         .bg(move || theme().primary) // nsh-base's theme
///         .on_press(move || cx.emit(ButtonEvent::Press))
///         .child(text(props.title))
/// }
/// ```
pub trait Component: 'static {
    /// Its props (`#[derive(Props)]`).
    type Props: Props;

    /// Its events (`#[derive(Event)]`; [`NoEvent`] for none).
    type Event: Event;

    /// The methods of its ref in JS: those of the [`Api`] its view
    /// registers (`Methods::of::<StepperApi>()`; none by default).
    const METHODS: Methods = Methods::NONE;

    /// Its documentation in TypeScript: the `#[component]` function's doc
    /// comment (none by default).
    const DOC: &'static str = "";

    /// What it shows: its elements, with bindings where values change (TS:
    /// a component's body). Runs once, under an owner of its own: what it
    /// makes (signals, effects, timers) goes with the component.
    fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;

    /// This component inside another one's view, given all its props.
    /// A `#[component]` has a constructor of its own, which Rust views use
    /// (`button().disabled(..)`); this stays for components implemented
    /// by hand and for code generic over components.
    fn element(props: Self::Props) -> ComponentElement<Self>
    where
        Self: Sized,
    {
        ComponentElement::new(props)
    }
}

/// A component's code panicked: what an error boundary
/// ([`super::catch_error`]) shows.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComponentError {
    /// The component that failed (its registered name: its type's).
    pub component: &'static str,
    /// What its code panicked with.
    pub message: String,
}

impl fmt::Display for ComponentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} failed: {}", self.component, self.message)
    }
}

/// Runs component code, catching a panic as its message.
pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
}

/// The message of a panic's payload.
pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
    match payload.downcast::<String>() {
        Ok(s) => *s,
        Err(payload) => match payload.downcast::<&'static str>() {
            Ok(s) => (*s).to_owned(),
            Err(_) => "a panic".to_owned(),
        },
    }
}

/// A method JS calls on a component's ref: one of its API's
/// ([`Api`]; `#[methods]` makes them).
pub struct Method {
    /// Its JS name (`setValue`).
    pub name: &'static str,
    /// Documentation.
    pub doc: &'static str,
    /// Its parameters: JS names and TypeScript types.
    pub params: &'static [Param],
    /// The TypeScript type of its result (`None`: it returns nothing, and
    /// JS gets `undefined`: the call runs in order with the props set
    /// before it, with nothing to wait for).
    pub returns: Option<TsType>,
    /// The classes its parameters and result name.
    pub refs: super::ClassRefs,
    /// Its call, the arguments converted in the JS call: what the core
    /// runs with the API, in order with the props set before it. A wrong
    /// argument's error starts with the method's name; the host puts its
    /// component's before it (`Stepper.setValue: ...`).
    pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
}

/// What a component's ref does in JS: a handle its view makes, holding the
/// signals its methods read and write, registered with
/// [`super::Scope::methods`]. `#[methods]` on its `impl` block implements
/// it.
pub trait Api: Sized + 'static {
    /// Its methods.
    const METHODS: &'static [Method];
}

/// The methods a component's ref has, for its spec and declarations:
/// [`Methods::of`] its [`Api`] (`#[component(methods = StepperApi)]`).
#[derive(Clone, Copy)]
pub struct Methods {
    specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
    refs: super::ClassRefs,
}

impl Methods {
    /// None.
    pub const NONE: Self = Self {
        specs: |_| Vec::new(),
        refs: |_| {},
    };

    /// Those of `A`.
    pub const fn of<A: Api>() -> Self {
        Self {
            specs: specs_of::<A>,
            refs: |out| {
                for m in A::METHODS {
                    (m.refs)(out);
                }
            },
        }
    }
}

fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
    A::METHODS
        .iter()
        .map(|m| MethodSpec {
            name: m.name,
            doc: m.doc,
            params: m
                .params
                .iter()
                .map(|(n, ts, optional)| (*n, ts(types), *optional))
                .collect(),
            returns: m.returns.map(|ts| ts(types)),
            call: m.call,
        })
        .collect()
}

/// A method's parameter: its JS name, its TypeScript type, and whether JS
/// may leave it out (an `Option` after which every parameter is optional).
pub type Param = (&'static str, TsType, bool);

/// One method, for the glue and its declarations.
#[derive(Debug, Clone)]
pub struct MethodSpec {
    /// Its JS name.
    pub name: &'static str,
    /// Documentation.
    pub doc: &'static str,
    /// Its parameters: JS names, TypeScript types, and whether each is
    /// optional.
    pub params: Vec<(&'static str, String, bool)>,
    /// The TypeScript type of its result; `None`: nothing (`void`).
    pub returns: Option<String>,
    /// Its call (the arguments converted in the JS call).
    pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
}

impl MethodSpec {
    /// Whether JS gets a `Promise` of the result: when the method returns
    /// a value (`Result<(), E>` too, rejected with an `Err`). One
    /// returning `()` gives `undefined` (`void`): the call runs in order
    /// with the UI and nothing answers it, and a wrong argument throws.
    pub fn promises(&self) -> bool {
        self.returns.is_some()
    }
}

/// What a prop is to the glue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropKind {
    /// A value: decoded in the JS call ([`PropSpec::decode`]), set by the
    /// core.
    Value,
    /// A render function (`Option<Renderer<T>>`): decoded in the JS call
    /// as a value is (a function, or none), its content rendered by JS
    /// when the core asks for it ([`super::JsEvent::Render`]).
    Renderer,
    /// A named slot: JSX in a holder node.
    Slot,
    /// The JSX children.
    Children,
    /// Virtualized rows: in JS `each`, a row renderer and the data props of
    /// `List` (the glue makes the list, the component places it).
    Items,
}

/// What converts a JS value into a prop's Rust type (the prop's
/// [`super::JsValue::from_js`], type-erased): `nsh-js` calls it when JS
/// sets the prop.
pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;

/// One prop, for the glue and its declarations.
#[derive(Debug, Clone)]
pub struct PropSpec {
    /// Its JS name (`accessibilityLabel`).
    pub name: &'static str,
    /// Its TypeScript type.
    pub ts: String,
    /// It may be left out.
    pub optional: bool,
    /// Documentation.
    pub doc: &'static str,
    /// What it is.
    pub kind: PropKind,
    /// A value prop's value from JS (`None` for slots, children and rows).
    pub decode: Option<PropDecode>,
}

/// One event, for the glue and its declarations.
#[derive(Debug, Clone)]
pub struct EventSpec {
    /// Its name (`press`: the handler is `onPress`).
    pub name: &'static str,
    /// The name of the handler's one argument in TypeScript (`event`;
    /// unused without data).
    pub arg: &'static str,
    /// The TypeScript type of its data (`void` for none), one object
    /// (`docs/dev/api-naming.md` "Payloads").
    pub data: String,
    /// Documentation.
    pub doc: &'static str,
}

/// A component's props. Derive it: `#[derive(Props)]`.
pub trait Props: Clone + PartialEq + 'static {
    /// The JS name of the [`super::Items`] prop, if it has one.
    #[doc(hidden)]
    const ITEMS: Option<&'static str> = None;

    /// Its children are made only while the view places them
    /// (`#[prop(lazy)]`).
    #[doc(hidden)]
    const LAZY_CHILDREN: bool = false;

    /// TS declares the props generic over `T`, the type of the rows a prop
    /// takes (`#[props(generic)]`; a prop's type names it, as
    /// [`super::Rows`] does).
    #[doc(hidden)]
    const GENERIC: bool = false;

    /// The props (their named types declared in `types`).
    fn spec(types: &mut TsTypes) -> Vec<PropSpec>;

    /// Every prop at its default.
    fn initial() -> Self;

    /// Prop `name` (its JS name) from JS, as [`PropSpec::decode`] made it;
    /// `None` restores its default. Returns whether it changed.
    fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;

    /// Slot `name` filled (`Some`) or not; returns whether it changed.
    fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;

    /// Whether the app passed children; returns whether it changed.
    fn set_children(&mut self, children: Children) -> bool;

    /// The props an instance keeps: each [`super::Prop`] field held in a
    /// signal of the current owner, so new values reach only what read it.
    #[doc(hidden)]
    fn held(&self) -> Self {
        self.clone()
    }

    /// An instance's props take `new`'s (a parent's region made the
    /// element again): held props update their readers; returns whether
    /// another field changed.
    #[doc(hidden)]
    fn update_from(&mut self, new: &Self) -> bool {
        if self == new {
            return false;
        }
        *self = new.clone();
        true
    }
}

/// The props of a component that has none (an app's root, say).
impl Props for () {
    fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
        Vec::new()
    }

    fn initial() -> Self {}

    fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
        Err(PropError(format!("unknown prop `{name}`")))
    }

    fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
        false
    }

    fn set_children(&mut self, _: Children) -> bool {
        false
    }
}

/// A component's events. Derive it: `#[derive(Event)]`. The element of a
/// `#[component]` emitting them gets a listener method per event, named
/// as its TSX handler in snake case (`onPress` is `.on_press(..)`): a
/// unit variant's takes `move || ..`, a one-field variant's the value
/// (`move |index: &u32| ..`), a named-field variant's the event itself
/// ([`ComponentBuilder`](super::ComponentBuilder)).
pub trait Event: 'static {
    /// The events (their named types declared in `types`).
    fn spec(types: &mut TsTypes) -> Vec<EventSpec>;

    /// This event's name.
    fn name(&self) -> &'static str;

    /// Its data as a JS value of `host` (converted when JS hears it).
    fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
}

/// The events of a component that has none.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoEvent {}

impl Event for NoEvent {
    fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
        Vec::new()
    }

    fn name(&self) -> &'static str {
        match *self {}
    }

    fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
        match *self {}
    }
}

/// What a component is to JS: its glue and declarations are generated
/// from it ([`declarations`]).
#[derive(Debug, Clone)]
pub struct ComponentSpec {
    /// Its registered name: its type's full path ([`std::any::type_name`]),
    /// unique within one binary.
    pub name: &'static str,
    /// Its JS export: the type's own name, the last segment of its path.
    pub export: String,
    /// Documentation.
    pub doc: &'static str,
    /// Its props, slots and children.
    pub props: Vec<PropSpec>,
    /// Its events.
    pub events: Vec<EventSpec>,
    /// The methods of its ref.
    pub methods: Vec<MethodSpec>,
    /// The named TypeScript types they use.
    pub types: TsTypes,
    /// JS makes the children only while the view places them
    /// (`#[prop(lazy)]` on its `Children`): the core tells it with a
    /// `$children` event on the host.
    pub lazy_children: bool,
    /// Its props are generic over `T`, the type of the rows one takes
    /// (`#[props(generic)]`), as a component with [`super::Items`] is.
    pub generic: bool,
}

/// The props JS sets on a component's host as on a view (TSX's
/// `ComponentHostProps` but `ref`): the app's classes and styles, its test
/// id, its accessibility, its tooltip, whether it is a stop of Tab, layout,
/// file drop, mouse and context menu events, and the actions assistive
/// technologies perform.
pub const HOST_PROPS: &[&str] = &[
    "class",
    "classList",
    "style",
    "activeStyle",
    "hoverStyle",
    "focusStyle",
    "focusWithinStyle",
    "focusVisibleStyle",
    "disabledStyle",
    "testID",
    "accessible",
    "accessibilityLabel",
    "accessibilityHint",
    "accessibilityDescription",
    "role",
    "accessibilityState",
    "accessibilityValue",
    "accessibilityElementsHidden",
    "importantForAccessibility",
    "accessibilityLiveRegion",
    "accessibilityActions",
    "accessibilityLevel",
    "accessibilityActiveDescendant",
    "accessibilityControls",
    "accessibilityDescribedBy",
    "tooltip",
    "focusable",
    "onLayout",
    "onFileDragEnter",
    "onFileDragLeave",
    "onFileDrop",
    "onMouseEnter",
    "onMouseMove",
    "onMouseLeave",
    "onMouseUp",
    "onContextMenu",
    "onAccessibilityAction",
];

/// What makes a component's props', events' and methods' specs.
type Specs = (
    fn(&mut TsTypes) -> Vec<PropSpec>,
    fn(&mut TsTypes) -> Vec<EventSpec>,
    fn(&mut TsTypes) -> Vec<MethodSpec>,
);

impl ComponentSpec {
    /// The [`HOST_PROPS`] JS sets on its host: those it does not declare
    /// itself. Its own prop or event of a host prop's name is the one apps
    /// get (`DataTable`'s `onContextMenu` reports a row and column).
    pub fn host_props(&self) -> impl Iterator<Item = &'static str> + '_ {
        HOST_PROPS.iter().copied().filter(|&name| {
            !self.props.iter().any(|p| p.name == name)
                && !self.events.iter().any(|e| handler_name(e.name) == name)
        })
    }

    pub(crate) fn of<C: Component>() -> Self {
        Self::build(
            name_of::<C>(),
            C::DOC,
            (C::Props::spec, C::Event::spec, C::METHODS.specs),
            C::Props::LAZY_CHILDREN,
            C::Props::GENERIC,
        )
    }

    /// [`Self::of`] past what depends on the component's type.
    #[inline(never)]
    fn build(
        name: &'static str,
        doc: &'static str,
        (props, events, methods): Specs,
        lazy_children: bool,
        generic: bool,
    ) -> Self {
        let mut types = TsTypes::default();
        let props = props(&mut types);
        let events = events(&mut types);
        let methods = methods(&mut types);
        Self {
            name,
            export: export_name(name).to_owned(),
            doc,
            props,
            events,
            methods,
            types,
            lazy_children,
            generic,
        }
    }

    /// Its named slots.
    pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.props
            .iter()
            .filter(|p| p.kind == PropKind::Slot)
            .map(|p| p.name)
    }

    /// Its render functions ([`PropKind::Renderer`]).
    pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.props
            .iter()
            .filter(|p| p.kind == PropKind::Renderer)
            .map(|p| p.name)
    }

    /// Whether it takes JSX children.
    pub fn takes_children(&self) -> bool {
        self.props.iter().any(|p| p.kind == PropKind::Children)
    }

    /// Its [`PropKind::Items`] prop (one at most).
    pub fn items(&self) -> Option<&'static str> {
        self.props
            .iter()
            .find(|p| p.kind == PropKind::Items)
            .map(|p| p.name)
    }

    /// The nodes the glue makes for it, by name: slots and the list.
    pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
        self.props
            .iter()
            .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
            .map(|p| p.name)
    }
}

/// The registered name of component `C`: its type's. It is only compared
/// within one binary, so the format of [`std::any::type_name`] may change
/// between compilers; the exports, which JS sees, are pinned by tests.
pub(crate) fn name_of<C: Component>() -> &'static str {
    std::any::type_name::<C>()
}

/// A type's own name, its JS export: the last segment of its path, without
/// a generic type's arguments (the test `components_are_named_after_their_types`).
pub(crate) fn export_name(type_name: &str) -> &str {
    let path = type_name.split('<').next().unwrap_or(type_name);
    path.rsplit("::").next().unwrap_or(path)
}

/// An instance: a component's props and view, their types erased.
pub(crate) trait AnyInstance {
    fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
    /// Props from the component whose view has this one.
    fn set_props(&mut self, props: &dyn Any);
    fn set_slot(&mut self, name: &'static str, filled: bool);
    fn set_children(&mut self, present: bool);
    /// The component goes away: what its view made goes with it.
    fn cleanup(&mut self);
    /// Its view, made once.
    fn view(&mut self) -> ElNode;
    /// Its registered name.
    fn name(&self) -> &'static str;
    /// A method of its ref (its arguments decoded); `None` when it has no
    /// ref of the method's type.
    fn call(&mut self, call: MethodCall) -> Option<JsResult>;
    /// Its view's owner, once its view is made.
    fn owner(&self) -> Option<super::Owner>;
    /// Where a failure of its code goes first: its owner, or where it is
    /// made before it has one.
    fn failure_owner(&self) -> super::Owner;
    /// Made by JS (where no owner is): its view will be made under
    /// `parent`, the owner of the nearest component above it in the tree,
    /// so it sees that one's context.
    fn adopt(&mut self, parent: super::Owner);
    /// It is the component of `host`, made where `parent` owns.
    fn place(&mut self, host: crate::NodeId, parent: super::Owner);
}

/// The root of a Rust app: makes the app's top component (on the engine
/// thread, where elements live). The engine mounts it as the content of the
/// surface (`nsh_engine::App::Rust`).
#[derive(Clone)]
pub struct Root {
    make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
    tokens: Option<Arc<super::Tokens>>,
    fonts: Vec<Arc<[u8]>>,
    appearance: Option<crate::platform::Appearance>,
    app_id: Option<String>,
    links: crate::url_scheme::AppLinks,
    capabilities: Option<crate::access::Capabilities>,
    status_bar: Option<crate::StatusBarSetting>,
    main_window: Option<crate::desktop::MainWindowOptions>,
    application: Option<crate::desktop::ApplicationOptions>,
    translations: Option<crate::i18n::Translations>,
    app_info: Option<crate::platform::AppInfo>,
}

impl Root {
    /// Component `C` with the props `props` makes.
    pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
        Self {
            make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
            tokens: None,
            fonts: Vec::new(),
            appearance: None,
            app_id: None,
            links: crate::url_scheme::AppLinks::default(),
            capabilities: None,
            status_bar: None,
            main_window: None,
            application: None,
            translations: None,
            app_info: None,
        }
    }

    /// The app's translations (its `locales/` files, which nsh's generated
    /// code compiles in): what [`t!`](crate::t) reads.
    pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
        self.translations = Some(translations);
        self
    }

    /// [`Root::translations`] from the JSON the build writes of the app's
    /// `locales/` files. A wrong one is logged and left out.
    #[doc(hidden)]
    pub fn translations_json(self, json: &str) -> Self {
        match crate::i18n::Translations::from_json(json) {
            Ok(translations) => self.translations(translations),
            Err(e) => {
                log::warn!("locales: {e}");
                self
            }
        }
    }

    /// The app's translations ([`Root::translations`]).
    pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
        self.translations.as_ref()
    }

    /// The app's id (`nsh.json` `"id"`, which nsh's generated code sets):
    /// it names where the app keeps its data (`nsh/storage`).
    pub fn app_id(mut self, id: impl Into<String>) -> Self {
        self.app_id = Some(id.into());
        self
    }

    /// The app's id ([`Root::app_id`]).
    pub fn app_id_ref(&self) -> Option<&str> {
        self.app_id.as_deref()
    }

    /// The app as it was built ([`crate::platform::AppInfo`]), which
    /// nsh's generated code sets: what [`crate::element::app_info`]
    /// answers.
    pub fn app_info(mut self, info: crate::platform::AppInfo) -> Self {
        self.app_info = Some(info);
        self
    }

    /// [`Root::app_info`] from the JSON `appInfo()` reports, which nsh's
    /// generated code compiles in. JSON it cannot read is an app with
    /// nothing known (logged).
    #[doc(hidden)]
    pub fn app_info_json(self, json: &str) -> Self {
        let info = match serde_json::from_str(json) {
            Ok(value) => crate::platform::AppInfo::from_json(&value),
            Err(e) => {
                log::warn!("appInfo: {e}, ignored");
                crate::platform::AppInfo::default()
            }
        };
        self.app_info(info)
    }

    /// The app as it was built ([`Root::app_info`]).
    #[doc(hidden)]
    pub fn app_info_ref(&self) -> Option<&crate::platform::AppInfo> {
        self.app_info.as_ref()
    }

    /// The URL schemes the app claims (`nsh.json` `schemes`): the links the
    /// core lets through ([`crate::url_scheme`],
    /// [`crate::element::next_url_scheme_open`]). Replaces the schemes of
    /// [`Root::links`], keeping its web links.
    pub fn url_schemes(mut self, schemes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.links.set_schemes(schemes);
        self
    }

    /// The schemes the app claims ([`Root::url_schemes`]).
    pub fn url_schemes_ref(&self) -> &[String] {
        self.links.schemes()
    }

    /// The links the app claims (`nsh.json` `schemes` and `links`, which
    /// nsh's generated code sets): URLs of its schemes and `https` URLs of
    /// its web links, the links the core lets through ([`crate::url_scheme`],
    /// [`crate::element::next_url_scheme_open`]).
    pub fn links(mut self, links: crate::url_scheme::AppLinks) -> Self {
        self.links = links;
        self
    }

    /// [`Root::links`] from `nsh.json`'s `schemes` and `links` as JSON text
    /// (`{"schemes": [...], "links": [...]}`), which nsh's generated code
    /// compiles in (checked when it was generated). Read as a package's
    /// `app.json` is: what this runtime cannot claim is left out (logged).
    #[doc(hidden)]
    pub fn links_json(self, json: &str) -> Self {
        let links = match serde_json::from_str::<serde_json::Value>(json) {
            Ok(config) => {
                let (links, ignored) = crate::url_scheme::AppLinks::from_json_lenient(&config);
                for what in ignored {
                    log::warn!("nsh.json: {what}, ignored");
                }
                links
            }
            Err(e) => {
                log::warn!("nsh.json: links: {e}; none claimed");
                crate::url_scheme::AppLinks::default()
            }
        };
        self.links(links)
    }

    /// The links the app claims ([`Root::links`]).
    pub fn links_ref(&self) -> &crate::url_scheme::AppLinks {
        &self.links
    }

    /// What the app declares it may reach (`nsh.json` `capabilities`, which
    /// nsh's generated code sets): the engine checks the app's requests,
    /// URLs it opens, media, web views, clipboard, picker and the rest
    /// against them, as it does a TSX app's. Without a declaration the app
    /// reaches what an app without `capabilities` does.
    pub fn capabilities(mut self, capabilities: crate::access::Capabilities) -> Self {
        self.capabilities = Some(capabilities);
        self
    }

    /// [`Root::capabilities`] from `nsh.json`'s `capabilities` as JSON
    /// text, which nsh's generated code compiles in (checked when it was
    /// generated). Read as a package's are: what this runtime does not know
    /// is not granted (logged), and a declaration it cannot read grants
    /// nothing.
    #[doc(hidden)]
    pub fn capabilities_json(self, json: &str) -> Self {
        let read = serde_json::from_str::<serde_json::Value>(json)
            .map_err(|e| e.to_string())
            .and_then(|v| crate::access::Capabilities::from_json_lenient(&v));
        let capabilities = match read {
            Ok((capabilities, dropped)) => {
                for what in dropped {
                    log::warn!("nsh.json: {what}, not granted");
                }
                capabilities
            }
            Err(e) => {
                log::warn!("nsh.json: capabilities: {e}; nothing granted");
                crate::access::Capabilities::default()
            }
        };
        self.capabilities(capabilities)
    }

    /// What the app declares it may reach ([`Root::capabilities`]); `None`:
    /// no declaration.
    pub fn capabilities_ref(&self) -> Option<&crate::access::Capabilities> {
        self.capabilities.as_ref()
    }

    /// Renders with design tokens `tokens` (`nsh-base`'s theme's; by
    /// default the UI sets' defaults).
    pub fn tokens(mut self, tokens: super::Tokens) -> Self {
        self.tokens = Some(Arc::new(tokens));
        self
    }

    /// Registers a font file (TrueType / OpenType) before the first render;
    /// styles name it by its family name.
    pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
        self.fonts.push(data.into());
        self
    }

    /// Shows the app in `appearance` whatever the system's (`nsh.json`
    /// `"appearance"`; later [`super::set_color_scheme`] calls
    /// change it).
    pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
        self.appearance = Some(appearance);
        self
    }

    /// The status bar's default (`nsh.json` `"statusBar"`), under what
    /// pages and dialogs set (`Screen::status_bar`, `Dialog::status_bar`).
    pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
        self.status_bar = Some(setting);
        self
    }

    /// The main window's launch options (`nsh.json` `"window"`, which nsh's
    /// generated code sets): the runners open the window by them, and the
    /// engine applies their attributes with the first frame and keeps the
    /// placement with `restore_bounds`, as for a TSX app's bundle.
    pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
        self.main_window = Some(options);
        self
    }

    /// [`Root::main_window`] from `nsh.json`'s `"window"` object as JSON
    /// text, which nsh's generated code compiles in (checked when it was
    /// generated). A wrong one is logged and left out.
    #[doc(hidden)]
    pub fn main_window_json(self, json: &str) -> Self {
        let options = serde_json::from_str::<serde_json::Value>(json)
            .map_err(|e| e.to_string())
            .and_then(|v| {
                crate::desktop::MainWindowOptions::from_json(&v).map_err(|e| e.to_string())
            });
        match options {
            Ok(options) => self.main_window(options),
            Err(e) => {
                log::warn!("nsh.json: window: {e}");
                self
            }
        }
    }

    /// The main window's launch options ([`Root::main_window`]).
    pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
        self.main_window.as_ref()
    }

    /// The app's lifecycle options (`nsh.json` `"application"`, which nsh's
    /// generated code sets): the engine sets the quit mode before the app
    /// runs, as for a TSX app's bundle.
    pub fn application(mut self, options: crate::desktop::ApplicationOptions) -> Self {
        self.application = Some(options);
        self
    }

    /// [`Root::application`] from `nsh.json`'s `"application"` object as
    /// JSON text, which nsh's generated code compiles in (checked when it
    /// was generated). A wrong one is logged and left out.
    #[doc(hidden)]
    pub fn application_json(self, json: &str) -> Self {
        let options = serde_json::from_str::<serde_json::Value>(json)
            .map_err(|e| e.to_string())
            .and_then(|v| {
                crate::desktop::ApplicationOptions::from_json(&v).map_err(|e| e.to_string())
            });
        match options {
            Ok(options) => self.application(options),
            Err(e) => {
                log::warn!("nsh.json: application: {e}");
                self
            }
        }
    }

    /// The app's lifecycle options ([`Root::application`]).
    pub fn application_ref(&self) -> Option<&crate::desktop::ApplicationOptions> {
        self.application.as_ref()
    }

    /// The status bar's default ([`Root::status_bar`]).
    pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
        self.status_bar
    }

    /// The appearance it starts in ([`Root::appearance`]; `None`: the
    /// system's).
    pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
        self.appearance
    }

    /// The design tokens it renders with.
    pub fn tokens_ref(&self) -> Option<&super::Tokens> {
        self.tokens.as_deref()
    }

    /// The font files to register.
    pub fn fonts(&self) -> &[Arc<[u8]>] {
        &self.fonts
    }

    /// Component `C` with default props.
    pub fn of<C: Component>() -> Self
    where
        C::Props: Default,
    {
        Self::new::<C>(C::Props::default)
    }

    /// The element of the root component.
    pub(crate) fn element(&self) -> super::AnyElement {
        (self.make)()
    }
}

impl fmt::Debug for Root {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Root")
    }
}

/// The name of [`missing_instance`], which `nsh-cli` looks for in a web
/// runtime's symbol table to know the app makes a component by name (it
/// then keeps every `nsh_part_*` gate). A test below fails when the two
/// stop matching.
pub const BY_NAME_MARKER: &str = "missing_instance";

/// What a component element made by name ([`super::ComponentElement::by_name`])
/// has for its `make`: never called, the registry makes it. Never inlined, so
/// every by-name element's code references this one function.
#[inline(never)]
pub(crate) fn missing_instance() -> Box<dyn AnyInstance> {
    unreachable!("a component made by name is made by its registry")
}

/// What a component element made by name has for its `spec`: never called.
pub(crate) fn missing_spec() -> ComponentSpec {
    unreachable!("a component made by name is made by its registry")
}

/// A new instance of `C`, its props not set yet.
pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
    Box::new(super::once::OnceInstance::<C>::new())
}

#[derive(Clone)]
struct ComponentType {
    spec: Arc<ComponentSpec>,
    make: fn() -> Box<dyn AnyInstance>,
    /// Tells two types of the same name apart (two versions of a crate).
    id: TypeId,
}

#[derive(Clone)]
struct ModuleType {
    spec: Arc<ModuleSpec>,
    /// The type that implements it.
    type_name: &'static str,
}

#[derive(Clone)]
struct ClassType {
    spec: Arc<ClassSpec>,
    /// The type that implements it.
    type_name: &'static str,
}

/// The bar of one scroll view or list that the core asks a UI set to make
/// ([`Registry::scrollbars_from`]).
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct BuiltInScrollbar {
    /// The scroll view or list it scrolls.
    pub target: crate::NodeId,
    /// Whether that view scrolls sideways.
    pub horizontal: bool,
    /// The view's own theme (its `scrollbar` object, as JSON); `None`
    /// with no [`Self::theme_value`]: the app's.
    pub theme: Option<Arc<crate::JsonValue>>,
    /// The view's own theme as Rust gave it
    /// ([`ScrollbarSetting::ThemeValue`](crate::ScrollbarSetting::ThemeValue)),
    /// a value of the set's theme type.
    pub theme_value: Option<super::AnyValue>,
    /// The app's theme, as the set gave it
    /// ([`set_builtin_scrollbars`](super::set_builtin_scrollbars)).
    pub app_theme: Option<super::AnyValue>,
}

/// Makes the built-in bar of a scroll view or list: a component element,
/// which the core lays out over the view's viewport and keeps there as
/// it scrolls; `None` leaves the view the platform's indicator
/// ([`Registry::scrollbars_from`]).
pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;

/// A theme of one view's own given in Rust
/// ([`ScrollbarSetting::ThemeValue`](crate::ScrollbarSetting::ThemeValue)):
/// a value of the theme type of the UI set that makes bars, with the set's
/// maker, so a Rust app that never registered the set gets the bar too (as
/// with [`set_builtin_scrollbars`](super::set_builtin_scrollbars)). Two are
/// equal when they hold the same value.
#[derive(Clone)]
pub struct ScrollbarThemeValue {
    source: ScrollbarSource,
    theme: super::AnyValue,
}

impl ScrollbarThemeValue {
    /// `theme`, drawn by `source` (which reads it as
    /// [`BuiltInScrollbar::theme_value`]).
    pub fn new(source: ScrollbarSource, theme: super::AnyValue) -> Self {
        Self { source, theme }
    }

    /// What makes the bar.
    pub fn source(&self) -> ScrollbarSource {
        self.source
    }

    /// The theme.
    pub fn theme(&self) -> &super::AnyValue {
        &self.theme
    }
}

impl PartialEq for ScrollbarThemeValue {
    fn eq(&self, other: &Self) -> bool {
        self.theme == other.theme
    }
}

impl std::fmt::Debug for ScrollbarThemeValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("ScrollbarThemeValue")
            .field(&self.theme)
            .finish()
    }
}

/// What a UI set exports to JS: its components and modules, and what it
/// passes on from the runtime. Cheap to clone.
#[derive(Clone, Default)]
pub struct Registry {
    types: Arc<FxHashMap<&'static str, ComponentType>>,
    modules: Arc<FxHashMap<&'static str, ModuleType>>,
    /// By the specifier of their set and their name: the sets merged for
    /// the core may have classes of the same name.
    classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
    /// Values and types of `nsh/_core` exported as they are.
    reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
    /// Values `nsh-js` makes for the set (declared by hand, not generated
    /// from a spec).
    native_values: Arc<Vec<&'static str>>,
    /// The runtime module the functions belong to (`nsh/android`): JS
    /// calls them as `nsh/android:BackHandler.exitApp`, apart from any UI set's.
    namespace: Option<&'static str>,
    /// The JS module a UI set is imported as (`app/native`).
    ui_set: Option<&'static str>,
    /// The files its crates ship, with the targets they are for
    /// ([`Registry::assets_for`]; none: every target).
    assets: Arc<Vec<(&'static [crate::platform::Os], &'static [super::AssetFile])>>,
    /// Makes the design tokens of a theme ([`Registry::tokens_from`]).
    tokens: Option<super::TokenSource>,
    /// Makes the views' built-in scroll bars ([`Registry::scrollbars_from`]).
    scrollbars: Option<ScrollbarSource>,
    /// The UI sets served under paths of this one's specifier
    /// ([`Registry::submodule`]).
    submodules: Arc<Vec<Registry>>,
    /// What each engine serving the set runs once ([`Registry::setup`]).
    setups: Arc<Vec<Setup>>,
    /// The stand-ins its modules give headless runs, by name
    /// ([`Registry::fake`]).
    fakes: Arc<Vec<(&'static str, Arc<dyn crate::fake::Fake>)>>,
    /// GPU views' renderers by name ([`Registry::gpu_renderer_source`]).
    gpu_renderers: Arc<Vec<(&'static str, crate::gpu::GpuSource)>>,
}

/// A function each engine serving a set runs once ([`Registry::setup`]).
type Setup = Arc<dyn Fn() + Send + Sync>;

impl fmt::Debug for Registry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.types.keys()).finish()
    }
}

impl Registry {
    /// An empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers component `C` under its type's name, exported to JS as
    /// the type's own name ([`ComponentSpec::name`], [`ComponentSpec::export`]).
    ///
    /// # Panics
    ///
    /// When `C` is registered already, another type of the same name is
    /// (two versions of one crate), or another component of the set has the
    /// same export: a mistake in the code, caught by the app's first run.
    #[track_caller]
    pub fn register<C: Component>(&mut self) -> &mut Self {
        let spec = ComponentSpec::of::<C>();
        let mut refs = Vec::new();
        (C::METHODS.refs)(&mut refs);
        self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
    }

    /// [`Self::register`] past what depends on the component's type: once,
    /// not once per component.
    #[track_caller]
    #[inline(never)]
    fn register_erased(
        &mut self,
        spec: ComponentSpec,
        make: fn() -> Box<dyn AnyInstance>,
        id: TypeId,
        refs: Vec<&'static ClassDef>,
    ) -> &mut Self {
        let types = Arc::make_mut(&mut self.types);
        if let Some(old) = types.get(spec.name) {
            let set = self.ui_set.or(self.namespace);
            panic!("{}", same_name(spec.name, old.id, id, set));
        }
        if self.classes.keys().any(|(_, name)| *name == spec.export) {
            panic!(
                "component `{}` is exported as `{}` like a class{}: rename one",
                spec.name,
                spec.export,
                of_set(self.ui_set.or(self.namespace)),
            );
        }
        if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
            panic!(
                "components `{}` and `{}` are both exported as `{}`{}: rename one",
                other.spec.name,
                spec.name,
                spec.export,
                of_set(self.ui_set.or(self.namespace)),
            );
        }
        types.insert(
            spec.name,
            ComponentType {
                spec: Arc::new(spec),
                make,
                id,
            },
        );
        self.classes_named(refs)
    }

    /// Registers module `M`: its functions on a JS object named
    /// [`Module::NAME`] (merged into the component exported by that name, if
    /// the set has one).
    ///
    /// # Panics
    ///
    /// When the set has a module of that name already.
    #[track_caller]
    pub fn module<M: Module>(&mut self) -> &mut Self {
        let type_name = std::any::type_name::<M>();
        if self.classes.keys().any(|(_, name)| *name == M::NAME) {
            panic!(
                "module `{type_name}` is named `{}` like a class{}: rename one",
                M::NAME,
                of_set(self.ui_set.or(self.namespace))
            );
        }
        let modules = Arc::make_mut(&mut self.modules);
        if let Some(old) = modules.get(M::NAME) {
            panic!(
                "{}",
                same_module(
                    M::NAME,
                    old.type_name,
                    type_name,
                    self.ui_set.or(self.namespace)
                )
            );
        }
        modules.insert(
            M::NAME,
            ModuleType {
                spec: Arc::new(ModuleSpec::of::<M>()),
                type_name,
            },
        );
        let mut refs = Vec::new();
        for f in M::FUNCTIONS {
            (f.refs)(&mut refs);
        }
        self.classes_named(refs)
    }

    /// Registers class `C` (`#[class]`): a JS class named [`Class::DEF`]'s
    /// name, which JS makes with `new` (when it has a constructor) and gets
    /// from the members that return one. The classes its members'
    /// signatures name are registered with it, as are those a module's
    /// functions or a component's methods name ([`Registry::module`],
    /// [`Registry::register`]): their objects reach JS, so they are
    /// exported and declared. Registering a class again does nothing.
    ///
    /// # Panics
    ///
    /// When the set has another class, a module or a component of that
    /// name already.
    #[track_caller]
    pub fn class<C: Class>(&mut self) -> &mut Self {
        self.class_def(C::DEF)
    }

    /// Registers the classes in `refs` (a signature names them), unless
    /// the set has them.
    #[track_caller]
    fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
        for def in refs {
            self.class_def(def);
        }
        self
    }

    #[track_caller]
    fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
        let type_name = (def.type_name)();
        let set = self.ui_set.or(self.namespace);
        if let Some(old) = self.classes.get(&(set, def.name)) {
            if (old.spec.def.type_id)() == (def.type_id)() {
                return self;
            }
            panic!("{}", same_class(def.name, old.type_name, type_name, set));
        }
        if self.modules.contains_key(def.name)
            || self.types.values().any(|t| t.spec.export == def.name)
        {
            panic!(
                "class `{type_name}` is named `{}` like a module or a component{}: rename one",
                def.name,
                of_set(set)
            );
        }
        Arc::make_mut(&mut self.classes).insert(
            (set, def.name),
            ClassType {
                spec: Arc::new(ClassSpec::of(def)),
                type_name,
            },
        );
        // What its members name, in turn (it is registered: a cycle ends).
        let mut refs = Vec::new();
        for m in def.members {
            (m.refs)(&mut refs);
        }
        self.classes_named(refs)
    }

    /// Exports `values` and `types` of the runtime as they are (accessors
    /// such as `safeArea`, hooks, types such as `Insets`).
    pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
        let r = Arc::make_mut(&mut self.reexports);
        r.0.extend_from_slice(values);
        r.1.extend_from_slice(types);
        self
    }

    /// The components of all of `sets`, for making them by name (the
    /// core's view of the sets a host serves). Not a module of its own.
    /// Components of different sets may share an export (JS imports them
    /// from different modules), not a name. Modules and classes are not
    /// in it: their calls carry what they run.
    ///
    /// # Panics
    ///
    /// When two sets register the same component, two types of the same
    /// name or two fakes of the same name ([`Registry::fake`]).
    #[track_caller]
    pub fn merged(sets: &[Registry]) -> Self {
        let mut out = Self::default();
        for set in sets.iter().flat_map(Registry::sets) {
            out.tokens = out.tokens.or(set.tokens);
            out.scrollbars = out.scrollbars.or(set.scrollbars);
            Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
            let fakes = Arc::make_mut(&mut out.fakes);
            for (name, fake) in set.fakes.iter() {
                assert!(
                    fakes.iter().all(|(n, _)| n != name),
                    "two fakes are named `{name}`, by two UI sets"
                );
                fakes.push((name, fake.clone()));
            }
            let renderers = Arc::make_mut(&mut out.gpu_renderers);
            for (name, source) in set.gpu_renderers.iter() {
                assert!(
                    renderers.iter().all(|(n, _)| n != name),
                    "two GPU renderers are named `{name}`, by two UI sets"
                );
                renderers.push((name, source.clone()));
            }
            let types = Arc::make_mut(&mut out.types);
            for (name, ty) in set.types.iter() {
                if let Some(old) = types.insert(name, ty.clone()) {
                    panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
                }
            }
        }
        out
    }

    /// The registry of a UI set apps import as `specifier`
    /// (`app/native`). An app's crate makes its own with
    /// `#[native_module("…")]`.
    pub fn ui_set(specifier: &'static str) -> Self {
        Self {
            ui_set: Some(specifier),
            ..Self::default()
        }
    }

    /// The JS module the registry is imported as: a UI set's, or the
    /// runtime module's (`None`: a Rust app's components).
    pub fn specifier(&self) -> Option<&'static str> {
        self.ui_set.or(self.namespace)
    }

    /// The runtime values and types exported as they are
    /// ([`Registry::reexport`]).
    pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
        (&self.reexports.0, &self.reexports.1)
    }

    /// Serves UI set `set` wherever this one is served, as a module of
    /// its own under a path of this set's specifier (`nsh/base/plot` of
    /// `nsh/base`, as `gpui-base`'s `plot` is a module of the crate): a
    /// family of components whose names (`Line`, `Grid`) only make sense
    /// together, apart from the set's other exports. Hosts, the toolchain
    /// and the declarations take the set's submodules with it
    /// ([`Registry::sets`]), so a list of UI sets names only the set.
    ///
    /// # Panics
    ///
    /// When `set`'s specifier is not a path under this set's.
    #[track_caller]
    pub fn submodule(&mut self, set: Registry) -> &mut Self {
        let under = match (self.ui_set, set.ui_set) {
            (Some(parent), Some(child)) => child
                .strip_prefix(parent)
                .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
            _ => false,
        };
        assert!(
            under,
            "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
            set.ui_set, self.ui_set
        );
        Arc::make_mut(&mut self.submodules).push(set);
        self
    }

    /// This set and its submodules ([`Registry::submodule`]), each one
    /// module apps import: what a host serves and the toolchain declares
    /// for it.
    pub fn sets(&self) -> Vec<&Registry> {
        let mut out = vec![self];
        for sub in self.submodules.iter() {
            out.extend(sub.sets());
        }
        out
    }

    /// Exports `values` `nsh-js` makes for the set (`NavStack`, `NavPage`),
    /// declared by hand rather than generated from a spec.
    pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
        Arc::make_mut(&mut self.native_values).extend_from_slice(values);
        self
    }

    /// Ships `files` with the apps that use the set (`assets!()`: a crate's
    /// `assets/` directory): `nsh run` serves them, `nsh package` copies
    /// them into the app, and the engine registers the fonts among them
    /// before the first render. `asset!` refers to one. Every target gets
    /// them; [`Registry::assets_for`] limits them to some.
    pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
        self.assets_for(&[], files)
    }

    /// Like [`Registry::assets`], for the packages of `targets` only: the
    /// others neither copy the files nor register their fonts, so a file
    /// only the web downloads stays out of the desktop and mobile
    /// packages. No `targets`: every target. A file the app reads on a
    /// target outside the list is not there to read.
    pub fn assets_for(
        &mut self,
        targets: &'static [crate::platform::Os],
        files: &'static [super::AssetFile],
    ) -> &mut Self {
        Arc::make_mut(&mut self.assets).push((targets, files));
        self
    }

    /// Makes the design tokens of the app's theme file, and the defaults
    /// (`nsh-base`'s theme): the core reads `nsh.json`'s `"theme"` with it.
    pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
        self.tokens = Some(source);
        self
    }

    /// Makes the built-in bar of the scroll views and lists that show one
    /// ([`set_builtin_scrollbars`](super::set_builtin_scrollbars), or a
    /// theme as their `scrollbar`) with `source`. Of the sets a host
    /// serves, the first that has one makes them.
    pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
        self.scrollbars = Some(source);
        self
    }

    /// How the set makes the views' built-in scroll bars
    /// ([`Registry::scrollbars_from`]).
    pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
        self.scrollbars
    }

    /// Runs `f` once on each engine that serves the set, in its reactive
    /// runtime, before the app's first op: what the set's crates keep per
    /// engine is set up there (the languages an `Editor` knows,
    /// `nsh_base::editor::register_language`; a value of
    /// [`global`](super::prelude::global)), as a Rust app's root sets it up
    /// before its children. An app's crate calls it from its
    /// `#[native_module]` function.
    pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
        Arc::make_mut(&mut self.setups).push(Arc::new(f));
        self
    }

    /// Registers `source` as the renderer of GPU views named `name`
    /// (`gpuView("gallery/scene", …)` in TSX, `gpu_view().renderer_named`
    /// in Rust); a later registration of a name replaces an earlier one.
    /// An app's crate calls `nsh-gpu`'s `gpu_renderer`, which makes the
    /// source, from its `#[native_module]` function ([`crate::gpu`]).
    pub fn gpu_renderer_source(
        &mut self,
        name: &'static str,
        source: crate::gpu::GpuSource,
    ) -> &mut Self {
        let renderers = Arc::make_mut(&mut self.gpu_renderers);
        renderers.retain(|(n, _)| *n != name);
        renderers.push((name, source));
        self
    }

    /// The renderer registered as `name` ([`Self::gpu_renderer_source`]).
    pub fn registered_gpu_renderer(&self, name: &str) -> Option<&crate::gpu::GpuSource> {
        self.gpu_renderers
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, s)| s)
    }

    /// Gives headless runs `fake` in place of what a module of the set asks
    /// of the platform, under `name` (`"nsh-extra/speech"`: the set's
    /// specifier and the module), which tests call it by
    /// ([`crate::fake`]). Apps never use it; the headless driver installs
    /// it before the app starts. An app's crate calls it from its
    /// `#[native_module]` function.
    ///
    /// # Panics
    ///
    /// When the set has a fake of that name already. Names are unique
    /// across the sets an app is served, too ([`Registry::merged`]).
    #[track_caller]
    pub fn fake(&mut self, name: &'static str, fake: Arc<dyn crate::fake::Fake>) -> &mut Self {
        assert!(
            self.fakes.iter().all(|(n, _)| *n != name),
            "two fakes are named `{name}`{}",
            of_set(self.ui_set.or(self.namespace))
        );
        Arc::make_mut(&mut self.fakes).push((name, fake));
        self
    }

    /// The fakes [`Registry::fake`] gave the set and the sets served under
    /// it, by name, in order: what the headless driver installs.
    #[doc(hidden)]
    pub fn fakes(&self) -> Vec<(&'static str, Arc<dyn crate::fake::Fake>)> {
        self.sets()
            .into_iter()
            .flat_map(|set| set.fakes.iter().cloned())
            .collect()
    }

    /// Runs the functions [`Registry::setup`] gave the set (a merged set's:
    /// every set's, in order). The core runs them when it takes its sets.
    pub(crate) fn run_setups(&self) {
        for setup in self.setups.iter() {
            setup();
        }
    }

    /// Runs the setup functions of this set that `old` does not have
    /// (`Core::extend_components`).
    pub(crate) fn run_setups_not_in(&self, old: &Registry) {
        for setup in self.setups.iter() {
            let known = old
                .setups
                .iter()
                .any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
            if !known {
                setup();
            }
        }
    }

    /// The tokens of theme file `json` (`None`: the defaults) and what of it
    /// was left out, by the source a set brings ([`Registry::tokens_from`];
    /// `None`: no set does).
    pub fn tokens(
        &self,
        json: Option<&str>,
    ) -> Option<Result<(super::Tokens, Vec<String>), String>> {
        self.tokens.map(|source| source(json))
    }

    /// How the set reads a theme file ([`Registry::tokens_from`]).
    pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
        self.tokens
    }

    /// The files [`Registry::assets`] and [`Registry::assets_for`] ship, for
    /// every target.
    pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
        self.assets.iter().flat_map(|(_, files)| files.iter())
    }

    /// The files of [`Registry::asset_files`] with the targets each is
    /// for (none: every target).
    pub fn scoped_asset_files(
        &self,
    ) -> impl Iterator<Item = (&'static [crate::platform::Os], &'static super::AssetFile)> + '_
    {
        self.assets
            .iter()
            .flat_map(|&(targets, files)| files.iter().map(move |file| (targets, file)))
    }

    /// The values of [`Registry::native_values`].
    pub fn native_value_names(&self) -> &[&'static str] {
        &self.native_values
    }

    /// A registry of the runtime's module `namespace` (`nsh/android`).
    pub(crate) fn runtime(namespace: &'static str) -> Self {
        Self {
            namespace: Some(namespace),
            ..Self::default()
        }
    }

    /// The runtime module the registry's functions belong to (`None`: a UI
    /// set's).
    pub fn namespace(&self) -> Option<&'static str> {
        self.namespace
    }

    /// The registered classes, by name.
    pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
        let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
        specs.sort_by_key(|s| s.name);
        specs
    }

    /// The registered modules, by name.
    pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
        let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
        specs.sort_by_key(|s| s.name);
        specs
    }

    /// The module whose functions JS finds on the function `function` of
    /// a flat module of the set: a module named like it
    /// (`#[module(name = "test")]`: `test.skip`), as a module named like a
    /// component is on the component.
    pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
        let exported = self.modules.values().any(|m| {
            m.spec.flat
                && m.spec
                    .functions
                    .iter()
                    .any(|f| !f.getter && f.name == function)
        });
        exported
            .then(|| {
                self.modules
                    .values()
                    .find(|m| !m.spec.flat && m.spec.name == function)
                    .map(|m| m.spec.clone())
            })
            .flatten()
    }

    /// The registered components, by export.
    pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
        let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
        specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
        specs
    }

    /// The exports of the set that TS sees without documentation, by
    /// their TS names (`Gauge`, `Gauge.max`, `Gauge.onChange`,
    /// `Ledger.copy`, `new Account`, `Account.balance`): what to give a
    /// doc comment. A component is documented by its `#[component]`
    /// function, a module or class by its struct, the rest by their own
    /// (a setter needs none beside its getter's; a module merged into a
    /// component or a function of its name, or exported flat, by that
    /// component or function, or its functions).
    pub fn undocumented(&self) -> Vec<String> {
        let mut out = Vec::new();
        let specs = self.specs();
        for c in &specs {
            if c.doc.is_empty() {
                out.push(c.export.clone());
            }
            for p in c.props.iter().filter(|p| p.doc.is_empty()) {
                out.push(format!("{}.{}", c.export, p.name));
            }
            for e in c.events.iter().filter(|e| e.doc.is_empty()) {
                out.push(format!("{}.{}", c.export, handler_name(e.name)));
            }
            for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
                out.push(format!("{}.{}", c.export, m.name));
            }
        }
        for m in self.module_specs() {
            let merged = specs.iter().any(|c| c.export == m.name)
                || (!m.flat && self.function_members(m.name).is_some());
            if m.doc.is_empty() && !merged && !m.flat {
                out.push(m.name.to_owned());
            }
            for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
                out.push(if m.flat {
                    f.name.to_owned()
                } else {
                    format!("{}.{}", m.name, f.name)
                });
            }
        }
        for c in self.class_specs() {
            if c.doc.is_empty() {
                out.push(c.name.to_owned());
            }
            let documented_getter = |name: &str| {
                c.members
                    .iter()
                    .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
            };
            for m in c.members.iter().filter(|m| m.doc.is_empty()) {
                match m.kind {
                    MemberKind::Constructor => out.push(format!("new {}", c.name)),
                    MemberKind::Setter if documented_getter(m.name) => {}
                    _ => out.push(format!("{}.{}", c.name, m.name)),
                }
            }
        }
        out
    }

    /// A new instance of the component of type `id`, and its registered
    /// name (a component element made by name).
    pub(crate) fn make_type(
        &self,
        id: TypeId,
    ) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
        self.types
            .values()
            .find(|t| t.id == id)
            .map(|t| (t.spec.clone(), (t.make)()))
    }

    /// A new instance of component `name`.
    pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
        self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
    }
}

/// The message of two registrations under component name `name`.
fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
    if old == new {
        format!("component `{name}` is registered twice{}", of_set(set))
    } else {
        format!(
            "two different types named `{name}` are registered{} (two versions of one crate?)",
            of_set(set)
        )
    }
}

/// The message of two modules named `name`.
fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
    if old == new {
        format!("module `{old}` is registered twice{}", of_set(set))
    } else {
        format!(
            "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
            of_set(set)
        )
    }
}

/// The message of two classes named `name`.
fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
    if old == new {
        format!("class `{old}` is registered twice{}", of_set(set))
    } else {
        format!(
            "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
            of_set(set)
        )
    }
}

/// ` in `app/native`` for a registry with a specifier.
fn of_set(set: Option<&str>) -> String {
    set.map(|s| format!(" in `{s}`")).unwrap_or_default()
}

/// The declarations of what `registry`'s specs export: one component per
/// spec (by its [`ComponentSpec::export`] name), one object per module
/// (its type `<Name>Module`; merged into a component of the same name; a
/// flat module's functions one by one), one class per class, and the
/// named types they use.
/// Exports named in `omit` are left out (their types stay): `nsh-js`
/// declares them, building on the module (`BackHandlerModule & ...`), as
/// it declares the re-exports and native values it makes.
pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
    let specs = registry.specs();
    let modules = registry.module_specs();
    let classes = registry.class_specs();
    use std::fmt::Write as _;
    let mut out = String::new();
    let doc = |out: &mut String, indent: &str, doc: &str| {
        if !doc.is_empty() {
            let _ = writeln!(out, "{indent}/** {doc} */");
        }
    };
    // The named types, once each.
    let mut types = TsTypes::default();
    for spec in &specs {
        types.merge(&spec.types);
    }
    for m in &modules {
        types.merge(&m.types);
    }
    for c in &classes {
        types.merge(&c.types);
    }
    for declaration in types.declarations() {
        let _ = write!(out, "{declaration}\n\n");
    }
    let module_of = |name: &str| modules.iter().find(|m| m.name == name);
    // A function's signatures: its own, or its overloads.
    let signatures = |f: &FunctionSpec| {
        let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
            let params = params
                .iter()
                .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
                .collect::<Vec<_>>()
                .join(", ");
            let value = returns.clone().unwrap_or_else(|| "void".to_owned());
            let returns = if f.promises() {
                format!("Promise<{value}>")
            } else {
                value
            };
            (params, returns)
        };
        if f.overloads.is_empty() {
            vec![one(&f.params, &f.returns)]
        } else {
            f.overloads
                .iter()
                .map(|(params, returns)| one(params, returns))
                .collect()
        }
    };
    // A module's object type.
    let module_object = |out: &mut String, m: &ModuleSpec| {
        out.push_str("{\n");
        for f in &m.functions {
            for (params, returns) in signatures(f) {
                doc(out, "  ", f.doc);
                if f.getter {
                    let _ = writeln!(out, "  readonly {}: {returns};", f.name);
                    continue;
                }
                let _ = writeln!(out, "  {}({params}): {returns};", f.name);
            }
        }
        for constant in &m.constants {
            doc(out, "  ", constant.doc);
            let _ = writeln!(
                out,
                "  readonly {}: {};",
                constant.name,
                constant.value.ts_type()
            );
        }
        out.push('}');
    };
    for spec in &specs {
        // A component with rows is generic over their type, like `List`.
        // Props generic over their rows' type default it to `any`, so a mark
        // without rows of its own takes any field name.
        let (generic, params, extends) = match spec.items() {
            Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
            None if spec.generic => ("<T>", "<T = any>", ""),
            None => ("", "", ""),
        };
        // A component with methods: its ref is an object of them. Host
        // props it declares itself are its own.
        let mut omit: Vec<&str> = HOST_PROPS
            .iter()
            .copied()
            .filter(|&h| !spec.host_props().any(|p| p == h))
            .collect();
        if !spec.methods.is_empty() {
            omit.insert(0, "ref");
        }
        let host = if omit.is_empty() {
            "ComponentHostProps".to_owned()
        } else {
            let names = omit.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>();
            format!("Omit<ComponentHostProps, {}>", names.join(" | "))
        };
        if !spec.methods.is_empty() {
            let _ = write!(
                out,
                "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n  /** The component's host node. */\n  readonly node: ViewRef;\n",
                spec.export
            );
            for m in &spec.methods {
                doc(&mut out, "  ", m.doc);
                let params = m
                    .params
                    .iter()
                    .map(|(n, ts, optional)| {
                        format!("{n}{}: {ts}", if *optional { "?" } else { "" })
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                let returns = match &m.returns {
                    Some(ts) => format!("Promise<{ts}>"),
                    None => "void".to_owned(),
                };
                let _ = writeln!(out, "  {}({params}): {returns};", m.name);
            }
            out.push_str("}\n\n");
        }
        let _ = writeln!(
            out,
            "export interface {}Props{params} extends {host}{extends} {{",
            spec.export
        );
        if !spec.methods.is_empty() {
            let _ = writeln!(
                out,
                "  ref?: {0}Ref | ((ref: {0}Ref) => void);",
                spec.export
            );
        }
        for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
            doc(&mut out, "  ", p.doc);
            let optional = if p.optional { "?" } else { "" };
            let _ = writeln!(out, "  {}{optional}: {};", p.name, p.ts);
        }
        for e in &spec.events {
            doc(&mut out, "  ", e.doc);
            let handler = handler_name(e.name);
            let arg = if e.data == "void" {
                String::new()
            } else {
                format!("{}: {}", e.arg, e.data)
            };
            let _ = writeln!(out, "  {handler}?: ({arg}) => void;");
        }
        out.push_str("}\n\n");
        if omit.contains(&spec.export.as_str()) {
            continue;
        }
        doc(&mut out, "", spec.doc);
        // A module of the same name: its functions on the component.
        let mut with = String::new();
        if let Some(m) = module_of(&spec.export) {
            with.push_str(" & ");
            module_object(&mut with, m);
        }
        let _ = write!(
            out,
            "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
            spec.export, spec.export,
        );
    }
    for m in &modules {
        if specs.iter().any(|s| s.export == m.name)
            || (!m.flat && registry.function_members(m.name).is_some())
        {
            continue;
        }
        if m.flat {
            for f in m
                .functions
                .iter()
                .filter(|f| !f.getter && !omit.contains(&f.name))
            {
                for (params, returns) in signatures(f) {
                    doc(&mut out, "", f.doc);
                    let _ = writeln!(
                        out,
                        "export declare function {}({params}): {returns};",
                        f.name
                    );
                }
                // A module of its name: its functions on the function.
                if let Some(members) = registry.function_members(f.name) {
                    let _ = writeln!(out, "export declare namespace {} {{", f.name);
                    for member in &members.functions {
                        for (params, returns) in signatures(member) {
                            doc(&mut out, "  ", member.doc);
                            let _ = if member.getter {
                                writeln!(out, "  const {}: {returns};", member.name)
                            } else {
                                writeln!(out, "  function {}({params}): {returns};", member.name)
                            };
                        }
                    }
                    for constant in &members.constants {
                        doc(&mut out, "  ", constant.doc);
                        let _ = writeln!(
                            out,
                            "  const {}: {};",
                            constant.name,
                            constant.value.ts_type()
                        );
                    }
                    out.push_str("}\n");
                }
                out.push('\n');
            }
            for constant in &m.constants {
                if !omit.contains(&constant.name) {
                    doc(&mut out, "", constant.doc);
                    let _ = writeln!(
                        out,
                        "export declare const {}: {};\n",
                        constant.name,
                        constant.value.ts_type()
                    );
                }
            }
            if m.default && !omit.contains(&"default") {
                let _ = write!(out, "declare const defaultExport: ");
                module_object(&mut out, m);
                // The registry's values `nsh-js` makes are on the object too.
                for native in registry.native_value_names() {
                    let _ = write!(out, " & {{ {native}: typeof {native} }}");
                }
                out.push_str(";\nexport default defaultExport;\n\n");
            }
            continue;
        }
        doc(&mut out, "", m.doc);
        let _ = write!(out, "export interface {}Module ", m.name);
        module_object(&mut out, m);
        out.push_str("\n\n");
        if !omit.contains(&m.name) {
            doc(&mut out, "", m.doc);
            let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
        }
        if m.default && !omit.contains(&"default") {
            let _ = write!(
                out,
                "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
                m.name
            );
        }
    }
    for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
        class_declaration(&mut out, c);
    }
    out
}

/// `export declare class Name { ... }`.
fn class_declaration(out: &mut String, c: &ClassSpec) {
    use std::fmt::Write as _;
    let doc = |out: &mut String, indent: &str, doc: &str| {
        if !doc.is_empty() {
            let _ = writeln!(out, "{indent}/** {doc} */");
        }
    };
    doc(out, "", c.doc);
    if c.def.interface {
        // No value: what its objects have.
        let _ = writeln!(out, "export interface {} {{", c.name);
        for m in &c.members {
            let params = m
                .params
                .iter()
                .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
                .collect::<Vec<_>>()
                .join(", ");
            let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
            let returns = if m.is_async {
                format!("Promise<{value}>")
            } else {
                value
            };
            doc(out, "  ", m.doc);
            let has_setter = |name| {
                c.members
                    .iter()
                    .any(|s| s.kind == MemberKind::Setter && s.name == name)
            };
            let _ = match m.kind {
                MemberKind::Method => writeln!(out, "  {}({params}): {returns};", m.name),
                MemberKind::Getter if has_setter(m.name) => {
                    writeln!(out, "  {}: {returns};", m.name)
                }
                MemberKind::Getter => writeln!(out, "  readonly {}: {returns};", m.name),
                // A setter's property is its getter's; constructors and
                // statics belong to a class value it has none of.
                _ => Ok(()),
            };
        }
        out.push_str("}\n\n");
        return;
    }
    let _ = writeln!(out, "export declare class {} {{", c.name);
    if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
        out.push_str("  /** Made by the class's members only. */\n  private constructor();\n");
    }
    let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
        let params = params
            .iter()
            .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
            .collect::<Vec<_>>()
            .join(", ");
        let value = returns.clone().unwrap_or_else(|| "void".to_owned());
        let returns = if m.is_async {
            format!("Promise<{value}>")
        } else {
            value
        };
        (params, returns)
    };
    for m in &c.members {
        if !m.overloads.is_empty() {
            for (params, returns) in &m.overloads {
                doc(out, "  ", m.doc);
                let (params, returns) = one(m, params, returns);
                let _ = match m.kind {
                    MemberKind::Static => {
                        writeln!(out, "  static {}({params}): {returns};", m.name)
                    }
                    _ => writeln!(out, "  {}({params}): {returns};", m.name),
                };
            }
            continue;
        }
        doc(out, "  ", m.doc);
        let (params, returns) = one(m, &m.params, &m.returns);
        let _ = match m.kind {
            MemberKind::Constructor => writeln!(out, "  constructor({params});"),
            MemberKind::Method => writeln!(out, "  {}({params}): {returns};", m.name),
            MemberKind::Getter => writeln!(out, "  get {}(): {returns};", m.name),
            MemberKind::Setter => writeln!(out, "  set {}({params});", m.name),
            MemberKind::Static => writeln!(out, "  static {}({params}): {returns};", m.name),
        };
    }
    out.push_str(
        "  /** Frees the Rust value now (else when the object is collected); the object throws after. */\n  dispose(): void;\n  [Symbol.dispose](): void;\n}\n\n",
    );
}

/// `press` -> `onPress`.
fn handler_name(event: &str) -> String {
    let mut chars = event.chars();
    match chars.next() {
        Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
        None => "on".to_owned(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::*;

    #[test]
    fn by_name_marker_names_the_stand_in_make() {
        let name = std::any::type_name_of_val(&missing_instance);
        assert!(
            name.ends_with(&format!("::{BY_NAME_MARKER}")),
            "{name} is not {BY_NAME_MARKER}: update nsh-cli's by-name detection"
        );
    }

    #[component]
    fn ByName() -> impl IntoElement {
        text("by name")
    }

    #[test]
    fn a_component_made_by_name_has_the_marked_make() {
        let mut element = crate::element::ComponentElement::<ByName>::named(());
        let crate::element::ElKind::Component(c) = &element.node().kind else {
            panic!("not a component element");
        };
        assert!(std::ptr::fn_addr_eq(
            c.make,
            missing_instance as fn() -> Box<dyn AnyInstance>
        ));
    }

    #[derive(Default)]
    struct Stepper;

    /// Picks a number.
    #[derive(Clone, PartialEq, Props)]
    struct StepperProps {
        /// The value.
        value: f64,
        #[prop(default)]
        size: StepperSize,
        max_value: Option<f64>,
        /// Above the control.
        label: Option<Slot>,
        children: Children,
    }

    #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
    enum StepperSize {
        #[default]
        Regular,
        ExtraLarge,
    }

    #[derive(Event)]
    enum StepperEvent {
        /// The value changed.
        Change {
            new_value: f64,
        },
        #[args(limit)]
        Limit(u32),
        Reset,
    }

    struct StepperApi;

    #[methods]
    impl StepperApi {
        /// Jumps to `value`.
        pub(crate) fn jump_to(&self, value: f64) {
            let _ = value;
        }

        pub(crate) fn value(&self) -> f64 {
            0.0
        }

        /// A helper without `pub`: not a method of the ref.
        #[allow(dead_code)]
        fn clamp(&self, value: f64) -> f64 {
            value
        }
    }

    impl Component for Stepper {
        type Props = StepperProps;
        type Event = StepperEvent;
        const METHODS: Methods = Methods::of::<StepperApi>();
        const DOC: &'static str = "Picks a number.";

        fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
            view()
        }
    }

    #[test]
    fn the_declarations_come_from_the_types() {
        let mut registry = Registry::new();
        registry.register::<Stepper>();
        let ts = declarations(&registry, &[]);
        for line in [
            "  /** The value. */\n  value: number;",
            "export type StepperSize = \"regular\" | \"extraLarge\";",
            "  size?: StepperSize;",
            "  maxValue?: number | null;",
            "  /** Above the control. */\n  label?: JSX.Element;",
            "  children?: JSX.Element;",
            "  /** The value changed. */\n  onChange?: (event: { newValue: number }) => void;",
            "  onLimit?: (event: { limit: number }) => void;",
            "  onReset?: () => void;",
            "/** Picks a number. */",
            "export interface StepperRef {",
            "  /** Jumps to `value`. */\n  jumpTo(value: number): void;",
            "  value(): Promise<number>;",
            "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n  ref?: StepperRef | ((ref: StepperRef) => void);",
            "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
        ] {
            assert!(ts.contains(line), "missing {line:?} in\n{ts}");
        }
        assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
        assert_eq!(StepperApi::METHODS.len(), 2);
        let mut props = StepperProps::initial();
        let size = |json| {
            let specs = StepperProps::spec(&mut TsTypes::default());
            let decode = specs
                .iter()
                .find(|p| p.name == "size")
                .unwrap()
                .decode
                .unwrap();
            super::super::json_host::decode(decode, json)
        };
        assert!(
            props
                .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
                .unwrap()
        );
        assert!(props.size == StepperSize::ExtraLarge);
        // A value of another type: the conversion fails (JS warns, the prop
        // keeps its value), and so does a decoded value of another prop's
        // type.
        assert!(size(serde_json::json!("huge")).is_err());
        assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
        assert!(props.set("size", None).unwrap());
        assert!(props.size == StepperSize::Regular);
        let data = |e: &StepperEvent| super::super::json_host::event_data(e);
        assert_eq!(
            data(&StepperEvent::Change { new_value: 2.5 }),
            Some(serde_json::json!({ "newValue": 2.5 }))
        );
        assert_eq!(
            data(&StepperEvent::Limit(3)),
            Some(serde_json::json!({ "limit": 3 }))
        );
        assert_eq!(data(&StepperEvent::Reset), None);
        assert_eq!(StepperEvent::Reset.name(), "reset");
    }

    #[test]
    fn exports_without_docs_are_listed() {
        let mut registry = Registry::new();
        registry.register::<Stepper>();
        // `size`, `maxValue`, `children`, `onLimit`, `onReset` and the
        // ref's `value` have no doc comment.
        assert_eq!(
            registry.undocumented(),
            [
                "Stepper.size",
                "Stepper.maxValue",
                "Stepper.children",
                "Stepper.onLimit",
                "Stepper.onReset",
                "Stepper.value",
            ]
        );
        let mut r = Registry::ui_set("test/maker");
        r.module::<Maker>();
        assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
    }

    /// A class no set registers.
    #[crate::element::class]
    struct Lonely;

    #[crate::element::class]
    impl Lonely {
        pub(crate) fn new() -> Self {
            Lonely
        }
    }

    /// Makes a `Lonely`.
    #[crate::element::module]
    struct Maker;

    #[crate::element::module]
    impl Maker {
        pub(crate) fn make() -> Instance<Lonely> {
            Instance::new(Lonely)
        }
    }

    #[test]
    fn the_classes_a_signature_names_are_registered_with_it() {
        let mut r = Registry::ui_set("test/maker");
        r.module::<Maker>();
        // The module's result names `Lonely`: it is the set's, declared and
        // exported.
        let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
        assert_eq!(names, ["Lonely"]);
        let ts = declarations(&r, &[]);
        assert!(ts.contains("export declare class Lonely"), "{ts}");
        assert!(ts.contains("make(): Lonely;"), "{ts}");
        // Registering it again does nothing.
        r.class::<Lonely>();
        assert_eq!(r.class_specs().len(), 1);
        let _ = Registry::merged(&[r]);
    }

    /// Checks.
    #[crate::element::module]
    struct Checks;

    #[crate::element::module(flat)]
    impl Checks {
        /// Declares a check.
        pub(crate) fn check(name: String) {
            let _ = name;
        }
    }

    /// Unused: a module's doc when its functions are on `check`.
    #[crate::element::module]
    struct CheckVariants;

    #[crate::element::module(name = "check")]
    impl CheckVariants {
        /// How many variants there are.
        pub(crate) const COUNT: u32 = 2;

        /// Declares a check that does not run.
        pub(crate) fn skip(name: String) {
            let _ = name;
        }

        pub(crate) fn todo(name: String) {
            let _ = name;
        }
    }

    /// Named like no function of the set: an object of its own.
    #[crate::element::module]
    struct Loose;

    #[crate::element::module(name = "loose")]
    impl Loose {
        /// Nothing.
        pub(crate) fn nothing() {}
    }

    #[test]
    fn a_module_named_like_a_function_puts_its_functions_on_it() {
        let mut r = Registry::ui_set("test/checks");
        r.module::<Checks>()
            .module::<CheckVariants>()
            .module::<Loose>();
        assert_eq!(r.function_members("check").unwrap().name, "check");
        assert!(r.function_members("loose").is_none());
        let ts = declarations(&r, &[]);
        assert!(
            ts.contains(
                "/** Declares a check. */\n\
                 export declare function check(name: string): void;\n\
                 export declare namespace check {\n  \
                 /** Declares a check that does not run. */\n  \
                 function skip(name: string): void;\n  \
                 function todo(name: string): void;\n  \
                 /** How many variants there are. */\n  \
                 const COUNT: number;\n}\n"
            ),
            "{ts}"
        );
        assert!(
            !ts.contains("CheckVariants") && !ts.contains("checkModule"),
            "{ts}"
        );
        assert!(
            ts.contains("export declare const loose: looseModule;"),
            "{ts}"
        );
        // The members are documented as the function's.
        assert_eq!(r.undocumented(), ["check.todo"]);
        let described = super::super::description::SetDescription::of(&r).unwrap();
        let exports: Vec<_> = described
            .exports
            .iter()
            .map(|e| (e.name.as_str(), e.kind))
            .collect();
        assert_eq!(
            exports,
            [
                ("check", super::super::description::ExportKind::Function),
                ("loose", super::super::description::ExportKind::Module)
            ]
        );
    }

    mod clash {
        /// Another class named `Lonely`.
        #[crate::element::class]
        pub(super) struct Lonely;

        #[crate::element::class]
        impl Lonely {
            pub(super) fn new() -> Self {
                Lonely
            }
        }
    }

    #[test]
    fn a_clash_through_a_signature_names_both_types() {
        let mut r = Registry::ui_set("test/maker");
        r.class::<clash::Lonely>();
        // `Maker.make` names the other `Lonely`.
        let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            r.module::<Maker>();
        }))
        .unwrap_err();
        let message = failed.downcast_ref::<String>().unwrap();
        assert!(
            message.contains("`nsh_core::element::component::tests::clash::Lonely`")
                && message.contains("`nsh_core::element::component::tests::Lonely`"),
            "{message}"
        );
    }

    #[test]
    fn components_are_named_after_their_types() {
        let mut registry = Registry::ui_set("test/ui");
        registry.register::<Stepper>();
        let specs = registry.specs();
        assert_eq!(
            specs[0].name,
            "nsh_core::element::component::tests::Stepper"
        );
        assert_eq!(specs[0].export, "Stepper");
        assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
        assert_eq!(export_name("Bare"), "Bare");
    }

    mod other {
        use crate::prelude::*;

        /// Another component exported as `Stepper`.
        #[derive(Default)]
        pub(super) struct Stepper;

        impl Component for Stepper {
            type Props = ();
            type Event = NoEvent;

            fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
                view()
            }
        }
    }

    #[test]
    #[should_panic(
        expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
    )]
    fn two_components_of_one_set_cannot_share_an_export() {
        Registry::ui_set("test/ui")
            .register::<Stepper>()
            .register::<other::Stepper>();
    }

    #[test]
    #[should_panic(
        expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
    )]
    fn a_component_is_registered_once() {
        Registry::new().register::<Stepper>().register::<Stepper>();
    }

    /// A set's submodules come with it, under paths of its specifier, and
    /// their components join the core's.
    #[test]
    fn a_sets_submodules_come_with_it() {
        let mut sub = Registry::ui_set("test/set/sub");
        sub.register::<Stepper>();
        let mut set = Registry::ui_set("test/set");
        set.submodule(sub);
        let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
        assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
        assert_eq!(Registry::merged(&[set]).specs().len(), 1);
        // Only a path under the set's own specifier.
        let elsewhere = std::panic::catch_unwind(|| {
            Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
        });
        assert!(elsewhere.is_err());
    }

    #[test]
    fn sets_may_share_exports_but_not_components() {
        let mut a = Registry::ui_set("test/a");
        a.register::<Stepper>();
        let mut b = Registry::ui_set("test/b");
        b.register::<other::Stepper>();
        let merged = Registry::merged(&[a.clone(), b]);
        assert_eq!(merged.specs().len(), 2);
        let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            Registry::merged(&[a.clone(), a])
        }));
        let message = *twice.unwrap_err().downcast::<String>().unwrap();
        assert_eq!(
            message,
            "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
        );
    }

    struct NoFake;

    impl crate::fake::Fake for NoFake {
        fn install(&self) {}

        fn call(&self, _: &str, _: &[crate::JsonValue]) -> Result<crate::JsonValue, String> {
            Ok(crate::JsonValue::Null)
        }
    }

    /// A test calls a fake by its name alone: two sets cannot give one name.
    #[test]
    fn fake_names_are_unique_across_sets() {
        let mut a = Registry::ui_set("test/a");
        a.fake("test/mic", Arc::new(NoFake));
        let mut b = Registry::ui_set("test/b");
        b.fake("test/camera", Arc::new(NoFake));
        let names: Vec<_> = Registry::merged(&[a.clone(), b])
            .fakes()
            .into_iter()
            .map(|(name, _)| name)
            .collect();
        assert_eq!(names, ["test/mic", "test/camera"]);
        let mut c = Registry::ui_set("test/c");
        c.fake("test/mic", Arc::new(NoFake));
        let twice =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Registry::merged(&[a, c])));
        let message = *twice.unwrap_err().downcast::<String>().unwrap();
        assert_eq!(message, "two fakes are named `test/mic`, by two UI sets");
    }
}

#[cfg(test)]
mod root_tests {
    use super::Root;
    use crate::{access::Capabilities, prelude::*};

    #[component]
    fn Empty() -> impl IntoElement {
        view()
    }

    #[test]
    fn a_root_reads_its_declared_capabilities_as_packages_are_read() {
        assert_eq!(Root::of::<Empty>().capabilities_ref(), None);
        // What this runtime does not know is not granted.
        let root = Root::of::<Empty>().capabilities_json(r#"{"clipboard":true,"bluetooth":true}"#);
        let expected = Capabilities {
            clipboard: true,
            ..Capabilities::default()
        };
        assert_eq!(root.capabilities_ref(), Some(&expected));
        // A declaration it cannot read grants nothing.
        let root = Root::of::<Empty>().capabilities_json("not json");
        assert_eq!(root.capabilities_ref(), Some(&Capabilities::default()));
    }
}