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
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
//! Rust components in the core ([`crate::element`]): creating instances,
//! expanding their views into nodes (once: what changes later comes as
//! patches, [`super::views`]), placing JS children and slots, and routing
//! events.
//!
//! A component's host node is the root of its expansion: the root element's
//! props and styles apply to it, its other elements become nodes with odd
//! ids (JS uses even ones) owned by the host. Ops from JS on a host are
//! intercepted ([`Core::apply`]): its `class` goes after the root's styles,
//! its children are placed where the view's `Children` is. Views are made
//! at the start of a commit, so a view starts with all the props set in
//! the JS turn before.

use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};

use rustc_hash::{FxHashMap, FxHashSet};

use super::{Core, Key, Kind, NO_KEY, views::Anchor};
use crate::{
    ApplyError, Command, EdgeInsets, EventKind, EventMask, EventPayload, NodeId, Op, Prop, ROOT_ID,
    Tag, TextEngine,
    element::{
        Action, AnswerSlot, AnyInstance, AnyValue, Attrs, Child, ClipboardRead, ComponentError,
        ComponentSpec, ElKind, ElNode, Environment, Executor, FileAnswer, ImageSize, IntoElement,
        JsEvent, JsResult, ListConfig, Listener, ModuleCx, ParentElement, PlaceFn, Position, Posts,
        Reactive, Registry, Root, RustCall, RustOp, SharedString, StyleRefinement, Task, Tokens,
        caught,
        responder::ResponderEl,
        services::FetchFailure,
        view,
        virtual_list::{self, RowFn, SeparatorFn, VirtualListEl},
    },
    geometry::Points,
    list_diff::ListDiff,
    tailwind::ClassList,
};

/// Lowered styles kept for reuse (many elements have the same styles);
/// cleared when full.
const STYLE_CACHE: usize = 4096;

/// Rounds of polls and updates per run of the tasks, at most.
const MAX_TASK_ROUNDS: u32 = 64;

/// A component made by name whose part is not registered yet.
struct ByName {
    id: std::any::TypeId,
    props: Box<dyn crate::element::builder::AnyProps>,
    /// Where it was made: its context comes from there.
    owner: crate::element::Owner,
}

thread_local! {
    /// What asks the platform for the part that registers a component
    /// made by name ([`set_part_requester`]).
    static PART_REQUESTER: std::cell::Cell<Option<fn(&str)>> = const { std::cell::Cell::new(None) };
}

/// Sets what asks the platform for the code of a component made by name
/// that no UI set registers yet (a web runtime loads the side module of
/// its part, then calls its gate): it gets the component's registered
/// name. Without one, such a component shows nothing until a set
/// registers it.
#[doc(hidden)]
pub fn set_part_requester(request: fn(&str)) {
    PART_REQUESTER.with(|r| r.set(Some(request)));
}

/// What renders on a host node.
enum Inner {
    /// Nothing is registered under the name: renders nothing.
    Missing,
    Component(Box<dyn AnyInstance>),
    /// A list cell of a component's list: the component's row function
    /// wraps the row the app rendered.
    Row {
        place: PlaceFn,
        index: usize,
    },
    /// A cell of a component's own list ([`crate::element::virtual_list`]): it
    /// renders row `index` with the list's row function.
    VirtualRow {
        list: NodeId,
        index: usize,
    },
}

/// A list's row count and keys.
type Rows = (u32, Option<Rc<[u64]>>);

/// The parts of a view's list cells that show rows: the index each one's
/// content reads, and the content's owner.
type CellRows = Rc<RefCell<CellRowMap>>;

/// The index and owner of each part of a list's cells showing a row.
type CellRowMap = FxHashMap<NodeId, (crate::element::Signal<usize>, crate::element::Owner)>;

/// A component's own list.
struct VirtualListState {
    /// The component whose view it is in (its rows' handlers are its).
    owner: NodeId,
    /// The owner of the run that made the list, if any: its rows are made
    /// under it and disposed with it. Shared with the cleanup each run
    /// registers, which disposes the rows only while the list is still
    /// that run's.
    scope: Rc<std::cell::Cell<Option<crate::element::Owner>>>,
    row: RowFn,
    count: u32,
    keys: Option<Rc<[u64]>>,
    separator: Option<SeparatorFn>,
    /// The cells, by recycling slot.
    cells: Vec<NodeId>,
    /// In a view: the live parts of its cells (cells and contents) with the
    /// index their content reads and its owner, for its rows' binding.
    rows: CellRows,
    /// The memo of a bound count or keys, which moves the cells' indices
    /// as the rows change: their positions run it before they are read.
    moves: Option<crate::element::reactive::Node>,
    /// The rows of another component's `Items` prop
    /// ([`crate::element::ComponentElement::items`]): each cell is that
    /// component's wrapper (`place`, its row function: an [`Inner::Row`])
    /// around a node rendering the row (an [`Inner::VirtualRow`], in
    /// `contents` by slot), so each part's handlers run with its own
    /// component.
    items: bool,
    place: Option<PlaceFn>,
    contents: Vec<NodeId>,
    /// Viewable rows: how long they must stay, the range reported last and
    /// the latest, and the report waiting for the time to pass.
    min_view: Option<std::time::Duration>,
    reported: Option<(u32, u32)>,
    latest: Option<(u32, u32)>,
    report: Option<Task<()>>,
}

/// Where a host's JS children are.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Placement {
    /// Out of the tree (the view has no place for them).
    None,
    /// In this node, before what the view puts after its `Children` (their
    /// anchor: a node, or a region, whose nodes may come later).
    At(NodeId, Anchor),
    /// Each in its own wrapper ([`ParentElement::children_each`]): placed
    /// by the view's region of wrappers.
    Each,
    /// Passed on as the children of the nested component hosted by this
    /// node (`<Inset>{children}</Inset>`), before the content after them
    /// (their anchor, as [`Self::At`]'s): its view places them.
    Nested(NodeId, Anchor),
}

/// A view's handlers of native events, by node, each node's in the order
/// its element was given them. A view can have thousands of nodes with
/// handlers (a rich editor's blocks, each with its layout listener), and
/// an event, a node made again and a check for a node's listener each
/// look at that node's handlers only: a list of the whole view would be
/// scanned for each, so mounting such a view would grow with its square.
#[derive(Default)]
pub(super) struct Handlers {
    by_node: FxHashMap<NodeId, Vec<(EventKind, Listener<EventPayload>)>>,
}

impl Handlers {
    /// Node `node`'s handlers, in order.
    pub(super) fn of(&self, node: NodeId) -> &[(EventKind, Listener<EventPayload>)] {
        self.by_node.get(&node).map_or(&[], Vec::as_slice)
    }

    /// Adds `listener` of `kind` to node `node`'s, after the ones it has.
    pub(super) fn push(&mut self, node: NodeId, kind: EventKind, listener: Listener<EventPayload>) {
        self.by_node.entry(node).or_default().push((kind, listener));
    }

    /// Drops node `node`'s handlers.
    pub(super) fn remove(&mut self, node: NodeId) {
        self.by_node.remove(&node);
    }

    /// Keeps the handlers of the nodes `keep` keeps.
    pub(super) fn retain_nodes(&mut self, mut keep: impl FnMut(&NodeId) -> bool) {
        self.by_node.retain(|node, _| keep(node));
    }

    /// Moves node `old`'s handlers to node `new` (a slot's target moving to
    /// another node), after the ones `new` has.
    pub(super) fn rename(&mut self, old: NodeId, new: NodeId) {
        if old == new {
            return;
        }
        if let Some(moved) = self.by_node.remove(&old) {
            self.by_node.entry(new).or_default().extend(moved);
        }
    }

    pub(super) fn clear(&mut self) {
        self.by_node.clear();
    }

    /// How many handlers there are, on all nodes.
    #[cfg(test)]
    pub(super) fn len(&self) -> usize {
        self.by_node.values().map(Vec::len).sum()
    }
}

/// A component instance on its host node.
pub(super) struct Instance {
    inner: Inner,
    spec: Option<Arc<ComponentSpec>>,
    /// The app's `class` and `classList` on the host.
    pub(super) class: Box<str>,
    pub(super) class_list: Vec<Box<str>>,
    /// The app's classes, or the styles the view this one is in gives it:
    /// applied after the root's own.
    pub(super) user: Option<std::rc::Rc<ClassList>>,
    /// Events JS listens to on the host.
    js_events: EventMask,
    /// The listeners the view this one is in gives its element
    /// (`.on_mouse_enter(..)` on a nested component's element), run by
    /// that view's component after the root's own, as JS's on a host are.
    given_handlers: Vec<(EventKind, Listener<EventPayload>)>,
    /// The events of `given_handlers`.
    given_events: EventMask,
    /// The view, expanded (its root is the host); a list cell's row as
    /// built last.
    root: Option<Expanded>,
    /// The host's JS children, in order.
    pub(super) js_children: Vec<NodeId>,
    /// Those of `js_children` that are text (a string, a `Text`), which
    /// `children_each` tells its wrappers ([`Child::is_text`]).
    js_texts: FxHashSet<NodeId>,
    pub(super) children_at: Placement,
    /// Lazy children (`#[prop(lazy)]`): whether JS was told to make them.
    children_wanted: bool,
    /// The glue's node of each slot the app passes.
    slots: Vec<(&'static str, NodeId)>,
    /// The view's handlers of native events, by node.
    pub(super) handlers: Handlers,
    /// The events of nested components, by their host (a handful: a list
    /// beats a map).
    pub(super) event_handlers: Vec<(NodeId, Listener<dyn Any>)>,
    /// The view's parts in the touch responder, by node.
    pub(super) responders: Vec<(NodeId, Rc<ResponderEl>)>,
    /// The app's `style` on the host, applied after the root's own inline
    /// style and animated values.
    pub(super) app_style: Option<crate::StylePatch>,
    dirty: bool,
    /// Its view is made again, in place of the one it showed (a component
    /// made by name, made when its part is registered).
    remake: bool,
    /// The nodes of its view with bindings: what was applied last. Boxed:
    /// a record is large, and a map's free slots are as large as its
    /// entries.
    pub(super) bound: FxHashMap<NodeId, Box<super::views::BoundNode>>,
    /// In a view placing its JS children one by one: them, each with
    /// whether it is text, as a signal.
    pub(super) js_kids: Option<crate::element::Signal<Vec<(NodeId, bool)>>>,
    /// A cell of a view's list: the owner of the row it shows.
    cell_owner: Option<crate::element::Owner>,
    /// ... and the index its content reads (its [`Position`]): a cell
    /// that shows another row sets it instead of being built again.
    row_index: Option<crate::element::Signal<usize>>,
    /// Lazy children a view passes: whether it places them, which what
    /// passes them reads.
    lazy_wanted: Option<crate::element::Signal<bool>>,
    /// In a view: the owner where it places its JS children (a region's),
    /// which the components JS made among them are under.
    children_owner: Option<crate::element::Owner>,
    /// It joined a host as its children or a slot's fill (content a view
    /// passed a nested component, `tabs().child(tab())`,
    /// `sub_menu().trigger(label())`, or inside plain views of that
    /// content): its view waits, as one JS made does, to be in the tree
    /// under where that host's view places it, so it reads the context
    /// there.
    joined: bool,
    /// The component its view's root is, made on this host (its alias,
    /// [`Core::alias`]): its view makes the host's node.
    rooted: Option<NodeId>,
    /// On such a component: the host (or alias) whose view's root it is.
    pub(super) above: Option<NodeId>,
    /// What the view this one is in fills its slots with ([`Fill`]).
    pub(super) fills: Vec<Fill>,
    /// What the view this one is in gives its element besides styles (its
    /// inline style, animated values, insets): they apply to its root,
    /// after the root's own, as the styles do.
    pub(super) given: Option<Box<Attrs>>,
    /// `given` changed since its root last took it.
    given_changed: bool,
    /// The insets its root's node has (its own, or given it).
    pub(super) root_insets_applied: (Option<crate::EdgeInsets>, Option<crate::EdgeInsets>),
    /// The host attributes its root's node was given over its own
    /// ([`RootContext::host`]).
    pub(super) root_host_applied: Vec<Prop>,
    /// The host attributes JS sets on its host ([`js_host_attribute`]):
    /// its root's node takes them over its own and over what views give
    /// it, as the outermost.
    pub(super) js_host: Vec<Prop>,
}

/// Whether `prop`, set by JS on a component's host, is a host attribute its
/// root's node takes over its own ([`RootContext::host`]): its test id,
/// tooltip, focus stop and what assistive technologies read of it but its
/// role and state, which say what the component is and stay its root's.
pub(super) fn js_host_attribute(prop: &Prop) -> bool {
    use crate::AccessibilityProp as A;
    match prop {
        Prop::TestId(_) | Prop::Tooltip(_) | Prop::Focusable(_) => true,
        Prop::Accessibility(a) => !matches!(a, A::Role(_) | A::State(_) | A::Orientation(_)),
        _ => false,
    }
}

/// Adds the host attributes of a nested component's root that `given` (a
/// component element's attributes) sets to `host`, over the ones of the
/// same kind there: its test id, tooltip, focus stop and the screen
/// readers' label, description, value, actions (added up), active
/// descendant and controlled element ([`crate::element::ComponentElement`]).
/// A `None` among them is none given: the root keeps its own.
pub(super) fn given_host(given: &Attrs, host: &mut Vec<Prop>) {
    use crate::AccessibilityProp as A;
    for prop in &given.props {
        if matches!(
            prop,
            Prop::TestId(Some(_))
                | Prop::Tooltip(_)
                | Prop::Focusable(_)
                | Prop::Accessibility(
                    A::Actions(_) | A::ActiveDescendant(Some(_)) | A::Controls(Some(_))
                )
        ) {
            give_host(host, prop.clone());
        }
    }
    if let Some(label) = &given.label {
        give_host(host, Prop::Accessibility(A::Label(Some(label.to_arc()))));
    }
    if let Some(rare) = &given.rare {
        if let Some(description) = &rare.description {
            give_host(
                host,
                Prop::Accessibility(A::Description(Some(description.to_arc()))),
            );
        }
        if let Some(value) = &rare.value {
            give_host(host, Prop::Accessibility(A::Value(Some(value.clone()))));
        }
    }
}

/// Sets host attribute `prop` among `props`: over the one of its kind, or
/// for accessibility actions after the ones there, replacing those of the
/// same names.
fn give_host(props: &mut Vec<Prop>, prop: Prop) {
    use crate::AccessibilityProp as A;
    let Prop::Accessibility(A::Actions(given)) = prop else {
        return crate::element::host::set_in(props, prop);
    };
    let own = props.iter_mut().find_map(|p| match p {
        Prop::Accessibility(A::Actions(own)) => Some(own),
        _ => None,
    });
    let Some(own) = own else {
        return props.push(Prop::Accessibility(A::Actions(given)));
    };
    for action in given {
        match own.iter_mut().find(|a| a.name == action.name) {
            Some(same) => *same = action,
            None => own.push(action),
        }
    }
}

/// `attrs` (a root's own) with the host attributes `host` given it
/// ([`given_host`]), as its node has them.
pub(super) fn with_host(mut attrs: Attrs, host: &[Prop]) -> Attrs {
    use crate::AccessibilityProp as A;
    for prop in host {
        match prop {
            Prop::Accessibility(A::Label(label)) => {
                attrs.label = label.clone().map(SharedString::from);
            }
            Prop::Accessibility(A::Description(description)) => {
                attrs.rare_mut().description = description.clone().map(SharedString::from);
            }
            Prop::Accessibility(A::Value(value)) => attrs.rare_mut().value = value.clone(),
            Prop::Accessibility(A::Hint(hint)) => {
                attrs.rare_mut().hint = hint.clone().map(SharedString::from);
            }
            Prop::Accessibility(A::Accessible(accessible)) => {
                attrs.rare_mut().accessible = *accessible;
            }
            prop => give_host(&mut attrs.props, prop.clone()),
        }
    }
    attrs
}

/// What a component's root takes from the components above it on its host
/// and the views that place them ([`Core::root_context`]).
pub(super) struct RootContext {
    /// Their styles, after the root's (the outer last).
    pub(super) user: Option<std::rc::Rc<ClassList>>,
    /// Whether `app` is what goes after the root's inline style (else the
    /// component's own app style is).
    pub(super) combined: bool,
    /// The inline styles and animated values they give it (the inner
    /// first), then the app's style on the top host.
    pub(super) app: Option<crate::StylePatch>,
    /// JS's events on the top host.
    pub(super) js: Option<EventMask>,
    /// The events of the listeners the views above give it (and the
    /// components whose root it is).
    pub(super) given_events: EventMask,
    /// The insets given it (the outer wins).
    inset_padding: Option<crate::EdgeInsets>,
    inset_margin: Option<crate::EdgeInsets>,
    /// The host attributes given it ([`given_host`]: the outer wins, JS's
    /// on the top host the outermost), over the root's own.
    pub(super) host: Vec<Prop>,
    /// Whether any view gives it anything besides styles.
    given: bool,
}

impl RootContext {
    /// `attrs` (a root's) with the insets given it.
    pub(super) fn over(&self, mut attrs: Attrs) -> Attrs {
        if let Some(insets) = self.inset_padding {
            attrs.rare_mut().inset_padding = Some(insets);
        }
        if let Some(insets) = self.inset_margin {
            attrs.rare_mut().inset_margin = Some(insets);
        }
        with_host(attrs, &self.host)
    }
}

/// What a view fills a nested component's slot with (`.fill(name, el)`, a
/// tag's slot method): nodes of that view, which the nested view places as
/// they are where it places the slot (a node of its own around them only
/// where it styles the slot). A slot JS fills has a holder node instead
/// (`Instance::slots`).
pub(super) struct Fill {
    pub(super) name: &'static str,
    /// Its parts in order: nodes, regions whose nodes come and go, and
    /// what fills the placing view's own slots.
    parts: Vec<FillPart>,
    /// The host of the view that fills it.
    from: NodeId,
    /// Where the nested view places them.
    pub(super) at: Placement,
    /// The slot of a component in the nested view whose fill places this
    /// one (`.fill(name, props.slot.place(|s| s))`): its nodes go there.
    forwarded: Option<(NodeId, &'static str)>,
}

/// A part of a [`Fill`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum FillPart {
    Node(NodeId),
    Region(u32),
    /// What fills the placing view's own slot of this name, passed on.
    Filled(&'static str),
}

impl Instance {
    fn new(
        inner: Inner,
        spec: Option<Arc<ComponentSpec>>,
        js_children: Vec<NodeId>,
        app_style: Option<crate::StylePatch>,
    ) -> Self {
        Self {
            inner,
            spec,
            class: "".into(),
            class_list: Vec::new(),
            user: None,
            js_events: EventMask::default(),
            given_handlers: Vec::new(),
            given_events: EventMask::default(),
            root: None,
            js_children,
            js_texts: FxHashSet::default(),
            children_at: Placement::None,
            children_wanted: false,
            slots: Vec::new(),
            handlers: Handlers::default(),
            event_handlers: Vec::new(),
            responders: Vec::new(),
            app_style,
            dirty: false,
            remake: false,
            bound: FxHashMap::default(),
            js_kids: None,
            cell_owner: None,
            row_index: None,
            lazy_wanted: None,
            children_owner: None,
            joined: false,
            rooted: None,
            above: None,
            fills: Vec::new(),
            given: None,
            given_changed: false,
            root_insets_applied: (None, None),
            root_host_applied: Vec::new(),
            js_host: Vec::new(),
        }
    }

    /// Its JS children changed: the view placing them one by one follows.
    fn js_children_changed(&self) {
        if let Some(children) = self.js_kids {
            // A nested component's view goes with the run that made it,
            // which can go in this commit before the region holding the
            // component is reconciled and releases it: a region in the
            // component's content and the list row it is in changed
            // together. Its content still leaves it, but its view, and so
            // what read the signal, is gone.
            children.try_set(self.js_kids());
        }
    }

    /// Its JS children, each with whether it is text.
    fn js_kids(&self) -> Vec<(NodeId, bool)> {
        self.js_children
            .iter()
            .map(|&c| (c, self.js_texts.contains(&c)))
            .collect()
    }

    /// Node `child` left its JS children.
    fn forget_js_child(&mut self, child: NodeId) {
        self.js_children.retain(|&c| c != child);
        self.js_texts.remove(&child);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Part {
    Node,
    /// A slot's node: JS's, never released by the core.
    Slot,
    /// Where the JS children are (no node of its own).
    Children,
    /// A nested component.
    Component(&'static str),
    /// A list of the component's own rows; its cells are the core's.
    VirtualList,
    /// One of the JS children (no node of its own).
    JsChild,
    /// A piece of a text's content: a raw text node.
    Raw,
    /// A region of a view's children (no node of its own:
    /// [`super::views`]).
    Region(u32),
    /// What this view fills a nested component's slot with (no node of
    /// its own: its children are the nodes).
    Fill(&'static str),
    /// Where this view places what fills its slot (no node of its own).
    Filled(&'static str),
    /// The tooltip this view gives a nested component's root (no node of
    /// its own: its child is the element, which that root's node shows).
    Tooltip,
}

/// A node's app classes ([`Components::app_classes`]): its own rules, the
/// classes, and what goes after them.
pub(super) type AppClass = (
    Option<std::rc::Rc<ClassList>>,
    SharedString,
    Option<std::rc::Rc<ClassList>>,
);

/// The node's classes: its styles lowered, and what was merged after them.
pub(super) type Classes = (
    Option<std::rc::Rc<ClassList>>,
    Option<std::rc::Rc<ClassList>>,
);

/// An element of a view, as it was applied.
pub(super) struct Expanded {
    pub(super) id: NodeId,
    pub(super) tag: Tag,
    pub(super) key: Option<SharedString>,
    /// A text's content and its raw text node.
    text: Option<(SharedString, NodeId)>,
    attrs: Attrs,
    style: StyleRefinement,
    classes: Classes,
    events: EventMask,
    /// A list's layout, when this element is a `VirtualList`.
    list: Option<Box<ListConfig>>,
    pub(super) part: Part,
    pub(super) children: Vec<Expanded>,
}

impl Expanded {
    /// A node of JS's in the view (`id` 0: the place of the children).
    pub(super) fn js(id: NodeId, part: Part) -> Self {
        Self {
            id,
            tag: Tag::View,
            key: None,
            text: None,
            attrs: Attrs::default(),
            style: StyleRefinement::default(),
            classes: (None, None),
            events: EventMask::default(),
            list: None,
            part,
            children: Vec::new(),
        }
    }
}

/// A child to match with a parent's old elements
/// ([`Core::match_children`]).
#[allow(
    clippy::large_enum_variant,
    reason = "elements are matched as they come: a box for each would allocate for every child"
)]
pub(super) enum NewChild {
    /// An element, applied under its owner when it has one.
    Made(Option<crate::element::Owner>, ElNode),
    /// The old element of this key stays as it is: of an `Each` row that
    /// was there before.
    Kept(SharedString),
}

/// The keyed old elements of a parent by key ([`Core::match_children`]),
/// indexed the first time one is looked up: a few elements are searched in
/// order, many once, so a long keyed list moved or reversed is matched in
/// linear time. Old elements are only ever taken (`None`) while matching,
/// so the index stays valid.
#[derive(Default)]
pub(super) struct OldKeys {
    /// The first old element of each key.
    first: FxHashMap<SharedString, usize>,
    /// The next old element of the same key after each one (`usize::MAX`
    /// for none).
    next: Vec<usize>,
    indexed: bool,
}

impl OldKeys {
    /// Up to this many old elements are searched rather than indexed.
    const SEARCHED: usize = 16;

    /// The first old element of key `key` left in `old` that is `ok`.
    fn find(
        &mut self,
        old: &[Option<Expanded>],
        key: &SharedString,
        ok: impl Fn(&Expanded) -> bool,
    ) -> Option<usize> {
        let is = |o: &Option<Expanded>| {
            o.as_ref()
                .is_some_and(|o| o.key.as_ref() == Some(key) && ok(o))
        };
        if old.len() <= Self::SEARCHED {
            return old.iter().position(is);
        }
        if !self.indexed {
            self.indexed = true;
            self.next = vec![usize::MAX; old.len()];
            // From the end, so each key's first is the earliest.
            for (at, o) in old.iter().enumerate().rev() {
                if let Some(k) = o.as_ref().and_then(|o| o.key.as_ref())
                    && let Some(next) = self.first.insert(k.clone(), at)
                {
                    self.next[at] = next;
                }
            }
        }
        // Those taken go from the front (duplicate keys taken in order are
        // not walked again).
        let first = self.first.get_mut(key)?;
        while *first != usize::MAX && old[*first].is_none() {
            *first = self.next[*first];
        }
        let mut at = *first;
        while at != usize::MAX {
            if is(&old[at]) {
                return Some(at);
            }
            at = self.next[at];
        }
        None
    }
}

/// Whether a slot's place only places it: no styles, props, listeners or
/// children of its own (what fills it then needs no node around it).
fn is_plain(el: &ElNode) -> bool {
    el.attrs == Attrs::default()
        && el.style.is_empty()
        && !el.is_bound()
        && el.handlers.is_empty()
        && el.responder.is_none()
        && el.children.is_empty()
        && el.text.is_none()
}

/// What a component's task waits for from the animation graph.
enum Awaited {
    /// An animation's end: whether it finished.
    End(AnswerSlot<bool>),
    /// A value read ([`crate::element::AnimatedValue::value`]).
    Value(AnswerSlot<f32>),
}

/// What the platform answered a clipboard read with (the root's
/// `Clipboard` event).
#[derive(Default)]
pub(super) struct ClipboardAnswer {
    /// Whether it holds what was asked.
    pub(super) has: bool,
    /// The text, for a text read.
    pub(super) text: Option<String>,
    /// Whether the person refused a text read (iOS's paste prompt): the
    /// clipboard holds text, but none was read.
    pub(super) denied: bool,
    /// The image, for an image read.
    pub(super) image: Option<crate::element::ClipboardImage>,
    /// The size in encoded bytes of an image over
    /// [`crate::platform::clipboard::MAX_IMAGE_BYTES`], left out of the
    /// answer.
    pub(super) too_large: Option<usize>,
    /// The files' `file:` URLs, for a files read.
    pub(super) files: Vec<String>,
}

impl ClipboardAnswer {
    pub(super) fn from_payload(payload: &EventPayload) -> ClipboardAnswer {
        let mut answer = ClipboardAnswer::default();
        let EventPayload::Map(entries) = payload else {
            return answer;
        };
        let (mut uri, mut width, mut height) = (None, 0.0, 0.0);
        for (k, v) in entries {
            match (*k, v) {
                ("has", crate::PayloadValue::Bool(b)) => answer.has = *b,
                ("text", crate::PayloadValue::Str(t)) => answer.text = Some(t.clone()),
                ("denied", crate::PayloadValue::Bool(b)) => answer.denied = *b,
                ("uri", crate::PayloadValue::Str(u)) => uri = Some(u.clone()),
                ("width", crate::PayloadValue::Number(n)) => width = *n,
                ("height", crate::PayloadValue::Number(n)) => height = *n,
                ("tooLarge", crate::PayloadValue::Number(n)) => {
                    answer.too_large = Some(*n as usize)
                }
                ("files", crate::PayloadValue::Str(f)) => {
                    answer.files = f
                        .lines()
                        .filter(|l| !l.is_empty())
                        .map(str::to_owned)
                        .collect()
                }
                _ => {}
            }
        }
        // Only an image NSH can show, a `data:` URI, and only one the VM
        // can hold (the web's player encodes its own).
        let uri = uri.filter(|u| u.starts_with("data:"));
        let bytes = uri.as_deref().map(crate::platform::clipboard::data_uri_len);
        if let Some(bytes) = bytes.filter(|&b| b > crate::platform::clipboard::MAX_IMAGE_BYTES) {
            answer.too_large = Some(bytes);
        } else {
            answer.image = uri.map(|url| crate::element::ClipboardImage {
                url,
                size: crate::geometry::Size::new(pixels(width), pixels(height)),
            });
        }
        answer
    }
}

/// An HTTP request of a task in flight ([`Core::fetch_event`]).
struct PendingFetch {
    /// What arrived so far.
    response: crate::element::HttpResponse,
    answer: AnswerSlot<Result<crate::element::HttpResponse, FetchFailure>>,
}

/// What notifications wait for ([`crate::notifications`]).
#[derive(Default)]
struct Notifications {
    /// The next request's id.
    next: u32,
    /// Permission requests waiting for the platform's answer.
    permissions: FxHashMap<u32, AnswerSlot<crate::notifications::NotificationPermission>>,
    /// Notifications waiting for the platform's answer.
    shows: FxHashMap<u32, AnswerSlot<bool>>,
    /// The platform was told to report presses.
    listening: bool,
    /// Presses no listener took yet.
    presses: std::collections::VecDeque<String>,
    /// The listener waiting for a press.
    next_press: Option<AnswerSlot<String>>,
}

/// The links that open the app ([`crate::url_scheme`]).
#[derive(Default)]
struct UrlScheme {
    /// The links the app claims: its schemes and web links.
    links: crate::url_scheme::AppLinks,
    /// The links some listener has yet to hear, by number, at most
    /// [`crate::url_scheme::MAX_PENDING`]: those no listener took yet (from
    /// [`Self::unheard`] on), and those a listener missed between two calls.
    recent: std::collections::VecDeque<(u64, String)>,
    /// The number of the next link.
    next_number: u64,
    /// The first link that came while nothing listened and no listener
    /// took yet, which the next new listener gets.
    unheard: u64,
    /// The tasks that listen, each with the number of the next link it is
    /// to hear: a task awaiting links in a loop is not waiting between two
    /// calls, and hears the links that came meanwhile at its next call.
    listeners: Vec<(u64, u64)>,
    /// The calls waiting for a link, with their task: each gets the next
    /// one.
    next: Vec<(Option<u64>, AnswerSlot<String>)>,
    /// The waits for a link of one scheme (lowered), in the order they
    /// came: the first takes the next link of its scheme, which no other
    /// listener gets ([`crate::element::next_url_scheme_open_for`]).
    next_of_scheme: Vec<(String, AnswerSlot<String>)>,
    /// Address moves no listener took yet
    /// ([`crate::url_scheme::AppUrlChange`]), kept once something listened
    /// ([`Self::hears_changes`]), at most [`crate::url_scheme::MAX_PENDING`].
    changes: std::collections::VecDeque<crate::url_scheme::AppUrlChange>,
    /// The listener waiting for an address move.
    next_change: Option<AnswerSlot<crate::url_scheme::AppUrlChange>>,
    /// Something listens to address moves: those before it are stale (the
    /// address has them), those after it wait between its answers.
    hears_changes: bool,
    /// The app's address: the last link taken, the page's on the web, or
    /// what the app set (`UrlScheme.setUrl`, `set_app_url`). The one copy,
    /// which every VM's `System` shares ([`Core::app_url_cell`]).
    address: crate::url_scheme::AppUrlCell,
}

impl UrlScheme {
    /// Hands `url`, a link for the app's listeners, to those waiting, and
    /// keeps it for those that are not (and for the next new listener when
    /// none was waiting).
    fn open(&mut self, url: String, alive: impl Fn(u64) -> bool) {
        let number = self.next_number;
        self.next_number += 1;
        self.listeners.retain(|&(task, _)| alive(task));
        if self.recent.len() == crate::url_scheme::MAX_PENDING
            && let Some((dropped, _)) = self.recent.pop_front()
            && dropped >= self.unheard
        {
            log::warn!(
                "link dropped: {} came while nothing listened",
                crate::url_scheme::MAX_PENDING
            );
            self.unheard = dropped + 1;
        }
        self.recent.push_back((number, url.clone()));
        // A listener whose answer went (its task ended, or it lost a
        // `select!`) leaves the link to the others.
        self.next
            .retain(|(_, answer)| crate::element::task::awaited(answer));
        // Came while something listened: the listeners between two calls
        // hear it at their next, and a listener that starts later does not
        // (only links that came while nothing listened wait for one).
        if !self.next.is_empty() || !self.listeners.is_empty() {
            self.unheard = number + 1;
        }
        if !self.next.is_empty() {
            for (task, answer) in std::mem::take(&mut self.next) {
                if let Some(task) = task {
                    self.heard(task, number);
                }
                answer.borrow_mut().deliver(url.clone());
            }
        }
        self.trim();
    }

    /// Answers a call of `task` (none: outside a task) waiting for a link:
    /// with the first link the task has not heard, a new listener's being
    /// the first no listener took; else with the next one to come.
    fn listen(
        &mut self,
        task: Option<u64>,
        answer: AnswerSlot<String>,
        alive: impl Fn(u64) -> bool,
    ) {
        self.listeners.retain(|&(task, _)| alive(task));
        let known = task.and_then(|task| {
            self.listeners
                .iter()
                .find(|&&(listener, _)| listener == task)
                .map(|&(_, next)| next)
        });
        let from = known.unwrap_or(self.unheard);
        if let Some((number, url)) = self.recent.iter().find(|(n, _)| *n >= from).cloned() {
            self.unheard = self.unheard.max(number + 1);
            if let Some(task) = task {
                self.heard(task, number);
            }
            answer.borrow_mut().deliver(url);
        } else {
            if let Some(task) = task
                && known.is_none()
            {
                self.listeners.push((task, self.next_number));
            }
            self.next
                .retain(|(_, answer)| crate::element::task::awaited(answer));
            self.next.push((task, answer));
        }
        self.trim();
    }

    /// `task` heard link `number`.
    fn heard(&mut self, task: u64, number: u64) {
        match self
            .listeners
            .iter_mut()
            .find(|(listener, _)| *listener == task)
        {
            Some((_, next)) => *next = number + 1,
            None => self.listeners.push((task, number + 1)),
        }
    }

    /// Lets go of the links every listener heard.
    fn trim(&mut self) {
        let keep = self
            .listeners
            .iter()
            .map(|&(_, next)| next)
            .fold(self.unheard, u64::min);
        while self
            .recent
            .front()
            .is_some_and(|&(number, _)| number < keep)
        {
            self.recent.pop_front();
        }
    }
}

/// Files the system opened the app with ([`crate::file_type`]).
#[derive(Default)]
struct OpenFiles {
    /// Files no listener took yet, at most [`crate::file_type::MAX_PENDING`].
    pending: std::collections::VecDeque<std::path::PathBuf>,
    /// The listener waiting for files.
    next: Option<AnswerSlot<Vec<std::path::PathBuf>>>,
}

/// Later launches of the app ([`crate::single_instance`]).
#[derive(Default)]
struct SecondInstances {
    /// Launches no listener took yet, at most
    /// [`crate::single_instance::MAX_PENDING`].
    pending: std::collections::VecDeque<crate::single_instance::SecondInstance>,
    /// The listener waiting for a launch.
    next: Option<AnswerSlot<crate::single_instance::SecondInstance>>,
}

/// The core's component state.
pub(super) struct Components {
    pub(super) web_evaluations: super::web_evaluation::Evaluations,
    pub(super) canvas_renders: super::canvas_render::Renders,
    registry: Registry,
    /// The specs of the components made by type (not by name from the
    /// registry), one per type.
    specs: FxHashMap<&'static str, Arc<ComponentSpec>>,
    /// The design tokens drawn with.
    pub(super) tokens: Arc<Tokens>,
    /// The app's tokens (a UI set's defaults, `nsh.json`'s theme, a Rust
    /// app's root): drawn with while the embedding app sets none
    /// ([`Core::set_host_tokens`]).
    app_tokens: Arc<Tokens>,
    /// The embedding app's tokens: win over [`Self::app_tokens`].
    host_tokens: Option<Arc<Tokens>>,
    /// Boxed: making a view (or applying its patches) takes its instance
    /// out of the map and back.
    pub(super) instances: FxHashMap<NodeId, Box<Instance>>,
    /// Hosts of components made by name whose part is not registered yet
    /// ([`crate::element::ComponentElement::by_name`]): made when it is.
    by_name: FxHashMap<NodeId, ByName>,
    /// Expanded node -> the host of the component whose view made it.
    pub(super) owners: FxHashMap<NodeId, NodeId>,
    /// Changes when reconciliation releases an expanded element or raw
    /// node. A region that only populates or retains nodes needs no sweep
    /// of its host's listeners and bindings.
    pub(super) release_generation: u64,
    /// Region hosts to clean before the next binding/event round. Several
    /// regions of one view can release nodes in the same patch batch.
    pub(super) released_hosts: FxHashSet<NodeId>,
    #[cfg(test)]
    pub(super) cleanup_work: super::views::CleanupWork,
    /// The handlers dispatches looked at to find a node's (for a probe that
    /// the count stays with the node's, whatever the view's size).
    #[cfg(test)]
    pub(super) handler_visits: std::cell::Cell<usize>,
    /// Siblings and overlays looked at to place views among them
    /// ([`Core::preceding`], `native_before_at`, `first_overlay_in`).
    #[cfg(test)]
    pub(super) placing_work: std::cell::Cell<usize>,
    /// Siblings looked at to find children's positions among them
    /// ([`Core::positions_changed`], `position_bits`).
    #[cfg(test)]
    pub(super) position_work: std::cell::Cell<usize>,
    /// Watched nodes looked at to tell which start and stop listening to
    /// touches or the pointer for the overlays (`Core::rewatch`).
    #[cfg(test)]
    pub(super) watch_work: std::cell::Cell<usize>,
    /// Mount items looked at when views take the kind of their
    /// component's root ([`Core::retag`]).
    #[cfg(test)]
    pub(super) retag_work: std::cell::Cell<usize>,
    /// Rounds of renders in which views took the kind of their
    /// component's root ([`Core::end_retags`]).
    #[cfg(test)]
    pub(super) retag_rounds: std::cell::Cell<usize>,
    /// Slot nodes (`componentSlot`) -> their slot's name.
    slot_names: FxHashMap<NodeId, Arc<str>>,
    /// Slot nodes in a host -> the host.
    pub(super) slot_hosts: FxHashMap<NodeId, NodeId>,
    /// Slot nodes whose element gives them more than styles -> where that
    /// goes ([`super::slots`]).
    pub(super) slot_targets: FxHashMap<NodeId, super::slots::SlotTarget>,
    /// The app's elements a slot's props go to -> their slot node.
    pub(super) adopted: FxHashMap<NodeId, NodeId>,
    /// The nodes views wrap a slot's fill in (the place gives it more than
    /// itself): slot nodes as JS's are, their props going to the fill's one
    /// element ([`Core::reconcile_wrapper`]).
    pub(super) fill_holders: FxHashSet<NodeId>,
    styles: FxHashMap<StyleRefinement, std::rc::Rc<ClassList>>,
    /// The styles a component on another's host gets from each above it,
    /// merged (by the lists', which the entry keeps).
    pub(super) merges: FxHashMap<(usize, usize), [std::rc::Rc<ClassList>; 3]>,
    /// While a view's slot content is matched: the nested component's host
    /// and the slot (its regions are the slot's).
    pub(super) filling: Option<(NodeId, &'static str)>,
    /// The parents nodes moved out of and into since the order watches
    /// last looked (`core/watch.rs`), as an app's keyed reorder moves its
    /// rows: only a watch whose elements share one of them (or an ancestor
    /// of one) looks again.
    pub(super) moved: Vec<NodeId>,
    /// The lists components place (the glue's, of `Items` props) -> the
    /// row function the component's view gave last, and the number of rows
    /// its wrappers last saw.
    lists: FxHashMap<NodeId, (PlaceFn, u32)>,
    pub(super) environment: Environment,
    /// Runs the components' async tasks and timers.
    pub(super) executor: Rc<Executor>,
    /// Windows JS opened (`<Window>`) -> the owner and ref the Rust
    /// components inside them render under ([`Core::js_window_owner`]).
    js_windows: FxHashMap<NodeId, (crate::element::Owner, crate::element::desktop::WindowRef)>,
    /// What the platform last reported of the windows of the app's own:
    /// their state and title bar area, for the refs made after it.
    window_reports: FxHashMap<
        NodeId,
        (
            Option<crate::desktop::WindowState>,
            crate::geometry::Edges<Points>,
        ),
    >,
    /// The status bar's settings, shared by components, modules and tasks.
    pub(super) status_bars: crate::element::status_bar::StatusBars,
    /// Dialogs components show, by id: their answers.
    dialogs: FxHashMap<u32, AnswerSlot<crate::element::DialogReply>>,
    next_dialog: u32,
    /// Image sizes asked for (`Image.getSize`), by request id: their answers.
    image_infos: FxHashMap<u32, AnswerSlot<Result<ImageSize, String>>>,
    next_image_info: u32,
    /// Clipboard reads (`Clipboard.readText` / `hasText`), by request
    /// id: their answers.
    clipboard_reads: FxHashMap<u32, ClipboardRead>,
    next_clipboard_read: u32,
    /// Picks waiting for the platform's picker, by request.
    #[allow(clippy::type_complexity)]
    picks: FxHashMap<
        u32,
        (
            crate::picker::Pick,
            AnswerSlot<Vec<crate::picker::PickedFile>>,
        ),
    >,
    next_pick: u32,
    /// The sounds and players open, by id: where their events go.
    audio: FxHashMap<u32, crate::audio::AudioSink>,
    /// What notifications wait for ([`crate::notifications`]).
    notifications: Notifications,
    /// The links that open the app ([`crate::url_scheme`]).
    url_schemes: UrlScheme,
    second_instances: SecondInstances,
    open_files: OpenFiles,
    /// Calls of the embedding app's functions (`nsh/host`), by request id:
    /// their answers.
    host_calls:
        FxHashMap<u64, AnswerSlot<Result<crate::JsonValue, crate::host_channel::HostError>>>,
    next_host_call: u64,
    /// The calls and posts not handed to the engine yet
    /// ([`Core::take_host_requests`]).
    host_requests: Vec<crate::host_channel::HostRequest>,
    /// The host's events no Rust listener heard, until one of their names
    /// is added ([`Core::release_host_events`]).
    host_inbox: crate::host_channel::HostInbox,
    /// URLs being opened (`openUrl`), by request id: their answers.
    url_opens: FxHashMap<u32, AnswerSlot<bool>>,
    /// The clipboard writes sent to the platform waiting for its result,
    /// in the order sent ([`crate::EventKind::ClipboardWrite`]).
    pub(super) clipboard_writes:
        std::collections::VecDeque<AnswerSlot<crate::element::ClipboardWrite>>,
    /// Those not handed to the engine yet ([`Core::take_url_opens`]).
    url_requests: Vec<(u32, String)>,
    /// The language the app asked to show in (`Some(None)`: the user's
    /// again), for the engine ([`Core::take_locale_request`]).
    pub(super) locale_request: Option<Option<crate::platform::Locale>>,
    /// The language of the app's text last sent to an iOS or Android
    /// platform ([`Command::TextLocale`]).
    text_locale: Option<crate::platform::Locale>,
    /// The app listened to quit requests at the last commit: the platform
    /// was told its quit requests go to the app
    /// ([`crate::desktop::DesktopCommand::SetQuitOnRequest`]).
    asks_quit: bool,
    /// Functions for the platform's main thread, for the engine
    /// ([`Core::take_main_thread_tasks`]).
    main_thread: Vec<crate::main_thread::MainThreadTask>,
    next_url_open: u32,
    /// The app's settings pages being opened (`AppSettings.open`), by
    /// request id: their answers.
    app_settings_opens: FxHashMap<u32, AnswerSlot<Result<bool, crate::mobile::AppSettingsError>>>,
    next_app_settings_open: u32,
    /// Colors being picked on the screen, by request id: their answers.
    screen_colors: FxHashMap<u32, AnswerSlot<Option<crate::Hsla>>>,
    next_screen_color: u32,
    /// Requests on local paths (`pick_paths`, `open_path`, ...), by
    /// request id: their answers.
    file_requests: FxHashMap<u32, FileAnswer>,
    next_file_request: u32,
    /// HTTP requests of tasks (`ui::fetch`), by request id: what arrived
    /// so far and the answer.
    fetches: FxHashMap<u32, PendingFetch>,
    /// Requests not handed to the engine's network stack yet.
    fetch_requests: Vec<(u32, crate::platform::HttpRequest)>,
    next_fetch: u32,
    /// The ends of the animations components started and the values they
    /// read, by id.
    animations: FxHashMap<crate::animation::AnimationId, Awaited>,
    /// Elements to measure once this commit is laid out
    /// ([`crate::element::ElementRef::measure`]).
    pub(super) measures: Vec<(NodeId, AnswerSlot<Option<crate::Measurement>>)>,
    /// Lists to tell where their viewports start once this commit is laid
    /// out ([`crate::element::ElementRef::measure_scroll_position`]).
    pub(super) scroll_positions: Vec<(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>)>,
    /// Elements whose transitions' time to tell once this commit is
    /// styled ([`crate::element::ElementRef::transition_time`]).
    pub(super) transition_times: Vec<(NodeId, AnswerSlot<std::time::Duration>)>,
    /// Elements whose text to tell once this commit is applied
    /// ([`crate::element::ElementRef::text_content`]).
    pub(super) text_contents: Vec<(NodeId, AnswerSlot<String>)>,
    /// Presses to pass on inside elements once this commit is laid out
    /// ([`crate::element::ElementRef::press_at`]).
    pub(super) presses: Vec<(NodeId, crate::PressEvent, AnswerSlot<bool>)>,
    /// Pointers to pass on inside elements as the next commit starts
    /// ([`crate::element::ElementRef::hover_at`]); `None`: it left.
    pub(super) hovers: Vec<(NodeId, Option<crate::MouseEvent>)>,
    /// The web views' downloads ([`crate::webview::downloads`]): the
    /// sessions, their files and the platform's replies.
    pub(super) downloads: crate::webview::downloads::Downloads,
    /// The next id of a platform command answering a web view request
    /// (shared by the downloads' commands).
    next_webview_request: u64,
    /// The components' own lists, by node.
    virtual_lists: FxHashMap<NodeId, VirtualListState>,
    /// Views JS made, waiting to be in the tree to make their view.
    waiting: Vec<NodeId>,
    /// Calls of components' methods made before their view was (a ref is
    /// given as its component is made, and the view registers what the
    /// methods act on): host, promise, call; run once the view is made.
    parked_methods: Vec<(NodeId, u32, crate::element::MethodCall)>,
    /// The row counts the cells of views' lists read (their positions), by
    /// list, each under a root of its own that goes with the list.
    list_counts: FxHashMap<NodeId, (crate::element::Owner, crate::element::Signal<usize>)>,
    /// The layouts of views' lists with bound parts, as applied last.
    pub(super) list_layouts: FxHashMap<NodeId, ListConfig>,
    /// The insets screens and modals reported (`onInsets`).
    insets: FxHashMap<NodeId, EdgeInsets>,
    /// JS listens to the back button (`BackHandler`) on the root.
    js_back: bool,
    /// JS listens to the back gesture's steps (`BackHandler.on("progress",
    /// ..)`) on the root.
    js_back_progress: bool,
    /// The app's listeners follow the back gesture under way: decided as it
    /// starts, so a gesture an overlay takes stays the overlay's to its end.
    back_gesture: bool,
    /// JS's keyboard shortcuts (`nsh/keymap`: the root's `Prop::Keymap`),
    /// which the root's table joins with the views'.
    js_keymap: Arc<crate::keymap::Keymap>,
    /// JS listens to the root's `KeyCommand`.
    js_keys: bool,
    /// The touches the components hear and their responder.
    pub(super) touch: super::touch::TouchState,
    /// Display frames and the layout direction.
    pub(super) services: super::services::Services,
    next_id: NodeId,
    dirty: Vec<NodeId>,
    /// A reused buffer.
    props: Vec<Prop>,
    /// The reactive graph of the components that run once.
    pub(super) runtime: crate::element::Runtime,
    /// What their bindings queued.
    pub(super) patches: super::views::Patches,
    /// Their views' regions, by id.
    pub(super) regions: FxHashMap<u32, super::views::RegionState>,
    pub(super) next_region: u32,
    /// The JS calls Rust posts (the engine's queue, shared with the
    /// script): a call posted during a synchronous call from JS waits for
    /// its op ([`RustCall::Post`]).
    posts: Posts,
    /// What the app's JS functions render for the views
    /// ([`crate::element::Renderer`]).
    pub(super) renders: super::renders::Renders,
    /// Nodes of views with the app's classes (`Element::app_class`): their
    /// own rules, the classes and what goes after them, resolved again
    /// when the tokens change.
    pub(super) app_classes: FxHashMap<NodeId, AppClass>,
}

impl Default for Components {
    fn default() -> Self {
        Self {
            registry: Registry::default(),
            specs: FxHashMap::default(),
            tokens: Arc::new(Tokens::default()),
            app_tokens: Arc::new(Tokens::default()),
            host_tokens: None,
            instances: FxHashMap::default(),
            by_name: FxHashMap::default(),
            owners: FxHashMap::default(),
            release_generation: 0,
            released_hosts: FxHashSet::default(),
            #[cfg(test)]
            cleanup_work: Default::default(),
            #[cfg(test)]
            handler_visits: Default::default(),
            #[cfg(test)]
            placing_work: Default::default(),
            #[cfg(test)]
            position_work: Default::default(),
            #[cfg(test)]
            watch_work: Default::default(),
            #[cfg(test)]
            retag_work: Default::default(),
            #[cfg(test)]
            retag_rounds: Default::default(),
            slot_names: FxHashMap::default(),
            slot_hosts: FxHashMap::default(),
            slot_targets: FxHashMap::default(),
            adopted: FxHashMap::default(),
            fill_holders: FxHashSet::default(),
            styles: FxHashMap::default(),
            merges: FxHashMap::default(),
            filling: None,
            moved: Vec::new(),
            lists: FxHashMap::default(),
            environment: Environment::default(),
            executor: Rc::new(Executor::default()),
            js_windows: FxHashMap::default(),
            window_reports: FxHashMap::default(),
            status_bars: Default::default(),
            dialogs: FxHashMap::default(),
            next_dialog: 1,
            image_infos: FxHashMap::default(),
            next_image_info: 1,
            clipboard_reads: FxHashMap::default(),
            url_opens: FxHashMap::default(),
            clipboard_writes: Default::default(),
            url_requests: Vec::new(),
            locale_request: None,
            text_locale: None,
            asks_quit: false,
            main_thread: Vec::new(),
            next_url_open: 0,
            app_settings_opens: FxHashMap::default(),
            next_app_settings_open: 1,
            screen_colors: FxHashMap::default(),
            next_screen_color: 1,
            file_requests: FxHashMap::default(),
            next_file_request: 1,
            next_clipboard_read: 1,
            picks: FxHashMap::default(),
            next_pick: 1,
            audio: FxHashMap::default(),
            notifications: Notifications::default(),
            url_schemes: UrlScheme::default(),
            second_instances: SecondInstances::default(),
            open_files: OpenFiles::default(),
            host_calls: FxHashMap::default(),
            next_host_call: 1,
            host_requests: Vec::new(),
            host_inbox: Default::default(),
            web_evaluations: Default::default(),
            canvas_renders: Default::default(),
            fetches: FxHashMap::default(),
            fetch_requests: Vec::new(),
            next_fetch: 1,
            animations: FxHashMap::default(),
            measures: Vec::new(),
            scroll_positions: Vec::new(),
            transition_times: Vec::new(),
            text_contents: Vec::new(),
            presses: Vec::new(),
            hovers: Vec::new(),
            downloads: crate::webview::downloads::Downloads::default(),
            next_webview_request: 1,
            virtual_lists: FxHashMap::default(),
            list_counts: FxHashMap::default(),
            waiting: Vec::new(),
            parked_methods: Vec::new(),
            list_layouts: FxHashMap::default(),
            insets: FxHashMap::default(),
            js_back: false,
            js_back_progress: false,
            back_gesture: false,
            js_keymap: Arc::new(crate::keymap::Keymap::default()),
            js_keys: false,
            touch: super::touch::TouchState::default(),
            services: Default::default(),
            // Odd: JS allocates the even ids (1 is the root).
            next_id: 3,
            dirty: Vec::new(),
            props: Vec::new(),
            runtime: crate::element::Runtime::default(),
            patches: super::views::Patches::default(),
            regions: FxHashMap::default(),
            next_region: 1,
            posts: Posts::default(),
            renders: Default::default(),
            app_classes: FxHashMap::default(),
        }
    }
}

impl Components {
    /// Whether `list` is one of the components' own lists (bound in the
    /// core).
    pub(super) fn is_virtual_list(&self, list: NodeId) -> bool {
        self.virtual_lists.contains_key(&list)
    }

    pub(super) fn for_viewport(viewport: crate::Size<crate::Points>) -> Self {
        let mut components = Self::default();
        components.environment.window = viewport;
        // What components that run once read of the core.
        components.runtime.set_services(components.executor.clone());
        components
            .runtime
            .set_app_url(components.url_schemes.address.clone());
        components.runtime.set_environment(components.environment);
        components.runtime.set_tokens(components.tokens.clone());
        components
    }

    pub(super) fn alloc(&mut self) -> NodeId {
        let id = self.next_id;
        self.next_id += 2;
        id
    }

    pub(super) fn mark(&mut self, host: NodeId) {
        if let Some(inst) = self.instances.get_mut(&host)
            && !inst.dirty
        {
            inst.dirty = true;
            self.dirty.push(host);
        }
    }

    /// `style` as rules, shared between the elements that have it (its
    /// static declarations: bound parts are applied by bindings).
    pub(super) fn lowered(&mut self, style: &StyleRefinement) -> std::rc::Rc<ClassList> {
        if style.is_bound() {
            return self.lowered(&style.static_part());
        }
        if let Some(list) = self.styles.get(style) {
            return list.clone();
        }
        if self.styles.len() >= STYLE_CACHE {
            self.styles.clear();
        }
        let list = std::rc::Rc::new(style.lower());
        self.styles.insert(style.clone(), list.clone());
        list
    }
}

/// The inline style of `id`: the declarations of its `Style` prop, then
/// the animated values bound to it, then (on a host) the app's style.
fn inline_style(
    id: NodeId,
    inline: Option<&crate::StylePatch>,
    animated: &[(crate::StyleDecl, crate::element::LiveNode)],
    app: Option<&crate::StylePatch>,
) -> Op {
    let mut style = Box::<crate::Style>::default();
    let mut patch = crate::StylePatch::default();
    let inline = inline.map(|p| p.decls()).unwrap_or_default();
    let app = app.map(|p| p.decls()).unwrap_or_default();
    for decl in inline
        .iter()
        .chain(animated.iter().map(|(d, _)| d))
        .chain(app)
    {
        let _ = patch.push(&mut style, decl.clone());
    }
    Op::SetStyle { id, style, patch }
}

fn same(a: &Option<std::rc::Rc<ClassList>>, b: &Option<std::rc::Rc<ClassList>>) -> bool {
    match (a, b) {
        (Some(a), Some(b)) => std::rc::Rc::ptr_eq(a, b),
        (None, None) => true,
        _ => false,
    }
}

impl Components {
    /// The GPU renderer the sets registered as `name`.
    pub(super) fn gpu_renderer(&self, name: &str) -> Option<crate::gpu::GpuSource> {
        self.registry.registered_gpu_renderer(name).cloned()
    }
}

impl<M: TextEngine> Core<M> {
    /// The components this core can render (from `nsh-base` and the
    /// like), and the design tokens their sets bring
    /// ([`Registry::tokens_from`]); set before the first op. Runs the
    /// sets' setup functions ([`Registry::setup`]).
    pub fn set_components(&mut self, registry: Registry) {
        if let Some(Ok((tokens, _))) = registry.tokens(None) {
            self.set_tokens(tokens);
        }
        {
            let _entered = self.components.runtime.enter();
            registry.run_setups();
        }
        self.components.registry = registry;
    }

    /// Replaces the components of a running core with `registry`, a
    /// superset of what it had (a UI set registered after the app started:
    /// a web runtime's late `nsh_part_*`). What is mounted from then on may
    /// use the new components; the tokens stay the app's, and only the
    /// setup functions the old sets did not bring run.
    pub fn extend_components(&mut self, registry: Registry) {
        {
            let _entered = self.components.runtime.enter();
            registry.run_setups_not_in(&self.components.registry);
        }
        self.components.registry = registry;
        self.make_by_name();
    }

    /// Makes the components made by name whose part is registered now.
    fn make_by_name(&mut self) {
        if self.components.by_name.is_empty() {
            return;
        }
        let _entered = self.components.runtime.enter();
        let hosts: Vec<NodeId> = self.components.by_name.keys().copied().collect();
        for host in hosts {
            let Some(waiting) = self.components.by_name.get(&host) else {
                continue;
            };
            let still = self
                .components
                .instances
                .get(&host)
                .is_some_and(|i| matches!(i.inner, Inner::Missing));
            if !still {
                self.components.by_name.remove(&host);
                continue;
            }
            let Some((spec, mut inner)) = self.components.registry.make_type(waiting.id) else {
                continue;
            };
            let waiting = self.components.by_name.remove(&host).expect("waiting");
            inner.place(host, waiting.owner);
            inner.set_props(waiting.props.as_any());
            // Its view is made in place of the empty one it showed.
            if let Some(inst) = self.components.instances.get_mut(&host) {
                inst.inner = Inner::Component(inner);
                inst.spec = Some(spec);
                inst.remake = true;
            }
            self.components.mark(host);
        }
    }

    /// Makes `host` the host of component element `c`: by its type, or
    /// by its registered name ([`crate::element::ComponentElement::by_name`]).
    fn create_instance_for(&mut self, host: NodeId, c: &crate::element::builder::ComponentEl) {
        let Some(id) = c.by_name else {
            self.create_instance_of(host, c.name, c.make, c.spec);
            return;
        };
        if self.is_host(host) {
            return;
        }
        match self.components.registry.make_type(id) {
            Some((spec, inner)) => self.insert_instance(host, Some(spec), Inner::Component(inner)),
            None => {
                self.insert_instance(host, None, Inner::Missing);
                self.components.by_name.insert(
                    host,
                    ByName {
                        id,
                        props: c.props.clone_box(),
                        owner: crate::element::Owner::current(),
                    },
                );
                let name = crate::element::component::export_name(c.name);
                match PART_REQUESTER.with(|r| r.get()) {
                    Some(request) => request(name),
                    None => log::debug!("`{name}` waits for the part that registers it"),
                }
            }
        }
    }

    /// Sets the props of `host`'s component from its element.
    fn set_element_props(&mut self, host: NodeId, props: &dyn crate::element::builder::AnyProps) {
        if let Some(waiting) = self.components.by_name.get_mut(&host) {
            waiting.props = props.clone_box();
            return;
        }
        if let Some(inst) = self.components.instances.get_mut(&host)
            && let Inner::Component(inner) = &mut inst.inner
        {
            inner.set_props(props.as_any());
        }
    }

    /// `uiTheme` on the root: the app's theme file (`nsh.json`, `setTheme`),
    /// which the UI set that reads themes makes tokens of. What it cannot
    /// read is left out and the rest applies, so a bundle made by a newer
    /// NSH keeps its theme here.
    pub(super) fn set_ui_theme(&mut self, json: &str) {
        match self.components.registry.tokens(Some(json)) {
            Some(Ok((tokens, left_out))) => {
                for what in left_out {
                    log::warn!("theme: {what}, ignored");
                }
                self.set_tokens(tokens);
            }
            Some(Err(e)) => log::warn!("theme: {e}"),
            None => log::warn!("theme: no UI set reads themes"),
        }
    }

    /// The app's design tokens; it is drawn with them unless the
    /// embedding app set its own ([`Core::set_host_tokens`]).
    pub fn set_tokens(&mut self, tokens: Tokens) {
        self.components.app_tokens = Arc::new(tokens);
        self.tokens_changed();
    }

    /// The app's translations ([`crate::i18n`]): what `t!` and TS's `t`
    /// read from now on.
    pub fn set_translations(&mut self, translations: crate::i18n::Translations) {
        let _entered = self.components.runtime.enter();
        let stored = crate::element::global::<crate::i18n::Translations>();
        let env = self.components.environment;
        let before =
            crate::i18n::text_locale(&stored.get(), env.locale, env.locale_settings.languages);
        stored.set(translations);
        if crate::i18n::text_locale(&stored.get(), env.locale, env.locale_settings.languages)
            != before
        {
            self.localize_platform();
        }
    }

    /// Merges `map` into this surface's translations and updates menus if the
    /// selected language changed.
    pub(crate) fn add_translations(
        &mut self,
        map: std::collections::HashMap<String, std::collections::HashMap<String, String>>,
    ) {
        if map.is_empty() {
            return;
        }
        let next = {
            let _entered = self.components.runtime.enter();
            crate::element::global::<crate::i18n::Translations>()
                .get_untracked()
                .extend(map)
        };
        self.set_translations(next);
    }

    /// Re-localizes menus when translations updated in place changed the
    /// selected language.
    fn translations_changed(&mut self, before: &crate::i18n::Translations) {
        let _entered = self.components.runtime.enter();
        let current = crate::element::global::<crate::i18n::Translations>().get_untracked();
        let env = self.components.environment;
        if crate::i18n::text_locale(&current, env.locale, env.locale_settings.languages)
            != crate::i18n::text_locale(before, env.locale, env.locale_settings.languages)
        {
            self.localize_platform();
        }
    }

    /// What NSH says itself on the platform uses the same language
    /// selection as the app's text: the menus it owns (macOS, Windows) and
    /// the screen reader's state words (iOS, Android).
    fn localize_platform(&mut self) {
        use crate::platform::Os;
        let _entered = self.components.runtime.enter();
        let env = self.components.environment;
        let desktop = matches!(env.os, Os::MacOs | Os::Windows)
            && env.idiom != crate::platform::Idiom::Terminal;
        if !desktop && !matches!(env.os, Os::Ios | Os::Android) {
            return;
        }
        let translations = crate::element::global::<crate::i18n::Translations>().get();
        let locale =
            crate::i18n::text_locale(&translations, env.locale, env.locale_settings.languages);
        if !desktop {
            if self.components.text_locale != Some(locale) {
                self.components.text_locale = Some(locale);
                self.commands
                    .push((crate::ROOT_ID, Command::TextLocale(locale)));
            }
            return;
        }
        let labels = crate::desktop::MenuLabels::for_locale(
            locale,
            self.components.environment.os == crate::platform::Os::MacOs,
        );
        let _ = self.apply_op(crate::Op::Command {
            id: crate::ROOT_ID,
            command: crate::Command::Desktop(Box::new(
                crate::desktop::DesktopCommand::SetMenuLabels(Box::new(labels)),
            )),
        });
    }

    /// The language the app asked to show in since the last call
    /// (`Some(None)`: the user's again), which the engine applies to the
    /// environment it gives the core and JS.
    pub fn take_locale_request(&mut self) -> Option<Option<crate::platform::Locale>> {
        self.components.locale_request.take()
    }

    /// The functions components, tasks and module functions asked to run
    /// on the platform's main thread since the last call
    /// ([`crate::element::run_on_main_thread`]), in order: the engine hands
    /// them to its sink after the commit.
    #[doc(hidden)]
    pub fn take_main_thread_tasks(&mut self) -> Vec<crate::main_thread::MainThreadTask> {
        std::mem::take(&mut self.components.main_thread)
    }

    /// The embedding app's design tokens (`None`: the app's again): an app
    /// embedded in a native app looks like it, whatever the app sets.
    /// Text inherits its `foreground` token unless it sets its own color.
    pub fn set_host_tokens(&mut self, tokens: Option<Tokens>) {
        self.components.host_tokens = tokens.map(Arc::new);
        self.tokens_changed();
        // Embedded content inherits the host's foreground unless it sets its own.
        let classes = if self.components.host_tokens.is_some() {
            vec!["text-foreground".into()]
        } else {
            Vec::new()
        };
        self.set_classes(self.root, None, Some(classes));
    }

    /// What [`Core::tokens`] become when the root's `uiTheme` (the app's
    /// theme file) is set, with the embedding app's tokens of now: JS reads
    /// them in the turn that sends the theme, before it reaches the core.
    pub fn theme_tokens(&self) -> crate::element::ThemeTokens {
        crate::element::ThemeTokens::new(
            self.components.registry.token_source(),
            self.components.host_tokens.clone(),
        )
    }

    /// The design tokens the app is drawn with now: the app's, under the
    /// embedding app's. A new value (not the same `Arc`) when they change.
    pub fn tokens(&self) -> &Arc<Tokens> {
        &self.components.tokens
    }

    /// The tokens drawn with now: a signal of the surface, so only the
    /// bindings that read them run again, and only when they changed.
    fn tokens_changed(&mut self) {
        let tokens = match &self.components.host_tokens {
            // The app's own tokens the host's do not have stay.
            Some(host) => Arc::new(host.over(&self.components.app_tokens)),
            None => self.components.app_tokens.clone(),
        };
        if *tokens == *self.components.tokens {
            self.components.tokens = tokens;
            return;
        }
        {
            let _entered = self.components.runtime.enter();
            self.components.tokens = tokens;
            self.components
                .runtime
                .set_tokens(self.components.tokens.clone());
        }
        // The platform's own controls (menus, Android's alerts) take their
        // colors from them.
        self.commands.push((
            crate::ROOT_ID,
            Command::Tokens(self.components.tokens.clone()),
        ));
        let font = self
            .components
            .tokens
            .font(crate::element::FONT_SANS)
            .map(|f| crate::style::FontFamily::new(f));
        self.set_default_font(font);
        self.class_tokens_changed();
    }

    /// Mounts a Rust app's root component as the content of the root view;
    /// its view is made in the next commit.
    pub fn mount_root(&mut self, root: &Root) {
        if let Some(setting) = root.status_bar_ref() {
            self.components.status_bars.set_base(setting);
        }
        let _entered = self.components.runtime.enter();
        let Some(id) = self.make_component(root.element(), |_, _| {}) else {
            return log::error!("the root is not a component");
        };
        let _ = self.apply_op(Op::Insert {
            parent: ROOT_ID,
            child: id,
            before: None,
        });
        self.mount_opened_windows();
        self.own_direction();
    }

    /// Mounts what renders the windows `open_window` opens, beside the
    /// app's root (desktops): a Rust app's ([`Self::mount_root`]) or a TSX
    /// app's, whose built-in windows (the update prompt) open the same way.
    pub fn mount_opened_windows(&mut self) {
        let _entered = self.components.runtime.enter();
        if !crate::element::os().is_desktop() {
            return;
        }
        use crate::element::Component as _;
        let host = crate::element::desktop::OpenedWindowsHost::element(()).into_element();
        if let Some(host) = self.make_component(host, |_, _| {}) {
            let _ = self.apply_op(Op::Insert {
                parent: ROOT_ID,
                child: host,
                before: None,
            });
        }
    }

    /// Makes the host of component element `el` (`None`: `el` is not a
    /// component), out of the tree; `made` sees its node first, before it
    /// renders.
    pub(super) fn make_component(
        &mut self,
        el: crate::element::AnyElement,
        made: impl FnOnce(&mut Self, NodeId),
    ) -> Option<NodeId> {
        let mut el = el.0;
        let ElKind::Component(c) = std::mem::replace(&mut el.kind, ElKind::Plain) else {
            return None;
        };
        let id = self.components.alloc();
        let _ = self.apply_op(Op::Create { id, tag: el.tag });
        made(self, id);
        self.create_instance_for(id, &c);
        self.set_element_props(id, c.props.as_ref());
        Some(id)
    }

    /// How the sets make the views' built-in scroll bars.
    pub(super) fn scrollbar_source(&self) -> Option<crate::element::ScrollbarSource> {
        self.components.registry.scrollbar_source()
    }

    /// The environment components read ([`crate::element::window`]
    /// and the like), as the platform reports it: what read a part that
    /// changed runs again. `dark` is the system's: the app's
    /// appearance wins over it ([`Core::set_appearance`]).
    pub fn set_environment(&mut self, mut environment: Environment) {
        let _entered = self.components.runtime.enter();
        environment.rtl = self.surface_rtl(environment.rtl);
        self.system_dark = environment.dark;
        environment.dark = self.shown_dark();
        self.apply_environment(environment);
    }

    /// Whether the platform's performance monitor measures
    /// (`fpsEnabled()`): what read it runs again.
    pub fn set_perf_monitor(&mut self, enabled: bool) {
        self.components.runtime.set_perf_monitor(enabled);
    }

    /// What the performance monitor measured last (`perfStats()`; `None`
    /// while it does not measure): what read it runs again.
    pub fn set_perf_stats(&mut self, stats: Option<crate::platform::PerfStats>) {
        self.components.runtime.set_perf_stats(stats);
    }

    /// The displays components read ([`crate::element::desktop::displays`]),
    /// as the platform reports them: what read them runs again.
    pub fn set_displays(&mut self, displays: Arc<[crate::desktop::Display]>) {
        self.components.runtime.set_displays(displays);
    }

    /// The environment components read is now `environment`.
    pub(super) fn apply_environment(&mut self, environment: Environment) {
        let _entered = self.components.runtime.enter();
        let changed = self.components.environment != environment;
        let language_changed = self.components.environment.idiom != environment.idiom
            || self.components.environment.os != environment.os
            || self.components.environment.locale != environment.locale
            || self.components.environment.locale_settings.languages
                != environment.locale_settings.languages;
        let keyboard_moved =
            self.components.environment.keyboard_height != environment.keyboard_height;
        self.keyboard_moved |= keyboard_moved;
        // The room the root view's anchored overlays keep to leaves the
        // keyboard out (`Core::overlay_area`): laid out and placed again.
        if keyboard_moved && self.root_overlay_shown() {
            self.needs_layout = true;
        }
        let ratio = self.components.environment.pixel_ratio;
        let window = self.components.environment.window;
        self.components.environment = environment;
        // Width and orientation variants follow the window `windowSize()`
        // reports (`Core::class_window`).
        if window != environment.window {
            self.restyle_where(crate::tailwind::deps::WIDTH | crate::tailwind::deps::HEIGHT);
        }
        if ratio != environment.pixel_ratio {
            self.repick_images(ratio, environment.pixel_ratio);
        }
        // Frames and text measurements are rounded to device pixels.
        self.pixel_ratio_changed(environment.pixel_ratio);
        // On a grid surface, lengths and frames are put on its Cells.
        self.cell_changed(environment.cell, environment.dark);
        if changed {
            // What reads a part that changed runs again.
            self.components.runtime.set_environment(environment);
        }
        if language_changed {
            self.localize_platform();
        }
        // A main window that keeps its placement saves it as it changes.
        if let Some(state) = environment.window_state {
            self.keep_window_placement(crate::ROOT_ID, &state);
        }
    }

    /// The surface's size changed (the environment's window).
    pub(super) fn components_viewport(&mut self, size: crate::Size<crate::Points>) {
        let environment = Environment {
            window: size,
            ..self.components.environment
        };
        self.apply_environment(environment);
    }

    /// Drops `ops` without applying them (the script was stopped): the
    /// calls into Rust among them are not made, and the promises waiting
    /// for them reject (their replies are in the next events); a JS call
    /// parked behind one is dropped.
    pub fn discard_ops(&mut self, ops: impl IntoIterator<Item = Op>) {
        for op in ops {
            if let Op::Rust(RustOp { call, run }) = op {
                // What the call holds (a post's place: released) (its arguments: instances, callbacks)
                // goes now.
                drop_caught(run);
                self.settle(call, Err("the script stopped before the call ran".into()));
            }
        }
    }

    /// The queue of the JS calls Rust posts: the one the engine hands the
    /// script too.
    pub fn set_posts(&mut self, posts: Posts) {
        self.components.posts = posts;
    }

    /// Wakes the engine when a component's task is woken (from any
    /// thread): it then calls [`Self::run_component_tasks`].
    pub fn set_task_notify(&mut self, notify: Arc<dyn Fn() + Send + Sync>) {
        self.components.executor.set_notify(notify.clone());
        self.components.downloads.set_notify(notify);
    }

    /// Where a platform's last stop acknowledgement goes after this core's
    /// engine is gone: the engine's control handle keeps it, and the core
    /// registers its staging directories and cancel requests with it.
    #[doc(hidden)]
    pub fn set_download_cleanup(&mut self, cleanup: crate::webview::downloads::DownloadCleanup) {
        self.components.downloads.set_cleanup(cleanup);
    }

    /// The tokio runtime the components' tasks are polled in the context
    /// of (their timers, IO and background work run on it).
    pub fn set_task_runtime(&mut self, runtime: tokio::runtime::Handle) {
        self.components.executor.set_runtime(runtime);
    }

    /// When the components' soonest timer is due ([`crate::element::timer`]):
    /// the engine wakes then and runs their tasks.
    pub fn next_task_timer(&self) -> Option<crate::time::Instant> {
        self.components.executor.next_timer()
    }

    /// Runs the components' woken tasks, with the state changes they ask
    /// for, until they all wait.
    pub fn run_component_tasks(&mut self) {
        let _entered = self.components.runtime.enter();
        let executor = self.components.executor.clone();
        executor.fire_timers(crate::time::now());
        // A task that keeps waking itself cannot hold the engine.
        for _ in 0..MAX_TASK_ROUNDS {
            let polled = executor.poll_ready();
            let actions = executor.take_actions();
            if !polled && actions.is_empty() {
                return;
            }
            for action in actions {
                self.apply_action(action);
            }
            for (host, message) in executor.take_failures() {
                self.component_failed(host, message);
            }
        }
    }

    /// Whether something runs as the app quits ([`crate::element::desktop::on_app_quit`],
    /// `Application.on("quit")`): the engine gives it time to.
    pub fn has_quit_listeners(&self) -> bool {
        !self.components.executor.quit.borrow().is_empty()
    }

    /// The app quits: starts each quit listener's work, oldest first, as
    /// tasks the engine runs ([`Core::run_component_tasks`]) until
    /// [`Core::quit_pending`] is false or
    /// [`QUIT_TIMEOUT`](crate::element::desktop::QUIT_TIMEOUT) has passed.
    /// Whether any started.
    pub fn start_quit(&mut self) -> bool {
        let _entered = self.components.runtime.enter();
        let executor = self.components.executor.clone();
        let listeners = executor.quit.borrow().all();
        for listener in listeners {
            match caught(|| listener()) {
                Ok(future) => {
                    let pending = crate::element::quit::Pending::new(&executor.quitting);
                    // Detached: it runs until it ends or the engine stops.
                    drop(crate::element::task::spawn_future(&executor, async move {
                        future.await;
                        drop(pending);
                    }));
                }
                Err(message) => log::error!(target: "js", "a quit listener failed: {message}"),
            }
        }
        self.apply_actions();
        self.quit_pending()
    }

    /// The user asked to quit while the app listens to quit requests:
    /// each listener hears it, oldest first.
    fn quit_requested(&mut self) {
        let _entered = self.components.runtime.enter();
        let listeners = self.components.executor.quit_requests.borrow().all();
        for listener in listeners {
            if let Err(message) = caught(|| listener()) {
                log::error!(target: "js", "a quit request listener failed: {message}");
            }
        }
        self.apply_actions();
    }

    /// The OS asked the app to show itself: each reopen listener hears it,
    /// oldest first. The app opens or focuses the window it wants.
    #[doc(hidden)]
    pub fn reopened(&mut self) {
        let _entered = self.components.runtime.enter();
        let listeners = self.components.executor.reopens.borrow().all();
        for listener in listeners {
            if let Err(message) = caught(|| listener()) {
                log::error!(target: "js", "a reopen listener failed: {message}");
            }
        }
        self.apply_actions();
    }

    /// The app's last window went: each listener hears it, oldest first.
    pub(crate) fn last_window_closed(&mut self) {
        let _entered = self.components.runtime.enter();
        let listeners = self.components.executor.last_window_closed.borrow().all();
        for listener in listeners {
            if let Err(message) = caught(|| listener()) {
                log::error!(target: "js", "a last window closed listener failed: {message}");
            }
        }
        self.apply_actions();
    }

    /// Tells the platform whether its quit requests go to the app, when
    /// that changed since the last call (a listener came or went): whether
    /// it did.
    pub(super) fn sync_quit_requests(&mut self) -> bool {
        let asks = !self.components.executor.quit_requests.borrow().is_empty();
        if asks == self.components.asks_quit {
            return false;
        }
        self.components.asks_quit = asks;
        let _ = self.apply_op(crate::Op::Command {
            id: crate::ROOT_ID,
            command: crate::Command::Desktop(Box::new(
                crate::desktop::DesktopCommand::SetQuitOnRequest(!asks),
            )),
        });
        true
    }

    /// Whether the work quit listeners started is still running.
    pub fn quit_pending(&self) -> bool {
        self.components.executor.quitting.get() > 0
    }

    /// Whether a JS call of an `async fn` into Rust (a native module's, a
    /// class's) has not answered yet: its answer comes from elsewhere (a
    /// request made in Rust, another thread), which nothing else counts.
    pub fn async_calls_pending(&self) -> bool {
        self.components.executor.calls.get() > 0
    }

    /// Runs the closures that waited for the app's answer to the events
    /// handed to JS before this commit ([`crate::element::after_answer`]),
    /// each under its owner; one whose owner went is dropped unrun.
    pub(super) fn run_answers(&mut self) {
        let _entered = self.components.runtime.enter();
        for answer in self.components.executor.take_due_answers() {
            let crate::element::AfterAnswer { owner, f } = answer;
            let result = if owner == crate::element::Owner::detached() {
                caught(f)
            } else if owner.is_live() {
                caught(|| owner.scope(f))
            } else {
                drop_caught(f);
                continue;
            };
            if let Err(message) = result {
                match self.host_of_owner(owner) {
                    Some(host) => self.component_failed(host, message),
                    None => {
                        log::error!(target: "js", "a closure after the app's answer failed: {message}")
                    }
                }
            }
            self.apply_actions();
        }
    }

    /// Whether `id` is a component's host.
    pub(super) fn is_host(&self, id: NodeId) -> bool {
        self.components.instances.contains_key(&id)
    }

    /// Ops from JS on a component's host take its place; others pass
    /// (`Some`).
    pub(super) fn intercept(&mut self, op: Op) -> Result<Option<Op>, ApplyError> {
        // The app's elements that take a slot's props: their props combine
        // with the component's ([`super::slots`]).
        // A component's host among them takes them from its view: JS's
        // ops on it are its component's.
        if !self.components.adopted.is_empty()
            && let Op::SetProp { id, .. } | Op::Listen { id, .. } | Op::Release { id } = &op
            && self.components.adopted.contains_key(id)
            && !self.is_host(*id)
        {
            return Ok(self.js_slot_op(op));
        }
        match op {
            // The app's style on a host goes after the root's own.
            Op::SetStyle { id, patch, .. } if self.is_host(id) => {
                let inst = self.components.instances.get_mut(&id).expect("host");
                inst.app_style = (!patch.is_empty()).then_some(patch);
                // The node's own style is the view's that makes it, then
                // what is given it.
                let base = self.base_of(id);
                let cx = self.root_context_of(base).expect("a host");
                let app = if cx.combined {
                    cx.app
                } else {
                    self.components.instances[&base].app_style.clone()
                };
                let (inline, animated) = match &self.components.instances[&base].root {
                    Some(root) => (root.attrs.inline.clone(), root.attrs.animated().to_vec()),
                    None => (None, Vec::new()),
                };
                Ok(Some(inline_style(
                    id,
                    inline.as_deref(),
                    &animated,
                    app.as_ref(),
                )))
            }
            // A render's holder joins its host: placed in its placeholder.
            Op::Insert { parent, child, .. }
                if self.is_host(parent) && self.is_render_holder(child) =>
            {
                self.insert_render_holder(parent, child);
                Ok(None)
            }
            Op::Remove { parent, child }
                if self.is_host(parent) && self.is_render_holder(child) =>
            {
                self.remove_render_holder(child, false);
                Ok(None)
            }
            Op::Release { id } if self.is_render_holder(id) => {
                self.remove_render_holder(id, true);
                Ok(Some(Op::Release { id }))
            }
            // A slot's node joins its host: the view places it.
            Op::Insert { parent, child, .. }
                if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
            {
                let name = self.components.slot_names[&child].clone();
                let inst = self.components.instances.get_mut(&parent).expect("host");
                let Some(slot) = inst.spec.as_ref().and_then(|s| s.holder(&name)) else {
                    log::warn!(target: "js", "the component has no slot `{name}`");
                    self.detach_id(child);
                    return Ok(None);
                };
                inst.slots.retain(|(_, n)| *n != child);
                inst.slots.push((slot, child));
                self.components.slot_hosts.insert(child, parent);
                self.components.mark(parent);
                Ok(None)
            }
            Op::Remove { parent, child }
                if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
            {
                self.unslot(child);
                self.detach_id(child);
                Ok(None)
            }
            // A component's list gets a cell: the component wraps its rows.
            Op::Insert { parent, child, .. }
                if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
            {
                self.apply_op(op)?;
                if let Some((place, _)) = self.components.lists.get(&parent).cloned() {
                    self.wrap_row(child, place);
                }
                Ok(None)
            }
            Op::Remove { parent, .. }
                if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
            {
                Ok(Some(op))
            }
            // A slot filled or emptied: the component's slot prop follows
            // (it is marked).
            Op::Insert { parent, .. } | Op::Remove { parent, .. }
                if self.components.slot_hosts.contains_key(&parent) =>
            {
                let empty = |core: &Self| {
                    core.key(parent)
                        .map_or(true, |k| core.nodes[k as usize].children.is_empty())
                };
                let before = empty(self);
                self.apply_op(op)?;
                if empty(self) != before {
                    let host = self.components.slot_hosts[&parent];
                    self.components.mark(host);
                }
                // The slot's props follow its one element.
                self.retarget_slot(parent, None);
                Ok(None)
            }
            Op::Release { id } if self.components.slot_names.contains_key(&id) => {
                self.unslot(id);
                self.components.slot_names.remove(&id);
                self.components.lists.remove(&id);
                self.forget_list_count(id);
                Ok(Some(Op::Release { id }))
            }
            // The number of rows changed: the rows' wrappers may depend on
            // it (the last row). They read it from a signal; one that does
            // not bind its row is built again.
            Op::SetProp {
                id,
                prop: Prop::Count(count),
            } if self.components.lists.contains_key(&id) => {
                let key = self.key(id)?;
                self.apply_op(Op::SetProp {
                    id,
                    prop: Prop::Count(count),
                })?;
                // A splice before may have changed the list's count already.
                let seen = &mut self.components.lists.get_mut(&id).expect("list").1;
                if std::mem::replace(seen, count) != count {
                    // A view's wrappers read it.
                    if let Some(&(_, signal)) = self.components.list_counts.get(&id) {
                        signal.set(count as usize);
                    }
                    let cells: Vec<NodeId> = self.nodes[key as usize]
                        .children
                        .iter()
                        .map(|&c| self.nodes[c as usize].id)
                        .collect();
                    for cell in cells {
                        let binds = self.components.instances.get(&cell).is_some_and(|inst| {
                            inst.row_index.is_some() && inst.cell_owner.is_some_and(|o| o.is_live())
                        });
                        if !binds {
                            self.components.mark(cell);
                        }
                    }
                }
                Ok(None)
            }
            // A row cell shows another row: its wrapper's position follows
            // (one that does not bind its row is built again).
            Op::SetProp {
                id,
                prop: Prop::CellIndex(index),
            } if self.is_host(id) => {
                let inst = self.components.instances.get_mut(&id).expect("host");
                if let Inner::Row { index: current, .. } = &mut inst.inner
                    && *current != index as usize
                {
                    *current = index as usize;
                    match inst.row_index {
                        // A view's wrapper keeps its content.
                        Some(row) if inst.cell_owner.is_some_and(|o| o.is_live()) => {
                            row.set(index as usize);
                        }
                        _ => self.components.mark(id),
                    }
                }
                Ok(Some(op))
            }
            Op::Insert {
                parent,
                child,
                before,
            } if self.is_host(parent) => {
                // A raw text run (`<Button>Open</Button>`) has no node
                // until a use needs one: the view places it, so it does.
                let run = self.runs.contains_key(&child);
                self.materialize_run(child)?;
                let key = self.key(child)?;
                let is_text = matches!(self.nodes[key as usize].kind, Kind::Text | Kind::RawText);
                let inst = self.components.instances.get_mut(&parent).expect("host");
                let was_empty = inst.js_children.is_empty();
                let moved = inst.js_children.contains(&child);
                inst.forget_js_child(child);
                let at = before.and_then(|b| inst.js_children.iter().position(|&c| c == b));
                inst.js_children
                    .insert(at.unwrap_or(inst.js_children.len()), child);
                if is_text {
                    inst.js_texts.insert(child);
                }
                let place = inst.children_at;
                inst.js_children_changed();
                if was_empty || place == Placement::Each {
                    self.components.mark(parent);
                }
                self.join_content(child);
                match place {
                    // Before its next JS sibling, else before what the
                    // view puts after the children.
                    Placement::At(p, anchor) => {
                        let anchor = self.anchor_node(anchor);
                        self.apply_op(Op::Insert {
                            parent: p,
                            child,
                            before: at.and(before).or(anchor),
                        })?;
                        if run
                            && self
                                .key(p)
                                .is_ok_and(|k| self.nodes[k as usize].kind != Kind::Text)
                        {
                            let text = self.key(child).map_or("", |k| &self.nodes[k as usize].text);
                            log::warn!(
                                target: "js",
                                "text in a component's children is not shown: text shows in a <Text> (`<Text>{text}</Text>`)"
                            );
                        }
                    }
                    Placement::Nested(nested, anchor) => {
                        let anchor = self.anchor_node(anchor);
                        self.join_nested_at(nested, child, at.and(before).or(anchor));
                    }
                    // Its wrapper is the view's (a region of them, keyed
                    // by the child): a child moved among the others keeps
                    // its wrapper, which the region moves.
                    Placement::Each if moved => {}
                    Placement::Each => self.detach_id(child),
                    Placement::None => self.detach_id(child),
                }
                Ok(None)
            }
            Op::Remove { parent, child } if self.is_host(parent) => {
                let inst = self.components.instances.get_mut(&parent).expect("host");
                inst.forget_js_child(child);
                inst.js_children_changed();
                let place = inst.children_at;
                if inst.js_children.is_empty() || place == Placement::Each {
                    self.components.mark(parent);
                }
                self.unplace(place, child);
                Ok(None)
            }
            // A host attribute: its root's node takes it over its own.
            Op::SetProp { id, prop }
                if js_host_attribute(&prop)
                    && self
                        .components
                        .instances
                        .get(&id)
                        .is_some_and(|i| matches!(i.inner, Inner::Component(_))) =>
            {
                let inst = self.components.instances.get_mut(&id).expect("host");
                let before = inst.js_host.len();
                // Cleared (set to its default): none given, the root's own
                // come back.
                if crate::element::host::reset(&prop).as_ref() == Some(&prop) {
                    inst.js_host
                        .retain(|p| !crate::element::host::same_kind(p, &prop));
                    if inst.js_host.len() == before {
                        return Ok(None);
                    }
                } else if inst.js_host.contains(&prop) {
                    return Ok(None);
                } else {
                    crate::element::host::set_in(&mut inst.js_host, prop);
                }
                // Before its view is made, its first render takes them.
                if inst.root.is_some() {
                    inst.given_changed = true;
                    self.components.mark(id);
                }
                Ok(None)
            }
            Op::SetProp {
                id,
                prop: Prop::Class(class),
            } if self.is_host(id) => {
                let inst = self.components.instances.get_mut(&id).expect("host");
                inst.class = class;
                self.update_user_class(id);
                Ok(None)
            }
            Op::SetProp {
                id,
                prop: Prop::ClassList(list),
            } if self.is_host(id) => {
                let inst = self.components.instances.get_mut(&id).expect("host");
                inst.class_list = list;
                self.update_user_class(id);
                Ok(None)
            }
            // The root listens to the back button while JS or a component
            // does.
            Op::Listen {
                id: crate::ROOT_ID,
                event: EventKind::BackPress,
                enabled,
            } => {
                self.components.js_back = enabled;
                let rust = !self.components.executor.back.borrow().list.is_empty();
                Ok(Some(Op::Listen {
                    id: crate::ROOT_ID,
                    event: EventKind::BackPress,
                    enabled: enabled || rust,
                }))
            }
            // The root listens to the back gesture's steps while JS or a
            // component does.
            Op::Listen {
                id: crate::ROOT_ID,
                event: EventKind::BackProgress,
                enabled,
            } => {
                self.components.js_back_progress = enabled;
                let rust = !self
                    .components
                    .executor
                    .back_progress
                    .borrow()
                    .list
                    .is_empty();
                Ok(Some(Op::Listen {
                    id: crate::ROOT_ID,
                    event: EventKind::BackProgress,
                    enabled: enabled || rust,
                }))
            }
            // The surface's shortcuts are JS's and the views'.
            Op::SetProp {
                id: crate::ROOT_ID,
                prop: Prop::Keymap(keymap),
            } => {
                self.components.js_keymap = keymap;
                Ok(Some(Op::SetProp {
                    id: crate::ROOT_ID,
                    prop: Prop::Keymap(self.keymap()),
                }))
            }
            Op::Listen {
                id: crate::ROOT_ID,
                event: EventKind::KeyCommand,
                enabled,
            } => {
                self.components.js_keys = enabled;
                let rust = !self.components.executor.keys.borrow().list.is_empty();
                Ok(Some(Op::Listen {
                    id: crate::ROOT_ID,
                    event: EventKind::KeyCommand,
                    enabled: enabled || rust,
                }))
            }
            // The component's events come from the core, not from the view.
            Op::Listen {
                id,
                event: EventKind::NativeEvent,
                ..
            } if self.is_host(id) => Ok(None),
            Op::Listen { id, event, enabled } if self.is_host(id) => {
                let inst = self.components.instances.get_mut(&id).expect("host");
                inst.js_events.set(event, enabled);
                Ok(Some(self.host_listen(id, event)))
            }
            Op::Rust(op) => {
                self.run_rust(op);
                Ok(None)
            }
            Op::Release { id } if self.is_host(id) => {
                self.release_instance(id);
                Ok(Some(Op::Release { id }))
            }
            op => Ok(Some(op)),
        }
    }

    /// Whether the host `id`'s node listens to `event` for someone outside
    /// its component's view: JS on the host, or a view above giving an
    /// element of this component (or of one whose root it is) a listener.
    fn outside_listens(&self, id: NodeId, event: EventKind) -> bool {
        let mut at = Some(self.base_of(id));
        while let Some(host) = at {
            let Some(inst) = self.components.instances.get(&host) else {
                break;
            };
            if inst.js_events.contains(event) || inst.given_events.contains(event) {
                return true;
            }
            at = inst.above;
        }
        false
    }

    /// What the host `id`'s node listens to of `event`: its root's own,
    /// the slot whose props it takes and those outside its view.
    fn host_listen(&mut self, id: NodeId, event: EventKind) -> Op {
        let outside = self.outside_listens(id, event);
        let base = self.base_of(id);
        let own = self.components.instances[&base]
            .root
            .as_ref()
            .is_some_and(|r| r.events.contains(event));
        let slot = self.target_listens(base, event, outside || own);
        Op::Listen {
            id,
            event,
            enabled: outside || own || slot,
        }
    }

    /// Gives the nested component on `id` the listeners `handlers` of the
    /// view it is in (in place of what that view gave it before): its node
    /// listens to their events as long as they are given.
    pub(super) fn set_given_handlers(
        &mut self,
        id: NodeId,
        handlers: Vec<(EventKind, Listener<EventPayload>)>,
    ) {
        let mut events = EventMask::default();
        for (kind, _) in &handlers {
            events.set(*kind, true);
        }
        let Some(inst) = self.components.instances.get_mut(&id) else {
            return;
        };
        let old = std::mem::replace(&mut inst.given_events, events);
        inst.given_handlers = handlers;
        let mut changed = old.bits() ^ events.bits();
        while changed != 0 {
            let kind = EventKind::ALL[changed.trailing_zeros() as usize];
            changed &= changed - 1;
            let op = self.host_listen(id, kind);
            let _ = self.apply_op(op);
        }
    }

    /// Runs the listeners of `kind` the views above give the host `base`
    /// (and the components whose root it is), each in the component whose
    /// view gave it; false when none was given.
    fn handle_given(&mut self, base: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
        let mut listeners = Vec::new();
        let mut at = Some(base);
        while let Some(host) = at {
            let Some(inst) = self.components.instances.get(&host) else {
                break;
            };
            if inst.given_events.contains(kind)
                && let Some(&owner) = self.components.owners.get(&host)
            {
                listeners.extend(
                    inst.given_handlers
                        .iter()
                        .filter(|(k, _)| *k == kind)
                        .map(|(_, l)| (owner, l.clone())),
                );
            }
            at = inst.above;
        }
        let mut handled = false;
        for (owner, listener) in listeners {
            handled |= self.run_listener(owner, &listener, payload);
        }
        handled
    }

    /// Whether JS listens to `kind` on the host whose node `base` makes
    /// (the top one of its chain).
    fn js_listens(&self, base: NodeId, kind: EventKind) -> bool {
        let mut at = Some(base);
        while let Some(host) = at {
            let Some(inst) = self.components.instances.get(&host) else {
                break;
            };
            if inst.js_events.contains(kind) {
                return true;
            }
            at = inst.above;
        }
        false
    }

    /// The number of rows of the list cell `cell` is in.
    fn rows_of_cell(&self, cell: NodeId) -> usize {
        let Ok(key) = self.key(cell) else { return 0 };
        self.nodes
            .get(self.nodes[key as usize].parent as usize)
            .and_then(|list| list.list.as_ref())
            .map_or(0, |list| list.count as usize)
    }

    /// The number of rows of list `list`.
    fn rows_of_list(&self, list: NodeId) -> u32 {
        self.key(list)
            .ok()
            .and_then(|k| self.nodes[k as usize].list.as_ref())
            .map_or(0, |l| l.count)
    }

    /// Whether `id` is a list.
    fn is_list(&self, id: NodeId) -> bool {
        self.key(id)
            .is_ok_and(|k| self.nodes[k as usize].list.is_some())
    }

    /// Item cell `cell` of a component's list: its rows are wrapped by
    /// `place`, the row function the component's view gave last.
    fn wrap_row(&mut self, cell: NodeId, place: PlaceFn) {
        let Ok(key) = self.key(cell) else { return };
        let node = &self.nodes[key as usize];
        if !matches!(node.slot, Some(crate::CellSlot::Item(_))) {
            return;
        }
        if let Some(inst) = self.components.instances.get_mut(&cell) {
            if let Inner::Row { place: current, .. } = &mut inst.inner {
                *current = place;
            }
            self.components.mark(cell);
            return;
        }
        // The row's content is already in the cell: it moves into the
        // wrapper.
        let js_children = node
            .children
            .iter()
            .map(|&c| self.nodes[c as usize].id)
            .collect();
        let instance = Instance::new(Inner::Row { place, index: 0 }, None, js_children, None);
        self.components.instances.insert(cell, Box::new(instance));
        self.components.mark(cell);
    }

    /// Runs a call JS made into Rust, in order with the ops before it: its
    /// result settles promise `call` (in the events, in order with them).
    pub(super) fn run_rust(&mut self, op: RustOp) {
        let posts = self.components.posts.clone();
        posts.in_op(|| self.run_rust_op(op));
    }

    fn run_rust_op(&mut self, op: RustOp) {
        let RustOp { call, run } = op;
        match run {
            RustCall::Op(run) => {
                let mut cx = ModuleCx::default();
                // The app's code: a panic rejects the call (its actions are
                // dropped) instead of unwinding through the engine. It runs
                // in the graph, as a listener does: it may `spawn` and use
                // signals.
                let ran = {
                    let _entered = self.components.runtime.enter();
                    caught(|| run(&mut cx))
                };
                let result = match ran {
                    Ok(result) => {
                        for action in std::mem::take(&mut cx.actions) {
                            self.apply_action(action);
                        }
                        result
                    }
                    Err(message) => Err(message.into()),
                };
                self.apply_actions();
                self.settle(call, result);
            }
            RustCall::Task(start) => match caught(start) {
                Ok(future) => {
                    let executor = Rc::downgrade(&self.components.executor);
                    let pending =
                        crate::element::quit::Pending::new(&self.components.executor.calls);
                    // A task of the root: it never goes away.
                    crate::element::task::spawn_raw(
                        &self.components.executor,
                        ROOT_ID,
                        Box::pin(async move {
                            let result = crate::element::module::catching(future).await;
                            drop(pending);
                            match executor.upgrade() {
                                Some(executor) if call != 0 => {
                                    executor.act(Action::Return(call, result));
                                }
                                _ => {
                                    if let Err(e) = &result {
                                        log::warn!(target: "js", "an async call into Rust failed: {e}");
                                    }
                                }
                            }
                        }),
                    );
                }
                Err(message) => self.settle(call, Err(message.into())),
            },
            RustCall::Method(host, method) if self.view_pending(host) => {
                // Called from its ref, which the app gets as the component
                // is made, before its view is (`render_components`).
                self.components.parked_methods.push((host, call, method));
            }
            RustCall::Method(host, method) => {
                let mut failed = None;
                let result = match self
                    .components
                    .instances
                    .get_mut(&host)
                    .map(|i| &mut i.inner)
                {
                    Some(Inner::Component(inner)) => match caught(|| inner.call(method)) {
                        Ok(Some(result)) => result,
                        Ok(None) => {
                            Err(format!("{} has no ref of this method's type", inner.name()).into())
                        }
                        Err(message) => {
                            failed = Some(message.clone());
                            Err(message.into())
                        }
                    },
                    _ => {
                        drop_caught(method);
                        Err(format!("node {host} hosts no Rust component").into())
                    }
                };
                self.apply_actions();
                if let Some(message) = failed {
                    self.component_failed(host, message);
                }
                self.settle(call, result);
            }
            // Its place, released: the call runs there.
            RustCall::Post(place) => drop(place),
        }
    }

    /// Settles promise `call` with `result` (in the events, in order with
    /// them); 0: JS does not wait, an error is logged.
    pub(super) fn settle(&mut self, call: u32, result: JsResult) {
        if call == 0 {
            if let Err(e) = &result {
                log::warn!(target: "js", "a call into Rust failed: {e}");
            }
            drop_caught(result);
            return;
        }
        self.events.push(JsEvent::Reply { call, result });
    }

    /// The app's classes on `host` changed.
    pub(super) fn update_user_class(&mut self, host: NodeId) {
        let inst = &self.components.instances[&host];
        let mut combined = String::with_capacity(inst.class.len() + 16 * inst.class_list.len());
        combined.push_str(&inst.class);
        for name in &inst.class_list {
            combined.push(' ');
            combined.push_str(name);
        }
        let user = (!combined.trim().is_empty()).then(|| self.tailwind.get(&combined).0);
        self.set_user(host, user);
    }

    /// What goes after `host`'s own styles.
    pub(super) fn set_user(&mut self, host: NodeId, user: Option<std::rc::Rc<ClassList>>) {
        let inst = self.components.instances.get_mut(&host).expect("host");
        if !same(&inst.user, &user) {
            inst.user = user;
            self.components.mark(host);
        }
    }

    /// Slot node `id` leaves its host.
    fn unslot(&mut self, id: NodeId) {
        self.drop_slot_target(id);
        if let Some(host) = self.components.slot_hosts.remove(&id) {
            if let Some(inst) = self.components.instances.get_mut(&host) {
                inst.slots.retain(|(_, n)| *n != id);
            }
            self.components.mark(host);
        }
    }

    /// `componentSlot` on a view: it holds a slot's JSX.
    pub(super) fn set_slot_name(&mut self, id: NodeId, name: Arc<str>) {
        self.components.slot_names.insert(id, name);
    }

    /// `Prop::Component` on a view: it becomes the host of component `name`.
    pub(super) fn create_instance(&mut self, host: NodeId, name: Arc<str>) {
        if self.is_host(host) {
            return;
        }
        let (spec, inner) = match self.components.registry.make(&name) {
            Some((spec, inner)) => (Some(spec), Inner::Component(inner)),
            None => {
                self.deny(format!(
                    "no component is registered as `{name}`: it renders nothing"
                ));
                (None, Inner::Missing)
            }
        };
        self.insert_instance(host, spec, inner);
    }

    /// View `host` becomes the host of the component `make` creates (a
    /// component a view or the app's root names by type).
    pub(super) fn create_instance_of(
        &mut self,
        host: NodeId,
        name: &'static str,
        make: fn() -> Box<dyn AnyInstance>,
        spec: fn() -> ComponentSpec,
    ) {
        if self.is_host(host) {
            return;
        }
        let spec = self
            .components
            .specs
            .entry(name)
            .or_insert_with(|| Arc::new(spec()))
            .clone();
        self.insert_instance(host, Some(spec), Inner::Component(make()));
    }

    fn insert_instance(
        &mut self,
        host: NodeId,
        spec: Option<Arc<ComponentSpec>>,
        mut inner: Inner,
    ) {
        // A style JS set before the component prop.
        let app_style = self
            .key(host)
            .ok()
            .map(|k| self.nodes[k as usize].inline_style.clone())
            .filter(|p| !p.is_empty());
        // A component is made where it is: its lifetime is that run's, and
        // so is its context until a view places it (`adopt`).
        if let Inner::Component(c) = &mut inner {
            c.place(host, crate::element::Owner::current());
        }
        let instance = Instance::new(inner, spec, Vec::new(), app_style);
        self.components.instances.insert(host, Box::new(instance));
        self.components.mark(host);
        // No box of its own while its view styles none of its layout and
        // holds one node: that node is laid out in its place, so an app's
        // `flex-1` on a component's slot (a menu's trigger) fills the
        // component's parent (#2008).
        if let Ok(k) = self.key(host) {
            self.lay_out_through(k);
        }
    }

    /// `$name` on a host: a prop of its component.
    pub(super) fn set_component_prop(
        &mut self,
        host: NodeId,
        name: &str,
        value: Option<AnyValue>,
    ) -> bool {
        let Some(inst) = self.components.instances.get_mut(&host) else {
            return false;
        };
        let Inner::Component(inner) = &mut inst.inner else {
            return true;
        };
        match inner.set_prop(name, value) {
            Ok(true) => self.components.mark(host),
            Ok(false) => {}
            Err(e) => {
                let component = inst.spec.as_ref().map_or("", |s| s.name);
                log::warn!(target: "js", "{component}: {e}");
            }
        }
        true
    }

    /// Applies what the views' bindings queued and makes the views of the
    /// components marked, until neither is left.
    pub(super) fn render_components(&mut self) {
        let _entered = self.components.runtime.enter();
        // Views' patches, then the marked components, until none is left (a
        // patch may mark a component, a view made queues patches).
        loop {
            let changed = self.drain_views();
            let rendered = self.render_dirty();
            let failed = self.report_failures();
            let woke = self.wake_waiting();
            let called = self.run_parked_methods();
            if !changed && !rendered && !failed && !woke && !called && !self.run_after_render() {
                break;
            }
        }
        self.flush_renders();
        self.end_retags();
    }

    /// Runs what waited for the commit's views ([`crate::element::after_render`]);
    /// whether there was any (what it asked for and changed renders in this
    /// round too).
    fn run_after_render(&mut self) -> bool {
        let rendered = self.components.executor.take_rendered();
        if rendered.is_empty() {
            return false;
        }
        for crate::element::AfterAnswer { f, .. } in rendered {
            if let Err(message) = caught(f) {
                log::error!(target: "js", "a closure after the views rendered failed: {message}");
            }
        }
        true
    }

    /// Node `id` goes: what the views' renders and the app's classes knew
    /// of it goes too.
    fn forget_node_extras(&mut self, id: NodeId) {
        if !self.components.renders.is_empty() {
            self.forget_render_place(id);
        }
        if !self.components.app_classes.is_empty() {
            self.components.app_classes.remove(&id);
        }
    }

    /// Sends the failures of views' code (bindings, effects, listeners) to
    /// the nearest error boundary, else to their component's; whether there
    /// were any.
    fn report_failures(&mut self) -> bool {
        let failures = self.components.runtime.take_failures();
        let any = !failures.is_empty();
        for (owner, message) in failures {
            let host = self.host_of_owner(owner);
            let component = host
                .and_then(|h| match &self.components.instances.get(&h)?.inner {
                    Inner::Component(inner) => Some(inner.name()),
                    _ => None,
                })
                .unwrap_or("a binding");
            if let Some(boundary) = crate::element::reactive::boundary_of(owner) {
                boundary.set(Some(ComponentError { component, message }));
                continue;
            }
            match host {
                Some(host) => self.component_failed(host, message),
                None => log::error!(target: "js", "a binding failed: {message}"),
            }
        }
        any
    }

    /// Makes the views of the components marked dirty (one made already
    /// takes its slots, children and styles; a list cell builds its row
    /// again); whether there were any.
    fn render_dirty(&mut self) -> bool {
        // What handles asked for since (animated values released, ...).
        for action in self.components.executor.take_actions() {
            self.apply_action(action);
        }
        if self.components.dirty.is_empty() {
            return false;
        }
        while let Some(host) = self.components.dirty.pop() {
            // A view JS made waits to be in the tree (under what places it):
            // its context comes from above it.
            if self.waits_for_tree(host) {
                if let Some(inst) = self.components.instances.get_mut(&host) {
                    inst.dirty = false;
                }
                if !self.components.waiting.contains(&host) {
                    self.components.waiting.push(host);
                }
                continue;
            }
            let Some(mut inst) = self.components.instances.remove(&host) else {
                continue;
            };
            inst.dirty = false;
            let rooted = inst.rooted;
            let failed = self.render(host, &mut inst);
            let rerooted = inst.rooted != rooted;
            self.components.instances.insert(host, inst);
            if rerooted {
                self.follow_base(host, rooted);
            }
            if let Some(message) = failed {
                self.component_failed(host, message);
            }
        }
        true
    }

    /// Applies the root styles of the view on `host` again over the app's
    /// (or its parent's) styles, which may have changed.
    fn restyle_view(&mut self, host: NodeId, inst: &mut Instance) {
        // The component its root is applies them to the node.
        if let Some(rooted) = inst.rooted {
            if std::mem::take(&mut inst.given_changed)
                && let Some(rooted) = self.components.instances.get_mut(&rooted)
            {
                rooted.given_changed = true;
            }
            self.components.mark(rooted);
            return;
        }
        let cx = self.root_context(inst);
        let given_changed = std::mem::take(&mut inst.given_changed);
        let attrs = if let Some(node) = inst.bound.get_mut(&host) {
            let (style, classes) = (node.style.clone(), node.classes.clone());
            let class = node.attrs.class.clone();
            let classes = self.apply_el_styles(
                host,
                &style,
                &style,
                classes,
                class.as_ref(),
                cx.user.clone(),
            );
            if let Some(node) = inst.bound.get_mut(&host) {
                node.classes = classes;
                given_changed.then(|| node.attrs.clone())
            } else {
                None
            }
        } else if let Some(root) = inst.root.as_mut() {
            let (style, classes) = (root.style.clone(), root.classes.clone());
            let class = root.attrs.class.clone();
            root.classes = self.apply_el_styles(
                host,
                &style,
                &style,
                classes,
                class.as_ref(),
                cx.user.clone(),
            );
            given_changed.then(|| root.attrs.clone())
        } else {
            None
        };
        // What the views above give it changed: applied again over its
        // root's own.
        if let Some(attrs) = attrs {
            let app = if cx.combined {
                cx.app.as_ref()
            } else {
                inst.app_style.as_ref()
            };
            let _ = self.apply_op(inline_style(
                host,
                attrs.inline.as_deref(),
                attrs.animated(),
                app,
            ));
            let applied = inst.root_insets_applied;
            let own_insets = attrs.insets();
            let insets = (
                cx.inset_padding.or(own_insets.0),
                cx.inset_margin.or(own_insets.1),
            );
            if insets.0 != applied.0 {
                let _ = self.apply_op(Op::SetProp {
                    id: host,
                    prop: Prop::InsetPadding(insets.0.unwrap_or_default()),
                });
            }
            if insets.1 != applied.1 {
                let _ = self.apply_op(Op::SetProp {
                    id: host,
                    prop: Prop::InsetMargin(insets.1.unwrap_or_default()),
                });
            }
            inst.root_insets_applied = insets;
            if cx.host != inst.root_host_applied {
                // As the root's own go: combined with a slot's where its
                // node takes one's props.
                let mut attrs = attrs;
                attrs.set_insets(insets);
                let old = with_host(attrs.clone(), &inst.root_host_applied);
                let new = with_host(attrs, &cx.host);
                if !self.apply_target_attrs(host, &new, &old, app) {
                    self.apply_attrs_over(host, &new, &old, app);
                }
                inst.root_host_applied = cx.host;
            }
        }
    }

    /// Node `id` joined a host as its children or a slot's fill: the
    /// components in it, the node itself or inside its plain views however
    /// deep
    /// (`tabs().child(view().child(tab()))`), are `joined`, so their views
    /// wait to be placed and read the context of the host's view as a
    /// direct child does. A component's own content joins it in turn.
    fn join_content(&mut self, id: NodeId) {
        let mut stack = vec![id];
        while let Some(id) = stack.pop() {
            if let Some(inst) = self.components.instances.get_mut(&id) {
                inst.joined = true;
                continue;
            }
            if let Ok(k) = self.key(id) {
                stack.extend(
                    self.nodes[k as usize]
                        .children
                        .iter()
                        .map(|&c| self.nodes[c as usize].id),
                );
            }
        }
    }

    /// Whether `host` is a component that runs once, made by JS (no owner
    /// placed it) or passed by a view as a nested component's content
    /// (`joined`), whose view is not made yet, out of the tree: the view
    /// that places it gives its context.
    fn waits_for_tree(&self, host: NodeId) -> bool {
        let Some(inst) = self.components.instances.get(&host) else {
            return false;
        };
        let Inner::Component(inner) = &inst.inner else {
            return false;
        };
        inst.root.is_none()
            && (inst.joined || !inner.failure_owner().is_live())
            && !self.id_in_tree(host)
    }

    /// Whether node `id` is in the root's tree.
    fn id_in_tree(&self, id: NodeId) -> bool {
        self.key(id).is_ok_and(|k| self.in_tree(k))
    }

    /// The views that waited for the tree and are in it now are made;
    /// whether there were any.
    fn wake_waiting(&mut self) -> bool {
        let waiting = std::mem::take(&mut self.components.waiting);
        let mut woke = false;
        for host in waiting {
            if !self.components.instances.contains_key(&host) {
                continue;
            }
            if self.id_in_tree(host) {
                self.components.mark(host);
                woke = true;
            } else {
                self.components.waiting.push(host);
            }
        }
        woke
    }

    /// Runs the calls of methods parked for components whose view is now
    /// made; whether any ran.
    fn run_parked_methods(&mut self) -> bool {
        if self.components.parked_methods.is_empty() {
            return false;
        }
        let parked = std::mem::take(&mut self.components.parked_methods);
        let mut ran = false;
        for (host, call, method) in parked {
            if self.view_pending(host) {
                self.components.parked_methods.push((host, call, method));
            } else {
                ran = true;
                self.run_rust(RustOp {
                    call,
                    run: RustCall::Method(host, method),
                });
            }
        }
        ran
    }

    /// Whether `host` hosts a component whose view is not made yet.
    fn view_pending(&self, host: NodeId) -> bool {
        self.components
            .instances
            .get(&host)
            .is_some_and(|i| matches!(&i.inner, Inner::Component(inner) if inner.owner().is_none()))
    }

    /// The owner of the nearest component above `host` in the tree (its
    /// view's, or a list cell's row), else none.
    fn owner_above(&self, host: NodeId) -> crate::element::Owner {
        let mut key = self.key(host).ok();
        while let Some(k) = key {
            let parent = self.nodes[k as usize].parent;
            if parent == NO_KEY {
                break;
            }
            key = Some(parent);
            // A component may return another component as its root. The
            // innermost one owns the content's placement context.
            let id = self.base_of(self.nodes[parent as usize].id);
            // What JS made is under a component through its JS children:
            // under where it places them.
            let owner = self
                .components
                .instances
                .get(&id)
                .and_then(|inst| match &inst.inner {
                    Inner::Component(inner) => inst
                        .children_owner
                        .filter(|o| o.is_live())
                        .or_else(|| inner.owner().filter(|o| o.is_live())),
                    _ => inst.cell_owner,
                });
            if let Some(owner) = owner {
                return owner;
            }
        }
        crate::element::Owner::detached()
    }

    /// The owner a component JS made in a window JS opened renders under
    /// when no component is above it: one per window, providing its ref,
    /// so [`crate::element::desktop::current_window`] is that window (its
    /// title bar area, its dialogs). `None` in the main window.
    fn js_window_owner(&mut self, host: NodeId) -> Option<crate::element::Owner> {
        let key = self.key(host).ok()?;
        let window = self.key_window(key);
        if window == ROOT_ID {
            return None;
        }
        if let Some((owner, _)) = self.components.js_windows.get(&window)
            && owner.is_live()
        {
            return Some(*owner);
        }
        let id = self
            .window_ids
            .iter()
            .find_map(|(id, (node, _))| (*node == window).then(|| id.clone()))?;
        let reported = self
            .components
            .window_reports
            .get(&window)
            .copied()
            .unwrap_or_default();
        let (owner, this) =
            crate::element::desktop::js_window(&id, window, &self.components.executor, reported);
        self.components.js_windows.insert(window, (owner, this));
        Some(owner)
    }

    /// The host of the component that runs once whose owner is `owner`, or
    /// whose view made it (a binding's own owner is under the component's).
    fn host_of_owner(&self, owner: crate::element::Owner) -> Option<NodeId> {
        let mut at = Some(owner);
        while let Some(owner) = at {
            let host =
                self.components
                    .instances
                    .iter()
                    .find_map(|(&host, inst)| match &inst.inner {
                        Inner::Component(inner) if inner.owner() == Some(owner) => Some(host),
                        _ => None,
                    });
            if host.is_some() {
                return host;
            }
            at = owner.parent();
        }
        None
    }

    /// The window the component that runs once under `owner` shows in (its
    /// root node), the main window's when there is none.
    fn window_of_owner(&self, owner: crate::element::Owner) -> NodeId {
        if self.window_ids.is_empty() {
            return crate::ROOT_ID;
        }
        self.host_of_owner(owner)
            .and_then(|host| self.key(host).ok())
            .map_or(crate::ROOT_ID, |key| self.key_window(key))
    }

    /// Makes `inst`'s view on `host` (once: a view made already takes its
    /// slots, children and styles), or builds a list cell's row again; what
    /// its code panicked with, if it did.
    fn render(&mut self, host: NodeId, inst: &mut Instance) -> Option<String> {
        let mut failure = None;
        let el = match &mut inst.inner {
            Inner::Component(inner) => {
                // What the app passed, as props.
                if let Some(spec) = &inst.spec {
                    for name in spec.slots() {
                        let filled = inst.slots.iter().any(|(s, node)| {
                            *s == name
                                && self
                                    .key(*node)
                                    .is_ok_and(|k| !self.nodes[k as usize].children.is_empty())
                        }) || inst
                            .fills
                            .iter()
                            .any(|f| f.name == name && !self.fill_nodes(f).is_empty());
                        inner.set_slot(name, filled);
                    }
                }
                inner.set_children(!inst.js_children.is_empty());
                // Its view is made: its props now reach what read them, and
                // the app's (or its parent's) styles may have changed.
                if inst.root.is_some() && !std::mem::take(&mut inst.remake) {
                    self.restyle_view(host, inst);
                    return None;
                }
                let owner = self.owner_above(host);
                let owner = if owner.is_live() {
                    owner
                } else {
                    self.js_window_owner(host).unwrap_or(owner)
                };
                inner.adopt(owner);
                // A view that fails shows nothing.
                caught(|| inner.view()).unwrap_or_else(|message| {
                    failure = Some(message);
                    ElNode::empty_view()
                })
            }
            // The cell itself stays the list's: the wrapper goes inside.
            Inner::Row { place, index } => {
                let (place, index) = (place.clone(), *index);
                let count = self.rows_of_cell(host);
                let list = self.list_of(host);
                // The wrapper reads its position from signals.
                let count_signal = list.map(|list| self.list_count(list, count));
                let moves = list
                    .and_then(|list| self.components.virtual_lists.get(&list))
                    .and_then(|state| state.moves);
                let made = std::cell::Cell::new(None);
                let build = || {
                    let at = row_position(index, count, count_signal, moves, &made);
                    view().child(place(Child::row(), at)).into_element().0
                };
                // The wrapper is the placing component's.
                let parent = self.list_component_owner(list);
                let el = self.build_cell(parent, inst, build);
                inst.row_index = made.take();
                if let (Some(list), Some(index), Some(owner)) =
                    (list, inst.row_index, inst.cell_owner)
                    && let Some(state) = self.components.virtual_lists.get(&list)
                {
                    state.rows.borrow_mut().insert(host, (index, owner));
                }
                match el {
                    Ok(el) => el,
                    Err(message) => {
                        failure = Some(message);
                        ElNode::empty_view()
                    }
                }
            }
            Inner::VirtualRow { list, index } => {
                let (list, index) = (*list, *index);
                let inverted = self
                    .key(list)
                    .ok()
                    .and_then(|k| self.nodes[k as usize].list.as_ref())
                    .is_some_and(|l| l.inverted);
                let state = self.components.virtual_lists.get(&list).map(|state| {
                    // The run that made the list went (its view goes in
                    // this commit): no row is made under it.
                    let scope = state.scope.get();
                    let gone = scope.is_some_and(|s| !s.is_live());
                    (
                        if gone { 0 } else { state.count as usize },
                        state.row.clone(),
                        state.separator.clone(),
                        state.rows.clone(),
                        scope,
                        state.moves,
                    )
                });
                match state {
                    // The row is gone (the list shrank): the cell shows
                    // nothing until the list unbinds it or binds it to a
                    // row again; the row function is never asked for a
                    // row past the end.
                    Some((count, ..)) if index >= count => {
                        if let Some(owner) = inst.cell_owner.take() {
                            owner.dispose();
                        }
                        inst.row_index = None;
                        ElNode::empty_view()
                    }
                    Some((count, row, separator, rows, scope, moves)) => {
                        let count_signal = Some(self.list_count(list, count));
                        let made = std::cell::Cell::new(None);
                        let build = || {
                            let at = row_position(index, count, count_signal, moves, &made);
                            let row = row(at);
                            // Between rows: after each but the last (before
                            // it, inverted), while it is not.
                            let separator = separator.map(|s| {
                                crate::element::when(move || !at.is_last(), move || s())
                                    .into_element()
                            });
                            match separator {
                                Some(s) if inverted => view().child(s).child(row),
                                Some(s) => view().child(row).child(s),
                                None => view().child(row),
                            }
                            .into_element()
                            .0
                        };
                        // Under the run that made the list, also when the
                        // row is inside another component's wrapper (an
                        // `Items` prop): the list is known here, not from
                        // the cell's parent.
                        let parent = scope.unwrap_or_else(|| self.list_component_owner(Some(list)));
                        let el = self.build_cell(parent, inst, build);
                        inst.row_index = made.take();
                        if let (Some(index), Some(owner)) = (inst.row_index, inst.cell_owner) {
                            rows.borrow_mut().insert(host, (index, owner));
                        }
                        match el {
                            Ok(el) => el,
                            Err(message) => {
                                failure = Some(message);
                                ElNode::empty_view()
                            }
                        }
                    }
                    None => ElNode::empty_view(),
                }
            }
            Inner::Missing => ElNode::empty_view(),
        };
        // The view binds under its owner.
        let owner = match &inst.inner {
            Inner::Component(inner) => inner.owner(),
            _ => inst.cell_owner,
        };
        match owner {
            Some(owner) => owner.run(|| self.expand_root(host, inst, el)),
            None => self.expand_root(host, inst, el),
        }
        failure
    }

    /// Builds a list cell's row with `build` under an owner of the cell's
    /// own (the previous row's goes), made under `parent` so the row sees
    /// its context.
    fn build_cell(
        &mut self,
        parent: crate::element::Owner,
        inst: &mut Instance,
        build: impl FnOnce() -> ElNode,
    ) -> Result<ElNode, String> {
        if let Some(owner) = inst.cell_owner.take() {
            owner.dispose();
        }
        let (owner, el) = parent.run(|| crate::element::create_root(|| caught(build)));
        inst.cell_owner = Some(owner);
        el
    }

    /// The owner of the component whose list `list` is (its own list, or
    /// the list it places another component's `Items` in).
    fn list_component_owner(&self, list: Option<NodeId>) -> crate::element::Owner {
        let component = list
            .and_then(|list| {
                self.components
                    .virtual_lists
                    .get(&list)
                    .map(|s| s.owner)
                    .or_else(|| self.components.slot_hosts.get(&list).copied())
            })
            .and_then(|host| self.components.instances.get(&host))
            .and_then(|inst| match &inst.inner {
                Inner::Component(inner) => inner.owner(),
                _ => None,
            });
        component.unwrap_or_else(crate::element::Owner::detached)
    }

    /// The text content `new` of node `id` (of `host`'s view), its raw
    /// text node made, changed or released from `old`.
    fn reconcile_text(
        &mut self,
        id: NodeId,
        host: NodeId,
        new: Option<SharedString>,
        old: Option<(SharedString, NodeId)>,
    ) -> Option<(SharedString, NodeId)> {
        match (new, old) {
            (Some(content), Some((old, raw))) => {
                if content != old {
                    let _ = self.apply_op(Op::SetText {
                        id: raw,
                        text: content.as_str().to_owned(),
                    });
                }
                Some((content, raw))
            }
            (Some(content), None) => {
                let raw = self.components.alloc();
                let _ = self.apply_op(Op::CreateText {
                    id: raw,
                    text: content.as_str().to_owned(),
                });
                self.components.owners.insert(raw, host);
                let _ = self.apply_op(Op::Insert {
                    parent: id,
                    child: raw,
                    before: None,
                });
                Some((content, raw))
            }
            (None, Some((_, raw))) => {
                self.release_id(raw);
                None
            }
            (None, None) => None,
        }
    }

    /// Applies a view's root `el` to `host` itself (over a list cell's
    /// previous row) and expands its children. A view's root can be any
    /// element: the host becomes its node (a screen, a modal, a text, a
    /// list), holds it (a region), or is the host of a component as the
    /// root ([`Self::expand_rooted`]).
    fn expand_root(&mut self, host: NodeId, inst: &mut Instance, mut el: ElNode) {
        if matches!(el.kind, ElKind::Component(_))
            && matches!(inst.inner, Inner::Component(_))
            && inst
                .root
                .as_ref()
                .is_none_or(|r| matches!(r.part, Part::Component(_)))
        {
            return self.expand_rooted(host, inst, el);
        }
        let node = matches!(el.kind, ElKind::Plain | ElKind::VirtualList(_));
        if !node || (el.tag != Tag::View && !self.retag(host, el.tag)) {
            if node {
                log::error!(target: "js", "a component's root takes its kind only when it is first mounted; it is placed in a view");
            }
            let inner = std::mem::replace(&mut el, ElNode::new(Tag::View));
            el.children.push(inner);
        }
        if !el.children.is_empty()
            && let Some(content) = el.bound_text.take()
        {
            let mut first = ElNode::new(Tag::Text);
            first.text = Some(SharedString::default());
            first.bound_text = Some(content);
            el.text = None;
            el.children.insert(0, first);
        }
        // Bound parts are bound first: what they read now is applied with
        // the static parts.
        let applied_layout = if matches!(el.kind, ElKind::VirtualList(_)) {
            self.components.list_layouts.remove(&host)
        } else {
            None
        };
        let bound = super::views::Bound::take(&mut el).map(|bound| {
            self.bind_parts(host, host, bound, &mut el);
        });
        inst.handlers.clear();
        inst.event_handlers.clear();
        inst.responders.clear();
        let old = inst.root.take();
        let first = old.is_none();
        let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
        // The root is the host itself.
        let (old_attrs, old_style, old_classes, old_events, old_children, old_text, old_list) =
            match old {
                Some(e) => (
                    e.attrs,
                    e.style,
                    e.classes,
                    e.events,
                    e.children,
                    e.text,
                    e.list.map(|l| *l).unwrap_or_default(),
                ),
                None => (
                    Attrs::default(),
                    StyleRefinement::default(),
                    (None, None),
                    EventMask::default(),
                    Vec::new(),
                    None,
                    ListConfig::default(),
                ),
            };
        // What the views above give it and the components on its host, the
        // outer last.
        let cx = self.root_context(inst);
        let app = if cx.combined {
            cx.app.as_ref()
        } else {
            inst.app_style.as_ref()
        };
        let attrs = cx.over(el.attrs.clone());
        // As it was applied: with the insets its node got.
        let mut old_over = old_attrs.clone();
        old_over.set_insets(inst.root_insets_applied);
        let old_over = with_host(old_over, &inst.root_host_applied);
        if !self.apply_target_attrs(host, &attrs, &old_over, app) {
            self.apply_attrs_over(host, &attrs, &old_over, app);
        }
        inst.root_insets_applied = attrs.insets();
        inst.root_host_applied = cx.host.clone();
        // Given an inline style or animated values while its own did not
        // change: they go now.
        let given_changed = std::mem::take(&mut inst.given_changed) || first;
        if cx.given
            && given_changed
            && attrs.inline == old_over.inline
            && attrs.animated() == old_over.animated()
        {
            let _ = self.apply_op(inline_style(
                host,
                attrs.inline.as_deref(),
                attrs.animated(),
                app,
            ));
        }
        let user = cx.user.clone();
        let top_js = cx.js;
        let given_events = cx.given_events;
        let classes = self.apply_el_styles(
            host,
            &el.style,
            &old_style,
            old_classes,
            el.attrs.class.as_ref(),
            user,
        );
        let text = self.reconcile_text(host, host, el.text.take(), old_text);
        if bound.is_some() {
            Self::keep_bound(
                inst,
                host,
                &el.attrs,
                &el.style,
                classes.clone(),
                text.clone(),
            );
        }
        // The host listens to its component's events, JS's and those the
        // views above give it.
        let js = top_js.unwrap_or(inst.js_events) | given_events;
        self.apply_handlers(host, host, &el, old_events | js, js, inst);
        let mut events = EventMask::default();
        for (kind, _) in &el.handlers {
            events.set(*kind, true);
        }
        events.set(
            EventKind::Touch,
            events.contains(EventKind::Touch) || el.responder.is_some(),
        );
        let new_children = std::mem::take(&mut el.children);
        let children = self.reconcile_children(host, old_children, new_children, host, inst);
        let (list, part) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
            ElKind::VirtualList(list) => {
                let config = list.config;
                let old_list = applied_layout.unwrap_or(old_list);
                self.update_virtual_list(self.native_id(host), host, *list, &old_list);
                (Some(Box::new(config)), Part::VirtualList)
            }
            _ => (None, Part::Node),
        };
        inst.root = Some(Expanded {
            id: host,
            tag: el.tag,
            key: None,
            text,
            attrs: el.attrs,
            style: el.style,
            classes,
            events,
            list,
            part,
            children,
        });
        self.children_placed(host, inst, old_place);
    }

    /// [`Self::expand_root`] of a view whose root is component element
    /// `el`: that component is made on `host` itself, under an alias of its
    /// node ([`Core::alias`]), and its view makes the node, with what this
    /// view gives it (props, styles, listeners, ref, content) and what the
    /// app gives this one (styles, events): no node of its own.
    fn expand_rooted(&mut self, host: NodeId, inst: &mut Instance, el: ElNode) {
        let ElKind::Component(c) = &el.kind else {
            return;
        };
        let part = Part::Component(c.name);
        inst.handlers.clear();
        inst.event_handlers.clear();
        inst.responders.clear();
        let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
        let prev = match inst.root.take() {
            Some(old) if old.part == part => old,
            old => {
                if let Some(old) = old {
                    self.release_expanded(old);
                }
                let id = self.components.alloc();
                if let Err(e) = self.alias(id, host) {
                    log::error!(target: "js", "a view's root component is not made: {e:?}");
                    return;
                }
                self.components.owners.insert(id, host);
                self.create_instance_for(id, c);
                if let Some(rooted) = self.components.instances.get_mut(&id) {
                    // The app's style is the top host's.
                    rooted.app_style = None;
                    rooted.above = Some(host);
                }
                Expanded::js(id, part)
            }
        };
        inst.rooted = Some(prev.id);
        let root = self.reconcile_node(Some(prev), el, part, host, inst);
        inst.root = Some(root);
        self.children_placed(host, inst, old_place);
    }

    /// The component whose view makes host `id`'s node: its own, or the
    /// one its view's root is (as deep as roots are components).
    pub(super) fn base_of(&self, id: NodeId) -> NodeId {
        let mut at = id;
        while let Some(next) = self.components.instances.get(&at).and_then(|i| i.rooted) {
            at = next;
        }
        at
    }

    /// What `inst`'s root takes besides its own: the styles, inline styles,
    /// animated values and insets the views above give it and the
    /// components whose views' roots it is (the outer last), the app's
    /// style and JS's events on the top host.
    pub(super) fn root_context(&mut self, inst: &Instance) -> RootContext {
        let mut cx = RootContext {
            user: inst.user.clone(),
            combined: false,
            app: None,
            js: None,
            given_events: inst.given_events,
            inset_padding: None,
            inset_margin: None,
            host: Vec::new(),
            given: false,
        };
        if inst.above.is_none() && inst.given.is_none() {
            cx.host.clone_from(&inst.js_host);
            return cx;
        }
        cx.combined = true;
        let mut decls: Vec<crate::StyleDecl> = Vec::new();
        let mut take = |cx: &mut RootContext, given: &Attrs| {
            cx.given = true;
            if let Some(inline) = &given.inline {
                decls.extend(inline.decls().iter().cloned());
            }
            if let Some(r) = &given.rare {
                decls.extend(r.animated.iter().map(|(d, _)| d.clone()));
                cx.inset_padding = r.inset_padding.or(cx.inset_padding);
                cx.inset_margin = r.inset_margin.or(cx.inset_margin);
            }
            given_host(given, &mut cx.host);
        };
        if let Some(given) = &inst.given {
            take(&mut cx, given);
        }
        // The classes the element was given in Rust (`app_class`), as the
        // app's `class` on its host.
        if let Some(class) = inst.given.as_ref().and_then(|g| g.class.clone()) {
            let given = self.app_class_list(&class);
            cx.user = self.merge_user(cx.user.take(), Some(given));
        }
        let mut app = inst.app_style.clone();
        // JS's on the top host.
        let mut js_host = None;
        let mut at = inst.above;
        while let Some(id) = at {
            let Some(above) = self.components.instances.get(&id) else {
                break;
            };
            let (outer, given) = (above.user.clone(), above.given.clone());
            app = above.app_style.clone();
            js_host = Some(above.js_host.clone());
            cx.js = Some(above.js_events);
            cx.given_events = cx.given_events | above.given_events;
            at = above.above;
            if let Some(given) = &given {
                take(&mut cx, given);
            }
            cx.user = self.merge_user(cx.user.take(), outer);
            if let Some(class) = given.and_then(|g| g.class.clone()) {
                let given = self.app_class_list(&class);
                cx.user = self.merge_user(cx.user.take(), Some(given));
            }
        }
        for prop in js_host.as_ref().unwrap_or(&inst.js_host) {
            give_host(&mut cx.host, prop.clone());
        }
        if let Some(app) = &app {
            decls.extend(app.decls().iter().cloned());
        }
        if !decls.is_empty() {
            let mut style = crate::Style::default();
            let mut patch = crate::StylePatch::default();
            for decl in decls {
                let _ = patch.push(&mut style, decl);
            }
            cx.app = Some(patch);
        }
        cx
    }

    /// [`Self::root_context`] of the component hosted by `host`.
    pub(super) fn root_context_of(&mut self, host: NodeId) -> Option<RootContext> {
        let inst = self.components.instances.remove(&host)?;
        let cx = self.root_context(&inst);
        self.components.instances.insert(host, inst);
        Some(cx)
    }

    /// What the view `host` is in gives its element besides styles is `attrs`:
    /// its root takes them.
    pub(super) fn set_given(&mut self, host: NodeId, mut attrs: Attrs) {
        attrs.set_element_ref(None);
        let given = (attrs != Attrs::default()).then(|| Box::new(attrs));
        let Some(inst) = self.components.instances.get_mut(&host) else {
            return;
        };
        if inst.given != given {
            inst.given = given;
            inst.given_changed = true;
            self.components.mark(host);
        }
    }

    /// `inner`'s rules, then `outer`'s (one list per pair, kept).
    pub(super) fn merge_user(
        &mut self,
        inner: Option<std::rc::Rc<ClassList>>,
        outer: Option<std::rc::Rc<ClassList>>,
    ) -> Option<std::rc::Rc<ClassList>> {
        match (inner, outer) {
            (Some(a), Some(b)) => {
                let key = (
                    std::rc::Rc::as_ptr(&a) as usize,
                    std::rc::Rc::as_ptr(&b) as usize,
                );
                if let Some([_, _, merged]) = self.components.merges.get(&key) {
                    return Some(merged.clone());
                }
                if self.components.merges.len() >= STYLE_CACHE {
                    self.components.merges.clear();
                }
                let merged = std::rc::Rc::new(a.merged(&b));
                self.components.merges.insert(key, [a, b, merged.clone()]);
                Some(merged)
            }
            (a, None) => a,
            (None, b) => b,
        }
    }

    /// Where the JS children of `host` go changed from `old_place`: they
    /// leave the tree when nothing places them, and lazy ones are asked for
    /// or dropped.
    pub(super) fn children_placed(
        &mut self,
        host: NodeId,
        inst: &mut Instance,
        old_place: Placement,
    ) {
        // No `Children` any more: the JS children leave the tree.
        if inst.children_at == Placement::None && old_place != Placement::None {
            for &child in &inst.js_children {
                self.unplace(old_place, child);
            }
        }
        // Lazy children are made while the view places them: by JS, or by
        // the view this one is in (what passes them reads a signal).
        let wanted = inst.children_at != Placement::None;
        if inst.children_wanted != wanted && inst.spec.as_ref().is_some_and(|s| s.lazy_children) {
            inst.children_wanted = wanted;
            match self.components.owners.get(&host).copied() {
                // A view's: what passes them follows (a view that passes
                // none made no signal). The run of the view that passed
                // them may be gone already, in this commit, before what it
                // made is released: a region of this component and the one
                // passing its children changed together (a menu and its
                // submenu ending their exits at once). Nothing reads its
                // signal then.
                Some(_) => {
                    if let Some(signal) = inst.lazy_wanted {
                        signal.try_set(wanted);
                    }
                }
                None => self.events.push(JsEvent::Children { host, wanted }),
            }
        }
    }

    /// The signal of whether the component hosted by `nested` places its
    /// lazy children, made under the current owner (the view passing them)
    /// the first time.
    fn children_wanted_signal(&mut self, nested: NodeId) -> crate::element::Signal<bool> {
        let Some(inst) = self.components.instances.get_mut(&nested) else {
            return crate::element::signal(false);
        };
        // Made again under this owner when the one that made it is gone
        // (the run that passed them before was disposed while the
        // component stayed).
        match inst.lazy_wanted {
            Some(signal) if signal.is_live() => signal,
            _ => {
                let signal = crate::element::signal(inst.children_wanted);
                inst.lazy_wanted = Some(signal);
                signal
            }
        }
    }

    /// JS child `child`, placed at `place`, leaves the tree (and the
    /// nested component it was passed on to).
    fn unplace(&mut self, place: Placement, child: NodeId) {
        match place {
            Placement::Nested(nested, _) if self.is_host(nested) => {
                let _ = self.intercept(Op::Remove {
                    parent: nested,
                    child,
                });
            }
            _ => self.detach_id(child),
        }
    }

    pub(super) fn detach_id(&mut self, id: NodeId) {
        self.unfold_run(id);
        if let Ok(key) = self.key(id)
            && self.nodes[key as usize].parent != NO_KEY
        {
            self.detach(key);
        }
    }

    pub(super) fn apply_attrs(&mut self, id: NodeId, new: &Attrs, old: &Attrs) {
        self.apply_attrs_over(id, new, old, None);
    }

    /// [`Self::apply_attrs`] for a host: the app's style goes after the
    /// root's (and is sent again with it).
    pub(super) fn apply_attrs_over(
        &mut self,
        id: NodeId,
        new: &Attrs,
        old: &Attrs,
        app: Option<&crate::StylePatch>,
    ) {
        // An element's ref names its node by its own id.
        let node = self.native_id(id);
        let has_rare = new.rare.is_some() || old.rare.is_some();
        if has_rare {
            let empty = crate::element::builder::RareAttrs::default();
            let nr = new.rare.as_deref().unwrap_or(&empty);
            let or = old.rare.as_deref().unwrap_or(&empty);
            if or.element_ref != nr.element_ref
                && let Some(r) = &or.element_ref
            {
                r.detach(node);
            }
            if let Some(r) = &nr.element_ref {
                r.attach(node);
            }
            if nr.render != or.render {
                self.update_render(node, or.render.as_ref(), nr.render.as_ref());
            }
        }
        let mut props = std::mem::take(&mut self.components.props);
        new.changes(old, &mut props);
        for prop in props.drain(..) {
            let _ = self.apply_op(Op::SetProp { id, prop });
        }
        self.components.props = props;
        let animated_changed = has_rare && new.animated() != old.animated();
        if new.inline != old.inline || animated_changed {
            let _ = self.apply_op(inline_style(id, new.inline.as_deref(), new.animated(), app));
        }
        if has_rare {
            let empty = crate::element::builder::RareAttrs::default();
            let nr = new.rare.as_deref().unwrap_or(&empty);
            let or = old.rare.as_deref().unwrap_or(&empty);
            if nr.drawing != or.drawing
                && let Some(drawing) = &nr.drawing
            {
                let _ = self.apply_op(Op::Draw {
                    id,
                    drawing: Box::new((**drawing).clone()),
                });
            }
            if nr.window != or.window
                && let Some(window) = &nr.window
            {
                // Opened once; then only its attributes follow (the record sends
                // what changed).
                let command = if or.window.is_none() {
                    crate::desktop::DesktopCommand::OpenWindow(Box::new(
                        crate::desktop::OpenWindow {
                            options: (**window).clone(),
                            ..Default::default()
                        },
                    ))
                } else {
                    crate::desktop::DesktopCommand::SetAttributes(Box::new(
                        window.attributes.clone(),
                    ))
                };
                let opens = or.window.is_none();
                let _ = self.apply_op(Op::Command {
                    id,
                    command: crate::Command::Desktop(Box::new(command)),
                });
                // What its ref was asked for before it existed follows its
                // opening, in order (`open_window(..)` then `focus()`).
                if opens {
                    for command in &nr.window_commands {
                        let _ = self.apply_op(Op::Command {
                            id,
                            command: crate::Command::Desktop(Box::new(command.clone())),
                        });
                    }
                }
            }
        }
    }

    /// Sets node `id`'s classes: `style` lowered, then `user` (a host's).
    pub(super) fn apply_styles(
        &mut self,
        id: NodeId,
        style: &StyleRefinement,
        old_style: &StyleRefinement,
        old: Classes,
        user: Option<std::rc::Rc<ClassList>>,
    ) -> Classes {
        let own = if style == old_style {
            old.0.clone()
        } else if style.is_empty() {
            None
        } else {
            Some(self.components.lowered(style))
        };
        if !same(&own, &old.0) || !same(&user, &old.1) {
            let list = self.merge_user(own.clone(), user.clone());
            if let Ok(key) = self.key(id) {
                self.set_class_list(key, list);
            }
        }
        (own, user)
    }

    /// [`Self::apply_styles`] for an element of a view: the app's classes
    /// it carries (`class`, [`crate::element::Element::app_class`]) go after its
    /// own styles, then `outer` (a root's: what the views and the app give
    /// its host).
    pub(super) fn apply_el_styles(
        &mut self,
        id: NodeId,
        style: &StyleRefinement,
        old_style: &StyleRefinement,
        old: Classes,
        class: Option<&SharedString>,
        outer: Option<std::rc::Rc<ClassList>>,
    ) -> Classes {
        let Some(class) = class.filter(|c| !c.trim().is_empty()) else {
            if !self.components.app_classes.is_empty() {
                self.components.app_classes.remove(&id);
            }
            return self.apply_styles(id, style, old_style, old, outer);
        };
        let app = self.app_class_list(class);
        let user = self.merge_user(Some(app), outer.clone());
        let classes = self.apply_styles(id, style, old_style, old, user);
        self.components
            .app_classes
            .insert(id, (classes.0.clone(), class.clone(), outer));
        classes
    }

    /// The rules of the app's classes `class` (the unknown ones warned of
    /// once, as a host's).
    pub(super) fn app_class_list(&mut self, class: &str) -> std::rc::Rc<ClassList> {
        let (list, fresh) = self.tailwind.get(class);
        if fresh && !list.unknown().is_empty() {
            log::warn!(
                "unknown classes: {}",
                list.unknown()
                    .iter()
                    .map(|s| &**s)
                    .collect::<Vec<_>>()
                    .join(" ")
            );
        }
        list
    }

    /// Registers `el`'s handlers for node `id` and listens to their events
    /// (plus `extra`, what JS listens to on a host); returns the mask.
    #[allow(
        clippy::too_many_arguments,
        reason = "the installed node and its owning view"
    )]
    fn apply_handlers(
        &mut self,
        host: NodeId,
        id: NodeId,
        el: &ElNode,
        old: EventMask,
        extra: EventMask,
        inst: &mut Instance,
    ) -> EventMask {
        let mut mask = extra;
        self.initialize_layout_listeners(host, id, el, old, inst);
        // A node made again (its region ran again) hears what this run
        // gives it, not also what the runs before gave it.
        if old.bits() != 0 {
            inst.handlers.remove(id);
            inst.responders.retain(|(n, _)| *n != id);
        }
        for (kind, handler) in &el.handlers {
            mask.set(*kind, true);
            inst.handlers.push(id, *kind, handler.clone());
        }
        // The responder hears the touches the platform reports.
        if let Some(responder) = &el.responder {
            mask.set(EventKind::Touch, true);
            inst.responders.push((id, responder.clone()));
        }
        // Only the events that changed (with a slot's own when the node
        // takes a slot's props: they stay).
        let own = self.target_events(id, mask);
        let mut changed = (mask.bits() ^ old.bits()) & !own.bits();
        while changed != 0 {
            let kind = EventKind::ALL[changed.trailing_zeros() as usize];
            changed &= changed - 1;
            let _ = self.apply_op(Op::Listen {
                id,
                event: kind,
                enabled: mask.contains(kind),
            });
        }
        mask
    }

    /// Queues the current frame for listeners belonging to a new region run.
    pub(super) fn initialize_layout_listeners(
        &mut self,
        host: NodeId,
        id: NodeId,
        el: &ElNode,
        old: EventMask,
        inst: &Instance,
    ) {
        // Only listeners of a new owner need the kept node's initial
        // frame. A listener passed in from outside the region stays live.
        if old.contains(EventKind::Layout)
            && let Ok(key) = self.key(id)
        {
            let frame = self.nodes[key as usize].frame;
            if !frame.origin.x.0.is_nan() {
                for (kind, listener) in &el.handlers {
                    if *kind == EventKind::Layout
                        && !inst
                            .handlers
                            .of(id)
                            .iter()
                            .any(|(k, old)| *k == *kind && old.same_owner(listener))
                    {
                        self.events.push(JsEvent::LayoutListener {
                            host,
                            id,
                            listener: listener.clone(),
                            frame,
                        });
                    }
                }
            }
        }
    }

    fn reconcile_children(
        &mut self,
        parent: NodeId,
        old: Vec<Expanded>,
        new: Vec<ElNode>,
        host: NodeId,
        inst: &mut Instance,
    ) -> Vec<Expanded> {
        if new.is_empty() && old.is_empty() {
            return Vec::new();
        }
        let new = new.into_iter().map(|el| NewChild::Made(None, el)).collect();
        let (out, placeholder) = self.match_children(parent, old, new, host, inst);
        // A region's nodes go before what follows it.
        self.set_region_anchors(&out, inst, Anchor::End);
        let nested = parent != host && self.is_host(parent);
        if nested {
            if let Some(at) = placeholder {
                let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
                inst.children_at = Placement::Nested(parent, anchor);
            }
            self.place_filled(&out, inst, Anchor::End, |anchor| {
                Placement::Nested(parent, anchor)
            });
            self.fill_nested(parent, &out, host, inst);
            self.join_nested(parent, &out, inst);
            return out;
        }
        if let Some(at) = placeholder {
            let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
            inst.children_at = Placement::At(parent, anchor);
        }
        self.place_filled(&out, inst, Anchor::End, |anchor| {
            Placement::At(parent, anchor)
        });
        // The native children in the view's order: the JS children in the
        // placeholder's place, a region's nodes in its (moves only when the
        // order changed).
        let wanted_ids: Vec<NodeId> = out
            .iter()
            .flat_map(|e| match e.part {
                Part::Children => inst.js_children.clone(),
                Part::Filled(name) => self
                    .fill_of(inst, name)
                    .map(|f| self.fill_nodes(f))
                    .unwrap_or_default(),
                Part::Region(region) => self.region_nodes(region),
                _ => vec![e.id],
            })
            .collect();
        let wanted = || wanted_ids.iter();
        // A list positions its cells itself: their order does not matter
        // (and the cells it binds are not the view's), new ones join it.
        if self.is_list(parent) {
            // (A region's nodes join it as they come.)
            for e in out.iter().filter(|e| e.id != 0) {
                let joined = self
                    .key(e.id)
                    .is_ok_and(|k| self.nodes[k as usize].parent != NO_KEY);
                if !joined {
                    let _ = self.apply_op(Op::Insert {
                        parent,
                        child: e.id,
                        before: None,
                    });
                }
            }
            return out;
        }
        let in_order = self.key(parent).is_ok_and(|k| {
            let have = &self.nodes[k as usize].children;
            have.len() == wanted().count()
                && have
                    .iter()
                    .zip(wanted())
                    .all(|(&c, &id)| self.nodes[c as usize].id == id)
        });
        if !in_order {
            // From the end, each child before the one after it: only the
            // children out of place move. Moving a native view takes it
            // out of the window for a moment, which ends its touches and
            // its focus (Android: an input that gains a sibling would lose
            // the keyboard on each keystroke).
            let ids: Vec<NodeId> = wanted().copied().collect();
            // A first fill appends them in order: no child to find its place
            // among (from the end, each would scan the ones placed already).
            let empty = self
                .key(parent)
                .is_ok_and(|k| self.nodes[k as usize].children.is_empty());
            if empty {
                for &child in &ids {
                    let _ = self.apply_op(Op::Insert {
                        parent,
                        child,
                        before: None,
                    });
                }
                return out;
            }
            let mut before = None;
            for &child in ids.iter().rev() {
                if !self.precedes(parent, child, before) {
                    let _ = self.apply_op(Op::Insert {
                        parent,
                        child,
                        before,
                    });
                }
                before = Some(child);
            }
        }
        out
    }

    /// Matches `new` with the `old` elements of `parent` and applies them;
    /// releases the old ones left. The elements as applied, and where the
    /// JS children go among them.
    pub(super) fn match_children(
        &mut self,
        parent: NodeId,
        old: Vec<Expanded>,
        new: Vec<NewChild>,
        host: NodeId,
        inst: &mut Instance,
    ) -> (Vec<Expanded>, Option<usize>) {
        // `children_each`: one wrapper per JS child, keyed by it; in a view,
        // a region following them.
        let new = if new.iter().any(
            |child| matches!(child, NewChild::Made(_, e) if matches!(e.kind, ElKind::EachChild(_))),
        ) {
            let mut each = Vec::with_capacity(new.len() + inst.js_children.len());
            for child in new {
                let NewChild::Made(owner, el) = child else {
                    each.push(child);
                    continue;
                };
                let ElKind::EachChild(place) = &el.kind else {
                    each.push(NewChild::Made(owner, el));
                    continue;
                };
                if inst.children_at != Placement::None {
                    log::error!(target: "js", "a view places its children once");
                    continue;
                }
                inst.children_at = Placement::Each;
                {
                    let children = match inst.js_kids {
                        Some(children) => children,
                        None => *inst.js_kids.insert(crate::element::signal_with(
                            inst.js_kids(),
                            crate::element::SignalEquals::Never,
                        )),
                    };
                    // A wrapper per child, kept while the child stays; its
                    // position follows it.
                    let place = place.clone();
                    let count = crate::element::computed(move || children.with(Vec::len));
                    let region = crate::element::each(
                        children,
                        |&(child, _): &(NodeId, bool)| child,
                        move |child, index| {
                            let at = Position::of(index.node(), count.node());
                            let (child, text) = child.get_untracked();
                            place(Child::js(child, text), at)
                        },
                    );
                    each.push(NewChild::Made(owner, region.0));
                }
            }
            each
        } else {
            new
        };
        let mut old: Vec<Option<Expanded>> = old.into_iter().map(Some).collect();
        let mut out = Vec::with_capacity(new.len());
        let mut placeholder = None;
        // Unkeyed elements take the next unused old element of their kind,
        // in order: an element that comes or goes (`.children(option)`)
        // does not shift its siblings onto new nodes.
        let mut cursor = 0;
        // Where the element after the last one kept was: kept rows mostly
        // follow each other as they did, and are then found without a
        // search of all the old ones for each.
        let mut after_kept = 0;
        // The keyed old elements by key, for the rows and elements not
        // where they were (a reversed list: each would search them all).
        let mut keys = OldKeys::default();
        for child in new {
            let (owner, el) = match child {
                NewChild::Made(owner, el) => (owner, el),
                // An `Each` row that stays: as it was. (One old element
                // at most has its key, which is its row's own.)
                NewChild::Kept(key) => {
                    let is = |o: &Option<Expanded>| {
                        o.as_ref().is_some_and(|o| o.key.as_ref() == Some(&key))
                    };
                    let at = if old.get(after_kept).is_some_and(is) {
                        Some(after_kept)
                    } else {
                        keys.find(&old, &key, |_| true)
                    };
                    match at.and_then(|at| {
                        after_kept = at + 1;
                        old[at].take()
                    }) {
                        Some(e) => out.push(e),
                        None => log::error!("a kept row is gone"),
                    }
                    continue;
                }
            };
            let child = |core: &mut Self| {
                core.match_child(
                    parent,
                    el,
                    host,
                    inst,
                    &mut old,
                    &mut out,
                    &mut placeholder,
                    &mut cursor,
                    &mut keys,
                );
            };
            match owner {
                Some(owner) => owner.run(|| child(self)),
                None => child(self),
            }
        }
        // Content of a nested component (`.child`, `.fill`): it leaves and
        // joins the nested host as JS children and slots do, so the nested
        // component's view places it.
        let nested = parent != host && self.is_host(parent);
        for o in old.into_iter().flatten() {
            // What fills a slot this view placed there stays (another
            // view's): it leaves first.
            self.unplace_filled(&o, inst);
            if nested && o.part == Part::Children {
                // The JS children passed on stay (JS's): they leave.
                for &child in &inst.js_children {
                    let _ = self.intercept(Op::Remove { parent, child });
                }
            } else if nested {
                for node in self.placed(&o) {
                    self.forget_nested(parent, node);
                }
            }
            self.release_expanded(o);
        }
        (out, placeholder)
    }

    /// Matches element `el` with one of the `old` elements of `parent` and
    /// applies it (see [`Self::match_children`]).
    #[allow(clippy::too_many_arguments, reason = "the matching's state")]
    fn match_child(
        &mut self,
        parent: NodeId,
        mut el: ElNode,
        host: NodeId,
        inst: &mut Instance,
        old: &mut [Option<Expanded>],
        out: &mut Vec<Expanded>,
        placeholder: &mut Option<usize>,
        cursor: &mut usize,
        keys: &mut OldKeys,
    ) {
        // A slot a view fills: placed as it is (`Filled`), or in a node of
        // this view's own when the view gives it anything, which lays its
        // one node out through while it styles none of its layout (as JS's
        // holders: `lay_out_through`).
        let mut wrapper = false;
        if let ElKind::Slot(name) = el.kind
            && inst.fills.iter().any(|f| f.name == name)
        {
            if is_plain(&el) {
                el.kind = ElKind::Filled(name);
            } else {
                el.kind = ElKind::Plain;
                let mut filled = ElNode::new(Tag::View);
                filled.kind = ElKind::Filled(name);
                el.children = vec![filled];
                el.key.get_or_insert_with(|| format!("slot:{name}").into());
                wrapper = true;
            }
        }
        match std::mem::replace(&mut el.kind, ElKind::Plain) {
            ElKind::Filled(name) => {
                if let Some(j) = old
                    .iter()
                    .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Filled(name)))
                {
                    old[j] = None;
                }
                out.push(Expanded::js(0, Part::Filled(name)));
            }
            ElKind::Fill(name) => {
                // Content of the nested component `parent`, as its children
                // are: nodes of this view, its regions bound here.
                let prev = old
                    .iter()
                    .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Fill(name)))
                    .and_then(|j| old[j].take());
                let old_children = prev.map(|p| p.children).unwrap_or_default();
                let new = std::mem::take(&mut el.children)
                    .into_iter()
                    .map(|c| NewChild::Made(None, c))
                    .collect();
                let filling = self.components.filling.replace((parent, name));
                let (children, _) = self.match_children(parent, old_children, new, host, inst);
                self.components.filling = filling;
                let mut e = Expanded::js(0, Part::Fill(name));
                e.children = children;
                out.push(e);
            }
            ElKind::Slot(name) => {
                // The slot's own node, while the app passes one.
                let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == name) else {
                    return;
                };
                let at = old.iter().position(|o| {
                    o.as_ref()
                        .is_some_and(|o| o.part == Part::Slot && o.id == node)
                });
                let prev = at.and_then(|j| old[j].take());
                out.push(self.reconcile_slot(prev, node, el, host, inst));
            }
            ElKind::Children => {
                if placeholder.is_some() || inst.children_at != Placement::None {
                    log::error!(target: "js", "a view places its children once");
                    return;
                }
                if let Some(j) = old
                    .iter()
                    .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Children))
                {
                    old[j] = None;
                }
                *placeholder = Some(out.len());
                inst.children_owner = Some(crate::element::Owner::current());
                out.push(Expanded::js(0, Part::Children));
            }
            ElKind::JsChild(id) => {
                // Taken over, not released (that would detach it).
                if let Some(j) = old.iter().position(|o| {
                    o.as_ref()
                        .is_some_and(|o| o.part == Part::JsChild && o.id == id)
                }) {
                    old[j] = None;
                }
                if inst.js_children.contains(&id) {
                    out.push(Expanded::js(id, Part::JsChild));
                }
            }
            // Expanded above.
            ElKind::EachChild(_) => {}
            // A view's region: bound, its nodes come with its patches.
            ElKind::Region(region) => {
                let id = self.bind_region(host, parent, region);
                let mut e = super::views::region_placeholder(id);
                // An `Each` row's region keeps its row's key: a run that
                // keeps the row finds it by that key (`NewChild::Kept`).
                e.key = el.key;
                out.push(e);
            }
            ElKind::List(list) => {
                // The glue's list: placed and laid out like a slot,
                // its rows wrapped by this view's row function.
                let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == list.name) else {
                    return;
                };
                let at = old.iter().position(|o| {
                    o.as_ref()
                        .is_some_and(|o| o.part == Part::Slot && o.id == node)
                });
                let prev = at.and_then(|j| old[j].take());
                let old_config = self
                    .components
                    .list_layouts
                    .remove(&node)
                    .or_else(|| prev.as_ref().and_then(|p| p.list.as_deref().copied()))
                    .unwrap_or_default();
                // Its bound layout is a binding.
                let parts = std::mem::take(&mut el.bound_list);
                let config = if parts.is_empty() {
                    list.config
                } else {
                    self.bind_list_layout(node, list.config, parts)
                };
                let mut props = std::mem::take(&mut self.components.props);
                config.changes(&old_config, &mut props);
                for prop in props.drain(..) {
                    let _ = self.apply_op(Op::SetProp { id: node, prop });
                }
                self.components.props = props;
                let mut e = self.reconcile_slot(prev, node, el, host, inst);
                e.list = Some(Box::new(config));
                let rows = self.rows_of_list(node);
                self.components.lists.insert(node, (list.row.clone(), rows));
                // Rows of the component whose view has this one: its
                // cells to come are wrapped too.
                if let Some(state) = self.components.virtual_lists.get_mut(&node) {
                    state.place = Some(list.row.clone());
                }
                let cells: Vec<NodeId> = match self.key(node) {
                    Ok(k) => self.nodes[k as usize]
                        .children
                        .iter()
                        .map(|&c| self.nodes[c as usize].id)
                        .collect(),
                    Err(_) => Vec::new(),
                };
                for cell in cells {
                    self.wrap_row(cell, list.row.clone());
                }
                out.push(e);
            }
            kind => {
                el.kind = kind;
                let part = match &el.kind {
                    ElKind::Component(c) => Part::Component(c.name),
                    ElKind::VirtualList(_) => Part::VirtualList,
                    ElKind::Raw => Part::Raw,
                    _ => Part::Node,
                };
                // A component made again is a new one, as in TSX: it runs
                // once, so an old instance cannot take a new element (its
                // view would keep what it made from the old props).
                let component = matches!(part, Part::Component(_));
                let matches = |o: &Expanded| !component && o.tag == el.tag && o.part == part;
                let at = match &el.key {
                    Some(k) => keys.find(old, k, matches),
                    None => {
                        let at = old[(*cursor).min(old.len())..]
                            .iter()
                            .position(|o| o.as_ref().is_some_and(|o| o.key.is_none() && matches(o)))
                            .map(|j| j + *cursor);
                        if let Some(j) = at {
                            *cursor = j + 1;
                        }
                        at
                    }
                };
                let prev = at.and_then(|j| old[j].take());
                let e = if wrapper {
                    self.reconcile_wrapper(prev, el, host, inst)
                } else {
                    self.reconcile_node(prev, el, part, host, inst)
                };
                out.push(e);
            }
        }
    }

    /// Whether `child` is content of the nested component hosted by
    /// `nested` right before `next` (the last when `next` is `None`).
    pub(super) fn nested_precedes(
        &self,
        nested: NodeId,
        child: NodeId,
        next: Option<NodeId>,
    ) -> bool {
        let Some(inst) = self.components.instances.get(&nested) else {
            return false;
        };
        let kids = &inst.js_children;
        kids.iter()
            .position(|&c| c == child)
            .is_some_and(|i| kids.get(i + 1).copied() == next)
    }

    /// Inserts `child` into the content of the nested component hosted by
    /// `nested`, before `before`, as JS inserts its children.
    pub(super) fn join_nested_at(&mut self, nested: NodeId, child: NodeId, before: Option<NodeId>) {
        if let Ok(Some(op)) = self.intercept(Op::Insert {
            parent: nested,
            child,
            before,
        }) {
            let _ = self.apply_op(op);
        }
    }

    /// Node `child` of this view, about to be released, is no longer
    /// content of the nested component hosted by `nested`: it leaves the
    /// component's children with no native removal (deleting a view
    /// detaches it, as a plain element's does).
    fn forget_nested(&mut self, nested: NodeId, child: NodeId) {
        if self.components.slot_names.remove(&child).is_some() {
            self.unslot(child);
            return;
        }
        let Some(inst) = self.components.instances.get_mut(&nested) else {
            return;
        };
        let count = inst.js_children.len();
        inst.forget_js_child(child);
        if inst.js_children.len() == count {
            return;
        }
        inst.js_children_changed();
        let place = inst.children_at;
        if inst.js_children.is_empty() || place == Placement::Each {
            self.components.mark(nested);
        }
        // Passed on deeper, it leaves those components' children too.
        if let Placement::Nested(deeper, _) = place
            && self.is_host(deeper)
        {
            self.forget_nested(deeper, child);
        }
    }

    /// The content `out` of the nested component hosted by `nested`, in
    /// order: its children as the host's JS children (`js_children`, the
    /// view's own JS children, where it passes them on), its slots' holders
    /// in their slots (inserted only when that changed).
    fn join_nested(&mut self, nested: NodeId, out: &[Expanded], inst: &Instance) {
        let insert = |core: &mut Self, child: NodeId, before: Option<NodeId>| {
            if let Ok(Some(op)) = core.intercept(Op::Insert {
                parent: nested,
                child,
                before,
            }) {
                let _ = core.apply_op(op);
            }
        };
        let (slots, children): (Vec<NodeId>, Vec<NodeId>) = out
            .iter()
            .flat_map(|e| match e.part {
                Part::Children => inst.js_children.clone(),
                Part::Filled(name) => self
                    .fill_of(inst, name)
                    .map(|f| self.fill_nodes(f))
                    .unwrap_or_default(),
                // A slot's: placed by the nested view where it places it.
                Part::Fill(_) | Part::Tooltip => Vec::new(),
                _ => self.placed(e),
            })
            .partition(|id| self.components.slot_names.contains_key(id));
        for slot in slots {
            if self.components.slot_hosts.get(&slot) != Some(&nested) {
                insert(self, slot, None);
            }
        }
        let same = self
            .components
            .instances
            .get(&nested)
            .is_some_and(|i| i.js_children == children);
        if !same {
            let mut before = None;
            for &child in children.iter().rev() {
                insert(self, child, before);
                before = Some(child);
            }
        }
    }

    /// The fill of slot `name` among `inst`'s.
    pub(super) fn fill_of<'a>(&self, inst: &'a Instance, name: &'static str) -> Option<&'a Fill> {
        inst.fills.iter().find(|f| f.name == name)
    }

    /// The nodes of `fill` now, in order.
    pub(super) fn fill_nodes(&self, fill: &Fill) -> Vec<NodeId> {
        self.fill_nodes_with(fill, None)
    }

    /// [`Self::fill_nodes`], with `out`'s instance for its host (one taken
    /// out of the instances while its view is reconciled).
    fn fill_nodes_with(&self, fill: &Fill, out: Option<(NodeId, &Instance)>) -> Vec<NodeId> {
        let mut nodes = Vec::with_capacity(fill.parts.len());
        for part in &fill.parts {
            match *part {
                FillPart::Node(id) => nodes.push(id),
                FillPart::Region(region) => self.fill_region_nodes(region, out, &mut nodes),
                FillPart::Filled(name) => self.passed_nodes(fill.from, name, out, &mut nodes),
            }
        }
        nodes
    }

    /// Adds the nodes of region `region` of a fill to `nodes`, what fills
    /// a slot of the region's view passed on among them.
    fn fill_region_nodes(
        &self,
        region: u32,
        out: Option<(NodeId, &Instance)>,
        nodes: &mut Vec<NodeId>,
    ) {
        let Some(state) = self.components.regions.get(&region) else {
            return;
        };
        for e in &state.children {
            match e.part {
                Part::Filled(name) => self.passed_nodes(state.host, name, out, nodes),
                Part::Region(inner) => self.fill_region_nodes(inner, out, nodes),
                _ => nodes.extend(self.placed(e)),
            }
        }
    }

    /// Adds the nodes of what fills slot `name` of the component on `host`
    /// to `nodes` (`out`: an instance taken out of the instances).
    fn passed_nodes(
        &self,
        host: NodeId,
        name: &'static str,
        out: Option<(NodeId, &Instance)>,
        nodes: &mut Vec<NodeId>,
    ) {
        let inst = match out {
            Some((h, inst)) if h == host => Some(inst),
            _ => self.components.instances.get(&host).map(|i| &**i),
        };
        if let Some(fill) = inst.and_then(|i| self.fill_of(i, name)) {
            nodes.extend(self.fill_nodes_with(fill, out));
        }
    }

    /// The slots of the view on `host` whose fills `parts` pass on (as they
    /// are, or in a region of them).
    fn passed_slots(&self, parts: &[FillPart], host: NodeId, names: &mut Vec<&'static str>) {
        fn of_region<M: TextEngine>(
            core: &Core<M>,
            region: u32,
            host: NodeId,
            names: &mut Vec<&'static str>,
        ) {
            let Some(state) = core.components.regions.get(&region) else {
                return;
            };
            for e in &state.children {
                match e.part {
                    Part::Filled(name) if state.host == host => names.push(name),
                    Part::Region(inner) => of_region(core, inner, host, names),
                    _ => {}
                }
            }
        }
        for part in parts {
            match *part {
                FillPart::Filled(name) => names.push(name),
                FillPart::Region(region) => of_region(self, region, host, names),
                FillPart::Node(_) => {}
            }
        }
    }

    /// Notes on the view on `host` (`inst`) which of its slots' fills go
    /// on into the fill of slot `name` of the nested component `nested`.
    pub(super) fn note_passed(
        &self,
        nested: NodeId,
        name: &'static str,
        host: NodeId,
        inst: &mut Instance,
    ) {
        let mut passed = Vec::new();
        if let Some(fill) = self
            .components
            .instances
            .get(&nested)
            .and_then(|t| self.fill_of(t, name))
        {
            self.passed_slots(&fill.parts, host, &mut passed);
        }
        for fill in &mut inst.fills {
            if passed.contains(&fill.name) {
                fill.forwarded = Some((nested, name));
            } else if fill.forwarded == Some((nested, name)) {
                fill.forwarded = None;
            }
        }
    }

    /// Where `out` (a view's children, or a region's, `end` after them)
    /// places what fills its slots: `place` of what follows each.
    pub(super) fn place_filled(
        &self,
        out: &[Expanded],
        inst: &mut Instance,
        end: Anchor,
        place: impl Fn(Anchor) -> Placement,
    ) {
        if inst.fills.is_empty() {
            return;
        }
        for (i, e) in out.iter().enumerate() {
            let Part::Filled(name) = e.part else {
                continue;
            };
            let at = place(self.anchor_after(&out[i + 1..], inst, end));
            if let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) {
                fill.at = at;
            }
        }
    }

    /// `e` and what it holds leave this view: what fills a slot it placed
    /// leaves its place (it stays: another view's).
    pub(super) fn unplace_filled(&mut self, e: &Expanded, inst: &mut Instance) {
        if inst.fills.is_empty() {
            return;
        }
        match e.part {
            Part::Filled(name) => {
                let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) else {
                    return;
                };
                let at = std::mem::replace(&mut fill.at, Placement::None);
                if at == Placement::None {
                    return;
                }
                let nodes = self.fill_nodes(self.fill_of(inst, name).expect("a fill"));
                for node in nodes {
                    self.unplace(at, node);
                }
            }
            Part::Region(region) => {
                let children = self
                    .components
                    .regions
                    .get_mut(&region)
                    .map(|s| std::mem::take(&mut s.children))
                    .unwrap_or_default();
                for c in &children {
                    self.unplace_filled(c, inst);
                }
                if let Some(state) = self.components.regions.get_mut(&region) {
                    state.children = children;
                }
            }
            _ => {
                for c in &e.children {
                    self.unplace_filled(c, inst);
                }
            }
        }
    }

    /// The slots the view on `host` (its instance `inst`) fills of the
    /// nested component hosted by `nested`, from its content `out`: they
    /// replace the ones before (a fill gone was released with its nodes,
    /// what was passed on and no longer is leaves its place), and go where
    /// the nested view places them.
    fn fill_nested(&mut self, nested: NodeId, out: &[Expanded], host: NodeId, inst: &mut Instance) {
        let fills: Vec<(&'static str, Vec<FillPart>)> = out
            .iter()
            .filter_map(|e| match e.part {
                Part::Fill(name) => Some((
                    name,
                    e.children
                        .iter()
                        .filter_map(|c| match c.part {
                            Part::Region(region) => Some(FillPart::Region(region)),
                            Part::Filled(name) => Some(FillPart::Filled(name)),
                            _ if c.id != 0 => Some(FillPart::Node(c.id)),
                            _ => None,
                        })
                        .collect(),
                )),
                _ => None,
            })
            .collect();
        // What fills this view's own slots goes where they are passed on.
        for fill in &mut inst.fills {
            if fill.forwarded.is_some_and(|(n, _)| n == nested) {
                fill.forwarded = None;
            }
        }
        for (name, parts) in &fills {
            let mut passed = Vec::new();
            self.passed_slots(parts, host, &mut passed);
            for fill in inst.fills.iter_mut().filter(|f| passed.contains(&f.name)) {
                fill.forwarded = Some((nested, name));
            }
        }
        let Some(target) = self.components.instances.get_mut(&nested) else {
            return;
        };
        if fills.is_empty() && target.fills.is_empty() {
            return;
        }
        let mut changed = target.fills.len() != fills.len();
        let old = std::mem::take(&mut target.fills);
        let mut joining = Vec::new();
        for (name, parts) in fills {
            let (at, forwarded, same) = match old.iter().find(|f| f.name == name) {
                Some(f) => (f.at, f.forwarded, f.parts == parts),
                None => (Placement::None, None, false),
            };
            changed |= !same;
            if !same {
                joining.push(name);
            }
            target.fills.push(Fill {
                name,
                parts,
                from: host,
                at,
                forwarded,
            });
        }
        if !changed {
            return;
        }
        // What was passed on and is no longer leaves its place (it stays:
        // the view above's); what was released went with its Delete.
        let out = Some((host, &*inst));
        let mut leaving = Vec::new();
        for fill in &old {
            let at = self.fill_place(nested, fill.name);
            let now = self
                .components
                .instances
                .get(&nested)
                .and_then(|t| self.fill_of(t, fill.name))
                .map(|f| self.fill_nodes_with(f, out))
                .unwrap_or_default();
            for node in self.fill_nodes_with(fill, out) {
                if !now.contains(&node) && self.key(node).is_ok() {
                    leaving.push((at, node));
                }
            }
        }
        for (at, node) in leaving {
            self.unplace(at, node);
        }
        for name in joining {
            self.join_fill(nested, name, out);
        }
        // Its slot props follow (`Some` while a fill has nodes).
        self.components.mark(nested);
        let names: Vec<&'static str> = self.components.instances[&nested]
            .fills
            .iter()
            .map(|f| f.name)
            .collect();
        for name in names {
            self.place_fill_with(nested, name, Some((host, &*inst)));
        }
    }

    /// The fill of slot `name` of the nested component hosted by `nested`
    /// is content its view places, as its children are
    /// ([`Self::join_content`]): the components in it wait to be placed
    /// and read the context of the view that places them (`out`: an
    /// instance taken out of the instances).
    pub(super) fn join_fill(
        &mut self,
        nested: NodeId,
        name: &'static str,
        out: Option<(NodeId, &Instance)>,
    ) {
        let nodes = self
            .components
            .instances
            .get(&nested)
            .and_then(|inst| self.fill_of(inst, name))
            .map(|fill| self.fill_nodes_with(fill, out))
            .unwrap_or_default();
        for node in nodes {
            self.join_content(node);
        }
    }

    /// Where the nodes of the fill of slot `name` of the nested component
    /// hosted by `nested` are placed: where its view places them, or where
    /// the slot it is passed on to is.
    fn fill_place(&self, nested: NodeId, name: &'static str) -> Placement {
        let Some(fill) = self
            .components
            .instances
            .get(&nested)
            .and_then(|inst| self.fill_of(inst, name))
        else {
            return Placement::None;
        };
        match (fill.at, fill.forwarded) {
            (Placement::None, Some((deeper, slot))) => self.fill_place(deeper, slot),
            (at, _) => at,
        }
    }

    /// Puts the nodes of the fill of slot `name` of the nested component
    /// hosted by `nested` where its view places them (a region of the fill
    /// changed, or the fill), and where it passes them on to.
    pub(super) fn place_fill(&mut self, nested: NodeId, name: &'static str) {
        self.place_fill_with(nested, name, None);
    }

    /// [`Self::place_fill`], with `out`'s instance for its host (one taken
    /// out of the instances while its view is reconciled).
    fn place_fill_with(
        &mut self,
        nested: NodeId,
        name: &'static str,
        out: Option<(NodeId, &Instance)>,
    ) {
        let Some(fill) = self
            .components
            .instances
            .get(&nested)
            .and_then(|inst| self.fill_of(inst, name))
        else {
            return;
        };
        let (nodes, at, forwarded) = (self.fill_nodes_with(fill, out), fill.at, fill.forwarded);
        if let Some((deeper, slot)) = forwarded {
            // Passed on: the deeper slot's fill holds them, and its prop
            // follows.
            self.components.mark(deeper);
            self.place_fill_with(deeper, slot, out);
        }
        match at {
            Placement::At(parent, anchor) => {
                let parent_key = self.key(parent).ok();
                // An anchor that left the parent: at the end.
                let mut before = self.anchor_node(anchor).filter(|&a| {
                    self.key(a)
                        .is_ok_and(|k| Some(self.nodes[k as usize].parent) == parent_key)
                });
                for &child in nodes.iter().rev() {
                    if !self.precedes(parent, child, before) {
                        let _ = self.apply_op(Op::Insert {
                            parent,
                            child,
                            before,
                        });
                    }
                    before = Some(child);
                }
                // In a holder: the slot's props follow its one element.
                if self.components.fill_holders.contains(&parent) {
                    self.retarget_slot(parent, None);
                }
            }
            Placement::Nested(other, anchor) => {
                let mut before = self.anchor_node(anchor);
                for &child in nodes.iter().rev() {
                    if !self.nested_precedes(other, child, before) {
                        self.join_nested_at(other, child, before);
                    }
                    before = Some(child);
                }
            }
            _ => {}
        }
    }

    /// Whether `child` is a child of `parent` right before `next` (the last
    /// one when `next` is `None`).
    pub(super) fn precedes(&self, parent: NodeId, child: NodeId, next: Option<NodeId>) -> bool {
        self.preceding(parent, child, next, None).is_some()
    }

    /// Where `child` is among `parent`'s children when it is right before
    /// `next` ([`Self::precedes`]). `hint` is where it is expected, looked
    /// at first: nodes checked from the last to the first, each before the
    /// one after it, are found without a search of the children for each.
    /// A node not among them, as each node of a region mounted for the
    /// first time, is known from its own parent without a search either.
    pub(super) fn preceding(
        &self,
        parent: NodeId,
        child: NodeId,
        next: Option<NodeId>,
        hint: Option<usize>,
    ) -> Option<usize> {
        let k = self.key(parent).ok()?;
        if self.nodes[self.key(child).ok()? as usize].parent != k {
            return None;
        }
        let children = &self.nodes[k as usize].children;
        let id = |at: usize| children.get(at).map(|&c| self.nodes[c as usize].id);
        let at = match hint {
            Some(at) if id(at) == Some(child) => at,
            _ => {
                let at = children
                    .iter()
                    .position(|&c| self.nodes[c as usize].id == child);
                self.placing(at.map_or(children.len(), |at| at + 1));
                at?
            }
        };
        (id(at + 1) == next).then_some(at)
    }

    /// `n` more siblings or overlays looked at to place a view
    /// ([`Components::placing_work`]).
    #[cfg(test)]
    pub(super) fn placing(&self, n: usize) {
        let work = &self.components.placing_work;
        work.set(work.get() + n);
    }

    #[cfg(not(test))]
    #[inline(always)]
    pub(super) fn placing(&self, _n: usize) {}

    /// `n` more mount items looked at for views taking the kind of their
    /// component's root ([`Components::retag_work`]).
    #[cfg(test)]
    pub(super) fn retagging(&self, n: usize) {
        let work = &self.components.retag_work;
        work.set(work.get() + n);
    }

    #[cfg(not(test))]
    #[inline(always)]
    pub(super) fn retagging(&self, _n: usize) {}

    /// Slot node `node` as element `el` of `host`'s view: its styles, props
    /// and handlers (its children are the app's JSX). Its bound parts are
    /// bound as a node's of the view are; what is not a style goes to the
    /// slot's target, the app's element when the node holds one
    /// ([`super::slots`]).
    fn reconcile_slot(
        &mut self,
        prev: Option<Expanded>,
        node: NodeId,
        mut el: ElNode,
        host: NodeId,
        inst: &mut Instance,
    ) -> Expanded {
        let bound = super::views::Bound::take(&mut el);
        // What its bindings applied since it was placed is what the node
        // has (an `Expanded` keeps what was applied with it).
        let applied = inst.bound.remove(&node);
        let (old_attrs, old_style, old_classes) = match (prev, applied) {
            (Some(_), Some(a)) => (a.attrs, a.style, a.classes),
            (Some(p), None) => (p.attrs, p.style, p.classes),
            (None, _) => (Attrs::default(), StyleRefinement::default(), (None, None)),
        };
        let bound = bound.map(|bound| self.bind_parts(host, node, bound, &mut el));
        self.apply_slot_attrs(node, host, &el.attrs, &old_attrs, Some(&mut *inst));
        let classes = self.apply_el_styles(
            node,
            &el.style,
            &old_style,
            old_classes,
            el.attrs.class.as_ref(),
            None,
        );
        if bound.is_some() {
            Self::keep_bound(inst, node, &el.attrs, &el.style, classes.clone(), None);
        }
        // Its events are the component's first (`component_event` finds it
        // by its host); the node stays JS's or the placing view's.
        let events = self.apply_slot_handlers(node, host, &el, inst);
        Expanded {
            id: node,
            tag: Tag::View,
            key: None,
            text: None,
            attrs: el.attrs,
            style: el.style,
            classes,
            events,
            list: None,
            part: Part::Slot,
            children: Vec::new(),
        }
    }

    /// The node of `host`'s view element `el` wraps a slot's fill in (its
    /// one child places the fill): a slot node as JS's holders are. Its
    /// styles are its own, and it lays the fill's one node out through
    /// while they style none of its layout; the rest of what the place
    /// gives goes to that node when the fill is one element
    /// ([`super::slots`]), so its focus, keys and presses reach the
    /// component's listeners as a JS app's element's do.
    fn reconcile_wrapper(
        &mut self,
        mut prev: Option<Expanded>,
        mut el: ElNode,
        host: NodeId,
        inst: &mut Instance,
    ) -> Expanded {
        let (id, old_children) = match &mut prev {
            Some(p) => (p.id, std::mem::take(&mut p.children)),
            None => {
                let id = self.components.alloc();
                let _ = self.apply_op(Op::Create { id, tag: el.tag });
                self.components.owners.insert(id, host);
                (id, Vec::new())
            }
        };
        self.components.fill_holders.insert(id);
        // The fill first: its one element is where the rest goes.
        let children = std::mem::take(&mut el.children);
        let children = self.reconcile_children(id, old_children, children, host, inst);
        let (tag, key) = (el.tag, el.key.clone());
        let mut e = self.reconcile_slot(prev, id, el, host, inst);
        if let Ok(k) = self.key(id) {
            self.lay_out_through(k);
        }
        e.tag = tag;
        e.key = key;
        e.part = Part::Node;
        e.children = children;
        e
    }

    pub(super) fn reconcile_node(
        &mut self,
        prev: Option<Expanded>,
        mut el: ElNode,
        part: Part,
        host: NodeId,
        inst: &mut Instance,
    ) -> Expanded {
        // A text whose content is bound, with spans: the content is its
        // first span.
        if !el.children.is_empty()
            && let Some(content) = el.bound_text.take()
        {
            let mut first = ElNode::new(Tag::Text);
            first.text = Some(SharedString::default());
            first.bound_text = Some(content);
            el.text = None;
            el.children.insert(0, first);
        }
        // Bound parts are bound once the node exists, and what they read
        // now is applied with its static parts. The styles given a nested
        // component are a binding of their own (its host's styles are its
        // own and the app's).
        let nested_style = (matches!(el.kind, ElKind::Component(_)) && el.style.is_bound())
            .then(|| el.style.clone());
        // So are its bound attributes (insets).
        let nested_attrs = (matches!(el.kind, ElKind::Component(_)) && !el.bound_attrs.is_empty())
            .then(|| (el.attrs.clone(), el.bound_attrs.clone()));
        let bound = if matches!(el.kind, ElKind::Component(_)) {
            el.resolve_once();
            None
        } else {
            super::views::Bound::take(&mut el)
        };
        if matches!(el.kind, ElKind::Raw) {
            return self.reconcile_raw(prev, el, host);
        }
        // A text with spans: its own content is the first piece, as JS
        // has it.
        if !el.children.is_empty()
            && let Some(content) = el.text.take()
            && !content.is_empty()
        {
            let mut raw = ElNode::new(Tag::Text);
            raw.text = Some(content);
            raw.kind = ElKind::Raw;
            el.children.insert(0, raw);
        }
        let old_list = prev
            .as_ref()
            .and_then(|p| p.list.as_deref().copied())
            .unwrap_or_default();
        let kept = prev.is_some();
        let (id, old_attrs, old_style, old_classes, old_events, old_children, old_text) = match prev
        {
            Some(mut p) => {
                // Bindings may have changed the node since this element
                // was applied. Diff against those latest values, even
                // when the new element has no bindings.
                if let Some(applied) = inst.bound.remove(&p.id) {
                    p.attrs = applied.attrs;
                    p.style = applied.style;
                    p.classes = applied.classes;
                    p.text = applied.text;
                }
                (
                    p.id, p.attrs, p.style, p.classes, p.events, p.children, p.text,
                )
            }
            None => {
                let id = self.components.alloc();
                let _ = self.apply_op(Op::Create { id, tag: el.tag });
                self.components.owners.insert(id, host);
                if let ElKind::Component(c) = &el.kind {
                    self.create_instance_for(id, c);
                }
                (
                    id,
                    Attrs::default(),
                    StyleRefinement::default(),
                    (None, None),
                    EventMask::default(),
                    Vec::new(),
                    None,
                )
            }
        };
        // The element snapshot predates any applied layout binding patches.
        let old_list = if matches!(el.kind, ElKind::VirtualList(_)) {
            self.components.list_layouts.remove(&id).unwrap_or(old_list)
        } else {
            old_list
        };
        let bound = bound.map(|bound| self.bind_parts(host, id, bound, &mut el));
        let (component, virtual_list) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
            ElKind::Component(c) => (Some(c), None),
            ElKind::VirtualList(list) => (None, Some(list)),
            _ => (None, None),
        };
        if let Some(c) = component {
            // A nested component: its props, and the styles as the app's
            // classes of its host.
            self.set_element_props(id, c.props.as_ref());
            if self.is_host(id) {
                if let Some(style) = nested_style {
                    el.style = self.bind_nested_style(id, style);
                }
                let user = (!el.style.is_empty()).then(|| self.components.lowered(&el.style));
                self.set_user(id, user);
            }
            // Made again, it hears this run's listeners only.
            if kept {
                inst.event_handlers.retain(|(n, _)| *n != id);
            }
            // The view's listeners of its node's events, after its root's.
            if self.is_host(id) {
                self.set_given_handlers(id, std::mem::take(&mut el.handlers));
            }
            inst.event_handlers
                .extend(c.on_event.into_iter().map(|listener| (id, listener)));
            // Its `ComponentRef`.
            let element_ref = el.attrs.take_element_ref();
            if old_attrs.element_ref() != element_ref.as_ref()
                && let Some(r) = old_attrs.element_ref()
            {
                r.detach(id);
            }
            if let Some(r) = &element_ref {
                r.attach(id);
            }
            // The tooltip it gives the root: an element of this view, which
            // the root's node shows as it shows JS's.
            let mut old_children = old_children;
            let tooltip =
                self.reconcile_given_tooltip(id, &mut old_children, &mut el.children, host, inst);
            let tooltip_prop = tooltip
                .as_ref()
                .and_then(|t| t.children.first())
                .filter(|e| e.id != 0)
                .map(|e| Prop::Tooltip(crate::overlay::TooltipContent::Node(e.id)));
            // The rest goes on its root, after the root's own.
            if self.is_host(id) {
                let given = match nested_attrs {
                    Some((mut base, parts)) => {
                        if let Some(prop) = &tooltip_prop {
                            crate::element::host::set_in(&mut base.props, prop.clone());
                        }
                        self.bind_nested_attrs(id, base, parts)
                    }
                    None => {
                        let mut given = std::mem::take(&mut el.attrs);
                        if let Some(prop) = tooltip_prop {
                            crate::element::host::set_in(&mut given.props, prop);
                        }
                        given
                    }
                };
                self.set_given(id, given);
            }
            // The content this view passes it (`.child`, `.fill`): nodes of
            // this view, inserted into its host as JS inserts its children,
            // so the nested component places them where its view says.
            // Lazy children are passed only while it places them, as JS
            // makes the app's (`$children`); slots and rows always are.
            let mut content = std::mem::take(&mut el.children);
            let is_slot = |c: &ElNode| {
                matches!(c.kind, ElKind::Fill(_))
                    || c.attrs
                        .props
                        .iter()
                        .any(|p| matches!(p, Prop::ComponentSlot(_)))
            };
            let lazy = self
                .components
                .instances
                .get(&id)
                .is_some_and(|i| i.spec.as_ref().is_some_and(|s| s.lazy_children));
            if lazy {
                // A view passes them while a signal of the nested
                // component's says it places them: a region of its own.
                let (slots, kids): (Vec<ElNode>, Vec<ElNode>) =
                    content.into_iter().partition(|c| is_slot(c));
                content = slots;
                if !kids.is_empty() {
                    let wanted = self.children_wanted_signal(id);
                    let shown = crate::element::when(wanted, move || {
                        kids.iter()
                            .cloned()
                            .map(crate::element::AnyElement)
                            .collect::<Vec<_>>()
                    });
                    content.push(shown.into_element().0);
                }
            }
            let mut children = self.reconcile_children(id, old_children, content, host, inst);
            children.extend(tooltip);
            let mut kept_attrs = Attrs::default();
            kept_attrs.set_element_ref(element_ref);
            return Expanded {
                id,
                tag: el.tag,
                key: el.key,
                text: None,
                attrs: kept_attrs,
                style: el.style,
                classes: (None, None),
                events: EventMask::default(),
                list: None,
                part,
                children,
            };
        }
        if !self.apply_target_attrs(id, &el.attrs, &old_attrs, None) {
            self.apply_attrs(id, &el.attrs, &old_attrs);
        }
        let classes = self.apply_el_styles(
            id,
            &el.style,
            &old_style,
            old_classes,
            el.attrs.class.as_ref(),
            None,
        );
        let text = self.reconcile_text(id, host, el.text.take(), old_text);
        if bound.is_some() {
            Self::keep_bound(
                inst,
                id,
                &el.attrs,
                &el.style,
                classes.clone(),
                text.clone(),
            );
        }
        let events = self.apply_handlers(host, id, &el, old_events, EventMask::default(), inst);
        let new_children = std::mem::take(&mut el.children);
        let children = self.reconcile_children(id, old_children, new_children, host, inst);
        let list = match virtual_list {
            Some(list) => {
                let config = list.config;
                self.update_virtual_list(id, host, *list, &old_list);
                Some(Box::new(config))
            }
            None => None,
        };
        Expanded {
            id,
            tag: el.tag,
            key: el.key,
            text,
            attrs: el.attrs,
            style: el.style,
            classes,
            events,
            list,
            part,
            children,
        }
    }

    /// The tooltip view `host` gives the root of the nested component on
    /// `nested` ([`ElKind::Tooltip`], taken out of its element's `content`),
    /// matched with the one it gave before (taken out of `old`, the
    /// element's children as applied): its element is a node of this view,
    /// out of the tree until the root's node shows it.
    fn reconcile_given_tooltip(
        &mut self,
        nested: NodeId,
        old: &mut Vec<Expanded>,
        content: &mut Vec<ElNode>,
        host: NodeId,
        inst: &mut Instance,
    ) -> Option<Expanded> {
        let prev = old
            .iter()
            .position(|e| e.part == Part::Tooltip)
            .map(|at| old.remove(at));
        let Some(at) = content
            .iter()
            .position(|c| matches!(c.kind, ElKind::Tooltip))
        else {
            if let Some(prev) = prev {
                self.release_expanded(prev);
            }
            return None;
        };
        let given = content.remove(at);
        let new = given
            .children
            .into_iter()
            .map(|c| NewChild::Made(None, c))
            .collect();
        let old = prev.map(|p| p.children).unwrap_or_default();
        let (children, _) = self.match_children(nested, old, new, host, inst);
        let mut tooltip = Expanded::js(0, Part::Tooltip);
        tooltip.children = children;
        Some(tooltip)
    }

    /// A piece `el` of a text's content: its raw text node, created or
    /// changed (the view's order puts it in place).
    fn reconcile_raw(&mut self, prev: Option<Expanded>, el: ElNode, host: NodeId) -> Expanded {
        let content = el.text.unwrap_or_else(|| "".into());
        let id = match prev {
            Some(p) => {
                if p.text.as_ref().is_none_or(|(old, _)| *old != content) {
                    let _ = self.apply_op(Op::SetText {
                        id: p.id,
                        text: content.as_str().to_owned(),
                    });
                }
                p.id
            }
            None => {
                let id = self.components.alloc();
                let _ = self.apply_op(Op::CreateText {
                    id,
                    text: content.as_str().to_owned(),
                });
                self.components.owners.insert(id, host);
                id
            }
        };
        Expanded {
            id,
            tag: Tag::Text,
            key: None,
            text: Some((content, id)),
            attrs: Attrs::default(),
            style: StyleRefinement::default(),
            classes: (None, None),
            events: EventMask::default(),
            list: None,
            part: Part::Raw,
            children: Vec::new(),
        }
    }

    /// A view's list of its own rows: its layout, its rows (a splice when
    /// the keys say rows came or went, then the count), and its live cells
    /// built again with the new row function (when the list is made
    /// again). A bound count or keys are a binding: a memo that moves the
    /// live cells' indices as the rows moved (dropping the content of cells
    /// whose row went) and queues the change for the list
    /// ([`Self::set_list_rows`]). The cells' positions run it before they
    /// are read, so the rows' own bindings never read the new rows at the
    /// old indices, whichever runs first.
    fn update_virtual_list(
        &mut self,
        id: NodeId,
        owner: NodeId,
        list: VirtualListEl,
        old: &ListConfig,
    ) {
        // The static layout (its bound parts come as patches).
        let mut props = std::mem::take(&mut self.components.props);
        list.config.changes(old, &mut props);
        for prop in props.drain(..) {
            let _ = self.apply_op(Op::SetProp { id, prop });
        }
        self.components.props = props;
        let before = self
            .components
            .virtual_lists
            .get(&id)
            .map(|state| (state.count, state.keys.clone()));
        // The rows of another component's `Items` prop (its slot's node).
        let items = self.components.slot_names.contains_key(&id);
        let state = self
            .components
            .virtual_lists
            .entry(id)
            .or_insert_with(|| VirtualListState {
                owner,
                scope: Rc::default(),
                row: list.row.clone(),
                count: 0,
                keys: None,
                separator: None,
                cells: Vec::new(),
                rows: CellRows::default(),
                moves: None,
                items,
                place: None,
                contents: Vec::new(),
                min_view: None,
                reported: None,
                latest: None,
                report: None,
            });
        // The rows go with the run that made the list. A list a later run
        // keeps takes that run's owner: its cells are made again below.
        if state.scope.get() != list.scope {
            state.scope.set(list.scope);
            if let Some(scope) = list.scope {
                let rows = Rc::downgrade(&state.rows);
                let current = Rc::downgrade(&state.scope);
                scope.run(|| {
                    crate::element::cleanup(move || {
                        // A run the list has since left keeps the rows of
                        // the run it is in now.
                        if current.upgrade().is_some_and(|c| c.get() == Some(scope)) {
                            dispose_rows(&rows);
                        }
                    })
                });
            }
        }
        let cells = state.rows.clone();
        let bound = matches!(list.count, Reactive::Bound(_)) || list.keys.is_some();
        let (count, keys) = (list.count, list.keys);
        let rows = move || (count.get(), keys.as_ref().map(|k| k()));
        let mut moves = None;
        let (count, keys) = if bound {
            let count_signal = self.list_count(id, 0);
            let patches = self.components.patches.clone();
            let first: Rc<RefCell<Option<Rows>>> = Rc::default();
            let slot = first.clone();
            let last: RefCell<Option<Rc<[u64]>>> = RefCell::new(None);
            let made = std::cell::Cell::new(false);
            let memo = crate::element::computed(move || {
                let (count, keys) = rows();
                let diff = match (&*last.borrow(), &keys) {
                    (Some(old), Some(new)) => ListDiff::new(old, new),
                    _ => None,
                };
                last.replace(keys.clone());
                if made.replace(true) {
                    move_rows(&cells, diff.as_ref(), count);
                    count_signal.set(count as usize);
                    patches.borrow_mut().push(super::views::Patch::Rows {
                        list: id,
                        binding: crate::element::Owner::current(),
                        count,
                        keys,
                    });
                } else {
                    count_signal.set(count as usize);
                    *slot.borrow_mut() = Some((count, keys));
                }
            });
            moves = Some(memo.node());
            first.take().expect("a memo runs when it is made")
        } else {
            let (count, keys) = crate::element::untracked(rows);
            // What the cells of a view (or a view's wrappers) read.
            {
                self.list_count(id, count as usize).set(count as usize);
            }
            (count, keys)
        };
        self.send_list_rows(id, before.as_ref(), count, keys.as_ref());
        if before.is_none()
            && let Some(command) = list.initial_scroll
        {
            let _ = self.apply_op(Op::Command { id, command });
        }
        let state = self.components.virtual_lists.get_mut(&id).expect("list");
        state.row = list.row;
        state.count = count;
        state.keys = keys;
        state.moves = moves;
        state.separator = list.separator;
        state.min_view = list.min_view_time;
        self.sync_virtual_cells(id, true);
    }

    /// Sends list `id` its rows' changes from `before` (none: a new list):
    /// how the keys say rows came, went or moved, then the count.
    fn send_list_rows(
        &mut self,
        id: NodeId,
        before: Option<&Rows>,
        count: u32,
        keys: Option<&Rc<[u64]>>,
    ) {
        if let (Some((_, Some(old))), Some(new)) = (before, keys)
            && let Some(diff) = ListDiff::new(old, new)
        {
            let _ = self.apply_op(Op::SetProp {
                id,
                prop: Prop::ListDiff(Rc::new(diff)),
            });
        }
        if before.map(|(count, _)| *count) != Some(count) {
            let _ = self.apply_op(Op::SetProp {
                id,
                prop: Prop::Count(count),
            });
        }
    }

    /// A view's list `id` has new rows (its bound count or keys changed):
    /// sent to the list. Its cells' bindings already follow their rows
    /// ([`move_rows`]); the core takes their indices, and the cells whose row
    /// went show nothing until the list shows another row in them.
    pub(super) fn set_list_rows(&mut self, id: NodeId, count: u32, keys: Option<Rc<[u64]>>) {
        let Some(state) = self.components.virtual_lists.get(&id) else {
            return;
        };
        let before = (state.count, state.keys.clone());
        self.send_list_rows(id, Some(&before), count, keys.as_ref());
        let state = self.components.virtual_lists.get_mut(&id).expect("list");
        state.count = count;
        state.keys = keys;
        self.sync_virtual_cells(id, false);
    }

    fn sync_virtual_cells(&mut self, id: NodeId, rebuild: bool) {
        let key = self.key(id).expect("virtual list node");
        let slots = &self.nodes[key as usize].list.as_ref().expect("list").slots;
        let state = &self.components.virtual_lists[&id];
        for (slot, (&cell, &content)) in state.cells.iter().zip(&state.contents).enumerate() {
            for part in [cell, content].into_iter().filter(|&part| part != 0) {
                let Some(inst) = self.components.instances.get_mut(&part) else {
                    continue;
                };
                let remake = rebuild || !inst.cell_owner.is_some_and(|o| o.is_live());
                if let Inner::VirtualRow { index, .. } | Inner::Row { index, .. } = &mut inst.inner
                {
                    if remake {
                        // The content owner can die while the slot still has a row.
                        *index = slots[slot].requested.map_or(usize::MAX, |i| i as usize);
                    } else if let Some(position) = inst.row_index {
                        *index = position.get_untracked();
                    }
                }
                if remake && !inst.dirty {
                    inst.dirty = true;
                    self.components.dirty.push(part);
                }
            }
        }
    }

    /// The row count the cells of list `list` read, made with `count` the
    /// first time.
    fn list_count(&mut self, list: NodeId, count: usize) -> crate::element::Signal<usize> {
        if let Some(&(_, signal)) = self.components.list_counts.get(&list) {
            return signal;
        }
        let made = crate::element::Owner::detached()
            .run(|| crate::element::create_root(|| crate::element::signal(count)));
        self.components.list_counts.insert(list, made);
        made.1
    }

    /// List `list` goes: so do the count its cells read and its layout.
    fn forget_list_count(&mut self, list: NodeId) {
        if let Some((owner, _)) = self.components.list_counts.remove(&list) {
            owner.dispose();
        }
        self.components.list_layouts.remove(&list);
    }

    /// Binds the cells of the components' own lists the last layout asked
    /// for (creating them as needed); false when there were none.
    pub(super) fn bind_virtual_lists(&mut self) -> bool {
        if self.components.virtual_lists.is_empty() {
            return false;
        }
        let _entered = self.components.runtime.enter();
        let mut binds = std::mem::take(&mut self.list_binds);
        let mut bound = false;
        binds.retain(|bind| {
            if !self.components.virtual_lists.contains_key(&bind.list) {
                return true;
            }
            for &(slot, index) in &bind.binds {
                self.bind_virtual_cell(bind.list, slot as usize, index as usize);
            }
            bound = true;
            false
        });
        self.list_binds = binds;
        bound
    }

    fn bind_virtual_cell(&mut self, list: NodeId, slot: usize, index: usize) {
        let state = &self.components.virtual_lists[&list];
        let owner = state.owner;
        let cell = match state.cells.get(slot).copied().filter(|&c| c != 0) {
            Some(cell) => {
                let content = state.contents.get(slot).copied().filter(|&c| c != 0);
                for part in [Some(cell), content].into_iter().flatten() {
                    if let Some(inst) = self.components.instances.get_mut(&part) {
                        match &mut inst.inner {
                            Inner::VirtualRow { index: current, .. }
                            | Inner::Row { index: current, .. } => *current = index,
                            _ => {}
                        }
                        // A view's cell keeps its content: what reads its
                        // position follows.
                        if let Some(row) = inst.row_index
                            && inst.cell_owner.is_some_and(|o| o.is_live())
                        {
                            row.set(index);
                            continue;
                        }
                    }
                    self.components.mark(part);
                }
                cell
            }
            None => {
                let (items, place) = (state.items, state.place.clone());
                let cell = self.components.alloc();
                let _ = self.apply_op(Op::Create {
                    id: cell,
                    tag: Tag::Cell,
                });
                self.components.owners.insert(cell, owner);
                let _ = self.apply_op(Op::SetProp {
                    id: cell,
                    prop: Prop::Slot(crate::CellSlot::Item(slot as u32)),
                });
                let _ = self.apply_op(Op::Insert {
                    parent: list,
                    child: cell,
                    before: None,
                });
                let row = Inner::VirtualRow { list, index };
                let content = if items {
                    // The placing component's wrapper in the cell, around
                    // the row's own node (placed as a row's content is).
                    let content = self.components.alloc();
                    let _ = self.apply_op(Op::Create {
                        id: content,
                        tag: Tag::View,
                    });
                    self.components.owners.insert(content, owner);
                    let _ = self.apply_op(Op::Insert {
                        parent: cell,
                        child: content,
                        before: None,
                    });
                    let instance = Instance::new(row, None, Vec::new(), None);
                    self.components
                        .instances
                        .insert(content, Box::new(instance));
                    self.components.mark(content);
                    let place = place.unwrap_or_else(|| Rc::new(|row, _| row.into_element()));
                    // The wrapper is the placing component's.
                    let wrapper =
                        Instance::new(Inner::Row { place, index }, None, vec![content], None);
                    self.components.instances.insert(cell, Box::new(wrapper));
                    content
                } else {
                    let instance = Instance::new(row, None, Vec::new(), None);
                    self.components.instances.insert(cell, Box::new(instance));
                    0
                };
                let state = self.components.virtual_lists.get_mut(&list).expect("list");
                if state.cells.len() <= slot {
                    state.cells.resize(slot + 1, 0);
                    state.contents.resize(slot + 1, 0);
                }
                state.cells[slot] = cell;
                state.contents[slot] = content;
                self.components.mark(cell);
                cell
            }
        };
        let _ = self.apply_op(Op::SetProp {
            id: cell,
            prop: Prop::CellIndex(index as u32),
        });
    }

    /// A component's own list reported its viewable rows: they are the
    /// owner's to handle now, or once they stayed so for the minimum view
    /// time (a change meanwhile starts the wait again).
    fn viewable_changed(&mut self, list: NodeId, payload: &EventPayload) {
        let executor = self.components.executor.clone();
        let Some(state) = self.components.virtual_lists.get_mut(&list) else {
            return;
        };
        state.latest = virtual_list::viewable_range(payload, "first", "last");
        match state.min_view {
            Some(delay) => {
                state.report = Some(crate::element::task::act_after(
                    &executor,
                    state.owner,
                    delay,
                    Action::ReportViewable(list),
                ));
            }
            None => self.report_viewable(list),
        }
    }

    /// Hands list `list`'s owner the rows viewable now, unless they are the
    /// ones reported last.
    fn report_viewable(&mut self, list: NodeId) {
        let Some(state) = self.components.virtual_lists.get_mut(&list) else {
            return;
        };
        state.report = None;
        if state.latest == state.reported {
            return;
        }
        let payload = virtual_list::viewable_payload(state.latest, state.reported);
        state.reported = state.latest;
        let owner = state.owner;
        self.handle(owner, list, EventKind::ViewableItemsChange, &payload);
    }

    fn release_id(&mut self, id: NodeId) {
        self.components.release_generation = self.components.release_generation.wrapping_add(1);
        if let Some(host) = self.components.owners.remove(&id) {
            // Cells can replace/empty their static root outside a region's
            // matching pass. Their released bindings need the same sweep
            // even if the next region only populates new nodes.
            self.components.released_hosts.insert(host);
        }
        self.forget_node_extras(id);
        // A root component's host is its view's: only the name goes.
        if self.is_alias(id) {
            self.unalias(id);
            return;
        }
        // A fill's node in a holder: the slot's props follow what is left.
        let holder = if self.components.fill_holders.is_empty() {
            None
        } else {
            self.key(id)
                .ok()
                .map(|k| self.nodes[k as usize].parent)
                .filter(|&p| p != NO_KEY)
                .map(|p| self.nodes[p as usize].id)
                .filter(|p| self.components.fill_holders.contains(p))
        };
        let _ = self.apply_op(Op::Release { id });
        if let Some(holder) = holder {
            self.retarget_slot(holder, None);
        }
    }

    /// Frees an expanded element and what it rendered (a slot's node is
    /// JS's: it only leaves the tree).
    pub(super) fn release_expanded(&mut self, e: Expanded) {
        // Slot/JS nodes can lose this view's part without being deleted or
        // leaving `owners`, so count expanded releases as well as raw IDs.
        self.components.release_generation = self.components.release_generation.wrapping_add(1);
        match e.part {
            Part::Slot => {
                self.drop_slot_target(e.id);
                self.detach_id(e.id);
                return;
            }
            // The JS children are placed (or detached) by the view, and
            // what fills a slot by the view that fills it.
            Part::Children | Part::Filled(_) => return,
            // Its nodes are its children's.
            Part::Fill(_) | Part::Tooltip => {
                for c in e.children {
                    self.release_expanded(c);
                }
                return;
            }
            // A JS child leaves the wrapper being released.
            Part::JsChild => {
                self.detach_id(e.id);
                return;
            }
            Part::Raw => {
                self.release_id(e.id);
                return;
            }
            // Its content is this view's, released below: deleting it
            // detaches it.
            Part::Component(_) => {
                let content: Vec<NodeId> = e.children.iter().flat_map(|c| self.placed(c)).collect();
                self.release_component(e.id, &content);
            }
            // Its nodes are the region's.
            Part::Region(region) => {
                self.release_region(region);
                return;
            }
            Part::VirtualList => self.release_virtual_list(e.id),
            // A fill's holder: its element gets its own props back.
            Part::Node => {
                if !self.components.fill_holders.is_empty()
                    && self.components.fill_holders.remove(&e.id)
                {
                    self.drop_slot_target(e.id);
                }
            }
        }
        if let Some(r) = e.attrs.rare.as_ref().and_then(|r| r.element_ref.as_ref()) {
            r.detach(e.id);
        }
        for c in e.children {
            self.release_expanded(c);
        }
        if let Some((_, raw)) = e.text {
            self.release_id(raw);
        }
        self.release_id(e.id);
    }

    /// Frees what a component made (not its host nor its JS children,
    /// which leave its view).
    pub(super) fn release_instance(&mut self, host: NodeId) {
        self.release_component(host, &[]);
    }

    /// [`Self::release_instance`], but of its JS children and slots, those
    /// in `content` are released right after (a view's content of a nested
    /// component: deleting them detaches them); the others leave its view
    /// natively (they stay: JS's, or passed on by the view).
    fn release_component(&mut self, host: NodeId, content: &[NodeId]) {
        let Some(mut inst) = self.components.instances.remove(&host) else {
            return;
        };
        // The app's element in a slot: the holder takes the slot's props.
        self.target_released(host);
        if self
            .components
            .parked_methods
            .iter()
            .any(|(h, ..)| *h == host)
        {
            let (gone, kept) = std::mem::take(&mut self.components.parked_methods)
                .into_iter()
                .partition(|(h, ..)| *h == host);
            self.components.parked_methods = kept;
            for (_, call, method) in gone {
                drop_caught(method);
                self.settle(
                    call,
                    Err(format!("node {host} hosts no Rust component").into()),
                );
            }
        }
        // Its root's (a render or classes of the app's) on the host.
        self.forget_node_extras(host);
        if let Inner::Component(inner) = &mut inst.inner {
            if let Err(message) = caught(|| inner.cleanup()) {
                log::error!(target: "js", "{} failed in its cleanup: {message}", inner.name());
            }
            self.apply_actions();
        }
        self.release_regions(host);
        self.components.runtime.forget_host(host);
        if let Some(owner) = inst.cell_owner.take() {
            owner.dispose();
        }
        for &child in &inst.js_children {
            if !content.contains(&child) {
                self.detach_id(child);
            }
        }
        for (_, node) in inst.slots {
            self.drop_slot_target(node);
            self.components.slot_hosts.remove(&node);
            if !content.contains(&node) {
                self.detach_id(node);
            }
        }
        if let Some(root) = inst.root {
            // The component its root is, with its alias.
            if matches!(root.part, Part::Component(_)) {
                self.release_expanded(root);
                return;
            }
            let node = self.native_id(host);
            if let Some(r) = root
                .attrs
                .rare
                .as_ref()
                .and_then(|r| r.element_ref.as_ref())
            {
                r.detach(node);
            }
            if root.part == Part::VirtualList {
                self.release_virtual_list(node);
            }
            if let Some((_, raw)) = root.text {
                self.release_id(raw);
            }
            for c in root.children {
                self.release_expanded(c);
            }
        }
    }

    /// Releases the component's own list `id`: its cells, and what knew of
    /// it.
    fn release_virtual_list(&mut self, id: NodeId) {
        if let Some(state) = self.components.virtual_lists.remove(&id) {
            let parts = state.contents.into_iter().chain(state.cells);
            for part in parts.filter(|&c| c != 0) {
                self.release_instance(part);
                self.release_id(part);
            }
        }
        // The rows of another component's `Items` prop: no longer its slot.
        if self.components.slot_names.remove(&id).is_some() {
            self.unslot(id);
        }
        self.components.lists.remove(&id);
        self.forget_list_count(id);
    }

    /// A native event on node `id`: true when a component handled it (its
    /// own parts' events never reach JS, which does not know them).
    pub fn component_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
        let _entered = self.components.runtime.enter();
        // A Rust text block's final layout, for its `on_text_layout`.
        let _geometry = (kind == EventKind::TextLayout)
            .then(|| self.geometries.remove(&id))
            .flatten()
            .map(crate::text::GeometryScope::enter);
        let handled = self.dispatch_event(id, kind, payload);
        self.flush_component_emits();
        handled
    }

    /// Whether node `id` has a listener for `event` (a JS handler or a Rust
    /// component's), as the platform sees it mounted. The engine skips
    /// nodes without one when it fans a key notification out.
    #[doc(hidden)]
    pub fn listens(&self, id: NodeId, event: EventKind) -> bool {
        self.key(id)
            .is_ok_and(|key| self.nodes[key as usize].mounted_events().contains(event))
    }

    /// Whether `id` or an enabled logical ancestor up to its window root
    /// hears a key transition (`KeyDown` or `KeyUp`) or has a capture rule
    /// that is not `None`. Follows the logical tree (`node.parent`), so an
    /// overlay's content finds the views it is logically in even where a
    /// backend mounts it elsewhere. No allocation: a walk per transition.
    #[doc(hidden)]
    pub fn key_interest(&self, id: NodeId) -> bool {
        let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
            return false;
        };
        let window = self.key_window(key);
        loop {
            let node = &self.nodes[key as usize];
            let disabled = node
                .props
                .as_ref()
                .is_some_and(|p| p.accessibility.state.disabled);
            if !disabled {
                let events = node.mounted_events();
                if events.contains(EventKind::KeyDown) || events.contains(EventKind::KeyUp) {
                    return true;
                }
                if node
                    .props
                    .as_ref()
                    .is_some_and(|p| !p.key_capture.is_none())
                {
                    return true;
                }
            }
            if node.id == window || node.parent == NO_KEY {
                return false;
            }
            key = node.parent;
        }
    }

    /// The views a key notification on `id` reaches, in order: `id`, then
    /// each enabled ancestor, up to and including the root of `id`'s window.
    /// The engine notifies every one of them (Rust and JS listeners alike)
    /// from one platform event; a native window is a keyboard boundary even
    /// when its declarative root remains in another window's logical tree.
    /// A disabled view hears nothing, and its enabled ancestors still do.
    #[doc(hidden)]
    pub fn key_path(&self, id: NodeId, out: &mut Vec<NodeId>) {
        out.clear();
        let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
            return;
        };
        let window = self.key_window(key);
        loop {
            let node = &self.nodes[key as usize];
            let disabled = node
                .props
                .as_ref()
                .is_some_and(|p| p.accessibility.state.disabled);
            if !disabled {
                out.push(node.id);
            }
            if node.id == window || node.parent == NO_KEY {
                return;
            }
            key = node.parent;
        }
    }

    /// Whether `id` or an enabled ancestor within its window captures the
    /// transition whose canonical shortcut stroke is `keystroke` under its
    /// mounted [`crate::KeyCapture`] rule (`captureKeys`). The platform
    /// decides before native defaults from the stroke its own shortcut
    /// vocabulary names, never from [`crate::KeyEvent`]'s `key` or `code`;
    /// `None` (a key no shortcut names) is captured only by
    /// [`crate::KeyCapture::All`]. A focused native text input keeps the
    /// keys that edit it: nothing captures them.
    #[doc(hidden)]
    pub fn key_captured(&self, id: NodeId, keystroke: Option<&crate::keymap::Keystroke>) -> bool {
        let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
            return false;
        };
        // A native text input owns the keys that edit it: an ancestor's
        // capture never intercepts its typing, caret or editing commands.
        if self.nodes[key as usize].kind == Kind::Input {
            return false;
        }
        let window = self.key_window(key);
        loop {
            let node = &self.nodes[key as usize];
            let disabled = node
                .props
                .as_ref()
                .is_some_and(|p| p.accessibility.state.disabled);
            if !disabled
                && node
                    .props
                    .as_ref()
                    .is_some_and(|p| p.key_capture.captures_key(keystroke))
            {
                return true;
            }
            if node.id == window || node.parent == NO_KEY {
                return false;
            }
            key = node.parent;
        }
    }

    /// Where a key transition reported at `key` starts. A backend with
    /// nothing focused in a window reports at the window's root (`ROOT_ID`,
    /// or a dialog window's root): the app's views are not its ancestors,
    /// so the transition starts at the view mounted there (the app's mount
    /// root, or the dialog's content) and bubbles from it, as a browser
    /// reports it at `document.body` (#2362). Any other node starts at
    /// itself.
    pub(super) fn key_start(&self, key: Key) -> Key {
        let node = &self.nodes[key as usize];
        if node.id != crate::ROOT_ID
            && (node.kind != Kind::Modal || self.key_window(key) != node.id)
        {
            return key;
        }
        node.children
            .iter()
            .copied()
            .find(|&child| !matches!(self.nodes[child as usize].kind, Kind::Overlay | Kind::Modal))
            .unwrap_or(key)
    }

    /// A window's staged keyboard target follows its logical children.
    pub(super) fn key_content_changed(&mut self, parent: Key) {
        let node = &self.nodes[parent as usize];
        if node.id == crate::ROOT_ID
            || (node.kind == Kind::Modal && self.key_window(parent) == node.id)
        {
            self.key_ancestry_dirty = true;
        }
    }

    /// The root of the window `key` is in, `key` itself when it is one.
    pub(super) fn key_window(&self, key: Key) -> NodeId {
        let node = &self.nodes[key as usize];
        if node.kind == Kind::Modal && self.window_ids.values().any(|(root, _)| *root == node.id) {
            node.id
        } else {
            self.window_of(key)
        }
    }

    fn flush_component_emits(&mut self) {
        // What views' listeners emitted reaches its listeners (JS hears it
        // in this turn).
        loop {
            let emits = self.components.runtime.take_emits();
            if emits.is_empty() {
                break;
            }
            for (host, event) in emits {
                self.route_emit(host, event);
            }
        }
    }

    /// Initializes one newly installed layout listener of a kept node.
    /// The engine delivers this in event order, without notifying the
    /// node's retained listeners or its JS handlers.
    #[doc(hidden)]
    pub fn component_layout(
        &mut self,
        host: NodeId,
        id: NodeId,
        listener: &Listener<EventPayload>,
        frame: crate::Bounds<Points>,
    ) {
        let _entered = self.components.runtime.enter();
        let installed = self.components.instances.get(&host).is_some_and(|inst| {
            inst.handlers
                .of(id)
                .iter()
                .any(|(kind, current)| *kind == EventKind::Layout && current.ptr_eq(listener))
        });
        if installed {
            self.run_listener(host, listener, &EventPayload::Layout(frame));
            self.flush_component_emits();
        }
    }

    fn dispatch_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
        // Before a cancelled press's release is dropped: it still ends the
        // span's press.
        self.span_state(id, kind);
        // A cancelled press's release reaches no one, JS included.
        if self.drop_cancelled_press(id, kind, payload) {
            return true;
        }
        // Touches come on the root with the listening nodes around each
        // finger: the components hear theirs, JS its own.
        if kind == EventKind::Touch && id == ROOT_ID {
            if let EventPayload::Touch(touch) = payload {
                self.overlay_touches(touch);
                self.touches(payload, touch);
            }
            return false;
        }
        // Hints follow the pointer on their anchors, whoever else listens.
        if matches!(kind, EventKind::MouseEnter | EventKind::MouseLeave) {
            let at = match payload {
                EventPayload::Mouse(mouse) => Some(mouse.page_position),
                _ => None,
            };
            self.overlay_hover(id, kind, at);
        }
        // A download event's listener gets a handle bound to the native
        // web view node the platform reported, not the component host its
        // handlers were registered on: only this dispatch can make one.
        let _target = matches!(kind, EventKind::DownloadPending | EventKind::Download)
            .then(|| crate::element::download_target(id, Rc::downgrade(&self.components.executor)));
        if self.platform_event(id, kind, payload) {
            return true;
        }
        if self.is_host(id) {
            // The component whose view makes the host's node handles them,
            // after the one whose slot's props it takes.
            let base = self.base_of(id);
            if let Some(slot) = self.adopted_host(base) {
                self.handle(slot, base, kind, payload);
            }
            let own = self.handle(base, base, kind, payload);
            // A context menu has one listener: a component showing its own
            // keeps it.
            if own && kind == EventKind::ContextMenu {
                return true;
            }
            let given = self.handle_given(base, kind, payload);
            // JS listening on the host hears it too.
            return (own || given) && !self.js_listens(base, kind);
        }
        // A component's own list reports its viewable rows as they settle.
        if kind == EventKind::ViewableItemsChange && self.components.virtual_lists.contains_key(&id)
        {
            self.viewable_changed(id, payload);
            return true;
        }
        // A slot's node: the component it is a slot of handles its events,
        // then whoever made it: the component whose view has it, or JS (the
        // app's list of an `Items` prop has the app's handlers). So does the
        // app's element that takes the slot's props, then JS.
        let slot_of = self
            .components
            .slot_hosts
            .get(&id)
            .copied()
            .or_else(|| self.adopted_host(id));
        let owner = self.components.owners.get(&id).copied();
        if let Some(host) = slot_of {
            self.handle(host, id, kind, payload);
        }
        if let Some(host) = owner
            && Some(host) != slot_of
        {
            self.handle(host, id, kind, payload);
        }
        // The core's nodes (odd ids) are the components': JS does not know
        // them.
        (slot_of.is_some() || owner.is_some()) && id % 2 == 1
    }

    /// The host of the component whose view has node `id` (for a host, the
    /// component whose view makes its node: itself, or its root
    /// component's).
    pub(super) fn host_of(&self, id: NodeId) -> Option<NodeId> {
        if self.is_host(id) {
            Some(self.base_of(id))
        } else {
            self.components.owners.get(&id).copied()
        }
    }

    /// Runs `host`'s component's handlers of `kind` on its node `id`, in
    /// the order the element was given them; false when it has none.
    fn handle(
        &mut self,
        host: NodeId,
        id: NodeId,
        kind: EventKind,
        payload: &EventPayload,
    ) -> bool {
        let id = self.base_of(id);
        let mut handled = false;
        let mut from = 0;
        while let Some((at, listener)) = self.next_handler(host, id, kind, from) {
            from = at + 1;
            // A listener may release the component: the rest go with it.
            if !self.run_listener(host, &listener, payload) {
                break;
            }
            handled = true;
        }
        handled
    }

    /// The first of `host`'s component's handlers of `kind` on its node `id`
    /// at or after index `from`, with its index: a dispatch walks them in
    /// order (an element given several listeners of one event calls them
    /// all) with no list of its own. The handlers stay as they are while it
    /// does: a view's regions change them when they are reconciled, in the
    /// commit, not as listeners run.
    pub(super) fn next_handler(
        &self,
        host: NodeId,
        id: NodeId,
        kind: EventKind,
        from: usize,
    ) -> Option<(usize, Listener<EventPayload>)> {
        let id = self.base_of(id);
        let inst = self.components.instances.get(&host)?;
        let handlers = inst.handlers.of(id);
        #[cfg(test)]
        self.components
            .handler_visits
            .set(self.components.handler_visits.get() + handlers.len().saturating_sub(from));
        handlers
            .iter()
            .enumerate()
            .skip(from)
            .find(|(_, (k, _))| *k == kind)
            .map(|(at, (_, l))| (at, l.clone()))
    }

    /// The part of `host`'s node `id` in the touch responder.
    pub(super) fn responder_el(&self, host: NodeId, id: NodeId) -> Option<Rc<ResponderEl>> {
        let id = self.base_of(id);
        self.components
            .instances
            .get(&host)?
            .responders
            .iter()
            .find(|(n, _)| *n == id)
            .map(|(_, r)| r.clone())
    }

    /// Runs `listener` of a node of `host`'s view (or of a list row of it);
    /// false when that component is gone.
    pub(super) fn run_listener<E: ?Sized + 'static>(
        &mut self,
        host: NodeId,
        listener: &Listener<E>,
        event: &E,
    ) -> bool {
        let Some(owner) = self.state_owner(host) else {
            return false;
        };
        if let Err(message) = caught(|| listener.call(event)) {
            self.component_failed(owner, message);
        }
        self.apply_actions();
        true
    }

    /// The component whose state `host`'s handlers change: its own, or for
    /// a list row the component's whose list it is.
    pub(super) fn state_owner(&self, host: NodeId) -> Option<NodeId> {
        match &self.components.instances.get(&host)?.inner {
            Inner::Component(_) => Some(host),
            Inner::VirtualRow { list, .. } => {
                self.components.virtual_lists.get(list).map(|s| s.owner)
            }
            Inner::Row { .. } => self
                .list_of(host)
                .and_then(|l| self.components.slot_hosts.get(&l))
                .copied(),
            Inner::Missing => None,
        }
    }

    /// The code of `host`'s component panicked: the nearest error boundary
    /// above it shows it ([`crate::element::catch_error`]); else it is reported.
    pub(super) fn component_failed(&mut self, host: NodeId, message: String) {
        let component = match self.components.instances.get(&host).map(|i| &i.inner) {
            Some(Inner::Component(inner)) => inner.name(),
            _ => "a list row",
        };
        let error = ComponentError { component, message };
        // The nearest error boundary of a view above it.
        let owner = self
            .components
            .instances
            .get(&host)
            .and_then(|inst| match &inst.inner {
                Inner::Component(inner) => Some(inner.failure_owner()),
                _ => inst.cell_owner,
            });
        let _entered = self.components.runtime.enter();
        match owner.and_then(crate::element::reactive::boundary_of) {
            Some(boundary) => boundary.set(Some(error)),
            None => log::error!(target: "js", "{error}"),
        }
    }

    /// The list cell `cell` is in.
    fn list_of(&self, cell: NodeId) -> Option<NodeId> {
        let key = self.key(cell).ok()?;
        let parent = self.nodes[key as usize].parent;
        (parent != NO_KEY).then(|| self.nodes[parent as usize].id)
    }

    /// Reads (`enabled` `None`) or changes whether the app launches at
    /// login: on the backend's thread when the runner gave the core one,
    /// the answer (on or not) delivered in a task here; without one the app
    /// does not launch at login, and a change fails.
    fn login_item_action(
        &mut self,
        enabled: Option<bool>,
        answer: crate::element::AnswerSlot<Result<bool, crate::desktop::LaunchAtLoginError>>,
    ) {
        use crate::desktop::{LaunchAtLoginError, LoginItemStatus};
        // Launching at login acts on the application as a whole: an app
        // declaring capabilities needs `application` to change it, and is
        // told it does not launch at login otherwise.
        if !self.access.allows_application() {
            answer.borrow_mut().deliver(match enabled {
                None => Ok(false),
                Some(_) => Err(LaunchAtLoginError::Denied),
            });
            return;
        }
        let Some(items) = self.login_item.as_mut() else {
            answer.borrow_mut().deliver(match enabled {
                None => Ok(false),
                Some(_) => Err(LaunchAtLoginError::Unavailable),
            });
            return;
        };
        let result = items.call(enabled);
        crate::element::task::spawn_raw(
            &self.components.executor,
            crate::ROOT_ID,
            Box::pin(async move {
                let result = match result.await {
                    // Nothing to change where the platform has no login
                    // item for the app (a sandboxed Linux app).
                    Ok(LoginItemStatus::Unavailable) if enabled.is_some() => {
                        Err(LaunchAtLoginError::Unavailable)
                    }
                    Ok(status) => Ok(status == LoginItemStatus::Enabled),
                    Err(error) => Err(LaunchAtLoginError::System(error)),
                };
                answer.borrow_mut().deliver(result);
            }),
        );
    }

    /// Applies what the app asks about notifications: granted and where
    /// the platform shows them, the platform answers with
    /// [`EventKind::Notification`]; otherwise the answer is given here.
    fn notification_action(&mut self, action: crate::element::NotificationAction) {
        use crate::{
            element::NotificationAction,
            notifications::{NotificationCommand, NotificationPermission},
        };
        let allowed = self.access.allows_notifications();
        let available = allowed && self.components.environment.notifications;
        let command = match action {
            NotificationAction::Permission { ask, answer } => {
                if !available {
                    answer
                        .borrow_mut()
                        .deliver(NotificationPermission::Unavailable);
                    return;
                }
                let state = &mut self.components.notifications;
                let id = state.next;
                state.next = id.wrapping_add(1);
                state.permissions.insert(id, answer);
                NotificationCommand::Permission { id, ask }
            }
            NotificationAction::Show {
                notification,
                answer,
            } => {
                if !available {
                    answer.borrow_mut().deliver(false);
                    return;
                }
                let state = &mut self.components.notifications;
                let id = state.next;
                state.next = id.wrapping_add(1);
                state.shows.insert(id, answer);
                NotificationCommand::Show { id, notification }
            }
            NotificationAction::Close(id) => {
                if !available {
                    return;
                }
                NotificationCommand::Close(id)
            }
            NotificationAction::CloseAll => {
                if !available {
                    return;
                }
                NotificationCommand::CloseAll
            }
            NotificationAction::SetBadge(count) => {
                if !allowed {
                    return;
                }
                NotificationCommand::SetBadge(count)
            }
            NotificationAction::NextPress(answer) => {
                let state = &mut self.components.notifications;
                if let Some(pressed) = state.presses.pop_front() {
                    answer.borrow_mut().deliver(pressed);
                    return;
                }
                state.next_press = Some(answer);
                if !available || state.listening {
                    return;
                }
                state.listening = true;
                NotificationCommand::Listen
            }
        };
        let _ = self.apply_op(Op::Command {
            id: crate::ROOT_ID,
            command: Command::Notification(command),
        });
    }

    /// The app's address, which the engine shares with every VM's
    /// `System` (`UrlScheme.url()` reads it there).
    #[doc(hidden)]
    pub fn app_url_cell(&self) -> crate::url_scheme::AppUrlCell {
        self.components.url_schemes.address.clone()
    }

    /// Hands `url`, a link the system gave the app, to the listener, or
    /// keeps it for the next; drops it when the app does not claim it.
    /// `page`: the address of the page the app is (the web), which needs
    /// no scheme of the app's; `quiet` only takes it as the address;
    /// `change`, an address the app moved to without making the move,
    /// goes to the change listener instead of `open`.
    fn url_scheme(
        &mut self,
        url: String,
        page: bool,
        quiet: bool,
        change: Option<crate::url_scheme::AppUrlChangeReason>,
    ) {
        let links = &mut self.components.url_schemes;
        // A file the system opened the app with (nsh.json `fileTypes`): the
        // platforms report it as a `file://` URL, the core hands it to the
        // app as a file ([`crate::file_type`]), never as a link.
        if !page && change.is_none() && crate::file_type::is_file_url(&url) {
            if !links
                .links
                .schemes()
                .iter()
                .any(|s| s == crate::file_type::FILE_SCHEME)
            {
                log::warn!("file dropped: the app declares no file types (nsh.json `fileTypes`)");
                return;
            }
            let Some(path) = crate::file_type::file_path(&url) else {
                log::warn!("file dropped: {url} is not a local file");
                return;
            };
            let files = &mut self.components.open_files;
            if let Some(answer) = files.next.take() {
                answer.borrow_mut().deliver(vec![path]);
                return;
            }
            if files.pending.len() == crate::file_type::MAX_PENDING {
                log::warn!(
                    "file dropped: {} came while nothing listened",
                    crate::file_type::MAX_PENDING
                );
                files.pending.pop_front();
            }
            files.pending.push_back(path);
            return;
        }
        let checked = if page {
            crate::url_scheme::check_page_url(&url)
        } else {
            links.links.check(&url)
        };
        if let Err(dropped) = checked {
            log::warn!("link dropped: {dropped}");
            return;
        }
        let links = &mut self.components.url_schemes;
        // A link a wait for its scheme takes is that wait's alone (a sign-in
        // session's callback): no listener of the app's hears it, and it
        // does not become the app's address.
        if !quiet && change.is_none() {
            let scheme = url.split_once(':').map_or("", |(scheme, _)| scheme);
            links
                .next_of_scheme
                .retain(|(_, answer)| crate::element::task::awaited(answer));
            if let Some(at) = links
                .next_of_scheme
                .iter()
                .position(|(waited, _)| waited.eq_ignore_ascii_case(scheme))
            {
                let (_, answer) = links.next_of_scheme.remove(at);
                answer.borrow_mut().deliver(url);
                return;
            }
        }
        links.address.set(url.clone());
        if quiet {
            return;
        }
        if let Some(reason) = change {
            if !links.hears_changes {
                return;
            }
            let change = crate::url_scheme::AppUrlChange { url, reason };
            if let Some(answer) = links.next_change.take() {
                answer.borrow_mut().deliver(change);
                return;
            }
            if links.changes.len() == crate::url_scheme::MAX_PENDING {
                links.changes.pop_front();
            }
            links.changes.push_back(change);
            return;
        }
        let executor = &self.components.executor;
        links.open(url, |task| executor.has_task(task));
    }

    /// The schemes the app claims (`nsh.json` `schemes`,
    /// [`crate::url_scheme`]), from the app's own resources: the links the
    /// platform reports of other schemes are dropped. None by default.
    /// [`Core::set_app_links`] sets them with the app's web links.
    pub fn set_url_schemes(&mut self, schemes: impl IntoIterator<Item = impl Into<String>>) {
        self.components.url_schemes.links.set_schemes(schemes);
    }

    /// The links the app claims (`nsh.json` `schemes` and `links`,
    /// [`crate::url_scheme::AppLinks`]), from the app's own resources: the
    /// links the platform reports that are none of them (another scheme, an
    /// `https` link of another host or path) are dropped. None by default.
    pub fn set_app_links(&mut self, links: crate::url_scheme::AppLinks) {
        self.components.url_schemes.links = links;
    }

    /// Answers what waits for the platform's [`EventKind::Notification`].
    fn notification_event(&mut self, payload: &EventPayload) {
        use crate::notifications::{NotificationEvent as Field, NotificationPermission};
        let EventPayload::Map(entries) = payload else {
            return;
        };
        let state = &mut self.components.notifications;
        let id = entries.iter().find_map(|(k, v)| match v {
            crate::PayloadValue::Number(n) if *k == Field::ID => Some(*n as u32),
            _ => None,
        });
        for (key, value) in entries {
            match (*key, value) {
                (Field::PERMISSION, crate::PayloadValue::Str(name)) => {
                    if let Some(answer) = id.and_then(|id| state.permissions.remove(&id)) {
                        let permission = NotificationPermission::from_name(name)
                            .unwrap_or(NotificationPermission::Unavailable);
                        answer.borrow_mut().deliver(permission);
                    }
                }
                (Field::SHOWN, crate::PayloadValue::Bool(shown)) => {
                    if let Some(answer) = id.and_then(|id| state.shows.remove(&id)) {
                        answer.borrow_mut().deliver(*shown);
                    }
                }
                (Field::PRESSED, crate::PayloadValue::Str(pressed)) => {
                    match state.next_press.take() {
                        Some(answer) => answer.borrow_mut().deliver(pressed.clone()),
                        None => state.presses.push_back(pressed.clone()),
                    }
                }
                _ => {}
            }
        }
    }

    /// Applies a sound's or a player's request: through the embedding
    /// app's audio stack when it gave one, else as commands on the root the
    /// platform answers with [`EventKind::Audio`].
    fn audio_action(&mut self, action: crate::element::AudioAction) {
        use crate::{
            audio::{AudioCommand, AudioError, AudioEvent},
            element::AudioAction,
        };
        let (command, sink) = match action {
            AudioAction::Available(answer) => {
                let available = match &self.audio {
                    Some(backend) => backend.available(),
                    None => self.components.environment.audio,
                };
                answer.borrow_mut().deliver(available);
                return;
            }
            AudioAction::Open { mut command, sink } => {
                debug_assert!(matches!(
                    command,
                    AudioCommand::Load { .. }
                        | AudioCommand::LoadUrl { .. }
                        | AudioCommand::Open { .. }
                ));
                let failed = |error, message: &str| AudioEvent::Failed {
                    error,
                    message: message.into(),
                };
                if !self.access.allows_audio() {
                    sink.send(failed(AudioError::NotAllowed, "sound is not granted"));
                    sink.close();
                    self.deny(
                        "sound is not granted: add `\"audio\": true` to capabilities in nsh.json"
                            .into(),
                    );
                    return;
                }
                // A sound loads what the check granted (`Access::media_url`).
                if let AudioCommand::Open { src, .. } | AudioCommand::LoadUrl { url: src, .. } =
                    &mut command
                {
                    match self.media_source(src) {
                        Some(granted) => {
                            if let Some(url) = granted {
                                *src = url.to_string();
                            }
                        }
                        None => {
                            let base = self.base_url.as_deref();
                            let capability = crate::access::media_capability(src, base);
                            let advice = crate::access::media_grant_advice(src, base);
                            // Worded without the app's text: the player's
                            // error names the capability from it.
                            sink.send(failed(
                                AudioError::NotAllowed,
                                &format!("{}{capability}", super::SOURCE_NOT_GRANTED),
                            ));
                            sink.close();
                            self.deny(format!(
                                "`{src}` is not granted by capabilities.{capability}: {advice}"
                            ));
                            return;
                        }
                    }
                }
                if self.audio.is_none() && !self.components.environment.audio {
                    sink.send(failed(AudioError::Unavailable, "nothing plays sound here"));
                    sink.close();
                    return;
                }
                self.components.audio.insert(command.id(), sink.clone());
                (command, sink)
            }
            AudioAction::Command(command) => {
                let id = command.id();
                let sink = if command.ends() {
                    self.components.audio.remove(&id)
                } else {
                    self.components.audio.get(&id).cloned()
                };
                // A command of an object that failed to open, or closed.
                let Some(sink) = sink else {
                    return;
                };
                if command.ends() {
                    sink.close();
                }
                (command, sink)
            }
        };
        match self.audio.clone() {
            Some(backend) => backend.command(command, &sink),
            None => {
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::Audio(command),
                });
            }
        }
    }

    fn apply_action(&mut self, action: Action) {
        match action {
            Action::Command(id, command) => {
                let _ = self.apply_op(Op::Command { id, command });
            }
            // Answered as the command leaves for the platform
            // (`Core::take_commands`) or when the platform reports it.
            Action::WriteClipboard(command, answer) => {
                self.components.clipboard_writes.push_back(answer);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command,
                });
            }
            Action::FocusBack { to, from } => self.focus_back = Some((to, from)),
            Action::FocusOrigin { to } => self.note_focus_origin(to),
            Action::Dialog(mut dialog, answer) => {
                dialog.id = self.components.next_dialog;
                self.components.next_dialog += 1;
                self.components.dialogs.insert(dialog.id, answer);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::Dialog(Box::new(dialog)),
                });
            }
            Action::CloseDialog(answer) => {
                // Answered already (or never shown): nothing to close.
                let Some(id) = self
                    .components
                    .dialogs
                    .iter()
                    .find_map(|(id, slot)| Rc::ptr_eq(slot, &answer).then_some(*id))
                else {
                    return;
                };
                self.components.dialogs.remove(&id);
                answer
                    .borrow_mut()
                    .deliver(crate::element::DialogReply::dismissed());
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::CloseDialog(id),
                });
            }
            Action::Return(call, result) => self.settle(call, result),
            Action::Animation(op) => {
                let _ = self.apply_op(Op::Animation(op));
            }
            Action::Animate { op, animation, end } => {
                self.components
                    .animations
                    .insert(animation, Awaited::End(end));
                let _ = self.apply_op(Op::Animation(op));
            }
            Action::ReadValue { node, value } => {
                let request = self.components.executor.next_animation_id();
                self.components
                    .animations
                    .insert(request, Awaited::Value(value));
                let _ = self.apply_op(Op::Animation(crate::animation::AnimationOp::Read {
                    node,
                    request,
                }));
            }
            Action::ReportViewable(list) => self.report_viewable(list),
            Action::Hint(overlay) => self.hint_due(overlay),
            Action::Frame(answer) => self.wait_frame(answer),
            Action::Appearance(appearance) => self.set_appearance(appearance),
            Action::Tokens(tokens) => self.set_tokens(tokens),
            Action::Translations(translations) => self.set_translations(translations),
            Action::AddTranslations(map) => self.add_translations(map),
            Action::TranslationsChanged(before) => self.translations_changed(&before),
            Action::Locale(locale) => self.components.locale_request = Some(locale),
            Action::MainThread(task) => self.components.main_thread.push(task),
            Action::BuiltInScrollbars(source, theme) => {
                self.set_builtin_scrollbars(theme.map(|theme| (source, theme)))
            }
            Action::Measure(id, answer) => self.components.measures.push((id, answer)),
            Action::MeasureScrollPosition(id, answer) => {
                self.components.scroll_positions.push((id, answer))
            }
            Action::Evaluate(node, script, timeout, answer) => {
                self.start_web_evaluation(node, script, timeout, answer)
            }
            Action::WebEvaluationTimeout(request) => self.timeout_web_evaluation(request),
            Action::CanvasRenderTimeout(id) => self.timeout_canvas_render(id),
            Action::TransitionTime(id, answer) => {
                self.components.transition_times.push((id, answer))
            }
            Action::TextContent(id, answer) => self.components.text_contents.push((id, answer)),
            Action::PressAt(id, press, answer) => self.components.presses.push((id, press, answer)),
            Action::HoverAt(id, mouse) => self.components.hovers.push((id, mouse)),
            Action::ImageInfo(uri, answer) => {
                let id = self.components.next_image_info;
                self.components.next_image_info += 1;
                self.components.image_infos.insert(id, answer);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::ImageInfo { id, uri },
                });
            }
            Action::Fetch(request, answer) => {
                let id = self.components.next_fetch;
                self.components.next_fetch += 1;
                self.components.fetches.insert(
                    id,
                    PendingFetch {
                        response: crate::element::HttpResponse::default(),
                        answer,
                    },
                );
                self.components.fetch_requests.push((id, *request));
            }
            Action::RegisterFont(data, answer) => {
                // The family is the answer: a font without one is refused.
                let family = crate::text::font_family(&data)
                    .and_then(|family| self.register_font(&data).map(|()| family));
                answer.borrow_mut().deliver(family);
            }
            Action::PickImages(request, answer) => {
                if !self.access.allows_picker() {
                    answer.borrow_mut().deliver(Vec::new());
                    self.deny(
                        "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
                            .into(),
                    );
                    return;
                }
                if let Some(picker) = self.picker.clone() {
                    let picked = picker.pick_images(request);
                    crate::element::task::spawn_raw(
                        &self.components.executor,
                        crate::ROOT_ID,
                        Box::pin(async move {
                            let files = crate::picker::finish(&request, picked.await);
                            answer.borrow_mut().deliver(files);
                        }),
                    );
                    return;
                }
                let id = self.components.next_pick;
                self.components.next_pick += 1;
                self.components
                    .picks
                    .insert(id, (crate::picker::Pick::Images(request), answer));
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::PickImages { id, request },
                });
            }
            Action::PickFiles(request, answer) => {
                if !self.access.allows_picker() {
                    answer.borrow_mut().deliver(Vec::new());
                    self.deny(
                        "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
                            .into(),
                    );
                    return;
                }
                if let Some(picker) = self.picker.clone() {
                    let picked = picker.pick_files(request.clone());
                    crate::element::task::spawn_raw(
                        &self.components.executor,
                        crate::ROOT_ID,
                        Box::pin(async move {
                            let files = crate::picker::finish_files(&request, picked.await);
                            answer.borrow_mut().deliver(files);
                        }),
                    );
                    return;
                }
                let id = self.components.next_pick;
                self.components.next_pick += 1;
                self.components
                    .picks
                    .insert(id, (crate::picker::Pick::Files(request.clone()), answer));
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::PickFiles { id, request },
                });
            }
            Action::ReadClipboard(read) => {
                let id = self.components.next_clipboard_read;
                self.components.next_clipboard_read += 1;
                let command = match &read {
                    ClipboardRead::Text(_) | ClipboardRead::CheckedText(_) => {
                        Command::ReadClipboard {
                            id,
                            has_only: false,
                        }
                    }
                    ClipboardRead::Has(_) => Command::ReadClipboard { id, has_only: true },
                    ClipboardRead::Image(_) | ClipboardRead::CheckedImage(_) => {
                        Command::ReadClipboardImage {
                            id,
                            has_only: false,
                        }
                    }
                    ClipboardRead::HasImage(_) => {
                        Command::ReadClipboardImage { id, has_only: true }
                    }
                    ClipboardRead::Files(_) => Command::ReadClipboardFiles { id },
                };
                self.components.clipboard_reads.insert(id, read);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command,
                });
            }
            // Checked here, before the engine routes them: the embedding
            // app's channel and the platform get only granted names.
            Action::HostCall { name, args, answer } => {
                use crate::host_channel::{HostError, MAX_PENDING_CALLS};
                let refused = crate::host_channel::refusal(&self.access, &name).or_else(|| {
                    (self.components.host_calls.len() >= MAX_PENDING_CALLS)
                        .then(|| HostError::TooManyCalls { name: name.clone() })
                });
                if let Some(error) = refused {
                    if !matches!(error, HostError::TooManyCalls { .. }) {
                        self.deny(error.to_string());
                    }
                    answer.borrow_mut().deliver(Err(error));
                    return;
                }
                let id = self.components.next_host_call;
                self.components.next_host_call += 1;
                self.components.host_calls.insert(id, answer);
                self.components
                    .host_requests
                    .push(crate::host_channel::HostRequest::Call { id, name, args });
            }
            Action::HostPost { name, args } => {
                if let Some(error) = crate::host_channel::refusal(&self.access, &name) {
                    self.deny(error.to_string());
                    return;
                }
                self.components
                    .host_requests
                    .push(crate::host_channel::HostRequest::Post { name, args });
            }
            // A call timed out (`runtime/host.rs`), its answer dropped: its
            // slot waits no more.
            Action::ForgetHostCalls => {
                self.components
                    .host_calls
                    .retain(|_, slot| std::rc::Rc::strong_count(slot) > 1);
            }
            Action::OpenUrl(url, answer) => {
                if let Err(refused) = crate::open_url::check_url(&url) {
                    log::warn!(target: "js", "{refused}");
                    answer.borrow_mut().deliver(false);
                    return;
                }
                if !self.access.allows_open_url(&url) {
                    answer.borrow_mut().deliver(false);
                    self.deny(crate::open_url::not_granted(&url).message().to_owned());
                    return;
                }
                let id = self.components.next_url_open;
                self.components.next_url_open = id.wrapping_add(1);
                self.components.url_opens.insert(id, answer);
                self.components.url_requests.push((id, url));
            }
            Action::OpenAppSettings(answer) => {
                use crate::mobile::AppSettingsError;
                // The app's settings page acts on the application as a
                // whole (the embedding app's, embedded): an app declaring
                // capabilities needs `application`.
                let refused = if !self.access.allows_application() {
                    Some(AppSettingsError::Denied)
                } else if !self.components.environment.app_settings {
                    Some(AppSettingsError::Unavailable)
                } else {
                    None
                };
                if let Some(error) = refused {
                    answer.borrow_mut().deliver(Err(error));
                    return;
                }
                let id = self.components.next_app_settings_open;
                self.components.next_app_settings_open = id.wrapping_add(1);
                self.components.app_settings_opens.insert(id, answer);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::OpenAppSettings { id },
                });
            }
            Action::AppSettingsAvailable(answer) => {
                let available =
                    self.components.environment.app_settings && self.access.allows_application();
                answer.borrow_mut().deliver(available);
            }
            Action::Audio(action) => self.audio_action(action),
            Action::Notification(action) => self.notification_action(action),
            Action::LoginItem(enabled, answer) => self.login_item_action(enabled, answer),
            Action::SnapToWindowMargin(margin) => self.set_snap_to_window_margin(margin),
            Action::ChooseMenuItem(item) => {
                // As the platform's menu bar reports a choice: a view's
                // handler runs here, JS's in JS.
                let payload =
                    EventPayload::Map(vec![("id", crate::PayloadValue::Number(f64::from(item)))]);
                if !self.dispatch_event(crate::ROOT_ID, EventKind::Menu, &payload) {
                    self.events.push(crate::element::JsEvent::Event(
                        crate::ROOT_ID,
                        EventKind::Menu,
                        payload,
                    ));
                }
            }
            Action::NextUrlSchemeOpen(task, answer) => {
                let executor = &self.components.executor;
                self.components
                    .url_schemes
                    .listen(task, answer, |task| executor.has_task(task));
            }
            Action::NextUrlSchemeOpenFor(scheme, answer) => {
                let links = &mut self.components.url_schemes;
                let claimed = links.links.schemes().contains(&scheme)
                    || (scheme == "https" && !links.links.web().is_empty());
                if !claimed {
                    log::warn!(
                        "next_url_scheme_open_for: the app does not claim `{scheme}` (nsh.json `schemes`), so no link of it comes"
                    );
                }
                links
                    .next_of_scheme
                    .retain(|(_, answer)| crate::element::task::awaited(answer));
                links.next_of_scheme.push((scheme, answer));
            }
            Action::NextOpenFiles(answer) => {
                let files = &mut self.components.open_files;
                if files.pending.is_empty() {
                    files.next = Some(answer);
                } else {
                    answer
                        .borrow_mut()
                        .deliver(files.pending.drain(..).collect());
                }
            }
            Action::NextSecondInstance(answer) => {
                let launches = &mut self.components.second_instances;
                match launches.pending.pop_front() {
                    Some(launch) => answer.borrow_mut().deliver(launch),
                    None => launches.next = Some(answer),
                }
            }
            Action::NextAppUrlChange(answer) => {
                let links = &mut self.components.url_schemes;
                links.hears_changes = true;
                match links.changes.pop_front() {
                    Some(change) => answer.borrow_mut().deliver(change),
                    None => links.next_change = Some(answer),
                }
            }
            Action::AppUrl(answer) => {
                let address = self.components.url_schemes.address.get();
                answer.borrow_mut().deliver(address);
            }
            Action::SetAppUrl(url, history) => {
                // Checked where the app called (`set_app_url`, `setUrl`);
                // where the app is the page, the address stays of its
                // origin (both refuse others first).
                let address = self.components.url_schemes.address.clone();
                if let Some(base) = address.page_base()
                    && !crate::url_scheme::same_origin(Some(base.as_str()), &url)
                {
                    log::warn!("set_app_url: {url} is not of the page's origin");
                    return;
                }
                // Again for `setUrl`, which wrote it as it was called: in
                // order with the page's address the core took since.
                address.set(url.clone());
                // The platform shows it: the web in its history entries,
                // iOS and macOS to the system when the app opts in
                // (Handoff).
                let command = match history {
                    crate::url_scheme::HistoryBehavior::Push => Command::PushAppUrl(url),
                    _ => Command::SetAppUrl(url),
                };
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command,
                });
            }
            Action::WebInputAvailable(answer) => {
                let available =
                    self.components.environment.web_input && self.access.allows_web_input();
                answer.borrow_mut().deliver(available);
            }
            Action::WebEvaluateAvailable(answer) => {
                let available =
                    self.components.environment.web_evaluate && self.access.allows_webviews();
                answer.borrow_mut().deliver(available);
            }
            Action::WebViewAvailable(answer) => {
                let available =
                    self.components.environment.web_views && self.access.allows_webviews();
                answer.borrow_mut().deliver(available);
            }
            Action::DownloadDecision {
                node,
                id,
                decision,
                answer,
            } => {
                let effects = self
                    .components
                    .downloads
                    .decide(node, &id, decision, answer);
                self.apply_download_effects(effects);
            }
            Action::PickScreenColor(answer) => {
                if !self.components.environment.screen_color {
                    answer.borrow_mut().deliver(None);
                    return;
                }
                let id = self.components.next_screen_color;
                self.components.next_screen_color = id.wrapping_add(1);
                self.components.screen_colors.insert(id, answer);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::PickScreenColor { id },
                });
            }
            Action::RenderCanvas(request, answer) => self.start_canvas_render(*request, answer),
            Action::FileRequest(request, answer) => {
                use crate::file_dialog::FileRequest;
                if !self.components.environment.file_requests {
                    answer.deliver(
                        Vec::new(),
                        Some("this platform has no file dialogs, file manager or trash".into()),
                    );
                    return;
                }
                if let FileRequest::OpenPath(path)
                | FileRequest::RevealPath(path)
                | FileRequest::MoveToTrash(path) = &request
                    && !path.is_absolute()
                {
                    let refused = format!("`{}` is not an absolute path", path.display());
                    log::warn!("{refused}");
                    answer.deliver(Vec::new(), Some(refused));
                    return;
                }
                let id = self.components.next_file_request;
                self.components.next_file_request = id.wrapping_add(1);
                self.components.file_requests.insert(id, answer);
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::FileRequest {
                        id,
                        request: Box::new(request),
                    },
                });
            }
        }
    }

    /// Applies what the downloads ask of the core
    /// ([`crate::webview::downloads::Effect`]).
    fn apply_download_effects(&mut self, effects: Vec<crate::webview::downloads::Effect>) {
        use crate::webview::downloads::Effect;
        for effect in effects {
            match effect {
                Effect::Event {
                    node,
                    kind,
                    payload,
                } => {
                    self.events
                        .push(crate::element::JsEvent::Event(node, kind, payload));
                }
                Effect::Command {
                    node,
                    operation,
                    track,
                } => {
                    let id = self.alloc_webview_request();
                    self.components.downloads.track(id, track);
                    let _ = self.apply_op(Op::Command {
                        id: node,
                        command: Command::WebViewRequest(crate::webview::WebViewRequest {
                            id,
                            operation,
                        }),
                    });
                }
                Effect::Answer { slot, result } => slot.borrow_mut().deliver(result),
            }
        }
    }

    /// A request id no outstanding download command uses (downloads and
    /// the app's platform replies share one id space per core).
    fn alloc_webview_request(&mut self) -> u64 {
        loop {
            let id = self.components.next_webview_request;
            self.components.next_webview_request = id.wrapping_add(1);
            if !self.components.downloads.tracks(id) {
                break id;
            }
        }
    }

    /// The node `id` is released (it unmounted): its downloads are
    /// cancelled with [`crate::webview::CancelReason::Teardown`]. The
    /// sessions (and their staging files) stay until the platform confirms
    /// its writer stopped, even though the node is gone: the reply or end
    /// still reaches the core, and only then is cleanup allowed.
    pub(super) fn webview_released(&mut self, id: NodeId) {
        let effects = self.components.downloads.teardown(id);
        // The node still exists but this commit's command queue was already
        // drained: put the cancel commands straight into the batch, before
        // the node's Delete, so the platform can still stop its writer.
        for effect in effects {
            match effect {
                crate::webview::downloads::Effect::Event {
                    node,
                    kind,
                    payload,
                } => self
                    .events
                    .push(crate::element::JsEvent::Event(node, kind, payload)),
                crate::webview::downloads::Effect::Command {
                    node,
                    operation,
                    track,
                } => {
                    let request = self.alloc_webview_request();
                    self.components.downloads.track(request, track);
                    self.mount.push(crate::MountItem::Command {
                        id: node,
                        command: Command::WebViewRequest(crate::webview::WebViewRequest {
                            id: request,
                            operation,
                        }),
                    });
                }
                crate::webview::downloads::Effect::Answer { slot, result } => {
                    slot.borrow_mut().deliver(result);
                }
            }
        }
    }

    /// A platform's report of a download ([`EventKind::DownloadOffer`],
    /// `DownloadProgress`, `DownloadEnd`): consumed here, so it never
    /// reaches a listener or JS.
    fn download_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
        match kind {
            EventKind::DownloadOffer => {
                let EventPayload::Json(value) = payload else {
                    return true;
                };
                let Some(offer) = crate::webview::downloads::parse_offer(value) else {
                    log::debug!(target: "js", "web view: dropped a malformed download offer: {value}");
                    return true;
                };
                let events = self
                    .key(id)
                    .ok()
                    .map(|key| self.nodes[key as usize].events)
                    .unwrap_or_default();
                let mode = if events.contains(EventKind::DownloadPending) {
                    crate::webview::downloads::Mode::Manual
                } else if events.contains(EventKind::Download) {
                    crate::webview::downloads::Mode::Automatic
                } else {
                    crate::webview::downloads::Mode::None
                };
                let automatic =
                    crate::webview::downloads::automatic_destination(&offer.id, &offer.filename);
                // The offer's URL is the response's, after the platform
                // followed its redirects: a download from a host takes the
                // grant a page there would, so a redirect cannot carry it to
                // a host the web view may not show. One of the page's own
                // content (`data:`, `blob:`) reaches no host, and stays
                // allowed as it was.
                let refused = (!self.access.is_unrestricted()
                    && !page_content(&offer.url)
                    && !self.access.allows_webview(&offer.url))
                .then(|| super::not_granted("the download", &offer.url, "webview.hosts"));
                if let Some(message) = &refused {
                    self.deny(message.clone());
                }
                let effects = self
                    .components
                    .downloads
                    .offer(id, offer, mode, automatic, refused);
                self.apply_download_effects(effects);
            }
            EventKind::DownloadProgress => {
                // Progress is not an app event yet; the platform may still
                // report it, and it is dropped here.
            }
            EventKind::DownloadEnd => {
                let EventPayload::Json(value) = payload else {
                    return true;
                };
                let Some(end) = crate::webview::downloads::parse_end(value) else {
                    log::debug!(target: "js", "web view: dropped a malformed download end: {value}");
                    return true;
                };
                let effects = self.components.downloads.end(id, end);
                self.apply_download_effects(effects);
            }
            _ => return false,
        }
        true
    }

    /// Applies the downloads' file work and deadlines (once per commit).
    pub(super) fn poll_downloads(&mut self) {
        let effects = self.components.downloads.poll(crate::time::now());
        if !effects.is_empty() {
            self.apply_download_effects(effects);
        }
    }

    /// The downloads' listeners as a round's final masks leave them: a web
    /// view whose `onDownload` and `onDownloadPending` listeners are both
    /// gone can neither hear of its downloads nor decide their offers, so
    /// they are cancelled ([`crate::webview::CancelReason::NoListener`]).
    /// The view stays mounted, and a listener removed and added back in the
    /// same turn changes nothing: only the mask the turn ended with counts.
    pub(super) fn sync_download_listeners(&mut self) {
        let nodes = self.components.downloads.unobserved_nodes(|node| {
            self.key(node).is_ok_and(|key| {
                let events = self.nodes[key as usize].events;
                events.contains(EventKind::Download) || events.contains(EventKind::DownloadPending)
            })
        });
        for node in nodes {
            let effects = self.components.downloads.lost_listener(node);
            self.apply_download_effects(effects);
        }
    }

    /// When the downloads' next deadline is due (the engine wakes then).
    pub fn download_deadline(&self) -> Option<crate::time::Instant> {
        self.components.downloads.deadline()
    }

    /// Native animations that ended: the components' resolve their
    /// [`crate::element::AnimationEnd`]s; JS's stay in `finished`.
    pub fn animations_finished(&mut self, finished: &mut Vec<crate::animation::Finished>) {
        finished.retain(|f| match self.components.animations.remove(&f.animation) {
            Some(Awaited::End(end)) => {
                end.borrow_mut().deliver(f.finished);
                false
            }
            Some(Awaited::Value(value)) => {
                value.borrow_mut().deliver(f.value.unwrap_or_default());
                false
            }
            // JS's are even.
            None => f.animation % 2 == 0,
        });
    }

    /// The answer to image info request `id`.
    pub(super) fn answer_image_info(&mut self, id: u32, size: Result<ImageSize, String>) {
        if let Some(answer) = self.components.image_infos.remove(&id) {
            answer.borrow_mut().deliver(size);
        }
    }

    /// Moves the URLs the app asked to open (`openUrl`, [`crate::element::open_url`])
    /// since the last call to `out`, by request id, checked and granted
    /// ([`crate::open_url`]). The engine asks the embedding app first, then
    /// answers each with [`Core::answer_open_url`] (the embedding app took
    /// it) or [`Core::open_url_on_platform`].
    pub fn take_url_opens(&mut self, out: &mut Vec<(u32, String)>) {
        out.append(&mut self.components.url_requests);
    }

    /// Answers the oldest clipboard write still waiting.
    pub(super) fn answer_clipboard_write(&mut self, result: crate::element::ClipboardWrite) {
        if let Some(answer) = self.components.clipboard_writes.pop_front() {
            answer.borrow_mut().deliver(result);
        }
    }

    /// Answers URL request `id`: whether the URL opened.
    pub fn answer_open_url(&mut self, id: u32, opened: bool) {
        if let Some(answer) = self.components.url_opens.remove(&id) {
            answer.borrow_mut().deliver(opened);
        }
    }

    /// Hands URL request `id` to the platform, which opens `url` and
    /// reports whether it did ([`crate::EventKind::OpenUrl`] on the root).
    pub fn open_url_on_platform(&mut self, id: u32, url: String) {
        if !self.components.url_opens.contains_key(&id) {
            return;
        }
        let _ = self.apply_op(Op::Command {
            id: crate::ROOT_ID,
            command: Command::OpenUrl { id, url },
        });
    }

    /// Moves the HTTP requests tasks made (`ui::fetch`) since the last call
    /// to `start`, by request id: the engine makes them with its network
    /// stack and reports what happens with [`Core::fetch_event`]. Requests
    /// nothing waits for any more (their task ended) go to `abandoned`, for
    /// the engine to cancel.
    pub fn take_fetches(
        &mut self,
        start: &mut Vec<(u32, crate::platform::HttpRequest)>,
        abandoned: &mut Vec<u32>,
    ) {
        start.append(&mut self.components.fetch_requests);
        if self.components.fetches.is_empty() {
            return;
        }
        self.components.fetches.retain(|&id, pending| {
            // Only the slot is left: the task awaiting it is gone.
            let wanted = Rc::strong_count(&pending.answer) > 1;
            if !wanted {
                abandoned.push(id);
            }
            wanted
        });
        start.retain(|(id, _)| !abandoned.contains(id));
    }

    /// What happened to the tasks' request `id`; false when nothing waits
    /// for it any more (the task ended, or the request is over): the engine
    /// then cancels it.
    pub fn fetch_event(&mut self, id: u32, event: crate::platform::FetchEvent) -> bool {
        use crate::platform::FetchEvent;
        let Some(pending) = self.components.fetches.get_mut(&id) else {
            return false;
        };
        // Only the slot is left: the task awaiting it is gone.
        if Rc::strong_count(&pending.answer) == 1 {
            self.components.fetches.remove(&id);
            return false;
        }
        match event {
            FetchEvent::BodyWanted => {}
            FetchEvent::Head(head) => pending.response.head = head,
            FetchEvent::Data(data) => pending.response.body.extend_from_slice(&data),
            FetchEvent::End => {
                if let Some(pending) = self.components.fetches.remove(&id) {
                    pending.answer.borrow_mut().deliver(Ok(pending.response));
                }
                return false;
            }
            FetchEvent::Failed(error) => {
                if let Some(pending) = self.components.fetches.remove(&id) {
                    pending
                        .answer
                        .borrow_mut()
                        .deliver(Err(FetchFailure::Failed(error)));
                }
                return false;
            }
        }
        true
    }

    /// Fails the tasks' request `id`, which the app's capabilities do not
    /// grant: `url` is the URL refused, the request's or a redirect's (the
    /// engine checks every hop), `message` why. A task's
    /// [`fetch`](crate::element::fetch) fails with the message; a module
    /// function's call rejects with `ERR_ACCESS_DENIED`, `permission`
    /// `"network"` and `resource` the URL, as JS's `fetch` does
    /// (`registerFont`).
    pub fn fetch_refused(&mut self, id: u32, message: String, url: String) {
        if let Some(pending) = self.components.fetches.remove(&id) {
            let refused = FetchFailure::Refused { message, url };
            pending.answer.borrow_mut().deliver(Err(refused));
        }
    }

    /// Resolves clipboard read `id` with the platform's answer (an empty
    /// one when the clipboard is not granted).
    pub(super) fn answer_clipboard(&mut self, id: u32, answer: ClipboardAnswer) {
        let ClipboardAnswer {
            has,
            text,
            denied,
            image,
            too_large,
            files,
        } = answer;
        let image = image.filter(|i| !i.url.is_empty());
        match self.components.clipboard_reads.remove(&id) {
            Some(ClipboardRead::Text(slot)) => slot.borrow_mut().deliver(text.unwrap_or_default()),
            Some(ClipboardRead::CheckedText(slot)) => slot
                .borrow_mut()
                .deliver((!denied).then(|| text.unwrap_or_default())),
            Some(ClipboardRead::Has(slot) | ClipboardRead::HasImage(slot)) => {
                slot.borrow_mut().deliver(has)
            }
            Some(ClipboardRead::Image(slot)) => slot.borrow_mut().deliver(image),
            Some(ClipboardRead::CheckedImage(slot)) => slot.borrow_mut().deliver(match too_large {
                Some(bytes) => Err(bytes),
                None => Ok(image),
            }),
            Some(ClipboardRead::Files(slot)) => slot.borrow_mut().deliver(files),
            None => {}
        }
    }

    /// The answer to host call `id`: the host's value, or its error. A
    /// call that timed out ([`crate::element::host_call_with`]) takes none:
    /// its late answer is dropped.
    #[doc(hidden)]
    pub fn answer_host(
        &mut self,
        id: u64,
        result: Result<crate::JsonValue, crate::host_channel::HostError>,
    ) {
        match self.components.host_calls.remove(&id) {
            Some(answer) if std::rc::Rc::strong_count(&answer) > 1 => {
                answer.borrow_mut().deliver(result);
            }
            _ => {
                log::debug!(target: "js", "nsh/host: dropped the answer to call {id}, which no longer waits")
            }
        }
    }

    /// Moves the host calls and posts of the app's Rust and JS
    /// ([`crate::element::host_call`], [`crate::element::host_post`])
    /// since the last call to `out`, checked and granted. The engine hands
    /// each to the embedding app's channel where it is configured (its
    /// answers come with [`Core::answer_host`]), else to
    /// [`Core::host_request_on_platform`].
    #[doc(hidden)]
    pub fn take_host_requests(&mut self, out: &mut Vec<crate::host_channel::HostRequest>) {
        out.append(&mut self.components.host_requests);
    }

    /// Hands `request` to the platform's host (the web page's): a call
    /// goes out as [`Command::HostCall`], answered by the root's
    /// [`EventKind::Host`] `{ type: "reply" }`, a post as
    /// [`Command::HostPost`]. Without one ([`Environment::host`]) a call
    /// fails at once ([`crate::host_channel::HostError::Unavailable`]) and
    /// a post goes nowhere, as a channel without a handler drops it.
    ///
    /// [`Environment::host`]: crate::platform::Environment::host
    #[doc(hidden)]
    pub fn host_request_on_platform(&mut self, request: crate::host_channel::HostRequest) {
        use crate::host_channel::{HostError, HostRequest};
        let host = self.components.environment.host;
        let command = match request {
            HostRequest::Call { id, .. } if !host => {
                self.answer_host(id, Err(HostError::Unavailable));
                return;
            }
            HostRequest::Post { .. } if !host => return,
            HostRequest::Call { id, name, args } => Command::HostCall { id, name, args },
            HostRequest::Post { name, args } => Command::HostPost { name, args },
        };
        let _ = self.apply_op(Op::Command {
            id: crate::ROOT_ID,
            command,
        });
    }

    /// The host's event `event` with `data`: the components' listeners of
    /// it ([`crate::element::on_host_event`]) run, oldest first. The
    /// engine calls it for the embedding app's events; the web page's come
    /// as the root's [`EventKind::Host`] events. Without a listener of its
    /// name the event is kept until one is added
    /// ([`Core::release_host_events`]), as JS keeps the embedding app's.
    #[doc(hidden)]
    pub fn host_event(&mut self, event: &str, data: &crate::JsonValue) {
        if !self.components.executor.host_events.borrow().listens(event) {
            // Quietly: in an app whose listeners are JS's, the events no
            // Rust code listens to fill this inbox, and JS warns of its own.
            if let Some((dropped, _)) = self
                .components
                .host_inbox
                .push(event.to_owned(), data.clone())
            {
                log::debug!(target: "js", "nsh/host: no Rust listener heard \"{dropped}\"; the oldest kept event was dropped");
            }
            return;
        }
        // Those kept for a listener added since the last commit go first.
        self.deliver_kept_host_events(event);
        self.dispatch_host_event(event, data);
    }

    /// Hands the host's events kept for want of a listener
    /// ([`Core::host_event`]) to the listeners of their names added since
    /// the last call, so listeners added after the app started (once it
    /// loaded something, say) hear what came before them. The engine calls
    /// it after each commit. True when some were delivered: what their
    /// listeners changed shows in another round.
    #[doc(hidden)]
    pub fn release_host_events(&mut self) -> bool {
        let names = {
            let mut listeners = self.components.executor.host_events.borrow_mut();
            if !std::mem::take(&mut listeners.added) || self.components.host_inbox.is_empty() {
                return false;
            }
            listeners.names()
        };
        let mut delivered = false;
        for name in names {
            delivered |= self.deliver_kept_host_events(&name);
        }
        delivered
    }

    /// Hands the kept events of `event` to its listeners, oldest first,
    /// while one is there: one that stops listening leaves the rest kept
    /// for the next. True when one was delivered.
    fn deliver_kept_host_events(&mut self, event: &str) -> bool {
        let mut delivered = false;
        while self.components.executor.host_events.borrow().listens(event) {
            let Some(data) = self.components.host_inbox.pop(event) else {
                break;
            };
            self.dispatch_host_event(event, &data);
            delivered = true;
        }
        delivered
    }

    /// Runs the listeners of `event` there now with `data`, oldest first;
    /// one that panics is reported and the others still run.
    fn dispatch_host_event(&mut self, event: &str, data: &crate::JsonValue) {
        let listeners = self.components.executor.host_events.borrow().of(event);
        let _entered = self.components.runtime.enter();
        for listener in listeners {
            let result = caught(|| listener(data));
            self.apply_actions();
            if let Err(message) = result {
                log::error!(target: "js", "a listener of the host's \"{event}\" failed: {message}");
            }
        }
    }

    /// What the platform reported of window `id` reaches the ref of the
    /// Rust components in it ([`Core::js_window_owner`]); a closed window's
    /// goes.
    fn report_window(&mut self, id: NodeId, event: &crate::desktop::WindowEvent) {
        use crate::desktop::WindowEvent;
        match event {
            WindowEvent::State(state) => {
                self.components.window_reports.entry(id).or_default().0 = Some(**state);
            }
            WindowEvent::TitleBar(area) => {
                self.components.window_reports.entry(id).or_default().1 = *area;
            }
            WindowEvent::Closed { .. } => {
                self.components.window_reports.remove(&id);
                if let Some((owner, _)) = self.components.js_windows.remove(&id) {
                    let _entered = self.components.runtime.enter();
                    owner.dispose();
                }
                return;
            }
            _ => return,
        }
        if let Some((_, this)) = self.components.js_windows.get(&id) {
            let _entered = self.components.runtime.enter();
            this.report(event);
        }
    }

    /// Events the components handle before anything else: dialog answers
    /// (theirs never reach JS), insets of screens and modals.
    fn platform_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
        if matches!(
            kind,
            EventKind::DownloadOffer | EventKind::DownloadProgress | EventKind::DownloadEnd
        ) {
            return self.download_event(id, kind, payload);
        }
        let number = |key: &str| match payload {
            EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
                crate::PayloadValue::Number(n) if *k == key => Some(*n),
                _ => None,
            }),
            _ => None,
        };
        match kind {
            // A window that keeps its placement saves it as it changes; the
            // event goes on to the app.
            EventKind::Window => {
                if let EventPayload::Window(event) = payload {
                    if id != ROOT_ID {
                        self.report_window(id, event);
                    }
                    match event.as_ref() {
                        crate::desktop::WindowEvent::State(state) => {
                            self.keep_window_placement(id, state);
                        }
                        // Rust listeners of the main window's; JS's hear it
                        // from the event.
                        crate::desktop::WindowEvent::ClosePress { reason }
                            if id == crate::ROOT_ID =>
                        {
                            self.components.runtime.main_close_pressed(*reason);
                        }
                        crate::desktop::WindowEvent::QuitRequest if id == crate::ROOT_ID => {
                            self.quit_requested();
                            return true;
                        }
                        _ => {}
                    }
                }
                false
            }
            EventKind::Dialog => {
                let Some(dialog) = number("id") else {
                    return false;
                };
                let Some(answer) = self.components.dialogs.remove(&(dialog as u32)) else {
                    return false;
                };
                let value = match payload {
                    EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
                        crate::PayloadValue::Str(text) if *k == "value" => Some(text.clone()),
                        _ => None,
                    }),
                    _ => None,
                };
                answer.borrow_mut().deliver(crate::element::DialogReply {
                    index: number("index").unwrap_or(-1.0) as i32,
                    value,
                });
                true
            }
            // A view's shortcut runs here; JS's go to JS.
            EventKind::KeyCommand if id == crate::ROOT_ID => {
                let EventPayload::Value(crate::PayloadValue::Number(binding)) = payload else {
                    return false;
                };
                let binding = *binding as u32;
                if binding < crate::element::keys::FIRST_ID {
                    return false;
                }
                if binding == super::overlay::ESCAPE_BINDING {
                    self.overlay_escape();
                    return true;
                }
                let found = self.components.executor.keys.borrow().handler(binding);
                // A binding removed since the platform matched it.
                if let Some((text, handler)) = found {
                    let result = caught(|| handler(&text));
                    self.apply_actions();
                    if let Err(message) = result {
                        log::error!(target: "js", "a keyboard shortcut failed: {message}");
                    }
                }
                true
            }
            // A view's menu item runs here; JS's go to JS. A context menu
            // closing settles the one either side showed, so both hear it.
            EventKind::Menu if id == crate::ROOT_ID => {
                let menus = self.components.executor.menus.clone();
                let closed = matches!(payload, EventPayload::Map(entries)
                    if entries.iter().any(|(k, v)| *k == "closed" && *v == crate::PayloadValue::Bool(true)));
                if closed {
                    menus.borrow_mut().settle_popup();
                    return false;
                }
                let Some(item) = number("id").map(|n| n as u32) else {
                    return false;
                };
                if item < crate::element::menus::FIRST_ID {
                    return false;
                }
                // The platform's answer to a global shortcut's registration.
                let registered = match payload {
                    EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
                        crate::PayloadValue::Bool(b) if *k == "registered" => Some(*b),
                        _ => None,
                    }),
                    _ => None,
                };
                if let Some(registered) = registered {
                    menus.borrow_mut().registered(item, registered);
                    self.apply_actions();
                    return true;
                }
                let click = menus.borrow().tray_click(item);
                if let Some(click) = click {
                    let bounds = match payload {
                        EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
                            crate::PayloadValue::Bounds(b) if *k == "bounds" => Some(*b),
                            _ => None,
                        }),
                        _ => None,
                    };
                    let result = caught(|| click(bounds));
                    self.apply_actions();
                    if let Err(message) = result {
                        log::error!(target: "js", "the tray's click failed: {message}");
                    }
                    return true;
                }
                let handler = menus.borrow().handler(item);
                // An item of a menu replaced since the platform showed it.
                if let Some(handler) = handler {
                    let result = caught(|| handler());
                    self.apply_actions();
                    if let Err(message) = result {
                        log::error!(target: "js", "a menu item failed: {message}");
                    }
                }
                true
            }
            EventKind::BackPress if id == crate::ROOT_ID => {
                // The top overlay listening takes it first.
                if self.overlay_cancel() {
                    return true;
                }
                let listeners = self.components.executor.back.borrow().newest_first();
                for listener in listeners {
                    if self.back_pressed(&listener) {
                        return true;
                    }
                }
                // JS's listeners run next (and go back when none handles
                // it).
                if self.components.js_back {
                    return false;
                }
                let _ = self.apply_op(Op::Command {
                    id: crate::ROOT_ID,
                    command: Command::Back,
                });
                true
            }
            EventKind::BackProgress if id == crate::ROOT_ID => {
                let Some(event) = crate::BackProgressEvent::from_payload(payload) else {
                    return true;
                };
                // The press of a gesture the top overlay listening to
                // `onCancel` takes is the overlay's: the app follows only
                // the gestures that start without one.
                if event.phase == crate::BackPhase::Start {
                    self.components.back_gesture = !self.overlay_state.cancel;
                }
                if !self.components.back_gesture {
                    return true;
                }
                if matches!(
                    event.phase,
                    crate::BackPhase::End | crate::BackPhase::Cancel
                ) {
                    self.components.back_gesture = false;
                }
                let listeners = self
                    .components
                    .executor
                    .back_progress
                    .borrow()
                    .newest_first();
                for listener in listeners {
                    let result = caught(|| listener(&event));
                    self.apply_actions();
                    if let Err(message) = result {
                        log::error!(target: "js", "a back progress listener failed: {message}");
                    }
                }
                // JS's listeners hear it next.
                !self.components.js_back_progress
            }
            EventKind::WebEvaluation => {
                self.answer_web_evaluation(id, payload);
                true
            }
            EventKind::ImageInfo if id == crate::ROOT_ID => {
                let Some(request) = number("id") else {
                    return false;
                };
                let error = match payload {
                    EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
                        crate::PayloadValue::Str(e) if *k == "error" => Some(e.clone()),
                        _ => None,
                    }),
                    _ => None,
                };
                let size = match (number("width"), number("height"), error) {
                    (Some(width), Some(height), None) => Ok(ImageSize {
                        width: pixels(width),
                        height: pixels(height),
                    }),
                    (_, _, error) => Err(error.unwrap_or_else(|| "no size".into())),
                };
                self.answer_image_info(request as u32, size);
                true
            }
            EventKind::Audio if id == crate::ROOT_ID => {
                let EventPayload::Audio { id: object, event } = payload else {
                    return false;
                };
                // Dropped once the object is closed.
                if let Some(sink) = self.components.audio.get(object) {
                    sink.send(event.clone());
                }
                true
            }
            EventKind::Pick if id == crate::ROOT_ID => {
                let EventPayload::Picked { id: request, files } = payload else {
                    return false;
                };
                if let Some((asked, answer)) = self.components.picks.remove(request) {
                    let files = asked.finish(files.clone());
                    answer.borrow_mut().deliver(files);
                }
                true
            }
            EventKind::Notification if id == crate::ROOT_ID => {
                self.notification_event(payload);
                true
            }
            EventKind::SecondInstance if id == crate::ROOT_ID => {
                let Some(launch) = crate::single_instance::SecondInstance::from_payload(payload)
                else {
                    return false;
                };
                let launches = &mut self.components.second_instances;
                if let Some(answer) = launches.next.take() {
                    answer.borrow_mut().deliver(launch);
                } else {
                    if launches.pending.len() == crate::single_instance::MAX_PENDING {
                        launches.pending.pop_front();
                    }
                    launches.pending.push_back(launch);
                }
                true
            }
            EventKind::UrlScheme if id == crate::ROOT_ID => {
                let EventPayload::Map(entries) = payload else {
                    return false;
                };
                let url = entries.iter().find_map(|(k, v)| match v {
                    crate::PayloadValue::Str(url) if *k == crate::url_scheme::URL => Some(url),
                    _ => None,
                });
                let Some(url) = url else {
                    return false;
                };
                let flag = |key: &str| {
                    entries.iter().find_map(|(k, v)| match v {
                        crate::PayloadValue::Bool(b) if *k == key => Some(*b),
                        _ => None,
                    })
                };
                let page = flag(crate::url_scheme::PAGE).unwrap_or(false);
                let quiet = flag(crate::url_scheme::QUIET).unwrap_or(false);
                // An address move the app did not make (the web's back or
                // forward), by its reason; one of a newer platform's reasons
                // is still the address, quietly.
                let change = entries.iter().find_map(|(k, v)| match v {
                    crate::PayloadValue::Str(s) if *k == crate::url_scheme::CHANGE => {
                        Some(crate::url_scheme::AppUrlChangeReason::parse(s))
                    }
                    _ => None,
                });
                let (quiet, change) = match change {
                    Some(None) => (true, None),
                    Some(reason) => (quiet, reason),
                    None => (quiet, None),
                };
                // The page's base URL (the web), which Rust's `set_app_url`
                // resolves against.
                if let Some(base) = entries.iter().find_map(|(k, v)| match v {
                    crate::PayloadValue::Str(s) if *k == crate::url_scheme::BASE => {
                        url::Url::parse(s).ok()
                    }
                    _ => None,
                }) {
                    self.components.url_schemes.address.set_page_base(base);
                }
                self.url_scheme(url.clone(), page, quiet, change);
                true
            }
            EventKind::ClipboardWrite if id == crate::ROOT_ID => {
                let written = match payload {
                    EventPayload::Map(entries) => entries
                        .iter()
                        .any(|(k, v)| *k == "written" && *v == crate::PayloadValue::Bool(true)),
                    _ => false,
                };
                self.answer_clipboard_write(if written {
                    crate::element::ClipboardWrite::Written
                } else {
                    crate::element::ClipboardWrite::Failed
                });
                true
            }
            EventKind::OpenUrl if id == crate::ROOT_ID => {
                let Some(request) = number("id") else {
                    return false;
                };
                let opened = match payload {
                    EventPayload::Map(entries) => entries
                        .iter()
                        .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
                    _ => false,
                };
                self.answer_open_url(request as u32, opened);
                true
            }
            EventKind::OpenAppSettings if id == crate::ROOT_ID => {
                let Some(request) = number("id") else {
                    return false;
                };
                let opened = match payload {
                    EventPayload::Map(entries) => entries
                        .iter()
                        .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
                    _ => false,
                };
                if let Some(answer) = self.components.app_settings_opens.remove(&(request as u32)) {
                    answer.borrow_mut().deliver(Ok(opened));
                }
                true
            }
            EventKind::ScreenColor if id == crate::ROOT_ID => {
                let Some(request) = number("id") else {
                    return false;
                };
                let color = number("color").map(|packed| crate::Color(packed as u32).into());
                if let Some(answer) = self.components.screen_colors.remove(&(request as u32)) {
                    answer.borrow_mut().deliver(color);
                }
                true
            }
            EventKind::CanvasImage if id == crate::ROOT_ID => self.answer_canvas_render(payload),
            EventKind::FileRequest if id == crate::ROOT_ID => {
                let EventPayload::FileRequest {
                    id: request,
                    paths,
                    error,
                } = payload
                else {
                    return false;
                };
                if let Some(answer) = self.components.file_requests.remove(request) {
                    answer.deliver(paths.clone(), error.clone());
                }
                true
            }
            // The platform's answer to a download command
            // ([`crate::webview::WebViewRequest`]), on the node it was sent
            // to. A reply whose writer stopped is the only thing that
            // permits cleaning a staging file.
            EventKind::WebViewReply => {
                let EventPayload::Json(reply) = payload else {
                    return false;
                };
                // JSON's numbers may come as floats (`1.0`); `1.5` is no
                // request.
                let request = reply.get("id").and_then(|id| {
                    id.as_u64().or_else(|| {
                        id.as_f64()
                            .filter(|n| n.is_finite() && n.fract() == 0.0 && *n >= 0.0)
                            .map(|n| n as u64)
                    })
                });
                let Some(request) = request else {
                    log::debug!(target: "js", "web view: dropped a reply without a request's id: {reply}");
                    return true;
                };
                if !self.components.downloads.tracks(request) {
                    log::debug!(target: "js", "web view: dropped a reply to unknown request {request}: {reply}");
                    return true;
                }
                let result = match reply.get("ok").and_then(crate::JsonValue::as_bool) {
                    Some(true) => Ok(()),
                    _ => Err(reply
                        .get("error")
                        .and_then(crate::JsonValue::as_str)
                        .unwrap_or("the web view did not answer")
                        .to_owned()),
                };
                let effects = self.components.downloads.reply(id, request, result);
                self.apply_download_effects(effects);
                true
            }
            EventKind::Clipboard if id == crate::ROOT_ID => {
                let Some(request) = number("id") else {
                    return false;
                };
                let answer = ClipboardAnswer::from_payload(payload);
                self.answer_clipboard(request as u32, answer);
                true
            }
            // The host's replies; its events reach the components'
            // listeners, then go on to `nsh/host`'s (`nsh-js`).
            EventKind::Host if id == crate::ROOT_ID => {
                let EventPayload::Json(reply) = payload else {
                    return false;
                };
                match reply.get("type").and_then(crate::JsonValue::as_str) {
                    Some("reply") => {}
                    Some("event") => {
                        if let Some(event) = reply.get("event").and_then(crate::JsonValue::as_str) {
                            let data = reply.get("payload").cloned().unwrap_or_default();
                            self.host_event(event, &data);
                        }
                        return false;
                    }
                    _ => return false,
                }
                // JSON's numbers may come as floats (`1.0`); `1.5` is no
                // call. Ids stay within JS' safe integers.
                let call = reply.get("id").and_then(|id| {
                    id.as_u64().or_else(|| {
                        id.as_f64()
                            .filter(|n| {
                                n.fract() == 0.0 && (1.0..=9_007_199_254_740_991.0).contains(n)
                            })
                            .map(|n| n as u64)
                    })
                });
                let Some(call) = call else {
                    log::debug!(target: "js", "nsh/host: dropped a reply without a call's id: {reply}");
                    return true;
                };
                let result = if reply.get("ok").and_then(crate::JsonValue::as_bool) == Some(true) {
                    Ok(reply.get("value").cloned().unwrap_or_default())
                } else {
                    Err(crate::host_channel::HostError::Failed(
                        reply
                            .get("error")
                            .and_then(crate::JsonValue::as_str)
                            .unwrap_or("nsh/host: the call failed")
                            .to_owned(),
                    ))
                };
                self.answer_host(call, result);
                true
            }
            EventKind::Insets => {
                let insets = EdgeInsets {
                    top: Points(number("top").unwrap_or(0.0) as f32),
                    right: Points(number("right").unwrap_or(0.0) as f32),
                    bottom: Points(number("bottom").unwrap_or(0.0) as f32),
                    left: Points(number("left").unwrap_or(0.0) as f32),
                };
                // The views reading them follow (`drain_views`).
                self.components.insets.insert(id, insets);
                // JS's screens keep them too.
                false
            }
            _ => false,
        }
    }

    /// Runs a back listener: whether it handled the press.
    fn back_pressed(&mut self, listener: &crate::element::BackListener) -> bool {
        let result = caught(|| listener());
        self.apply_actions();
        result.unwrap_or_else(|message| {
            log::error!(target: "js", "a back press listener failed: {message}");
            false
        })
    }

    /// The root listens to the back button while JS or a component does:
    /// follows the components' listeners coming and going.
    pub(super) fn sync_back(&mut self) {
        let rust = {
            let mut back = self.components.executor.back.borrow_mut();
            if !std::mem::take(&mut back.changed) {
                return;
            }
            !back.list.is_empty()
        };
        let _ = self.apply_op(Op::Listen {
            id: crate::ROOT_ID,
            event: EventKind::BackPress,
            enabled: rust || self.components.js_back || self.overlay_state.cancel,
        });
    }

    /// The root listens to the back gesture's steps while JS or a component
    /// does: follows the components' listeners coming and going.
    pub(super) fn sync_back_progress(&mut self) {
        let rust = {
            let mut progress = self.components.executor.back_progress.borrow_mut();
            if !std::mem::take(&mut progress.changed) {
                return;
            }
            !progress.list.is_empty()
        };
        let _ = self.apply_op(Op::Listen {
            id: crate::ROOT_ID,
            event: EventKind::BackProgress,
            enabled: rust || self.components.js_back_progress,
        });
    }

    /// The root's shortcuts follow the views' bindings coming and going:
    /// the table JS's and theirs make, listened to while either has one.
    pub(super) fn sync_keys(&mut self) {
        let escape_to_focus = self.focus_takes_escape();
        if escape_to_focus != self.overlay_state.escape_to_focus {
            self.overlay_state.escape_to_focus = escape_to_focus;
            self.components.executor.keys.borrow_mut().changed = true;
        }
        let rust = {
            // The windows' refs read the graph.
            let _entered = self.components.runtime.enter();
            let mut keys = self.components.executor.keys.borrow_mut();
            // A binding of a window that was not mounted yet is placed
            // once it is.
            if !std::mem::take(&mut keys.changed) && !keys.unplaced {
                return;
            }
            !keys.list.is_empty()
        };
        let keymap = self.keymap();
        let _ = self.apply_op(Op::SetProp {
            id: crate::ROOT_ID,
            prop: Prop::Keymap(keymap),
        });
        let _ = self.apply_op(Op::Listen {
            id: crate::ROOT_ID,
            event: EventKind::KeyCommand,
            enabled: rust
                || self.components.js_keys
                || self.overlay_state.cancel
                || self.overlay_state.hint_escape,
        });
    }

    /// The surface's table: JS's bindings, then the views' (the newest that
    /// may fire wins, so a view's wins over JS's of the same keystroke).
    fn keymap(&self) -> Arc<crate::keymap::Keymap> {
        let mut keys = self.components.executor.keys.borrow_mut();
        let overlay = self.overlay_key_binding();
        if keys.list.is_empty() && overlay.is_none() {
            keys.unplaced = false;
            return self.components.js_keymap.clone();
        }
        let views = {
            let _entered = self.components.runtime.enter();
            // Bindings share a few owners (a component's effect binds many):
            // each is looked up once.
            let mut known: Vec<(crate::element::Owner, NodeId)> = Vec::new();
            keys.bindings(|owner| {
                if let Some(&(_, window)) = known.iter().find(|(o, _)| *o == owner) {
                    return window;
                }
                let window = self.window_of_owner(owner);
                known.push((owner, window));
                window
            })
        };
        drop(keys);
        // JS's first, then the views', where the newest that may fire wins:
        // a focused component's keys win over the app's. Bindings
        // `OverFocused::Always` come after both, so they win over the components';
        // the overlay's Escape (a popup closing) stays last.
        let js = self.components.js_keymap.bindings();
        let bindings = js
            .iter()
            .filter(|b| !b.comes_after_views())
            .chain(views.iter().filter(|b| !b.comes_after_views()))
            .chain(js.iter().filter(|b| b.comes_after_views()))
            .chain(views.iter().filter(|b| b.comes_after_views()))
            .copied()
            .chain(overlay)
            .collect();
        Arc::new(crate::keymap::Keymap::new(bindings))
    }

    /// The insets where `host` renders: its screen's or modal's, else the
    /// surface's safe area.
    pub(super) fn insets_of(&self, host: NodeId) -> EdgeInsets {
        let safe = self.components.environment.safe_area;
        let mut key = self.key(host).ok();
        while let Some(k) = key {
            let node = &self.nodes[k as usize];
            if let Some(insets) = self.components.insets.get(&node.id) {
                return *insets;
            }
            match node.kind {
                // Not reported yet: a screen's header covers the top.
                Kind::Screen => {
                    return EdgeInsets {
                        top: Points::ZERO,
                        ..safe
                    };
                }
                Kind::Modal => return safe,
                _ => {}
            }
            key = (node.parent != NO_KEY).then_some(node.parent);
        }
        safe
    }

    /// Whether `key` or a view around it already stands clear of the
    /// software keyboard (`Prop::ClearsKeyboard`, a bottom sheet the
    /// keyboard lifts): the keyboard takes nothing more from it.
    fn clears_keyboard(&self, key: super::Key) -> bool {
        let mut key = key;
        loop {
            let node = &self.nodes[key as usize];
            if node.clears_keyboard {
                return true;
            }
            if node.parent == NO_KEY {
                return false;
            }
            key = node.parent;
        }
    }

    /// What `env` (a node's `env()` terms) comes to for `key` now: the
    /// insets of the root view it renders in ([`Self::insets_of`]) and the
    /// software keyboard's height, 0 where a view around it stands clear
    /// of the keyboard already ([`Self::clears_keyboard`]).
    pub(super) fn env_insets(
        &self,
        key: super::Key,
        env: &crate::style::EnvEdges,
    ) -> [EdgeInsets; 2] {
        use crate::style::EnvVar;
        let mut root = None;
        let mut value = |var: Option<EnvVar>| {
            let Some(var) = var else {
                return Points::ZERO;
            };
            if var == EnvVar::KeyboardInsetHeight {
                if self.clears_keyboard(key) {
                    return Points::ZERO;
                }
                return self
                    .components
                    .environment
                    .keyboard_height
                    .max(Points::ZERO);
            }
            let insets = *root.get_or_insert_with(|| self.insets_of(self.nodes[key as usize].id));
            match var {
                EnvVar::SafeAreaInsetTop => insets.top,
                EnvVar::SafeAreaInsetRight => insets.right,
                EnvVar::SafeAreaInsetBottom => insets.bottom,
                _ => insets.left,
            }
        };
        let mut edges = |vars: &[Option<EnvVar>; 4]| EdgeInsets {
            top: value(vars[0]),
            right: value(vars[1]),
            bottom: value(vars[2]),
            left: value(vars[3]),
        };
        [edges(&env.padding), edges(&env.margin)]
    }

    /// The nodes whose padding or margin uses `env()` follow the
    /// environment: restyled where what their terms come to changed (a
    /// safe area, a page's insets, the keyboard, a move to another root
    /// view). What a change of the keyboard's height moves (those terms,
    /// or the styles an app derives from `keyboardFrame()` in the same
    /// commit) animates with the keyboard, natively, unless the app
    /// configured this commit's animation itself.
    pub(super) fn sync_env(&mut self) {
        let mut keyboard_moved = std::mem::take(&mut self.keyboard_moved);
        if !self.env_styled.is_empty() {
            keyboard_moved |= self.restyle_env();
        }
        let duration = self.components.environment.keyboard_duration;
        if keyboard_moved && duration > 0.0 && self.layout_animation.is_none() {
            use crate::props::{LayoutAnimation, LayoutCurve, LayoutProperty, LayoutTransition};
            self.layout_animation = Some(LayoutAnimation {
                create: None,
                update: Some(LayoutTransition {
                    curve: LayoutCurve::Keyboard,
                    property: LayoutProperty::Opacity,
                    duration_ms: duration,
                    delay_ms: 0.0,
                }),
                delete: None,
            });
        }
    }

    /// Restyles the nodes whose `env()` terms came to something else;
    /// whether the keyboard moved one of them.
    fn restyle_env(&mut self) -> bool {
        let mut ids = std::mem::take(&mut self.env_scratch);
        ids.extend(self.env_styled.iter().copied());
        let mut keyboard_moved = false;
        for &id in &ids {
            let node = self.key(id).ok().and_then(|key| {
                let env = self.nodes[key as usize].env.as_deref().copied()?;
                Some((key, env))
            });
            let Some((key, (env, applied))) = node else {
                self.env_styled.remove(&id);
                continue;
            };
            let now = self.env_insets(key, &env);
            if now == applied {
                continue;
            }
            // The edges the keyboard moves.
            let keyboard = |vars: &[Option<crate::style::EnvVar>; 4],
                            was: &EdgeInsets,
                            now: &EdgeInsets| {
                let (was, now) = (
                    [was.top, was.right, was.bottom, was.left],
                    [now.top, now.right, now.bottom, now.left],
                );
                (0..4).any(|i| {
                    vars[i] == Some(crate::style::EnvVar::KeyboardInsetHeight) && was[i] != now[i]
                })
            };
            keyboard_moved |= keyboard(&env.padding, &applied[0], &now[0])
                || keyboard(&env.margin, &applied[1], &now[1]);
            self.restyle(key);
        }
        ids.clear();
        self.env_scratch = ids;
        keyboard_moved
    }

    /// Applies what handlers, handles (element refs, animated values) and
    /// services asked for, in order.
    pub(super) fn apply_actions(&mut self) {
        for action in self.components.executor.take_actions() {
            self.apply_action(action);
        }
    }

    /// An event the component on `host` emitted: to the component whose
    /// view has it, if it handles it (a list row's handlers run with the
    /// component whose list it is), else to JS.
    pub(super) fn route_emit(
        &mut self,
        host: NodeId,
        event: Box<dyn crate::element::builder::AnyEvent>,
    ) {
        match self.components.owners.get(&host).copied() {
            Some(parent) => {
                let Some(owner) = self.state_owner(parent) else {
                    return;
                };
                // In order, found one at a time (no list per event).
                let mut from = 0;
                while let Some((at, listener)) =
                    self.components.instances.get(&parent).and_then(|inst| {
                        inst.event_handlers
                            .iter()
                            .enumerate()
                            .skip(from)
                            .find(|(_, (n, _))| *n == host)
                            .map(|(at, (_, l))| (at, l.clone()))
                    })
                {
                    from = at + 1;
                    if let Err(message) = caught(|| listener.call(event.as_any())) {
                        self.component_failed(owner, message);
                    }
                    self.apply_actions();
                }
            }
            None => self.events.push(JsEvent::Component { host, event }),
        }
    }
}

/// Drops `value`, which holds the app's values (a call's arguments or
/// result): a panic in their `Drop` is logged instead of unwinding
/// through the core.
fn drop_caught<T>(value: T) {
    if let Err(message) = caught(move || drop(value)) {
        log::error!(target: "js", "a value of a call into Rust panicked as it dropped: {message}");
    }
}

/// Disposes the contents of a list's cells: the run that made the list went.
fn dispose_rows(rows: &std::rc::Weak<RefCell<CellRowMap>>) {
    let Some(rows) = rows.upgrade() else {
        return;
    };
    let owners: Vec<_> = rows.borrow_mut().drain().map(|(_, (_, o))| o).collect();
    for owner in owners {
        owner.dispose();
    }
}

/// Moves the live cells of a view's list as its rows moved (`diff`, now
/// `count` rows): each keeps its row, at the row's new index. A cell whose
/// row went keeps its index, and shows the row now there, unless that row
/// came there with its own cell: then, as past the rows, its content is
/// disposed before its bindings could read there, so a row never shows in
/// two cells (`ListState::adopt_orphans` in `core/list.rs`, by the same
/// rule).
fn move_rows(cells: &CellRows, diff: Option<&ListDiff>, count: u32) {
    let parts: Vec<_> = cells
        .borrow()
        .iter()
        .map(|(&id, &(index, owner))| (id, index, owner))
        .collect();
    let mut gone = Vec::new();
    // The new index of each cell's row, `None` for a row that went.
    let moves: Vec<_> = parts
        .iter()
        .map(|&(id, index, owner)| {
            let i = index.get_untracked();
            let to = match diff {
                Some(d) => d.new_index(i as u32).map(|(to, _)| to as usize),
                None => Some(i),
            };
            (id, index, owner, i, to)
        })
        .collect();
    let mut taken: Vec<usize> = moves
        .iter()
        .filter(|m| m.2.is_live())
        .filter_map(|m| m.4)
        .collect();
    taken.sort_unstable();
    for (id, index, owner, i, to) in moves {
        if !owner.is_live() {
            gone.push(id);
            continue;
        }
        let to = match to {
            Some(to) => Some(to),
            // The row went: the cell reads the row now at its index, if
            // that one's cell is not there too.
            None => Some(i).filter(|i| taken.binary_search(i).is_err()),
        };
        match to {
            Some(to) if to < count as usize => index.set(to),
            _ => {
                owner.dispose();
                gone.push(id);
            }
        }
    }
    let mut cells = cells.borrow_mut();
    for id in gone {
        cells.remove(&id);
    }
}

/// The position of row `index` of `count` that a cell's content reads: in a
/// view (`count_signal`), its index a signal of the cell's (handed back in
/// `made`) and the list's count, both written by the list's memo `moves`
/// when its rows are bound; else fixed.
fn row_position(
    index: usize,
    count: usize,
    count_signal: Option<crate::element::Signal<usize>>,
    moves: Option<crate::element::reactive::Node>,
    made: &std::cell::Cell<Option<crate::element::Signal<usize>>>,
) -> Position {
    match count_signal {
        Some(count) => {
            let index = crate::element::signal(index);
            made.set(Some(index));
            Position::of_row(index.node(), count.node(), moves)
        }
        None => Position::fixed(index, count),
    }
}

/// A pixel count a platform reports as a number (whole for what it
/// decodes).
fn pixels(n: f64) -> crate::geometry::DevicePixels {
    crate::geometry::DevicePixels(n.round() as i32)
}

/// Whether `url` names content of the page itself (`data:`, `blob:`), which
/// a download takes from the page rather than from a host.
fn page_content(url: &str) -> bool {
    let scheme = url.split(':').next().unwrap_or_default();
    url.contains(':')
        && (scheme.eq_ignore_ascii_case("data") || scheme.eq_ignore_ascii_case("blob"))
}