lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
#[cfg(feature = "devtools")]
use std::sync::atomic::AtomicUsize;
use std::{
  any::{Any, TypeId},
  collections::HashSet,
  sync::{
    Arc,
    atomic::{AtomicBool, AtomicU64, Ordering},
  },
  task::Context as TaskContext,
  time::Duration,
};

use parking_lot::Mutex;

#[cfg(feature = "devtools")]
use super::component::{ComponentInfo, DevtoolsInspectable};
use super::{
  app_state::App,
  component::Component,
  events::MouseEvent,
  i18n::I18n,
  theme::Theme,
  window::{Window, WindowWaker},
};
#[cfg(feature = "devtools")]
use crate::time::{SystemTime, UNIX_EPOCH};
use crate::{
  core::{
    ContextMap, ElementRef, ElementRefMut, ReactiveContext, Store,
    cell_ref::Ref,
    effect::Effect,
    memo::Memo,
    signal::{Signal, SignalValue},
    tracking,
  },
  node::{Element, HitTestBehavior, Node},
  time::Instant,
};

mod frames;
mod futures;

pub(crate) use frames::WindowFrames;
pub use frames::{Frame, FrameCallback};
pub use futures::{FutureAction, FutureHandle, FutureState, FutureStatus, StreamEmitter, StreamHandle};
use futures::{FutureSlot, RuntimeFutureHandle};

static NEXT_COMPONENT_SLOT_ID: AtomicU64 = AtomicU64::new(1);

fn next_component_slot_id() -> u64 {
  NEXT_COMPONENT_SLOT_ID.fetch_add(1, Ordering::Relaxed)
}

static NEXT_RENDER_GENERATION: AtomicU64 = AtomicU64::new(1);

/// Orders the outputs slots keep: a later render has a greater one.
fn next_render_generation() -> u64 {
  NEXT_RENDER_GENERATION.fetch_add(1, Ordering::Relaxed)
}

#[cfg(feature = "devtools")]
fn set_component_debug_metadata(node: &mut Node, ctx: &Ctx) {
  node.set_component_props_debug(ctx.props_debug());
  node.set_component_signals_debug(ctx.signals_debug());
  node.set_component_memos_debug(ctx.memos_debug());
  node.set_component_effects_debug(ctx.effects_debug());
  node.set_component_contexts_debug(ctx.contexts_debug());
  node.set_component_render_debug(Some(ctx.render_debug()));
}

fn attach_component_metadata(
  mut node: Box<Node>,
  tag_name: Arc<str>,
  slot_id: u64,
  key: Option<&str>,
  #[cfg(feature = "devtools")] ctx: &Ctx,
) -> Box<Node> {
  if node.component_slot_id().is_some() {
    node = Box::new(Node::logical().child(*node));
  }

  node.set_tag_name(tag_name);
  node.set_component_slot_id(slot_id);
  node.set_component_key(key);
  #[cfg(feature = "devtools")]
  set_component_debug_metadata(&mut node, ctx);
  node
}

pub(crate) fn component_tag_name<C: 'static>() -> Arc<str> {
  let type_name = std::any::type_name::<C>();
  let base = type_name.split('<').next().unwrap_or(type_name);
  Arc::from(base.rsplit("::").next().unwrap_or(base))
}

pub(crate) type ClickOutsideCallback = Arc<dyn Fn(&MouseEvent) + Send + Sync>;

struct ClickOutsideEntry {
  scope_id: u64,
  cursor: usize,
  element_ref: ElementRef,
  callback: ClickOutsideCallback,
}

#[derive(Clone)]
pub enum OpenState {
  Static(bool),
  Signal(Signal<bool>),
}

impl OpenState {
  pub fn is_open(&self) -> bool {
    match self {
      Self::Static(open) => *open,
      Self::Signal(open) => open.get(),
    }
  }

  pub(crate) fn signal(&self) -> Option<Signal<bool>> {
    match self {
      Self::Static(_) => None,
      Self::Signal(open) => Some(open.clone()),
    }
  }
}

impl From<bool> for OpenState {
  fn from(value: bool) -> Self {
    Self::Static(value)
  }
}

impl From<Signal<bool>> for OpenState {
  fn from(value: Signal<bool>) -> Self {
    Self::Signal(value)
  }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Placement {
  TopStart,
  Top,
  TopEnd,
  #[default]
  BottomStart,
  Bottom,
  BottomEnd,
  LeftStart,
  Left,
  LeftEnd,
  RightStart,
  Right,
  RightEnd,
}

#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for Placement {
  fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
    formatter.value_debug(self);
  }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CollisionStrategy {
  None,
  Clamp,
  Flip,
  #[default]
  FlipThenClamp,
}

/// What a left press outside an open popup does besides closing it, for
/// overlays with `dismiss_on_outside_click(true)` (`Popup`, `Popover`,
/// `Overlay`) and for `Select` menus.
///
/// A press is outside a popup when it lands neither on the popup, nor on its
/// anchor (a select's trigger), nor on a layer opened above it, such as a
/// select menu or a popup opened from inside it.
///
/// A press on another dropdown's trigger is always delivered, so one press
/// switches dropdowns, like a menu bar. The first interactive element under
/// the pointer (a button, a select, anything focusable) is a trigger when it is
/// a `Select`, or the anchor itself of a signal-driven overlay with
/// `dismiss_on_outside_click(true)`, open or closed, that has not opted out
/// with `switch_on_anchor_press(false)`. Other elements inside an anchor, such
/// as the other half of a split button, are not triggers. An overlay that is
/// only declared while open has no trigger while it is closed: declare it
/// always and drive it with its open signal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OutsidePress {
  /// The press only closes the popup, like a native menu: the element under
  /// the pointer receives no press, release or click, and focus does not move.
  /// Pressing again reaches it. A press on another dropdown's trigger is
  /// delivered all the same.
  #[default]
  Consume,
  /// The press closes the popup and is also delivered to the element under
  /// the pointer, like a light-dismiss web popover.
  PassThrough,
}

/// What runs when a press outside an overlay or Escape closes it: see [`Overlay::on_dismiss`].
pub(crate) type OverlayDismiss = std::sync::Arc<dyn Fn() + Send + Sync>;

pub(crate) struct OverlaySpec {
  pub(crate) anchor: ElementRef,
  pub(crate) node: Node,
  pub(crate) placement: Placement,
  pub(crate) offset_x: f32,
  pub(crate) offset_y: f32,
  pub(crate) match_anchor_width: bool,
  pub(crate) collision: CollisionStrategy,
  pub(crate) hit_test: HitTestBehavior,
  pub(crate) open_signal: Option<Signal<bool>>,
  pub(crate) dismiss_on_outside_click: bool,
  pub(crate) outside_press: OutsidePress,
  pub(crate) dismiss_on_escape: bool,
  /// What runs when a press outside the overlay or Escape closes it.
  pub(crate) on_dismiss: Option<OverlayDismiss>,
  /// Whether the focus goes into the overlay as it opens and back as it closes: see [`Overlay::takes_focus`].
  pub(crate) takes_focus: bool,
  /// Whether Tab goes through the overlay right after its anchor, the focus staying where it is as it opens:
  /// see [`Overlay::tab_after_anchor`].
  pub(crate) tab_after_anchor: bool,
  /// Whether Tab stays in the overlay while the focus is in it: see [`Overlay::traps_tab`].
  pub(crate) traps_tab: bool,
  /// A point of the window it stands at in place of its anchor: see [`Overlay::at`].
  pub(crate) at: Option<(f32, f32)>,
  /// Where it stands by that point, as by an anchor of no size: see [`Overlay::at_placed`].
  pub(crate) at_placement: Option<Placement>,
  /// What of the window's edges it keeps clear of, top, right, bottom, left: see [`Overlay::keep_clear`].
  pub(crate) clear: [f32; 4],
  /// The element whose box it is kept inside besides the window: see [`Overlay::within`].
  pub(crate) within: Option<ElementRef>,
  /// How far inside that element's box it stays, top, right, bottom, left: see [`Overlay::within_inset`].
  pub(crate) within_inset: [f32; 4],
  /// The element it is placed by in place of its anchor, wholly or on the side it opens on: see
  /// [`Overlay::placed_by`] and [`Overlay::clear_of`].
  pub(crate) frame: Option<PlacingFrame>,
}

/// An element an overlay is placed by in place of its anchor, and how.
#[derive(Clone)]
pub(crate) enum PlacingFrame {
  /// It stands by the element's box as by its anchor's: see [`Overlay::placed_by`].
  Box(ElementRef),
  /// It keeps clear of the element's box on the side it opens on, and lines up with its anchor along it: see
  /// [`Overlay::clear_of`].
  ClearOf(ElementRef),
}

impl PlacingFrame {
  /// The element it is placed by.
  pub(crate) fn element(&self) -> &ElementRef {
    let (Self::Box(element) | Self::ClearOf(element)) = self;
    element
  }

  /// The box an overlay with this frame is placed by, given its anchor's, the frame's as it is laid out (`None`
  /// where it is not) and its placement: the anchor's where the frame has no box.
  pub(crate) fn rect(
    &self,
    anchor: crate::core::ElementRect,
    frame: Option<crate::core::ElementRect>,
    placement: Placement,
  ) -> crate::core::ElementRect {
    let Some(frame) = frame.filter(|frame| frame.width > 0.0 || frame.height > 0.0) else {
      return anchor;
    };
    let beside = matches!(
      placement,
      Placement::LeftStart
        | Placement::Left
        | Placement::LeftEnd
        | Placement::RightStart
        | Placement::Right
        | Placement::RightEnd
    );
    match self {
      Self::Box(_) => frame,
      // Stretched across the side's axis to the frame: beside it, to its width; above or below it, to its height.
      Self::ClearOf(_) if beside => crate::core::ElementRect {
        x: frame.x,
        relative_x: anchor.relative_x + (frame.x - anchor.x),
        width: frame.width,
        ..anchor
      },
      Self::ClearOf(_) => crate::core::ElementRect {
        y: frame.y,
        relative_y: anchor.relative_y + (frame.y - anchor.y),
        height: frame.height,
        ..anchor
      },
    }
  }
}

#[derive(Clone)]
pub enum ModalTarget {
  Parent,
  Root,
  Element(ElementRef),
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Parent;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Root;

impl From<Parent> for ModalTarget {
  fn from(_: Parent) -> Self {
    Self::Parent
  }
}

impl From<Root> for ModalTarget {
  fn from(_: Root) -> Self {
    Self::Root
  }
}

impl From<ElementRef> for ModalTarget {
  fn from(value: ElementRef) -> Self {
    Self::Element(value)
  }
}

impl From<ElementRefMut> for ModalTarget {
  fn from(value: ElementRefMut) -> Self {
    Self::Element(value.into())
  }
}

/// What an open modal layer is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ModalLayer {
  /// A dialog declared with `Modal`: the topmost one is the Tab scope and traps Tab.
  Dialog,
  /// `WindowChrome`'s title bar and resize zones: window decoration over the
  /// page, not a dialog, so it never becomes a Tab scope. Its stops, if any,
  /// are part of the window's order.
  WindowChrome,
}

pub(crate) struct ModalSpec {
  pub(crate) target: ModalTarget,
  pub(crate) node: Node,
  pub(crate) open_signal: Option<Signal<bool>>,
  pub(crate) dismiss_on_escape: bool,
  pub(crate) layer: ModalLayer,
  /// Whether the focus goes into the modal as it opens and back to what had it as it closes.
  pub(crate) takes_focus: bool,
  /// What runs after a person dismissed the modal, its open signal set to `false`: see [`Modal::on_dismiss`].
  pub(crate) on_dismiss: Option<OverlayDismiss>,
}

impl ModalSpec {
  pub(crate) fn clone_for_reuse(&self) -> Self {
    self.clone_with_node(self.node.clone_for_reuse())
  }

  /// This declaration around `node`, a clone of its node.
  pub(crate) fn clone_with_node(&self, node: Node) -> Self {
    Self {
      target: self.target.clone(),
      node,
      open_signal: self.open_signal.clone(),
      dismiss_on_escape: self.dismiss_on_escape,
      layer: self.layer,
      takes_focus: self.takes_focus,
      on_dismiss: self.on_dismiss.clone(),
    }
  }
}

impl OverlaySpec {
  pub(crate) fn clone_for_reuse(&self) -> Self {
    self.clone_with_node(self.node.clone_for_reuse())
  }

  /// This declaration around `node`, a clone of its node.
  pub(crate) fn clone_with_node(&self, node: Node) -> Self {
    Self {
      anchor: self.anchor.clone(),
      node,
      placement: self.placement,
      offset_x: self.offset_x,
      offset_y: self.offset_y,
      match_anchor_width: self.match_anchor_width,
      collision: self.collision,
      hit_test: self.hit_test,
      open_signal: self.open_signal.clone(),
      dismiss_on_outside_click: self.dismiss_on_outside_click,
      outside_press: self.outside_press,
      dismiss_on_escape: self.dismiss_on_escape,
      on_dismiss: self.on_dismiss.clone(),
      takes_focus: self.takes_focus,
      tab_after_anchor: self.tab_after_anchor,
      traps_tab: self.traps_tab,
      at: self.at,
      at_placement: self.at_placement,
      clear: self.clear,
      within: self.within.clone(),
      within_inset: self.within_inset,
      frame: self.frame.clone(),
    }
  }
}

pub struct Modal {
  node: Box<Node>,
  open: OpenState,
  target: ModalTarget,
  dismiss_on_escape: bool,
  layer: ModalLayer,
  dismiss: Option<Signal<bool>>,
  takes_focus: bool,
  on_dismiss: Vec<OverlayDismiss>,
}

impl Modal {
  pub fn new(content: impl Into<Element>) -> Self {
    Self {
      node: content.into().node,
      open: OpenState::Static(true),
      target: ModalTarget::Parent,
      dismiss_on_escape: true,
      layer: ModalLayer::Dialog,
      dismiss: None,
      takes_focus: false,
      on_dismiss: Vec::new(),
    }
  }

  pub fn open(mut self, open: impl Into<OpenState>) -> Self {
    self.open = open.into();
    self
  }

  pub fn open_when(mut self, open: bool) -> Self {
    self.open = OpenState::Static(open);
    self
  }

  pub fn target(mut self, target: impl Into<ModalTarget>) -> Self {
    self.target = target.into();
    self
  }

  pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
    self.dismiss_on_escape = dismiss;
    self
  }

  /// Whether the focus goes into the modal as it opens, to its first stop of Tab, and back to what had it when
  /// it closes, as a browser's `<dialog>` opened with `showModal()` does. A focus that has gone somewhere else
  /// by then stays there. Off by default.
  pub fn takes_focus(mut self, takes: bool) -> Self {
    self.takes_focus = takes;
    self
  }

  /// What runs after a person dismissed the modal, its open signal set to `false` first: Escape, wherever the
  /// focus is, for a modal driven by a signal that Escape closes; and whatever the app's own content calls a
  /// dismissal (a press on its veil) through the same handler. Not when the app sets the signal. A second
  /// handler is called after the first.
  pub fn on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
    self.on_dismiss.push(std::sync::Arc::new(handler));
    self
  }

  /// The signal Escape sets to `false`, for a modal that stays open after it: one that is shown on its way
  /// out, as a [`Sheet`](crate::components::Sheet) is.
  pub(crate) fn dismisses(mut self, open: Signal<bool>) -> Self {
    self.dismiss = Some(open);
    self
  }

  /// Marks this layer as `WindowChrome`'s decoration instead of a dialog.
  pub(crate) fn window_chrome_layer(mut self) -> Self {
    self.layer = ModalLayer::WindowChrome;
    self
  }

  fn into_spec(self) -> Option<ModalSpec> {
    if !self.open.is_open() {
      return None;
    }

    let handlers = self.on_dismiss;
    let on_dismiss = (!handlers.is_empty()).then(|| {
      std::sync::Arc::new(move || {
        for handler in &handlers {
          handler();
        }
      }) as OverlayDismiss
    });
    Some(ModalSpec {
      target: self.target,
      node: *self.node,
      open_signal: self.dismiss.or_else(|| self.open.signal()),
      dismiss_on_escape: self.dismiss_on_escape,
      layer: self.layer,
      takes_focus: self.takes_focus,
      on_dismiss,
    })
  }
}

impl From<Modal> for Element {
  fn from(modal: Modal) -> Self {
    let mut node = Node::logical();
    node.set_layout_neutral(true);
    if let Some(spec) = modal.into_spec() {
      node.set_modal_declaration(spec);
    }
    Element::from_node(node)
  }
}

pub struct Overlay {
  anchor: Option<ElementRef>,
  node: Box<Node>,
  open: OpenState,
  placement: Placement,
  offset_x: f32,
  offset_y: f32,
  match_anchor_width: bool,
  collision: CollisionStrategy,
  hit_test: HitTestBehavior,
  dismiss_on_outside_click: bool,
  outside_press: OutsidePress,
  dismiss_on_escape: bool,
  on_dismiss: Option<OverlayDismiss>,
  switch_on_anchor_press: bool,
  takes_focus: bool,
  tab_after_anchor: bool,
  traps_tab: bool,
  at: Option<(f32, f32)>,
  at_placement: Option<Placement>,
  clear: [f32; 4],
  within: Option<ElementRef>,
  within_inset: [f32; 4],
  frame: Option<PlacingFrame>,
}

impl Overlay {
  pub fn new(content: impl Into<Element>) -> Self {
    Self {
      anchor: None,
      node: content.into().node,
      open: OpenState::Static(true),
      placement: Placement::default(),
      offset_x: 0.0,
      offset_y: 0.0,
      match_anchor_width: false,
      collision: CollisionStrategy::default(),
      hit_test: HitTestBehavior::Auto,
      dismiss_on_outside_click: false,
      outside_press: OutsidePress::default(),
      dismiss_on_escape: false,
      on_dismiss: None,
      switch_on_anchor_press: true,
      takes_focus: false,
      tab_after_anchor: false,
      traps_tab: false,
      at: None,
      at_placement: None,
      clear: [0.0; 4],
      within: None,
      within_inset: [0.0; 4],
      frame: None,
    }
  }

  pub fn anchor(mut self, anchor: impl Into<ElementRef>) -> Self {
    self.anchor = Some(anchor.into());
    self
  }

  pub fn open(mut self, open: impl Into<OpenState>) -> Self {
    self.open = open.into();
    self
  }

  pub fn open_when(mut self, open: bool) -> Self {
    self.open = OpenState::Static(open);
    self
  }

  pub fn placement(mut self, placement: Placement) -> Self {
    self.placement = placement;
    self
  }

  pub fn offset(mut self, x: f32, y: f32) -> Self {
    self.offset_x = x;
    self.offset_y = y;
    self
  }

  pub fn match_anchor_width(mut self, match_anchor_width: bool) -> Self {
    self.match_anchor_width = match_anchor_width;
    self
  }

  pub fn collision(mut self, collision: CollisionStrategy) -> Self {
    self.collision = collision;
    self
  }

  pub fn hit_test(mut self, behavior: HitTestBehavior) -> Self {
    self.hit_test = behavior;
    self
  }

  /// Closes the overlay on a left press outside it and its anchor. Needs a
  /// signal-backed open state.
  pub fn dismiss_on_outside_click(mut self, dismiss: bool) -> Self {
    self.dismiss_on_outside_click = dismiss;
    self
  }

  /// Whether the press that closes the overlay also reaches the element under
  /// the pointer. Defaults to [`OutsidePress::Consume`].
  pub fn outside_press(mut self, outside_press: OutsidePress) -> Self {
    self.outside_press = outside_press;
    self
  }

  pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
    self.dismiss_on_escape = dismiss;
    self
  }

  /// What runs after a press outside the overlay or Escape closed it, its open signal set to `false`: what a
  /// dismissal means to the app, beyond the overlay closing. Only an overlay driven by a signal is dismissed.
  pub fn on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
    self.on_dismiss = Some(std::sync::Arc::new(handler));
    self
  }

  /// Whether the anchor is this overlay's trigger, which a left press opens.
  /// While another dropdown is open, a press on a trigger closes it and goes
  /// on to the trigger, so one press switches dropdowns. Defaults to `true`;
  /// set `false` when a left press on the anchor does something else, as for
  /// a context menu or an autocomplete list. Applies to overlays with
  /// `dismiss_on_outside_click(true)` and a signal-backed open state.
  pub fn switch_on_anchor_press(mut self, switch: bool) -> Self {
    self.switch_on_anchor_press = switch;
    self
  }

  /// Whether the keyboard focus goes into the overlay as it opens and back as
  /// it closes, as [`Modal::takes_focus`] does for a modal: a popover's, a
  /// menu's.
  ///
  /// - As it opens, the focus goes to the first element in it that takes the focus. An app's focus request in the same
  ///   pass wins. The ring shows as the input that opened it shows it: after a key, not after a press of the pointer.
  /// - As it closes with the focus inside it, the focus goes back to what had it when it opened (the button that opened
  ///   a menu, the item of a submenu), or, where that is gone or nothing had it, to its anchor. A focus that has gone
  ///   somewhere else stays there.
  /// - Tab goes through its elements right after its anchor's, as a web popover's come after its invoker's.
  /// - An overlay that is hidden because its anchor is out of view is still open: it does not take the focus again when
  ///   the anchor comes back.
  ///
  /// Off by default.
  pub fn takes_focus(mut self, takes: bool) -> Self {
    self.takes_focus = takes;
    self
  }

  /// Whether Tab goes through the overlay's elements right after its
  /// anchor's, as with [`Self::takes_focus`], while the focus stays where it
  /// is as the overlay opens: a hover card's links, a toggletip's, a teaching
  /// tip that does not take the focus from what a person is doing. As it
  /// closes with the focus inside it, the focus goes back to its anchor. Off
  /// by default; [`Self::takes_focus`] does this and more.
  pub fn tab_after_anchor(mut self, tab: bool) -> Self {
    self.tab_after_anchor = tab;
    self
  }

  /// Whether Tab stays in the overlay while the focus is in it, as it stays in a modal: from its last element
  /// Tab goes to its first, and Shift+Tab from its first to its last, where it would go on to what follows its
  /// anchor. For an overlay a person is to finish before going on that is no modal: the card of a tour.
  ///
  /// - It holds Tab only while the focus is in it, or in an overlay that hangs from an element of it. With the focus on
  ///   the page Tab goes through the page, and into the overlay after its anchor.
  /// - It does not close the page to the pointer, and Escape and a press outside close it as its other settings say. As
  ///   it closes the focus goes back as [`Self::takes_focus`] says.
  /// - A modal opened over it holds Tab itself.
  /// - With nothing in it that takes the focus, Tab does nothing while the focus is in it.
  ///
  /// Its elements are in the order of Tab right after its anchor's, as with [`Self::tab_after_anchor`]. Off by
  /// default.
  pub fn traps_tab(mut self, traps: bool) -> Self {
    self.traps_tab = traps;
    self
  }

  /// A point of the window, in logical pixels, that the overlay stands at in
  /// place of its anchor: where a secondary press or a long press was, for a
  /// context menu. `None`, the default, places it by its anchor.
  ///
  /// It opens down and toward the end from the point, `offset` away from it,
  /// and on the other side of the point along an axis where the window has no
  /// room that way; then the collision strategy keeps it inside the window as
  /// it does an anchored one. The placement is not used. The anchor is still
  /// what it hangs from: a press on it is not outside it, the focus goes back
  /// to it, and it is hidden while the anchor is out of view.
  pub fn at(mut self, point: Option<(f32, f32)>) -> Self {
    self.at = point;
    self
  }

  /// With [`at`](Self::at), stands the overlay by the point as by an anchor of no size, at `placement` of it,
  /// measured first: `Placement::Top` centres it above the point, and the collision strategy flips it below
  /// where there is no room above. What lurq shows at a finger (the menu of editing commands) stands so.
  pub(crate) fn at_placed(mut self, placement: Placement) -> Self {
    self.at_placement = Some(placement);
    self
  }

  /// Keeps the overlay off the window's edges by these, top, right, bottom and left, in logical pixels, where the
  /// collision strategy clamps it: a phone's safe area.
  pub(crate) fn keep_clear(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
    self.clear = [top, right, bottom, left];
    self
  }

  /// Keeps the overlay inside the box of `element`, as it was last laid out, besides the window: where the collision
  /// strategy flips it, it flips where that box has no room on its side, and where it clamps, it is moved into that
  /// box and then into the window, which wins where they differ. A popover that belongs in a column, a menu that
  /// stays in a panel. An overlay larger than the box keeps its start at the box's start. Before the element is laid
  /// out, and with no clamping or flipping, the overlay is placed as it would be without it.
  pub fn within(mut self, element: impl Into<ElementRef>) -> Self {
    self.within = Some(element.into());
    self
  }

  /// [`within`](Self::within) the box of `element` less `top`, `right`, `bottom` and `left` on its sides, in logical
  /// pixels: a popover that ends 12 before the end of the column it belongs in. A negative inset lets it stand that
  /// far past the box's edge.
  pub fn within_inset(mut self, element: impl Into<ElementRef>, top: f32, right: f32, bottom: f32, left: f32) -> Self {
    self.within = Some(element.into());
    self.within_inset = [top, right, bottom, left];
    self
  }

  /// Places the overlay by the box of `element`, as it was last laid out, in place of its anchor's: it stands at its
  /// placement of that box, `offset` away, and flips and is clamped there as it would be by its anchor. The anchor
  /// stays what it hangs from: its trigger, what a press on is not outside it, where the focus goes back, what hides
  /// it while out of view. A status bar's popover that stands over the bar and at its end while the bar's item opens
  /// it. Before the element is laid out the overlay is placed by its anchor. Replaces [`Self::clear_of`].
  pub fn placed_by(mut self, element: impl Into<ElementRef>) -> Self {
    self.frame = Some(PlacingFrame::Box(element.into()));
    self
  }

  /// Keeps the overlay clear of the box of `element`, as it was last laid out, on the side it opens on: its distance
  /// is measured from that box's edge, and along the edge it lines up with its anchor as it would. A tooltip of a chip
  /// that opens over the field the chip sits in, not over the chip. It flips to the box's other side where there is
  /// no room. Before the element is laid out the overlay is placed by its anchor. Replaces [`Self::placed_by`].
  pub fn clear_of(mut self, element: impl Into<ElementRef>) -> Self {
    self.frame = Some(PlacingFrame::ClearOf(element.into()));
    self
  }

  fn into_spec(self) -> Option<OverlaySpec> {
    if !self.open.is_open() {
      return None;
    }

    let open_signal = self.open.signal();

    Some(OverlaySpec {
      anchor: self.anchor?,
      node: *self.node,
      placement: self.placement,
      offset_x: self.offset_x,
      offset_y: self.offset_y,
      match_anchor_width: self.match_anchor_width,
      collision: self.collision,
      hit_test: self.hit_test,
      open_signal,
      dismiss_on_outside_click: self.dismiss_on_outside_click,
      outside_press: self.outside_press,
      dismiss_on_escape: self.dismiss_on_escape,
      on_dismiss: self.on_dismiss,
      takes_focus: self.takes_focus,
      tab_after_anchor: self.tab_after_anchor,
      traps_tab: self.traps_tab,
      at: self.at,
      at_placement: self.at_placement,
      clear: self.clear,
      within: self.within,
      within_inset: self.within_inset,
      frame: self.frame,
    })
  }
}

impl From<Overlay> for Element {
  fn from(overlay: Overlay) -> Self {
    let mut node = Node::logical();
    node.set_layout_neutral(true);
    if overlay.dismiss_on_outside_click
      && overlay.switch_on_anchor_press
      && matches!(overlay.open, OpenState::Signal(_))
      && let Some(anchor) = &overlay.anchor
    {
      node.set_dropdown_anchor(anchor.clone());
    }
    if let Some(spec) = overlay.into_spec() {
      node.set_overlay_declaration(spec);
    }
    Element::from_node(node)
  }
}

#[derive(Clone)]
pub struct Timeout {
  timer: Timer,
}

#[derive(Clone)]
pub struct Interval {
  timer: Timer,
}

#[derive(Clone)]
struct Timer {
  inner: Arc<Mutex<TimerInner>>,
}

struct TimerInner {
  duration: Duration,
  repeat: bool,
  next_fire: Option<Instant>,
  callback: Arc<dyn Fn() + Send + Sync>,
  /// Wakes the event loop when the timer gets a new fire time, so a shell that waits for the earliest timer learns
  /// about it; `None` outside a window.
  wake: Option<WindowWaker>,
}

impl Timeout {
  /// A timeout no window runs: starting it never fires. For a component's
  /// render run outside a window, such as a Markdown document rendered to
  /// find its text.
  #[cfg(feature = "markdown")]
  pub(crate) fn detached(f: impl Fn() + Send + Sync + 'static) -> Self {
    Self {
      timer: Timer::new(Duration::ZERO, false, f, None),
    }
  }

  pub fn start(&self) {
    self.timer.start();
  }

  pub fn restart(&self) {
    self.timer.restart();
  }

  pub fn cancel(&self) {
    self.timer.stop();
  }

  /// The delay of the next start or restart; a running timeout keeps its
  /// fire time.
  pub(crate) fn set_duration(&self, duration: Duration) {
    self.timer.inner.lock().duration = duration;
  }

  pub fn is_active(&self) -> bool {
    self.timer.is_active()
  }
}

impl Interval {
  pub fn start(&self) {
    self.timer.start();
  }

  pub fn restart(&self) {
    self.timer.restart();
  }

  pub fn stop(&self) {
    self.timer.stop();
  }

  pub fn is_active(&self) -> bool {
    self.timer.is_active()
  }
}

thread_local! {
  /// The moment a timer started on this thread takes as now, where a test drives time itself
  /// ([`set_timer_clock`]): the wall clock where there is none.
  static TIMER_CLOCK: std::cell::Cell<Option<Instant>> = const { std::cell::Cell::new(None) };
}

/// Has every timer started or restarted on this thread from now on count its delay from `now`, until set back to
/// `None`: `Tree::tick_timers_at` then fires it at moments a test counts from its own clock, however long the
/// machine takes between them.
pub(crate) fn set_timer_clock(now: Option<Instant>) {
  TIMER_CLOCK.with(|clock| clock.set(now));
}

/// The moment a timer starts at: the test's, or the wall clock's.
fn timer_now() -> Instant {
  TIMER_CLOCK.with(std::cell::Cell::get).unwrap_or_else(Instant::now)
}

impl Timer {
  fn new(
    duration: Duration,
    repeat: bool,
    callback: impl Fn() + Send + Sync + 'static,
    wake: Option<WindowWaker>,
  ) -> Self {
    Self {
      inner: Arc::new(Mutex::new(TimerInner {
        duration,
        repeat,
        next_fire: None,
        callback: Arc::new(callback),
        wake,
      })),
    }
  }

  fn start(&self) {
    let now = timer_now();
    let wake = {
      let mut inner = self.inner.lock();
      if inner.next_fire.is_some() {
        return;
      }
      inner.next_fire = Some(now + inner.duration);
      inner.wake.clone()
    };
    Self::wake(wake);
  }

  fn restart(&self) {
    self.restart_at(timer_now());
  }

  fn restart_at(&self, now: Instant) {
    let wake = {
      let mut inner = self.inner.lock();
      inner.next_fire = Some(now + inner.duration);
      inner.wake.clone()
    };
    Self::wake(wake);
  }

  /// Called outside the timer's lock: the waker may re-enter window state.
  fn wake(wake: Option<WindowWaker>) {
    if let Some(wake) = wake {
      wake();
    }
  }

  fn next_fire(&self) -> Option<Instant> {
    self.inner.lock().next_fire
  }

  fn stop(&self) {
    self.inner.lock().next_fire = None;
  }

  fn is_active(&self) -> bool {
    self.inner.lock().next_fire.is_some()
  }

  fn tick(&self, now: Instant) -> bool {
    let callback = {
      let mut inner = self.inner.lock();
      let Some(next_fire) = inner.next_fire else {
        return false;
      };
      if now < next_fire {
        return false;
      }
      if inner.repeat {
        inner.next_fire = Some(now + inner.duration);
      } else {
        inner.next_fire = None;
      }
      inner.callback.clone()
    };
    callback();
    true
  }
}

/// What components asked the runtime to do with an element of the tree,
/// shared by every `Ctx` of a window and applied once the render that
/// attaches the element is reconciled (focus) or laid out (scroll).
#[derive(Default)]
struct ElementRequests {
  focus: Option<ElementRef>,
  /// The focus is to go on as Tab would from where it is, or was, and back where nothing follows: see
  /// [`FocusHandle::focus_onward`].
  focus_onward: bool,
  scroll_into_view: Option<ElementRef>,
  /// An element to scroll to the start of what scrolls it.
  scroll_into_view_start: Option<ElementRef>,
  /// A range of a text to scroll into view, in bytes of its content.
  scroll_range_into_view: Option<(ElementRef, std::ops::Range<usize>)>,
  blur: bool,
  scroll_to_top: bool,
  /// The scroll containers to take to their tops, by their states.
  scroll_states_to_top: Vec<crate::layout::layout_kind::ScrollState>,
  /// The scroll containers to take to an offset, by their states: the last asked of each.
  scroll_states_to: Vec<(crate::layout::layout_kind::ScrollState, f32, f32)>,
}

/// What moves the focus from a handler, which has no `Ctx`: made by [`Ctx::focus_handle`], kept by a component and
/// given to its handlers. Its requests are carried out once the render that follows them is reconciled, as
/// [`Ctx::focus`]'s are.
#[derive(Clone)]
pub struct FocusHandle {
  requests: Arc<Mutex<ElementRequests>>,
  window: Option<crate::app::window::Window>,
}

impl FocusHandle {
  fn wake(&self) {
    if let Some(window) = &self.window {
      window.wake();
    }
  }

  /// Focuses `element`, as [`Ctx::focus`] does.
  pub fn focus(&self, element: &ElementRef) {
    self.requests.lock().focus = Some(element.clone());
    self.wake();
  }

  /// Moves the focus on to the next stop of Tab after where it is, or after where it was where what had it has
  /// left the tree; to the stop before where nothing follows; and nowhere where there is no stop. What a control
  /// that takes itself out of the tree asks where nothing better is known: the close of a preview in a draft, a
  /// chip a person removed. The focus is never left to nothing.
  pub fn focus_onward(&self) {
    self.requests.lock().focus_onward = true;
    self.wake();
  }
}

/// Whether a screen is the one in front, as the outlet that holds it says, and the same of what that outlet is
/// in: what [`Ctx::is_in_front`] reads. An outlet that keeps screens that are not shown (a `StackOutlet`, a
/// `TabOutlet`) gives each of them one.
#[derive(Clone)]
pub(crate) struct InFront {
  own: Signal<bool>,
  around: Option<Arc<InFront>>,
}

impl InFront {
  /// Of a screen whose outlet sets `own`, in what `around` is of.
  pub(crate) fn new(own: Signal<bool>, around: Option<InFront>) -> Self {
    Self {
      own,
      around: around.map(Arc::new),
    }
  }

  /// Whether it is in front, and what it is in is: every one of them is read, so that a change of any renders
  /// what read it again.
  fn get(&self) -> bool {
    let own = self.own.get();
    let around = self.around.as_ref().is_none_or(|around| around.get());
    own && around
  }
}

/// What DevTools shows of this context: whether the screen is in front.
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for InFront {
  fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
    formatter.value_debug(&self.own.get_untracked());
  }
}

/// What a component's descendants keep clear of at the bottom, more than the window's own bottom inset, for
/// a bar the component draws over them there: [`Ctx::safe_area`] adds it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum BottomBarInset {
  Over(f32),
}

/// What DevTools shows of this context: its value as it is debugged.
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for BottomBarInset {
  fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
    formatter.value_debug(self);
  }
}

crate::register_inspectable!(BottomBarInset);

/// A component keeps its descendants clear of everything at the window's edges itself: for them
/// [`Ctx::safe_area`] is nothing at every side. A sheet's content is such: the sheet stands clear of the status
/// bar, and pads its content by the home indicator and the keyboard.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SafeAreaTaken;

/// What DevTools shows of this context: its value as it is debugged.
#[cfg(feature = "devtools")]
impl crate::app::component::DevtoolsInspectable for SafeAreaTaken {
  fn inspect(&self, formatter: &mut crate::app::component::DevtoolsFormatter<'_>) {
    formatter.value_debug(self);
  }
}

crate::register_inspectable!(SafeAreaTaken);

/// What runs a command of editing on the focus of a window, from a handler: [`Ctx::edit_runner`].
#[derive(Clone)]
pub struct EditRunner {
  window: Option<crate::app::window::Window>,
}

impl EditRunner {
  /// Runs `command` on what has the focus once the event that asked is handled; see [`Ctx::edit`].
  pub fn run(&self, command: crate::app::events::EditCommand) {
    if let Some(window) = &self.window {
      window.request_edit(command);
    }
  }
}

/// What goes back or forward in a window from a handler, as the keys and the mouse's side buttons do:
/// [`Ctx::history_runner`].
#[derive(Clone)]
pub struct HistoryRunner {
  window: Option<crate::app::window::Window>,
}

impl HistoryRunner {
  /// Goes back once the event that asked is handled; see [`Ctx::history_back`].
  pub fn back(&self) {
    self.run(crate::app::events::NavigationCommand::Back);
  }

  /// Goes forward once the event that asked is handled; see [`Ctx::history_forward`].
  pub fn forward(&self) {
    self.run(crate::app::events::NavigationCommand::Forward);
  }

  /// Goes back or forward by `command`, on what has the focus and out from it.
  pub fn run(&self, command: crate::app::events::NavigationCommand) {
    self.request(command, crate::app::window::NavigationOrigin::Focus, None);
  }

  /// Goes back or forward from a part of the window, the element `part` is on: from the focused element where it
  /// is in that part, otherwise from the last element in it that has a handler for the command, or from the part
  /// itself; then out from there, as from the focus. What a back button of a panel runs, which has the focus itself
  /// and stands beside what goes back.
  pub fn run_in(&self, part: &crate::core::ElementRef, command: crate::app::events::NavigationCommand) {
    self.request(command, crate::app::window::NavigationOrigin::Part(part.clone()), None);
  }

  /// As [`run_in`](Self::run_in), from `source`, with `done` told whether something took the command.
  #[cfg_attr(not(feature = "router"), allow(dead_code))]
  pub(crate) fn run_in_then(
    &self,
    part: &crate::core::ElementRef,
    command: crate::app::events::NavigationCommand,
    source: crate::app::events::NavigationSource,
    done: impl FnOnce(bool) + Send + Sync + 'static,
  ) {
    let request = crate::app::window::NavigationRequest {
      command,
      source,
      origin: crate::app::window::NavigationOrigin::Part(part.clone()),
      done: Some(Box::new(done)),
    };
    match &self.window {
      Some(window) => window.request_navigation(request),
      None => {
        if let Some(done) = request.done {
          done(false);
        }
      }
    }
  }

  fn request(
    &self,
    command: crate::app::events::NavigationCommand,
    origin: crate::app::window::NavigationOrigin,
    done: Option<crate::app::window::NavigationDone>,
  ) {
    if let Some(window) = &self.window {
      window.request_navigation(crate::app::window::NavigationRequest {
        command,
        source: crate::app::events::NavigationSource::App,
        origin,
        done,
      });
    }
  }
}

pub struct Ctx {
  dirty: Arc<AtomicBool>,
  subtree_dirty: Arc<AtomicBool>,
  dirty_child_slots: Arc<Mutex<Vec<u64>>>,
  ancestor_dirty_slots: Vec<DirtyAncestor>,
  batch: Arc<BatchState>,
  props: Option<Box<dyn Any + Send>>,
  #[cfg(feature = "devtools")]
  props_debug: Option<DevtoolsInspectableDebug>,
  #[cfg(feature = "devtools")]
  signals_debug: Vec<ComponentSignalDebug>,
  #[cfg(feature = "devtools")]
  memos_debug: Vec<ComponentMemoDebug>,
  #[cfg(feature = "devtools")]
  effects_debug: Vec<ComponentEffectDebug>,
  #[cfg(feature = "devtools")]
  contexts_debug: Vec<ComponentContextDebug>,
  #[cfg(feature = "devtools")]
  render_debug: ComponentRenderDebug,
  /// When the render that is running began: what its time is measured from.
  #[cfg(feature = "devtools")]
  render_started: Option<Instant>,
  theme: Option<Theme>,
  window: Option<crate::app::window::Window>,
  breakpoint: Option<crate::core::Memo<Option<crate::app::theme::Breakpoint>>>,
  i18n: Option<I18n>,
  app: Option<App>,
  element_requests: Arc<Mutex<ElementRequests>>,
  #[cfg(feature = "tokio")]
  runtime_future_handle: RuntimeFutureHandle,
  context_map: ContextMap,
  /// Values this component provided outside render (in `create`). They are
  /// re-applied on top of the inherited contexts whenever those change.
  provided_contexts: ContextMap,
  /// Inherited contexts with `provided_contexts` on top: what every render of
  /// this component starts from.
  base_contexts: ContextMap,
  /// Revision of the parent's context map the inherited values were taken from.
  inherited_context_revision: u64,
  /// The types this component read from its contexts (`use_context`,
  /// `consume_context`), in `create`, a render or a handler: a change of
  /// an inherited value of one of them renders the component again, a
  /// change of any other does not.
  context_reads: Vec<TypeId>,
  /// Whether the last render provided a value: such a component renders
  /// again whenever its inherited contexts change, so it provides again.
  provided_in_render: bool,
  /// The map the previous render left, while this one renders: a value
  /// `provide_if_changed` finds unchanged in it keeps its entry.
  previous_render_contexts: Option<ContextMap>,
  slot_children: Option<Vec<Element>>,
  children: Vec<ChildSlot>,
  child_cursor: usize,
  scope_id: u64,
  element_ref_cursor: usize,
  future_cursor: usize,
  watch_handles: Vec<Box<dyn Any + Send + Sync>>,
  render_watch_handles: Vec<Box<dyn Any + Send + Sync>>,
  effects: Vec<Effect>,
  timers: Vec<Timer>,
  /// The callbacks of `ctx.on_frame`.
  frames: frames::ComponentFrames,
  /// Slots of the `ctx.future`, `ctx.stream` and `ctx.future_action` calls of
  /// a render, by call position.
  future_slots: Vec<FutureSlot>,
  /// Slots of those calls made outside render (in `create`): one each, kept
  /// until the component unmounts.
  stable_future_slots: Vec<FutureSlot>,
  /// The component this context belongs to, for diagnostics.
  component_name: &'static str,
  #[cfg(feature = "query")]
  query_registry: crate::query::QueryRegistry,
  #[cfg(feature = "query")]
  query_slots: Vec<crate::query::Observer>,
  #[cfg(feature = "query")]
  query_cursor: usize,
  element_refs: Vec<ElementRefMut>,
  click_outside_registry: Arc<Mutex<Vec<ClickOutsideEntry>>>,
  click_outside_cursor: usize,
  click_outside_active_cursors: Vec<usize>,
  rendering: bool,
  /// A mount gives a node that stands for an unchanged component in place of a copy of its output: set while a
  /// declared component is mounted ([`Self::mount_holding`]).
  holding: bool,
}

#[derive(Clone)]
struct DirtyAncestor {
  subtree_dirty: Arc<AtomicBool>,
  dirty_child_slots: Arc<Mutex<Vec<u64>>>,
  child_slot_id: u64,
}

#[cfg(feature = "devtools")]
#[derive(Clone, Debug, PartialEq)]
pub struct DevtoolsInspectableDebug {
  pub type_name: Arc<str>,
  pub fields: Vec<ComponentInfo>,
}

#[cfg(feature = "devtools")]
#[derive(Clone, Debug)]
pub struct ComponentSignalDebug {
  pub id: usize,
  pub type_name: Arc<str>,
  value: Arc<Mutex<Option<Arc<str>>>>,
  history: Arc<Mutex<Vec<ComponentValueChangeDebug>>>,
  subscriber_count: Arc<AtomicUsize>,
}

#[cfg(feature = "devtools")]
#[derive(Clone, Debug)]
pub struct ComponentMemoDebug {
  pub id: usize,
  pub type_name: Arc<str>,
  value: Arc<Mutex<Option<Arc<str>>>>,
  history: Arc<Mutex<Vec<ComponentValueChangeDebug>>>,
  subscriber_count: Arc<AtomicUsize>,
}

#[cfg(feature = "devtools")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ComponentValueChangeDebug {
  /// Which change this is among all the changes of every signal and memo of the process, from 1: a later one has
  /// a greater number, so what happened after a moment is told from what happened before it.
  pub sequence: u64,
  pub timestamp: String,
  pub from_value: String,
  pub to_value: String,
}

/// Numbers the changes DevTools is told of ([`ComponentValueChangeDebug::sequence`]).
#[cfg(feature = "devtools")]
static NEXT_VALUE_CHANGE: AtomicU64 = AtomicU64::new(1);

#[cfg(feature = "devtools")]
#[derive(Clone, Debug, PartialEq)]
pub struct ComponentEffectDebug {
  pub id: usize,
}

/// How a component has rendered, for DevTools: counted where its render is called.
#[cfg(feature = "devtools")]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ComponentRenderDebug {
  /// How many times it has rendered since it was mounted.
  pub count: u64,
  /// How long its last render took, with the renders of what it mounted in it.
  pub last: Duration,
}

#[cfg(feature = "devtools")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ComponentContextKind {
  Provided,
  Consumed,
}

#[cfg(feature = "devtools")]
#[derive(Clone, Debug)]
pub struct ComponentContextDebug {
  pub kind: ComponentContextKind,
  pub type_name: Arc<str>,
  /// Whether it is a reactive context (`create_context`, `consume_context`): one whose value is set, and
  /// renders what reads it again.
  pub reactive: bool,
  /// What a provided context holds, and how that changed. A context that is read here has neither: they are
  /// its provider's.
  value: Arc<Mutex<Option<Vec<ComponentInfo>>>>,
  history: Arc<Mutex<Vec<ComponentContextChangeDebug>>>,
}

/// One change of what a context holds, as its type wrote the value before and the value after.
#[cfg(feature = "devtools")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ComponentContextChangeDebug {
  /// Which change this is among all the changes DevTools is told of, as a signal's is
  /// ([`ComponentValueChangeDebug::sequence`]): the two count together.
  pub sequence: u64,
  pub timestamp: String,
  pub from_value: Vec<ComponentInfo>,
  pub to_value: Vec<ComponentInfo>,
}

#[cfg(feature = "devtools")]
impl ComponentContextDebug {
  /// What the context holds, as its type writes itself for DevTools: its fields, or one `value`. Empty for a
  /// type that writes nothing of itself; `None` for a context that is read here and not provided.
  pub fn value(&self) -> Option<Vec<ComponentInfo>> {
    self.value.lock().clone()
  }

  /// The last 64 changes of what it holds, the oldest first.
  pub fn history(&self) -> Vec<ComponentContextChangeDebug> {
    self.history.lock().clone()
  }
}

#[cfg(feature = "devtools")]
impl PartialEq for ComponentContextDebug {
  fn eq(&self, other: &Self) -> bool {
    self.kind == other.kind
      && self.type_name == other.type_name
      && self.reactive == other.reactive
      && self.value() == other.value()
      && self.history() == other.history()
  }
}

/// Takes the value a provided context holds now: where it is another than the one held before, the change is
/// recorded.
#[cfg(feature = "devtools")]
fn record_context_value(
  held: &Mutex<Option<Vec<ComponentInfo>>>,
  history: &Mutex<Vec<ComponentContextChangeDebug>>,
  next: Vec<ComponentInfo>,
) {
  let mut held = held.lock();
  if held.as_ref() == Some(&next) {
    return;
  }
  if let Some(previous) = held.as_ref() {
    let mut history = history.lock();
    history.push(ComponentContextChangeDebug {
      sequence: NEXT_VALUE_CHANGE.fetch_add(1, Ordering::Relaxed),
      timestamp: current_compact_timestamp(),
      from_value: previous.clone(),
      to_value: next.clone(),
    });
    if history.len() > 64 {
      let overflow = history.len() - 64;
      history.drain(0..overflow);
    }
  }
  *held = Some(next);
}

/// What a value writes of itself for DevTools, where its type registered an inspector
/// (`#[derive(DevtoolsInspectable)]`, `register_inspectable!`): nothing where it did not. No bound asks a
/// context's type for one.
#[cfg(feature = "devtools")]
fn inspected<T: 'static>(value: &T) -> Vec<ComponentInfo> {
  crate::app::component::inspect_registered(value).unwrap_or_default()
}

#[cfg(feature = "devtools")]
impl DevtoolsInspectableDebug {
  fn from_props<T: DevtoolsInspectable + 'static>(props: &T) -> Self {
    let mut fields = Vec::new();
    props.write_info(&mut fields);
    Self {
      type_name: Arc::from(std::any::type_name::<T>()),
      fields,
    }
  }
}

#[cfg(feature = "devtools")]
impl ComponentSignalDebug {
  pub fn formatted_value(&self) -> Option<String> {
    self.value.lock().as_ref().map(|value| value.to_string())
  }

  pub fn history(&self) -> Vec<ComponentValueChangeDebug> {
    self.history.lock().clone()
  }

  pub fn subscriber_count(&self) -> usize {
    self.subscriber_count.load(Ordering::Relaxed)
  }

  #[cfg_attr(not(feature = "perf_profile"), allow(dead_code))]
  pub(crate) fn estimated_memory_bytes(&self) -> usize {
    let history = self.history.lock();
    self.value.lock().as_ref().map(|value| value.len()).unwrap_or(0)
      + history.capacity() * std::mem::size_of::<ComponentValueChangeDebug>()
      + history
        .iter()
        .map(ComponentValueChangeDebug::estimated_memory_bytes)
        .sum::<usize>()
  }
}

#[cfg(feature = "devtools")]
impl ComponentMemoDebug {
  pub fn formatted_value(&self) -> Option<String> {
    self.value.lock().as_ref().map(|value| value.to_string())
  }

  pub fn history(&self) -> Vec<ComponentValueChangeDebug> {
    self.history.lock().clone()
  }

  pub fn subscriber_count(&self) -> usize {
    self.subscriber_count.load(Ordering::Relaxed)
  }

  pub(crate) fn estimated_memory_bytes(&self) -> usize {
    let history = self.history.lock();
    self.value.lock().as_ref().map(|value| value.len()).unwrap_or(0)
      + history.capacity() * std::mem::size_of::<ComponentValueChangeDebug>()
      + history
        .iter()
        .map(ComponentValueChangeDebug::estimated_memory_bytes)
        .sum::<usize>()
  }
}

#[cfg(feature = "devtools")]
impl ComponentValueChangeDebug {
  #[cfg_attr(not(feature = "perf_profile"), allow(dead_code))]
  fn estimated_memory_bytes(&self) -> usize {
    self.timestamp.capacity() + self.from_value.capacity() + self.to_value.capacity()
  }
}

#[cfg(feature = "devtools")]
impl PartialEq for ComponentSignalDebug {
  fn eq(&self, other: &Self) -> bool {
    self.id == other.id
      && self.type_name == other.type_name
      && self.formatted_value() == other.formatted_value()
      && self.history() == other.history()
      && self.subscriber_count() == other.subscriber_count()
  }
}

#[cfg(feature = "devtools")]
impl PartialEq for ComponentMemoDebug {
  fn eq(&self, other: &Self) -> bool {
    self.id == other.id
      && self.type_name == other.type_name
      && self.formatted_value() == other.formatted_value()
      && self.history() == other.history()
      && self.subscriber_count() == other.subscriber_count()
  }
}

#[cfg(feature = "devtools")]
fn update_debug_value_history(
  current_value: &Arc<Mutex<Option<Arc<str>>>>,
  history: &Arc<Mutex<Vec<ComponentValueChangeDebug>>>,
  next_value: Option<Arc<str>>,
) {
  let mut current_value = current_value.lock();
  if *current_value == next_value {
    return;
  }

  if let Some(previous) = current_value.as_ref() {
    let mut history = history.lock();
    history.push(ComponentValueChangeDebug {
      sequence: NEXT_VALUE_CHANGE.fetch_add(1, Ordering::Relaxed),
      timestamp: current_compact_timestamp(),
      from_value: previous.to_string(),
      to_value: next_value
        .as_ref()
        .map(|value| value.to_string())
        .unwrap_or_else(|| "<unknown>".to_owned()),
    });
    if history.len() > 64 {
      let overflow = history.len() - 64;
      history.drain(0..overflow);
    }
  }

  *current_value = next_value;
}

/// The moment a value changed, as DevTools writes it: by the clock and the zone of the system, where the
/// engine can read the zone (`core::Time::now`), and in UTC where it cannot.
#[cfg(feature = "devtools")]
fn current_compact_timestamp() -> String {
  let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
  compact_timestamp(
    duration.as_secs(),
    duration.subsec_millis(),
    crate::core::Time::now().seconds(),
  )
}

/// `utc_seconds` and `millis` since 1970 as a time of day in the zone where it is `local_seconds` after
/// midnight now. The two clocks are read a moment apart, so the zone is taken to the quarter of an hour every
/// zone is at, and the seconds and the milliseconds are those of one reading.
#[cfg(feature = "devtools")]
fn compact_timestamp(utc_seconds: u64, millis: u32, local_seconds: i64) -> String {
  const DAY: i64 = 86_400;
  const QUARTER: i64 = 900;
  let utc_of_day = (utc_seconds % DAY as u64) as i64;
  let zone = ((local_seconds - utc_of_day) as f64 / QUARTER as f64).round() as i64 * QUARTER;
  let seconds_of_day = (utc_of_day + zone).rem_euclid(DAY);
  let hour = seconds_of_day / 3_600;
  let minute = seconds_of_day % 3_600 / 60;
  let second = seconds_of_day % 60;
  format!("{hour:02}:{minute:02}:{second:02}.{millis:03}")
}

#[cfg(all(test, feature = "devtools"))]
mod timestamp_tests {
  use super::compact_timestamp;

  #[test]
  fn a_change_is_timed_by_the_clock_of_the_zone() {
    // 09:29:40.005 in UTC, read where it is two hours later.
    let utc = 9 * 3_600 + 29 * 60 + 40;
    assert_eq!(compact_timestamp(utc, 5, (utc + 2 * 3_600) as i64), "11:29:40.005");
    // The zone's clock was read a second later: the seconds are still those of the first reading.
    assert_eq!(compact_timestamp(utc, 5, (utc + 2 * 3_600 + 1) as i64), "11:29:40.005");
    // A zone behind UTC, across midnight, and one at a quarter of an hour.
    assert_eq!(compact_timestamp(3_600, 0, 20 * 3_600), "20:00:00.000");
    assert_eq!(
      compact_timestamp(utc, 0, (utc + 5 * 3_600 + 45 * 60) as i64),
      "15:14:40.000"
    );
    // Where the zone is not read the clock is UTC's.
    assert_eq!(compact_timestamp(utc, 250, utc as i64), "09:29:40.250");
    // Days since 1970 do not matter.
    assert_eq!(compact_timestamp(20_000 * 86_400 + utc, 0, utc as i64), "09:29:40.000");
  }
}

#[cfg(feature = "devtools")]
fn format_debug_value<T: DevtoolsInspectable + 'static>(value: &T) -> Option<Arc<str>> {
  let mut fields = Vec::new();
  value.write_info(&mut fields);
  format_debug_fields(&fields).map(Arc::from)
}

#[cfg(feature = "devtools")]
fn format_debug_fields(fields: &[ComponentInfo]) -> Option<String> {
  if fields.is_empty() {
    return None;
  }

  if fields.len() == 1 {
    let info = &fields[0];
    if matches!(info.name(), "value" | "variant")
      && let Some(value) = info.formatted_value()
    {
      return Some(value.to_owned());
    }
  }

  Some(fields.iter().map(format_debug_info).collect::<Vec<_>>().join(", "))
}

#[cfg(feature = "devtools")]
fn format_debug_info(info: &ComponentInfo) -> String {
  if let Some(value) = info.formatted_value() {
    if info.name() == "value" {
      value.to_owned()
    } else {
      format!("{}: {}", info.name(), value)
    }
  } else if let Some(children) = format_debug_fields(info.children()) {
    if info.name() == "Some" {
      format!("Some({children})")
    } else {
      format!("{}: {{{children}}}", info.name())
    }
  } else {
    format!("{}: {}", info.name(), info.type_name())
  }
}

#[derive(Default)]
struct BatchState {
  inner: Mutex<BatchStateInner>,
  /// Wakes the window's event loop when a write off its thread marks components dirty
  /// ([`Window::off_loop_waker`]); `None` without a window.
  off_loop_wake: Option<WindowWaker>,
}

#[derive(Default)]
struct BatchStateInner {
  depth: usize,
  pending_dirty: Vec<Arc<AtomicBool>>,
}

struct BatchGuard<'a> {
  state: &'a BatchState,
}

impl BatchState {
  fn waking(off_loop_wake: WindowWaker) -> Self {
    Self {
      inner: Mutex::default(),
      off_loop_wake: Some(off_loop_wake),
    }
  }

  fn batch<R>(&self, f: impl FnOnce() -> R) -> R {
    self.inner.lock().depth += 1;
    let guard = BatchGuard { state: self };
    let result = f();
    drop(guard);
    result
  }

  /// Marks `dirty`, or holds the mark back until the batch ends. Returns whether the flag went from clean to
  /// dirty now: a flag already dirty has its pass coming, so marking it again needs no wake.
  fn mark_dirty(&self, dirty: &Arc<AtomicBool>) -> bool {
    let mut inner = self.inner.lock();
    if inner.depth == 0 {
      drop(inner);
      return !dirty.swap(true, Ordering::Relaxed);
    }

    inner.pending_dirty.push(dirty.clone());
    false
  }

  fn end_batch(&self) {
    let pending = {
      let mut inner = self.inner.lock();
      debug_assert!(inner.depth > 0);
      inner.depth = inner.depth.saturating_sub(1);
      if inner.depth > 0 {
        return;
      }
      std::mem::take(&mut inner.pending_dirty)
    };
    let mut seen = HashSet::new();
    let mut newly_dirty = false;
    for dirty in pending {
      let ptr = Arc::as_ptr(&dirty) as usize;
      if seen.insert(ptr) {
        newly_dirty |= !dirty.swap(true, Ordering::Relaxed);
      }
    }
    if newly_dirty {
      self.wake_loop();
    }
  }

  /// Wakes the event loop for a write off its thread that made a component dirty. Only a flag that goes from
  /// clean to dirty wakes it, so a thread writing thousands of times before the loop renders wakes it once
  /// instead of posting a message per write.
  fn wake_loop(&self) {
    if let Some(wake) = &self.off_loop_wake {
      wake();
    }
  }
}

impl Drop for BatchGuard<'_> {
  fn drop(&mut self) {
    self.state.end_batch();
  }
}

struct ChildSlot {
  id: u64,
  key: Option<String>,
  component: Box<dyn AnyComponent>,
  ctx: Ctx,
  /// The component's own output from its last render, with placeholders for
  /// the components it mounted (`node/component_output.rs`). It shares its
  /// runtime state (scroll states, text-input states, canvases) with the
  /// live tree. Read to hand an unchanged component back to a parent that
  /// renders again ([`Self::assembled_output`]) and to carry runtime state
  /// over to the component's next render, the only source of that state for
  /// a component resuming from offstage.
  rendered: Option<Box<Node>>,
  /// When `rendered` was rendered ([`next_render_generation`]).
  rendered_at: u64,
  mounted: bool,
  offstage: bool,
  offstage_dirty: bool,
}

trait AnyComponent: Send + Sync + 'static {
  fn render(&self, ctx: &mut Ctx) -> Element;
  fn after_layout(&self);
  fn on_mounted(&self);
  fn on_unmounted(&self);
  fn type_name(&self) -> &'static str;
  fn tag_name(&self) -> Arc<str>;
}

struct ComponentWrapper<C: Component> {
  component: C,
}

impl<C: Component> AnyComponent for ComponentWrapper<C> {
  fn render(&self, ctx: &mut Ctx) -> Element {
    let mut element: Element = self.component.render(ctx).into();
    // The components its output declares (`Element::component`) are mounted now that `ctx` is free again.
    element.node.mount_declared_components(ctx);
    element
  }

  fn after_layout(&self) {
    self.component.after_layout();
  }

  fn on_mounted(&self) {
    self.component.on_mounted();
  }

  fn on_unmounted(&self) {
    self.component.on_unmounted();
  }

  fn type_name(&self) -> &'static str {
    std::any::type_name::<C>()
  }

  fn tag_name(&self) -> Arc<str> {
    component_tag_name::<C>()
  }
}

impl Ctx {
  pub fn new_root() -> Self {
    Self::new()
  }

  pub(crate) fn new() -> Self {
    Self {
      dirty: Arc::new(AtomicBool::new(true)),
      subtree_dirty: Arc::new(AtomicBool::new(true)),
      dirty_child_slots: Arc::new(Mutex::new(Vec::new())),
      ancestor_dirty_slots: Vec::new(),
      batch: Arc::new(BatchState::default()),
      props: None,
      #[cfg(feature = "devtools")]
      props_debug: None,
      #[cfg(feature = "devtools")]
      signals_debug: Vec::new(),
      #[cfg(feature = "devtools")]
      memos_debug: Vec::new(),
      #[cfg(feature = "devtools")]
      effects_debug: Vec::new(),
      #[cfg(feature = "devtools")]
      contexts_debug: Vec::new(),
      #[cfg(feature = "devtools")]
      render_debug: ComponentRenderDebug::default(),
      #[cfg(feature = "devtools")]
      render_started: None,
      theme: None,
      window: None,
      breakpoint: None,
      i18n: None,
      app: None,
      element_requests: Arc::default(),
      #[cfg(feature = "tokio")]
      runtime_future_handle: None,
      context_map: ContextMap::default(),
      provided_contexts: ContextMap::default(),
      base_contexts: ContextMap::default(),
      inherited_context_revision: 0,
      context_reads: Vec::new(),
      provided_in_render: false,
      previous_render_contexts: None,
      slot_children: None,
      children: Vec::new(),
      child_cursor: 0,
      scope_id: 0,
      element_ref_cursor: 0,
      future_cursor: 0,
      watch_handles: Vec::new(),
      render_watch_handles: Vec::new(),
      effects: Vec::new(),
      timers: Vec::new(),
      frames: frames::ComponentFrames::default(),
      future_slots: Vec::new(),
      stable_future_slots: Vec::new(),
      component_name: "root",
      #[cfg(feature = "query")]
      query_registry: crate::query::QueryRegistry::default(),
      #[cfg(feature = "query")]
      query_slots: Vec::new(),
      #[cfg(feature = "query")]
      query_cursor: 0,
      element_refs: Vec::new(),
      click_outside_registry: Arc::new(Mutex::new(Vec::new())),
      click_outside_cursor: 0,
      click_outside_active_cursors: Vec::new(),
      rendering: false,
      holding: false,
    }
  }

  pub(crate) fn with_theme(mut self, theme: Theme) -> Self {
    self.theme = Some(theme);
    self
  }

  pub(crate) fn with_window(mut self, window: crate::app::window::Window) -> Self {
    self.batch = Arc::new(BatchState::waking(window.off_loop_waker()));
    self.window = Some(window);
    self
  }

  /// Builds the reactive breakpoint memo from the current window and theme.
  /// Must be called after `with_theme` and `with_window`. The memo recomputes on
  /// window resize and theme changes but only notifies subscribers when the
  /// resolved breakpoint actually changes, so `breakpoint()`/`responsive()`
  /// re-render on threshold crossings, not on every resize tick.
  pub(crate) fn with_breakpoint(mut self) -> Self {
    if let (Some(window), Some(theme)) = (self.window.clone(), self.theme.clone()) {
      self.breakpoint = Some(crate::core::Memo::new(move || {
        window.track_access();
        theme.track_access();
        theme.breakpoints().resolve(window.info().logical_width())
      }));
    }
    self
  }

  pub(crate) fn with_i18n(mut self, i18n: I18n) -> Self {
    self.i18n = Some(i18n);
    self
  }

  pub(crate) fn set_app_ref(&mut self, app: &mut App) {
    self.app = Some(app.clone());
    #[cfg(feature = "tokio")]
    {
      self.runtime_future_handle = app.tokio_handle();
    }
    for slot in &mut self.children {
      slot.ctx.set_app_ref(app);
    }
  }

  fn runtime_future_handle(&self) -> RuntimeFutureHandle {
    #[cfg(feature = "tokio")]
    {
      self.runtime_future_handle.clone()
    }
    #[cfg(not(feature = "tokio"))]
    {}
  }

  pub fn is_dirty(&self) -> bool {
    self.dirty.load(Ordering::Relaxed)
  }

  fn mark_dirty_targets(
    batch: &BatchState,
    dirty: &Arc<AtomicBool>,
    subtree_dirty: &Arc<AtomicBool>,
    ancestor_dirty_slots: &[DirtyAncestor],
  ) {
    // Every flag is marked; any that was clean wakes the loop once the marks are stored. Inside a batch, its
    // end stores and wakes.
    let mut newly_dirty = batch.mark_dirty(dirty);
    newly_dirty |= batch.mark_dirty(subtree_dirty);
    for ancestor in ancestor_dirty_slots {
      newly_dirty |= batch.mark_dirty(&ancestor.subtree_dirty);
      Self::mark_dirty_child_slot(&ancestor.dirty_child_slots, ancestor.child_slot_id);
    }
    if newly_dirty {
      batch.wake_loop();
    }
  }

  fn mark_self_dirty(&self) {
    self.dirty.store(true, Ordering::Relaxed);
    self.subtree_dirty.store(true, Ordering::Relaxed);
    for ancestor in &self.ancestor_dirty_slots {
      ancestor.subtree_dirty.store(true, Ordering::Relaxed);
      Self::mark_dirty_child_slot(&ancestor.dirty_child_slots, ancestor.child_slot_id);
    }
  }

  fn mark_dirty_child_slot(dirty_child_slots: &Mutex<Vec<u64>>, slot_id: u64) {
    let mut dirty_child_slots = dirty_child_slots.lock();
    if !dirty_child_slots.contains(&slot_id) {
      dirty_child_slots.push(slot_id);
    }
  }

  fn inherit_dirty_ancestors_from(&mut self, parent: &Ctx, slot_id: u64) {
    self.ancestor_dirty_slots = parent.ancestor_dirty_slots.clone();
    self.ancestor_dirty_slots.push(DirtyAncestor {
      subtree_dirty: parent.subtree_dirty.clone(),
      dirty_child_slots: parent.dirty_child_slots.clone(),
      child_slot_id: slot_id,
    });
  }

  fn update_subtree_dirty_from_children(&self) {
    let dirty = self.is_dirty() || !self.dirty_child_slots.lock().is_empty();
    self.subtree_dirty.store(dirty, Ordering::Relaxed);
  }

  fn take_dirty_child_slot_ids(&self) -> Vec<u64> {
    let mut dirty_child_slots = self.dirty_child_slots.lock();
    std::mem::take(&mut *dirty_child_slots)
  }

  pub(crate) fn clear_dirty(&self) {
    self.dirty.store(false, Ordering::Relaxed);
    self.subtree_dirty.store(false, Ordering::Relaxed);
    self.dirty_child_slots.lock().clear();
  }

  pub fn batch<R>(&self, f: impl FnOnce() -> R) -> R {
    self.batch.batch(f)
  }

  pub fn props<T: Send + PartialEq + 'static>(&self) -> &T {
    self
      .props
      .as_ref()
      .and_then(|props| props.downcast_ref::<T>())
      .expect("component props are not available for this type")
  }

  #[cfg(feature = "devtools")]
  fn set_props<T: Send + PartialEq + DevtoolsInspectable + 'static>(&mut self, props: T) {
    self.props_debug = Some(DevtoolsInspectableDebug::from_props(&props));
    self.props = Some(Box::new(props));
  }

  #[cfg(not(feature = "devtools"))]
  fn set_props<T: Send + PartialEq + 'static>(&mut self, props: T) {
    self.props = Some(Box::new(props));
  }

  pub(crate) fn set_component_name(&mut self, name: &'static str) {
    self.component_name = name;
  }

  /// The `std::any::type_name` of this context's component.
  #[cfg(feature = "perf_profile")]
  pub(crate) fn component_name(&self) -> &'static str {
    self.component_name
  }

  /// What a notification from `source` runs for this component: marks it
  /// dirty and, while a detailed recording runs, notes `source` as a cause of
  /// its next render.
  fn dirty_notifier(
    &self,
    #[cfg(feature = "perf_profile")] source: crate::app::profiler::RenderSource,
  ) -> impl Fn() + Send + Sync + 'static {
    let dirty = self.dirty.clone();
    let subtree_dirty = self.subtree_dirty.clone();
    let ancestor_dirty_slots = self.ancestor_dirty_slots.clone();
    let batch = self.batch.clone();
    #[cfg(feature = "perf_profile")]
    let component = self.component_name;
    move || {
      #[cfg(feature = "perf_profile")]
      crate::app::profiler::detail::note(&dirty, component, source);
      Self::mark_dirty_targets(&batch, &dirty, &subtree_dirty, &ancestor_dirty_slots);
    }
  }

  /// In an update a detailed recording records, the span of this
  /// component's render, with its causes noted: the notifications it got and
  /// `trigger()`, the reason its parent rendered it, if any. None otherwise.
  #[cfg(feature = "perf_profile")]
  pub(crate) fn render_span(
    &self,
    trigger: impl FnOnce() -> Option<crate::app::profiler::RenderTrigger>,
  ) -> Option<crate::app::profiler::detail::ComponentSpan> {
    crate::app::profiler::detail::component_render(&self.dirty, self.component_name, trigger)
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn set_root_props<T: Send + PartialEq + DevtoolsInspectable + 'static>(&mut self, props: T) {
    self.set_props(props);
  }

  #[cfg(not(feature = "devtools"))]
  pub(crate) fn set_root_props<T: Send + PartialEq + 'static>(&mut self, props: T) {
    self.set_props(props);
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn update_root_props<T: Send + PartialEq + DevtoolsInspectable + 'static>(&mut self, props: T) -> bool {
    if !self.props_changed(&props) {
      return false;
    }
    self.set_props(props);
    self.mark_self_dirty();
    true
  }

  #[cfg(not(feature = "devtools"))]
  pub(crate) fn update_root_props<T: Send + PartialEq + 'static>(&mut self, props: T) -> bool {
    if !self.props_changed(&props) {
      return false;
    }
    self.set_props(props);
    self.mark_self_dirty();
    true
  }

  fn props_changed<T: Send + PartialEq + 'static>(&self, props: &T) -> bool {
    self.props.as_ref().and_then(|existing| existing.downcast_ref::<T>()) != Some(props)
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn props_debug(&self) -> Option<DevtoolsInspectableDebug> {
    self.props_debug.clone()
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn render_debug(&self) -> ComponentRenderDebug {
    self.render_debug
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn signals_debug(&self) -> Vec<ComponentSignalDebug> {
    self.signals_debug.clone()
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn memos_debug(&self) -> Vec<ComponentMemoDebug> {
    self.memos_debug.clone()
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn effects_debug(&self) -> Vec<ComponentEffectDebug> {
    self.effects_debug.clone()
  }

  #[cfg(feature = "devtools")]
  pub(crate) fn contexts_debug(&self) -> Vec<ComponentContextDebug> {
    self.contexts_debug.clone()
  }

  // --- Reactive primitives ---

  #[cfg(feature = "devtools")]
  pub fn signal<T: Send + Sync + DevtoolsInspectable + 'static>(&mut self, initial: T) -> Signal<T> {
    let debug_value = Arc::new(Mutex::new(format_debug_value(&initial)));
    let debug_history = Arc::new(Mutex::new(Vec::new()));
    let sig = Signal::new(initial);
    self.signals_debug.push(ComponentSignalDebug {
      id: sig.id(),
      type_name: Arc::from(std::any::type_name::<T>()),
      value: debug_value.clone(),
      history: debug_history.clone(),
      subscriber_count: sig.devtools_subscriber_count(),
    });
    let debug_handle = sig.subscribe_debug(move |value| {
      update_debug_value_history(&debug_value, &debug_history, format_debug_value(value));
    });
    let handle = sig.watch(self.dirty_notifier(crate::app::profiler::detail::source_of::<T>(
      crate::app::profiler::RenderTrigger::Signal,
    )));
    self.watch_handles.push(Box::new(debug_handle));
    self.watch_handles.push(Box::new(handle));
    sig
  }

  #[cfg(not(feature = "devtools"))]
  pub fn signal<T: SignalValue + Send + Sync + 'static>(&mut self, initial: T) -> Signal<T> {
    let sig = Signal::new(initial);
    let handle = sig.watch(self.dirty_notifier(
      #[cfg(feature = "perf_profile")]
      crate::app::profiler::detail::source_of::<T>(crate::app::profiler::RenderTrigger::Signal),
    ));
    self.watch_handles.push(Box::new(handle));
    sig
  }

  #[cfg(feature = "devtools")]
  pub fn memo<T: Clone + PartialEq + Send + Sync + DevtoolsInspectable + 'static>(
    &mut self,
    f: impl Fn() -> T + Send + Sync + 'static,
  ) -> Memo<T> {
    let memo = Memo::new(f);
    let debug_value = Arc::new(Mutex::new(memo.with(|value| format_debug_value(value))));
    let debug_history = Arc::new(Mutex::new(Vec::new()));
    self.memos_debug.push(ComponentMemoDebug {
      id: memo.id(),
      type_name: Arc::from(std::any::type_name::<T>()),
      value: debug_value.clone(),
      history: debug_history.clone(),
      subscriber_count: memo.devtools_subscriber_count(),
    });
    let debug_handle = memo.subscribe(move |value| {
      update_debug_value_history(&debug_value, &debug_history, format_debug_value(value));
    });
    self.watch_handles.push(Box::new(debug_handle));
    memo
  }

  #[cfg(not(feature = "devtools"))]
  pub fn memo<T: SignalValue + Clone + PartialEq + Send + Sync + 'static>(
    &mut self,
    f: impl Fn() -> T + Send + Sync + 'static,
  ) -> Memo<T> {
    Memo::new(f)
  }

  pub fn create_ref<T: Send + Sync + 'static>(&self, initial: T) -> Ref<T> {
    Ref::new(initial)
  }

  pub fn on_effect(&mut self, f: impl Fn() + Send + Sync + 'static) {
    let effect = Effect::new(f);
    #[cfg(feature = "devtools")]
    self.effects_debug.push(ComponentEffectDebug { id: effect.id() });
    self.effects.push(effect);
  }

  pub fn create_timeout(&mut self, duration: Duration, f: impl Fn() + Send + Sync + 'static) -> Timeout {
    let timer = Timer::new(duration, false, f, self.window.as_ref().map(Window::loop_waker));
    self.timers.push(timer.clone());
    Timeout { timer }
  }

  pub fn create_interval(&mut self, duration: Duration, f: impl Fn() + Send + Sync + 'static) -> Interval {
    let timer = Timer::new(duration, true, f, self.window.as_ref().map(Window::loop_waker));
    self.timers.push(timer.clone());
    Interval { timer }
  }

  #[cfg(feature = "form")]
  pub fn form(&mut self, options: crate::components::FormOptions) -> crate::components::FormHandle {
    crate::components::FormHandle::with_dirty(
      options,
      Arc::new(self.dirty_notifier(
        #[cfg(feature = "perf_profile")]
        crate::app::profiler::RenderSource {
          trigger: crate::app::profiler::RenderTrigger::Form,
          value_type: None,
        },
      )),
    )
  }

  #[cfg(feature = "form")]
  pub fn form_view<R>(&mut self, form: crate::components::FormHandle, render: impl FnOnce(&mut Ctx) -> R) -> Element
  where
    R: Into<Element>,
  {
    self.form_view_with(crate::components::FormProps::new(form), render)
  }

  #[cfg(feature = "form")]
  pub fn form_view_with<R>(
    &mut self,
    props: crate::components::FormProps,
    render: impl FnOnce(&mut Ctx) -> R,
  ) -> Element
  where
    R: Into<Element>,
  {
    let previous_context = self.context_map.clone();
    if let Some(form) = props.form.clone() {
      self.provide(crate::components::FormContext::new(form));
    }
    let child = render(self).into();
    self.context_map = previous_context;
    crate::components::Form::element(props, child)
  }

  #[cfg(feature = "form")]
  pub fn form_control<T>(&mut self, control: &crate::components::Control<T>) -> crate::components::ResolvedControl<T>
  where
    T: SignalValue + Clone + PartialEq + Send + Sync + 'static,
  {
    control.resolve()
  }

  #[cfg(feature = "form")]
  pub fn string_control(&mut self, name: impl Into<Arc<str>>) -> crate::components::ResolvedControl<String> {
    self.current_form().string_control(name).resolve()
  }

  #[cfg(feature = "form")]
  pub fn number_control(&mut self, name: impl Into<Arc<str>>) -> crate::components::ResolvedControl<f64> {
    self.current_form().number_control(name).resolve()
  }

  #[cfg(feature = "form")]
  pub fn bool_control(&mut self, name: impl Into<Arc<str>>) -> crate::components::ResolvedControl<bool> {
    self.current_form().bool_control(name).resolve()
  }

  /// The control of a range slider's field, its low value and its high one, in the nearest form.
  #[cfg(feature = "form")]
  pub fn range_control(&mut self, name: impl Into<Arc<str>>) -> crate::components::ResolvedControl<(f64, f64)> {
    self.current_form().range_control(name).resolve()
  }

  #[cfg(feature = "form")]
  fn current_form(&mut self) -> crate::components::FormHandle {
    self
      .use_context::<crate::components::FormContext>()
      .map(|ctx| ctx.form())
      .expect("form controls must be resolved inside a Form render context")
  }

  #[cfg(feature = "router")]
  pub fn router(&mut self, routes: crate::router::Routes) -> crate::router::RouterHandle {
    crate::router::RouterHandle::new(routes)
  }

  #[cfg(feature = "router")]
  pub fn navigator(&mut self) -> Option<crate::router::Navigator> {
    self.use_context::<crate::router::Navigator>()
  }

  #[cfg(feature = "router")]
  pub fn route_params(&mut self) -> crate::router::Params {
    self
      .use_context::<crate::router::route_match::RouterMatches>()
      .and_then(|matches| matches.0.last().map(|m| m.params().clone()))
      .or_else(|| {
        self
          .use_context::<crate::router::route_match::OutletDepth>()
          .and_then(|depth| {
            self
              .use_context::<crate::router::route_match::RouterMatches>()
              .and_then(|matches| matches.0.get(depth.0).map(|m| m.params().clone()))
          })
      })
      .unwrap_or_default()
  }

  #[cfg(feature = "router")]
  pub fn route_path(&mut self) -> String {
    self
      .use_context::<crate::router::Navigator>()
      .map(|nav| nav.path().get())
      .unwrap_or_default()
  }

  #[cfg(feature = "router")]
  pub fn route_query(&mut self) -> crate::router::Query {
    self
      .use_context::<crate::router::Navigator>()
      .map(|nav| crate::router::Query::from_path(&nav.path().get()))
      .unwrap_or_default()
  }

  #[cfg(feature = "router")]
  pub fn route_state<T: std::any::Any + Send + Sync>(&mut self) -> Option<std::sync::Arc<T>> {
    // A screen of a stack keeps its own entry's state under the screens pushed over it.
    if let Some(state) = self.use_context::<crate::router::route_match::StackState>() {
      return state.0?.downcast::<T>().ok();
    }
    let nav = self.use_context::<crate::router::Navigator>()?;
    // Subscribe to navigations so this re-runs when the location (and its state) changes.
    let _ = nav.path().get();
    nav.state::<T>()
  }

  /// Says what the bar of the [`StackOutlet`](crate::components::StackOutlet) this screen is in shows for it:
  /// its title, what the way back to it says, what is at the bar's end. Call it in the screen's `render`.
  /// It does nothing outside a stack.
  #[cfg(feature = "router")]
  pub fn navigation_item(&mut self, item: crate::components::NavigationItem) {
    if let Some(slot) = self.use_context::<crate::components::stack_outlet::NavigationSlot>() {
      slot.set(item);
    }
  }

  /// Returns the client provided by a stable ancestor or this root context.
  #[cfg(feature = "query")]
  pub fn query_client(&mut self) -> crate::query::QueryClient {
    let client = self
      .use_context::<crate::query::QueryClient>()
      .expect("QueryClient is missing: call ctx.provide(QueryClient::new()) in the root component's create method");
    self.query_registry.attach(
      &client,
      self.window.as_ref().map(|window| window.loop_waker()),
      #[cfg(feature = "tokio")]
      self.runtime_future_handle.clone(),
    );
    client
  }

  /// Observe a typed query during render. Repeated renders reuse the observer;
  /// equal descriptors in different components share their cache and request.
  #[cfg(feature = "query")]
  pub fn query<D: crate::query::QueryDefinition>(
    &mut self,
    query: crate::query::Query<D>,
  ) -> crate::query::QueryHandle<D::Data, D::Error> {
    assert!(self.rendering, "ctx.query must be called during render");
    let client = self.query_client();
    let cursor = self.query_cursor;
    self.query_cursor += 1;
    if let Some(observer) = self.query_slots.get(cursor)
      && observer.matches(&client, &query)
    {
      return observer.handle::<D>();
    }
    let (handle, observer) = client.observe(query, Instant::now());
    if cursor < self.query_slots.len() {
      self.query_slots[cursor] = observer;
    } else {
      self.query_slots.push(observer);
    }
    handle
  }

  pub fn watch<T: SignalValue + Send + Sync + 'static>(
    &mut self,
    signal: &Signal<T>,
    f: impl Fn(&T) + Send + Sync + 'static,
  ) {
    let sub = signal.subscribe(f);
    self.watch_handles.push(Box::new(sub));
  }

  // --- Store + Lenses ---

  pub fn store<T: SignalValue + Clone + Send + Sync + 'static>(&mut self, initial: T) -> Store<T> {
    let store = Store::new(initial);
    let handle = store.signal().watch(self.dirty_notifier(
      #[cfg(feature = "perf_profile")]
      crate::app::profiler::detail::source_of::<T>(crate::app::profiler::RenderTrigger::Store),
    ));
    self.watch_handles.push(Box::new(handle));
    store
  }

  // --- Context (Dependency Injection) ---

  /// Provides `value` to this component and its descendants, shadowing a
  /// value of the same type from an ancestor.
  ///
  /// A value provided in `create` stays provided for the component's lifetime,
  /// across re-renders of the component and of its ancestors, until it
  /// provides another value of the same type. A value provided during `render`
  /// belongs to that render: later code in the render and the children it
  /// mounts see it, and the next render starts without it unless it is
  /// provided again.
  ///
  /// A provided value counts as new, since nothing compares it: the
  /// descendants that read its type render again, the others do not. A
  /// render that provides a value it computes every time passes it with
  /// [`provide_if_changed`](Self::provide_if_changed) so an equal value
  /// renders nothing again.
  pub fn provide<T: Clone + Send + Sync + 'static>(&mut self, value: T) {
    #[cfg(feature = "devtools")]
    self.note_provided(std::any::type_name::<T>(), false, inspected(&value));
    #[cfg(feature = "router")]
    if self.rendering
      && let Some(navigator) = (&value as &dyn std::any::Any).downcast_ref::<crate::router::Navigator>()
    {
      crate::router::navigator::provide_in_render(navigator.clone());
    }
    self.store_context(value);
  }

  /// [`provide`](Self::provide), unless the value equals the one this
  /// component provided before: then the descendants that read it see the
  /// same providing and do not render again for it. In `render` the value
  /// is compared with the previous render's, also when this render was
  /// caused by a change of the inherited contexts; in `create` or a
  /// handler, with the one provided there.
  pub fn provide_if_changed<T: Clone + PartialEq + Send + Sync + 'static>(&mut self, value: T) {
    #[cfg(feature = "devtools")]
    self.note_provided(std::any::type_name::<T>(), false, inspected(&value));
    let id = TypeId::of::<T>();
    if self.rendering {
      let unchanged = self
        .previous_render_contexts
        .as_ref()
        .and_then(|previous| previous.entry(id))
        .filter(|entry| entry.value::<T>() == Some(&value))
        .cloned();
      match unchanged {
        Some(entry) => {
          self.context_map.insert(id, entry);
          // With every entry the previous render left in place, the map is
          // that render's: the children mounted after this find nothing
          // to inherit.
          if let Some(previous) = &self.previous_render_contexts
            && self.context_map.has_same_entries(previous)
          {
            self.context_map.set_revision(previous.revision());
          }
        }
        None => self.context_map.provide(value),
      }
      self.provided_in_render = true;
      return;
    }
    let unchanged = self
      .provided_contexts
      .entry(id)
      .is_some_and(|entry| entry.value::<T>() == Some(&value));
    if !unchanged {
      self.store_context(value);
    }
  }

  fn store_context<T: Clone + Send + Sync + 'static>(&mut self, value: T) {
    if self.rendering {
      self.context_map.provide(value);
      self.provided_in_render = true;
      return;
    }
    self.provided_contexts.provide(value.clone());
    self.base_contexts.provide(value);
    self.context_map = self.base_contexts.clone();
  }

  fn note_context_read(&mut self, id: TypeId) {
    if !self.context_reads.contains(&id) {
      self.context_reads.push(id);
    }
  }

  pub fn use_context<T: Clone + Send + Sync + 'static>(&mut self) -> Option<T> {
    #[cfg(feature = "devtools")]
    self.note_consumed(std::any::type_name::<T>(), false);
    self.note_context_read(TypeId::of::<T>());
    self.context_map.get::<T>()
  }

  pub fn create_context<T: Clone + std::hash::Hash + Send + Sync + 'static>(&mut self, value: T) -> ReactiveContext<T> {
    #[cfg(feature = "devtools")]
    let (held, history) = self.note_provided(std::any::type_name::<ReactiveContext<T>>(), true, inspected(&value));
    let ctx = ReactiveContext::new(value);
    // Each value the context is set to from now on is the same record's next change.
    #[cfg(feature = "devtools")]
    ctx.inspect_with(move |value: &T| record_context_value(&held, &history, inspected(value)));
    self.store_context(ctx.clone());
    ctx.subscribe(self.dirty_notifier(
      #[cfg(feature = "perf_profile")]
      crate::app::profiler::detail::source_of::<T>(crate::app::profiler::RenderTrigger::Context),
    ));
    ctx
  }

  pub fn consume_context<T: Clone + std::hash::Hash + Send + Sync + 'static>(&mut self) -> Option<ReactiveContext<T>> {
    #[cfg(feature = "devtools")]
    self.note_consumed(std::any::type_name::<ReactiveContext<T>>(), true);
    self.note_context_read(TypeId::of::<ReactiveContext<T>>());
    let ctx = self.context_map.get::<ReactiveContext<T>>()?;
    ctx.subscribe(self.dirty_notifier(
      #[cfg(feature = "perf_profile")]
      crate::app::profiler::detail::source_of::<T>(crate::app::profiler::RenderTrigger::Context),
    ));
    Some(ctx)
  }

  /// Takes the contexts `parent` passes down, keeping the values this
  /// component provided on top, and tells whether the component renders
  /// again for them: when a value it read changed, or when its last render
  /// provided a value, which only a render provides again.
  fn inherit_contexts(&mut self, parent: &ContextMap) -> Inherited {
    if self.inherited_context_revision == parent.revision() {
      return Inherited::Same;
    }
    self.inherited_context_revision = parent.revision();
    let left_by_render = self.context_map.revision() != self.base_contexts.revision();
    let previous = std::mem::replace(
      &mut self.base_contexts,
      ContextMap::layered(parent, &self.provided_contexts),
    );
    // The map the last render left is kept for the next render to compare
    // its values with (`provide_if_changed`), as `begin_render` keeps it.
    if left_by_render {
      self.previous_render_contexts = Some(std::mem::take(&mut self.context_map));
    }
    self.context_map = self.base_contexts.clone();
    let read_changed = self
      .context_reads
      .iter()
      .any(|id| previous.entry_revision(*id) != self.base_contexts.entry_revision(*id));
    if read_changed || self.provided_in_render {
      Inherited::Changed
    } else {
      Inherited::Refreshed
    }
  }

  /// Passes refreshed contexts down a component that does not render again:
  /// a descendant component that read a changed value is marked dirty and
  /// renders in place with the pass (`refresh_dirty_subtrees`), the others
  /// pass the contexts on to theirs. A `for_each` item is rendered by its
  /// owner's render alone (its closure lives there), so an item that read a
  /// changed value, or provides, needs its owner rendered again: the nearest
  /// component above it is marked, or, when that is this component, `true`
  /// is returned so the caller renders it.
  fn propagate_contexts(&mut self) -> bool {
    let contexts = std::mem::take(&mut self.context_map);
    let mut render_again = false;
    for slot in self.children.iter_mut().filter(|slot| !slot.offstage) {
      let for_each_item = slot.component.type_name() == ForEachSlot::TYPE_NAME;
      let changed = match slot.ctx.inherit_contexts(&contexts) {
        Inherited::Same => false,
        Inherited::Refreshed => slot.ctx.propagate_contexts(),
        Inherited::Changed => true,
      };
      if !changed {
        continue;
      }
      if for_each_item {
        render_again = true;
      } else {
        #[cfg(feature = "perf_profile")]
        crate::app::profiler::detail::note(
          &slot.ctx.dirty,
          slot.ctx.component_name,
          crate::app::profiler::RenderSource {
            trigger: crate::app::profiler::RenderTrigger::Context,
            value_type: None,
          },
        );
        slot.ctx.mark_dirty();
      }
    }
    self.context_map = contexts;
    render_again
  }

  /// Marks this component dirty, with its ancestors' subtree flags, and
  /// wakes the loop when it was clean.
  fn mark_dirty(&self) {
    Self::mark_dirty_targets(
      &self.batch,
      &self.dirty,
      &self.subtree_dirty,
      &self.ancestor_dirty_slots,
    );
  }

  #[cfg(feature = "devtools")]
  /// The record of a context of `kind` and `type_name` this component has, made where it has none.
  fn context_debug(
    &mut self,
    kind: ComponentContextKind,
    type_name: &'static str,
    reactive: bool,
  ) -> &ComponentContextDebug {
    let at = self
      .contexts_debug
      .iter()
      .position(|ctx| ctx.kind == kind && ctx.type_name.as_ref() == type_name);
    let at = at.unwrap_or_else(|| {
      self.contexts_debug.push(ComponentContextDebug {
        kind,
        type_name: Arc::from(type_name),
        reactive,
        value: Arc::default(),
        history: Arc::default(),
      });
      self.contexts_debug.len() - 1
    });
    &self.contexts_debug[at]
  }

  /// Tells DevTools the component provides a context that holds `value` now, and gives back the record of
  /// what it holds and of its changes: a reactive context goes on writing to it as it is set.
  #[cfg(feature = "devtools")]
  #[allow(clippy::type_complexity)]
  fn note_provided(
    &mut self,
    type_name: &'static str,
    reactive: bool,
    value: Vec<ComponentInfo>,
  ) -> (
    Arc<Mutex<Option<Vec<ComponentInfo>>>>,
    Arc<Mutex<Vec<ComponentContextChangeDebug>>>,
  ) {
    let debug = self.context_debug(ComponentContextKind::Provided, type_name, reactive);
    let (held, history) = (debug.value.clone(), debug.history.clone());
    record_context_value(&held, &history, value);
    (held, history)
  }

  /// Tells DevTools the component reads a context.
  #[cfg(feature = "devtools")]
  fn note_consumed(&mut self, type_name: &'static str, reactive: bool) {
    self.context_debug(ComponentContextKind::Consumed, type_name, reactive);
  }

  // --- Theme ---

  /// Builds an element in `theme`: a dark side bar in a light window, a
  /// dense inspector. The theme is that of everything `build` builds and
  /// mounts, down to the paint: components take their recipes and their
  /// sizes from it, and the element is laid out and painted with its
  /// palette, its radii, its type and its shadows. The components mounted in
  /// it keep the theme when they render again on their own, and what
  /// rendered it renders again when the theme changes.
  pub fn in_theme<E: Into<Element>>(&mut self, theme: &Theme, build: impl FnOnce(&mut Ctx) -> E) -> Element {
    theme.track_access();
    let outer = self.theme.replace(theme.clone());
    // A builder becomes an element here, in the theme: a component that is returned unbuilt is built in it.
    let mut element: Element = crate::ui::in_theme(theme, || build(self).into());
    self.theme = outer;
    element.node.set_theme_scope(theme);
    element
  }

  pub fn theme(&self) -> &Theme {
    let theme = self.theme.as_ref().expect("theme not set");
    theme.track_access();
    theme
  }

  /// Whether motion is to be reduced: the app's decision, or else the
  /// system's accessibility setting (see `Theme::reduced_motion`). Reading it
  /// renders the component again when it changes. Transitions of an
  /// element's place and size already end at once while it is; use it to hold
  /// back a keyframe animation that moves, or to swap it for a fade.
  pub fn reduced_motion(&self) -> bool {
    self.theme().reduced_motion()
  }

  /// Current window geometry/state plus platform window commands.
  /// Reading this subscribes the component to window resize/move/scale changes.
  /// The window of the tree being rendered, untracked; `None` where none is set.
  pub(crate) fn window_untracked(&self) -> Option<&crate::app::window::Window> {
    self.window.as_ref()
  }

  pub fn window(&self) -> crate::app::window::WindowHandle {
    let window = self.window.as_ref().expect("window not set");
    window.track_access();
    window.handle()
  }

  /// Current viewport breakpoint, resolved from the window's logical width
  /// against the theme's breakpoint thresholds. `None` is the base tier (below
  /// the smallest breakpoint). Reading this subscribes the component to
  /// breakpoint changes only — it re-renders when the resolved breakpoint
  /// crosses a threshold, not on every resize.
  pub fn breakpoint(&self) -> Option<crate::app::theme::Breakpoint> {
    self.breakpoint.as_ref().and_then(|memo| memo.get())
  }

  /// Resolve a [`Responsive`](crate::responsive::Responsive) value for the
  /// current breakpoint. Re-renders when the resolved breakpoint changes.
  pub fn responsive<T: Clone>(&self, value: &crate::responsive::Responsive<T>) -> T {
    value.resolve(self.breakpoint()).clone()
  }

  /// Shared application services retained by this component. The handle stays
  /// valid if the App passed to the tree is moved or dropped.
  pub fn app_ref(&self) -> &App {
    self.app.as_ref().expect("app ref not set")
  }

  /// The retained app services, borrowed, if a pass or mount set them.
  pub(crate) fn app_if_set(&self) -> Option<&App> {
    self.app.as_ref()
  }

  /// The retained app services, if a pass or mount set them.
  pub(crate) fn app_handle(&self) -> Option<App> {
    self.app.clone()
  }

  /// Cloneable handle for opening secondary OS windows; safe to capture in
  /// event handlers (see [`crate::app::WindowOpener`]).
  pub fn window_opener(&self) -> crate::app::WindowOpener {
    self.app_ref().window_opener()
  }

  /// Opens `url` in the app the system keeps for it: a web page in the browser. It is
  /// [`open_url`](crate::app::open_url()), which a handler with no `Ctx` calls too.
  pub fn open_url(&self, url: &str) -> Result<(), crate::app::OpenUrlError> {
    crate::app::open_url(url)
  }

  /// Shows the system's share sheet for `share` over the window this component is in: it is
  /// [`WindowHandle::share`](crate::app::WindowHandle::share), which a handler with no `Ctx` calls on the window
  /// it holds (`ctx.window()`).
  pub fn share(&self, share: crate::app::Share) -> Result<(), crate::app::ShareError> {
    self.window().share(share)
  }

  /// Mutates the same shared services as the App passed to the tree.
  pub fn app_ref_mut(&mut self) -> &mut App {
    self.app.as_mut().expect("app ref not set")
  }

  #[cfg(feature = "persistent_storage")]
  pub fn persistent_value<T: crate::persistent_storage::PersistentValue>(&self, key: &str) -> Option<T> {
    self.app_ref().persistent_value(key)
  }

  #[cfg(feature = "persistent_storage")]
  pub fn set_persistent_value<T: crate::persistent_storage::IntoPersistentValue>(
    &self,
    key: &str,
    value: T,
  ) -> Result<(), crate::persistent_storage::PersistentStorageError> {
    self.app_ref().set_persistent_value(key, value)
  }

  #[cfg(feature = "persistent_storage")]
  pub fn read_bulk<I, K>(
    &self,
    keys: I,
  ) -> Result<crate::persistent_storage::PersistentReadBatch, crate::persistent_storage::PersistentStorageError>
  where
    I: IntoIterator<Item = K>,
    K: AsRef<str>,
  {
    self.app_ref().read_bulk(keys)
  }

  #[cfg(feature = "persistent_storage")]
  pub fn read_bulk_values<T, I, K>(
    &self,
    keys: I,
  ) -> Result<Vec<Option<T>>, crate::persistent_storage::PersistentStorageError>
  where
    T: crate::persistent_storage::PersistentValue,
    I: IntoIterator<Item = K>,
    K: AsRef<str>,
  {
    self.app_ref().read_bulk_values(keys)
  }

  #[cfg(feature = "persistent_storage")]
  pub fn write_bulk<I, E>(&self, entries: I) -> Result<(), crate::persistent_storage::PersistentStorageError>
  where
    I: IntoIterator<Item = E>,
    E: crate::persistent_storage::IntoPersistentWrite,
  {
    self.app_ref().write_bulk(entries)
  }

  pub fn i18n(&self) -> &I18n {
    let i18n = self.i18n.as_ref().expect("i18n not set");
    i18n.track_access();
    i18n
  }

  pub fn t(&self, key: &str) -> Arc<str> {
    self.i18n().t(key)
  }

  pub fn t_ns(&self, namespace: &str, key: &str) -> Arc<str> {
    self.i18n().t_ns(namespace, key)
  }

  pub fn t_args<I, K, V>(&self, key: &str, args: I) -> Arc<str>
  where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<str>,
    V: ToString,
  {
    self.i18n().t_args(key, args)
  }

  pub fn t_ns_args<I, K, V>(&self, namespace: &str, key: &str, args: I) -> Arc<str>
  where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<str>,
    V: ToString,
  {
    self.i18n().t_ns_args(namespace, key, args)
  }

  // --- Slot Children ---

  pub fn children(&self) -> &[Element] {
    self.slot_children.as_deref().unwrap_or(&[])
  }

  pub fn has_children(&self) -> bool {
    self.slot_children.as_ref().is_some_and(|c| !c.is_empty())
  }

  // --- Helpers ---

  pub fn element_ref(&mut self) -> ElementRef {
    self.element_ref_mut().as_ref()
  }

  /// Requests focus after the current render is reconciled. The ref may be
  /// attached by the render that follows this call (for example after navigation).
  /// Requests for refs absent from that tree are ignored. The last request wins.
  ///
  /// The focused element is then scrolled into view like
  /// [`Ctx::scroll_into_view`], as a browser's `element.focus()` does.
  pub fn focus(&self, element: &ElementRef) {
    self.element_requests.lock().focus = Some(element.clone());
    self.wake_window();
  }

  /// Scrolls the element into view after the current render is laid out:
  /// every scroll container around it scrolls by the smallest amount that
  /// shows it, innermost first, on each axis the container scrolls — the
  /// web's `scrollIntoView({ block: "nearest", inline: "nearest" })`. An
  /// element already in view does not move anything; one larger than a
  /// viewport is aligned to the viewport start. The frame that follows is
  /// drawn at the new position.
  ///
  /// The ref may be attached by the render that follows this call. Requests
  /// for refs absent from that tree are ignored. The last request wins.
  ///
  /// Inside a [`VirtualizedList`](crate::components::VirtualizedList) this
  /// reaches elements of mounted rows only; reveal a row that may be outside
  /// the rendered window with
  /// [`VirtualizedList::reveal_key`](crate::components::VirtualizedList::reveal_key).
  pub fn scroll_into_view(&self, element: &ElementRef) {
    self.element_requests.lock().scroll_into_view = Some(element.clone());
    self.wake_window();
  }

  /// Scrolls an element to the start of what scrolls it after the current render is laid out: every scroll
  /// container around it that scrolls down brings the element's top to the top of its viewport, as far as its
  /// content lets it, and one that scrolls sideways moves by the smallest amount that shows it: the web's
  /// `scrollIntoView({ block: "start", inline: "nearest" })`. What a list of a page's sections does when one of
  /// them is pressed. The top it is brought to is clear of what sticks to the container's top, as
  /// [`Ctx::scroll_into_view`] keeps clear of it.
  ///
  /// The ref may be attached by the render that follows this call. Requests for refs absent from that tree are
  /// ignored. The last request wins.
  pub fn scroll_into_view_start(&self, element: &ElementRef) {
    self.element_requests.lock().scroll_into_view_start = Some(element.clone());
    self.wake_window();
  }

  /// Scrolls a range of a text into view after the current render is laid
  /// out, as [`Ctx::scroll_into_view`] scrolls an element: the lines bytes
  /// `range` of the text's content cover, and no more, are brought into
  /// view. The current match of a search, which the text highlights
  /// (`Text::highlights`). `element` is the text's ref; a range that is empty
  /// or past the text's end scrolls nothing. The text must know where its
  /// characters are drawn, which a text that is selectable or has highlights
  /// does: of another one the whole element is brought into view. The last
  /// request wins.
  ///
  /// ```
  /// use lurq::{app::ctx::Ctx, components::Text, core::ElementRef, node::Element};
  ///
  /// # fn build(ctx: &mut Ctx, text: &ElementRef) -> Element {
  /// // The fourth word of the text, wherever it was wrapped to.
  /// ctx.scroll_range_into_view(text, 15..20);
  /// Text::new("one two three four five").ref_element(text.clone()).into()
  /// # }
  /// ```
  pub fn scroll_range_into_view(&self, element: &ElementRef, range: std::ops::Range<usize>) {
    self.element_requests.lock().scroll_range_into_view = Some((element.clone(), range));
    self.wake_window();
  }

  pub(crate) fn take_scroll_range_into_view_request(&self) -> Option<(ElementRef, std::ops::Range<usize>)> {
    self.element_requests.lock().scroll_range_into_view.take()
  }

  fn wake_window(&self) {
    if let Some(window) = &self.window {
      window.wake();
    }
  }

  /// Whether a focus or scroll-into-view request is waiting for the runtime.
  pub(crate) fn has_element_request(&self) -> bool {
    let requests = self.element_requests.lock();
    requests.focus.is_some()
      || requests.scroll_into_view.is_some()
      || requests.scroll_into_view_start.is_some()
      || requests.scroll_range_into_view.is_some()
      || requests.blur
      || requests.scroll_to_top
      || requests.focus_onward
  }

  /// Runs a command of editing on what has the focus, as its key does: Undo, Redo, Cut, Copy, Paste or Select All.
  /// A focused text input does it to its own text first; otherwise the focused element's handlers (`on_undo`,
  /// `on_redo`, `on_select_all`, `on_copy`, `on_paste`), and its ancestors' innermost first, until one takes it
  /// ([`EditCommand`](crate::app::events::EditCommand)). What an Edit menu's item or a toolbar's tool runs, through
  /// [`Ctx::edit_runner`], which a handler keeps.
  ///
  /// It is run once the event that asked is handled, on what has the focus then: after the focus the event moved is
  /// where it goes (a menu that closed gave it back to what had it). So a control that runs it does not keep the
  /// focus itself: a tool of a bar that is not focusable (`.focusable(false)`), or an item of a menu. A paste asked
  /// for while lurq delivers synthetic input (an MCP client's click) reads no clipboard. With no window (a component
  /// rendered with no tree) it does nothing.
  pub fn edit(&self, command: crate::app::events::EditCommand) {
    self.edit_runner().run(command);
  }

  /// What runs a command of editing on what has the focus ([`Ctx::edit`]), to keep in a handler: an Edit menu's
  /// item, a toolbar's tool. Reading it does not render the component again when the window changes.
  ///
  /// ```
  /// use lurq::{app::{ctx::Ctx, events::EditCommand}, components::Button, node::Element};
  ///
  /// # fn build(ctx: &mut Ctx) -> Element {
  /// let edit = ctx.edit_runner();
  /// Button::new("Undo").focusable(false).on_click(move |_| edit.run(EditCommand::Undo)).into()
  /// # }
  /// ```
  pub fn edit_runner(&self) -> EditRunner {
    EditRunner {
      window: self.window.clone(),
    }
  }

  /// Goes back, as Alt+← (Cmd+[ on a Mac), the mouse's back button and Android's back do: on the focused element
  /// and out from it, innermost first, its `on_history_back` handlers and the routers mounted there, until one takes
  /// it; then the routers mounted elsewhere in the window, the innermost first
  /// ([`NavigationCommand`](crate::app::events::NavigationCommand)). What a menu's item or a button runs, through
  /// [`Ctx::history_runner`], which a handler keeps: a dialog open over the page closes on it where it hears it, as
  /// on a key.
  ///
  /// It is run once the event that asked is handled, on what has the focus then. With no window (a component
  /// rendered with no tree) it does nothing.
  pub fn history_back(&self) {
    self.history_runner().back();
  }

  /// Goes forward, as Alt+→ (Cmd+] on a Mac) and the mouse's forward button do; see [`Ctx::history_back`].
  pub fn history_forward(&self) {
    self.history_runner().forward();
  }

  /// What goes back or forward ([`Ctx::history_back`]), to keep in a handler: a menu's item, a toolbar's button.
  /// Reading it does not render the component again when the window changes.
  ///
  /// ```
  /// use lurq::{app::ctx::Ctx, components::Button, node::Element};
  ///
  /// # fn build(ctx: &mut Ctx) -> Element {
  /// let history = ctx.history_runner();
  /// Button::new("Back").on_click(move |_| history.back()).into()
  /// # }
  /// ```
  pub fn history_runner(&self) -> HistoryRunner {
    HistoryRunner {
      window: self.window.clone(),
    }
  }

  /// Takes the focus from whatever has it, after the current render: a text input being typed into is left,
  /// and a phone's keyboard goes away. A request to focus made in the same render wins.
  pub fn blur(&self) {
    self.element_requests.lock().blur = true;
    self.wake_window();
  }

  pub(crate) fn take_blur_request(&self) -> bool {
    std::mem::take(&mut self.element_requests.lock().blur)
  }

  /// Scrolls the page to its top, after the current render, as a tap on a phone's status bar does: the
  /// outermost list at the middle of the window that scrolls down and is away from its top, unless it is left
  /// out with `ScrollState::set_scrolls_to_top(false)`.
  pub fn scroll_to_top(&self) {
    self.element_requests.lock().scroll_to_top = true;
    self.wake_window();
  }

  pub(crate) fn take_scroll_to_top_request(&self) -> bool {
    std::mem::take(&mut self.element_requests.lock().scroll_to_top)
  }

  /// Scrolls the container `state` is the state of to its top, after the current render: over the frames that
  /// follow, as a tap on a phone's status bar scrolls the page ([`Ctx::scroll_to_top`]), and at once while
  /// motion is reduced or the theme's smooth scroll is off. A wheel or a finger that scrolls the container
  /// meanwhile stops it where it is. A state that scrolls nothing in the tree, or is at its top already, asks
  /// for nothing. What a button that takes a page back to its top calls
  /// ([`BackToTop`](crate::ui::BackToTop)).
  pub fn scroll_to_top_of(&self, state: &crate::layout::layout_kind::ScrollState) {
    let mut requests = self.element_requests.lock();
    if !requests.scroll_states_to_top.iter().any(|asked| asked.same(state)) {
      requests.scroll_states_to_top.push(state.clone());
    }
    drop(requests);
    self.wake_window();
  }

  pub(crate) fn take_scroll_states_to_top(&self) -> Vec<crate::layout::layout_kind::ScrollState> {
    std::mem::take(&mut self.element_requests.lock().scroll_states_to_top)
  }

  /// Scrolls the container `state` is the state of to the offset `(x, y)`, after the current render: over
  /// the frames that follow, on the curve a mouse's wheel scrolls by, and at once while motion is reduced or
  /// the theme's smooth scroll is off. The offset is held to the content. A wheel or a finger that scrolls the
  /// container meanwhile stops it where it is, and a second request before the render is applied replaces
  /// the first. What a carousel turns to a slide with ([`Carousel`](crate::ui::Carousel)).
  pub fn scroll_state_to(&self, state: &crate::layout::layout_kind::ScrollState, x: f32, y: f32) {
    let mut requests = self.element_requests.lock();
    requests.scroll_states_to.retain(|(asked, ..)| !asked.same(state));
    requests.scroll_states_to.push((state.clone(), x, y));
    drop(requests);
    self.wake_window();
  }

  pub(crate) fn take_scroll_states_to(&self) -> Vec<(crate::layout::layout_kind::ScrollState, f32, f32)> {
    std::mem::take(&mut self.element_requests.lock().scroll_states_to)
  }

  /// Whether the screen this component is in is the one in front: the top screen of its stack
  /// (`StackOutlet`) and, where that is in a set of tabs (`TabOutlet`), in the tab that is shown. `true` where
  /// it is in neither. Read in `render`, it renders the component again when it changes, at any depth inside
  /// the screen: what plays (a video, a sound) is paused with it and played on when the screen is in front
  /// again.
  ///
  /// The top screen is the one at the end of the stack's history. A screen pushed over another is in front
  /// from the moment it is pushed, and the one under it is not, though both are seen while the new one comes
  /// in. While a finger from the edge drags the top screen aside, the top screen is still the one in front,
  /// and the one seen under it is not; it is from the moment the finger lets go far enough for the stack to go
  /// back. A screen that leaves the stage as it stops being in front (a tab that is no longer shown) is
  /// rendered once more first, and hears it. A sheet, a dialog or another window over a screen does not
  /// change it.
  ///
  /// ```no_run
  /// # use lurq::{app::ctx::Ctx, node::Element, ui::VideoPlayer, core::Signal};
  /// fn render(playing: &Signal<bool>, ctx: &mut Ctx) -> Element {
  ///   let playing = playing.clone();
  ///   let plays = playing.get() && ctx.is_in_front();
  ///   VideoPlayer::new()
  ///     .playing_controlled(plays, move |to| playing.set(to))
  ///     .mount(ctx)
  /// }
  /// ```
  pub fn is_in_front(&mut self) -> bool {
    self.use_context::<InFront>().is_none_or(|front| front.get())
  }

  /// How far in from each edge of the window this component's content stays clear of what is over it there:
  /// the window's [`safe_area`](crate::app::window::WindowInfo), and at the bottom also the bar a component
  /// around this one draws over its content, as a `TabOutlet` does. Content
  /// that scrolls under such a bar is padded by this inside its list, and shows through the bar.
  pub fn safe_area(&mut self) -> crate::app::window::SafeAreaInsets {
    if self.use_context::<SafeAreaTaken>().is_some() {
      return crate::app::window::SafeAreaInsets::default();
    }
    let mut safe_area = self.window().safe_area;
    match self.use_context::<BottomBarInset>() {
      Some(BottomBarInset::Over(bar)) => safe_area.bottom += bar,
      None => {}
    }
    safe_area
  }

  /// What moves the focus from a handler, which has no `Ctx`: [`FocusHandle::focus`] and
  /// [`FocusHandle::focus_onward`].
  pub fn focus_handle(&self) -> FocusHandle {
    FocusHandle {
      requests: self.element_requests.clone(),
      window: self.window.clone(),
    }
  }

  pub(crate) fn take_focus_onward_request(&self) -> bool {
    std::mem::take(&mut self.element_requests.lock().focus_onward)
  }

  pub(crate) fn focus_request(&self) -> Option<ElementRef> {
    self.element_requests.lock().focus.clone()
  }

  pub(crate) fn take_focus_request(&self) -> Option<ElementRef> {
    self.element_requests.lock().focus.take()
  }

  pub(crate) fn take_scroll_into_view_request(&self) -> Option<ElementRef> {
    self.element_requests.lock().scroll_into_view.take()
  }

  pub(crate) fn take_scroll_into_view_start_request(&self) -> Option<ElementRef> {
    self.element_requests.lock().scroll_into_view_start.take()
  }

  pub fn element_ref_mut(&mut self) -> ElementRefMut {
    if !self.rendering {
      return ElementRefMut::new();
    }

    let cursor = self.element_ref_cursor;
    self.element_ref_cursor += 1;

    if cursor == self.element_refs.len() {
      self.element_refs.push(ElementRefMut::new());
    }

    self.element_refs[cursor].clone()
  }

  pub fn interaction(&self) -> crate::node::interaction_state::InteractionState {
    crate::node::interaction_state::InteractionState::new()
  }

  pub fn on_click_outside(
    &mut self,
    element_ref: impl Into<ElementRef>,
    f: impl Fn(&MouseEvent) + Send + Sync + 'static,
  ) {
    if !self.rendering {
      return;
    }

    let cursor = self.click_outside_cursor;
    self.click_outside_cursor += 1;
    self.click_outside_active_cursors.push(cursor);

    let element_ref = element_ref.into();
    let callback: ClickOutsideCallback = Arc::new(f);
    let mut registry = self.click_outside_registry.lock();
    if let Some(entry) = registry
      .iter_mut()
      .find(|entry| entry.scope_id == self.scope_id && entry.cursor == cursor)
    {
      entry.element_ref = element_ref;
      entry.callback = callback;
      return;
    }

    registry.push(ClickOutsideEntry {
      scope_id: self.scope_id,
      cursor,
      element_ref,
      callback,
    });
  }

  pub(crate) fn click_outside_callbacks_at(&self, x: f32, y: f32) -> Vec<ClickOutsideCallback> {
    self
      .click_outside_registry
      .lock()
      .iter()
      .filter(|entry| element_ref_is_click_outside(&entry.element_ref, x, y))
      .map(|entry| entry.callback.clone())
      .collect()
  }

  // --- Component mounting ---

  pub fn mount<C: Component>(&mut self, props: C::Props) -> Element {
    self.mount_inner::<C>(None, props, None, true)
  }

  pub fn mount_keyed<C: Component>(&mut self, key: &str, props: C::Props) -> Element {
    self.mount_inner::<C>(Some(key), props, None, true)
  }

  /// Retains a component and its complete context while excluding its output
  /// from the active tree. Offstage components keep their slots, signals,
  /// futures, and last rendered node, but do not participate in layout,
  /// painting, hit testing, dirty refreshes, timers, or future polling until
  /// they become active again. Future polling means applying results: a future
  /// or stream polled cooperatively (no Tokio handle) waits, while a task
  /// already running on Tokio keeps running and the results it produced while
  /// offstage are applied, in order, once the component is active again. A
  /// component removed while offstage unmounts and its tasks are cancelled.
  /// A component that goes offstage in the pass in which a signal it reads
  /// changed, or one a component below it reads, is rendered once more
  /// first: what it does in its render is done (a player told to pause
  /// because its screen is no longer in front, [`Self::is_in_front`]), and
  /// what it renders goes to no tree.
  /// When it becomes active again, its output takes back the runtime state it
  /// had: scroll offsets (including those of scroll areas whose `ScrollState`
  /// the component does not hold), text-input carets and selections, open
  /// selects and canvases.
  pub fn mount_offstage<C: Component>(&mut self, props: C::Props, active: bool) -> Element {
    self.mount_inner::<C>(None, props, None, active)
  }

  /// Keyed variant of [`Self::mount_offstage`].
  pub fn mount_keyed_offstage<C: Component>(&mut self, key: &str, props: C::Props, active: bool) -> Element {
    self.mount_inner::<C>(Some(key), props, None, active)
  }

  pub fn mount_with<C: Component>(&mut self, props: C::Props, slot_children: Vec<Element>) -> Element {
    self.mount_inner::<C>(None, props, Some(slot_children), true)
  }

  pub fn mount_keyed_with<C: Component>(&mut self, key: &str, props: C::Props, slot_children: Vec<Element>) -> Element {
    self.mount_inner::<C>(Some(key), props, Some(slot_children), true)
  }

  /// Runs `mount` with unchanged components held back: where the component it mounts is unchanged, the
  /// element is a node that stands for it (`Node::held_component`), for the tree to put the component's live
  /// nodes in. For a mount whose element nothing touches before the tree has it.
  pub(crate) fn mount_holding(&mut self, mount: impl FnOnce(&mut Ctx) -> Element) -> Element {
    let was = std::mem::replace(&mut self.holding, true);
    let element = mount(self);
    self.holding = was;
    element
  }

  /// A copy of the last output of the component in slot `slot`, anywhere below this one, put together from
  /// its slot and those of the components in it.
  pub(crate) fn cached_output_of(&self, slot: u64) -> Option<Box<Node>> {
    self.descendant_slot(slot)?.assembled_output()
  }

  fn mount_inner<C: Component>(
    &mut self,
    key: Option<&str>,
    props: C::Props,
    slot_children: Option<Vec<Element>>,
    active: bool,
  ) -> Element {
    let holding = self.holding;
    let cursor = self.child_cursor;
    self.child_cursor += 1;

    let type_name = std::any::type_name::<C>();

    if let Some(key) = key
      && let Some(found) = self.children[cursor..]
        .iter()
        .position(|slot| slot.key.as_deref() == Some(key) && slot.component.type_name() == type_name)
        .map(|offset| cursor + offset)
      && found != cursor
    {
      let slot = self.children.remove(found);
      self.children.insert(cursor, slot);
    }

    let can_reuse = self.children.get(cursor).is_some_and(|slot| {
      let key_match = match key {
        Some(k) => slot.key.as_deref() == Some(k),
        None => slot.key.is_none(),
      };
      key_match && slot.component.type_name() == type_name
    });

    if can_reuse {
      let slot = &mut self.children[cursor];
      let has_slot_children = slot.ctx.slot_children.is_some() || slot_children.is_some();
      let props_changed = slot.ctx.props_changed(&props);
      let inherited = slot.ctx.inherit_contexts(&self.context_map);
      // A component is in the theme it is mounted in now (`in_theme`), not the one its slot was made in: a stage
      // switched to the other appearance renders what is on it again, in that theme.
      let theme_changed = match (&slot.ctx.theme, &self.theme) {
        (Some(held), Some(now)) => !held.same_theme(now),
        (None, Some(_)) => true,
        _ => false,
      };
      if theme_changed {
        slot.ctx.theme = self.theme.clone();
      }
      slot.ctx.slot_children = slot_children;
      if props_changed {
        slot.ctx.set_props(props);
      }
      if !active {
        // What it reads changed as it leaves the stage (its screen is no longer the one in front): it is
        // rendered once more first, and what it mounts hears it. It is not rendered again until it is back.
        if !slot.offstage && slot.rendered.is_some() && slot.ctx.any_dirty() {
          slot.render_as_it_leaves();
        }
        slot.offstage = true;
        slot.offstage_dirty = true;
        slot.ctx.clear_modal_entries_recursive();
        slot.ctx.clear_dirty();
        return Element::new();
      }

      slot.offstage = false;
      #[cfg(feature = "perf_profile")]
      let resumed = slot.rendered.is_none() || slot.offstage_dirty;
      #[cfg(feature = "perf_profile")]
      let mut context_changed = inherited == Inherited::Changed;
      let mut needs_render = has_slot_children
        || props_changed
        || theme_changed
        || inherited == Inherited::Changed
        || slot.ctx.any_dirty()
        || slot.rendered.is_none()
        || slot.offstage_dirty;
      slot.offstage_dirty = false;
      if !needs_render && inherited == Inherited::Refreshed && slot.ctx.propagate_contexts() {
        needs_render = true;
        #[cfg(feature = "perf_profile")]
        {
          context_changed = true;
        }
      }
      if needs_render {
        #[cfg(feature = "perf_profile")]
        let _span = slot.ctx.render_span(|| {
          use crate::app::profiler::RenderTrigger;
          if resumed {
            Some(RenderTrigger::Mount)
          } else if props_changed {
            Some(RenderTrigger::Props)
          } else if context_changed {
            Some(RenderTrigger::Context)
          } else if has_slot_children {
            Some(RenderTrigger::SlotChildren)
          } else {
            None
          }
        });
        // Carry runtime state over from the previous render, as a dirty
        // refresh does, so `rendered` keeps sharing the live scroll states
        // with the active tree. A slot resuming from offstage has no node in
        // the active tree, so this is the only place its scroll offsets,
        // text-input carets and selections come back from.
        let previous = slot.rendered.take();
        slot.ctx.begin_render();
        let mut element = slot.component.render(&mut slot.ctx);
        slot.ctx.end_render();
        element.node = attach_component_metadata(
          element.node,
          slot.component.tag_name(),
          slot.id,
          slot.key.as_deref(),
          #[cfg(feature = "devtools")]
          &slot.ctx,
        );
        if let Some(previous) = previous.as_ref() {
          element.node.preserve_runtime_state_from(previous);
        }
        slot.keep_rendered(&element.node);
        return element;
      }
      if holding {
        return Element::from_node(Node::held_component(slot.id, slot.key.as_deref()));
      }
      let output = slot
        .assembled_output()
        .expect("a component that is not rendered again has kept its output");
      return Element::from_boxed_node(output);
    }

    let slot_id = next_component_slot_id();
    let mut child_ctx = Ctx::new();
    child_ctx.inherit_dirty_ancestors_from(self, slot_id);
    child_ctx.batch = self.batch.clone();
    child_ctx.theme = self.theme.clone();
    child_ctx.window = self.window.clone();
    child_ctx.breakpoint = self.breakpoint.clone();
    child_ctx.app = self.app.clone();
    child_ctx.element_requests = self.element_requests.clone();
    #[cfg(feature = "tokio")]
    {
      child_ctx.runtime_future_handle = self.runtime_future_handle.clone();
    }
    #[cfg(feature = "query")]
    {
      child_ctx.query_registry = self.query_registry.clone();
    }
    child_ctx.click_outside_registry = self.click_outside_registry.clone();
    {
      child_ctx.i18n = self.i18n.clone();
    }
    child_ctx.inherit_contexts(&self.context_map);
    child_ctx.slot_children = slot_children;
    child_ctx.set_props(props);
    child_ctx.scope_id = slot_id;
    child_ctx.component_name = type_name;
    // A first mount's span takes in `create` too.
    #[cfg(feature = "perf_profile")]
    let _span = active
      .then(|| child_ctx.render_span(|| Some(crate::app::profiler::RenderTrigger::Mount)))
      .flatten();
    let component = C::create(&mut child_ctx);
    let wrapper = ComponentWrapper { component };
    let mut element = Element::new();
    if active {
      child_ctx.begin_render();
      element = wrapper.render(&mut child_ctx);
      child_ctx.end_render();
      element.node = attach_component_metadata(
        element.node,
        wrapper.tag_name(),
        slot_id,
        key,
        #[cfg(feature = "devtools")]
        &child_ctx,
      );
    } else {
      child_ctx.clear_dirty();
    }

    let mut slot = ChildSlot {
      id: slot_id,
      key: key.map(str::to_owned),
      component: Box::new(wrapper),
      ctx: child_ctx,
      rendered: None,
      rendered_at: 0,
      mounted: false,
      offstage: !active,
      offstage_dirty: !active,
    };
    if active {
      slot.keep_rendered(&element.node);
    }

    if key.is_some() {
      self.insert_child_slot(cursor, slot);
    } else {
      self.set_child_slot(cursor, slot);
    }

    element
  }

  // --- Keyed list rendering ---

  pub fn for_each<T, K, KF, CF>(
    &mut self,
    items: impl IntoIterator<Item = T>,
    key_fn: KF,
    component_fn: CF,
  ) -> Vec<Element>
  where
    K: std::fmt::Display,
    KF: Fn(&T) -> K,
    CF: Fn(&mut Ctx, T) -> Element,
  {
    let cursor = self.child_cursor;
    self.child_cursor += 1;

    let can_reuse_group = self
      .children
      .get(cursor)
      .is_some_and(|slot| slot.key.is_none() && slot.component.type_name() == ForEachSlot::TYPE_NAME);

    if !can_reuse_group {
      let slot_id = next_component_slot_id();
      let mut group_ctx = Ctx::new();
      group_ctx.inherit_dirty_ancestors_from(self, slot_id);
      group_ctx.batch = self.batch.clone();
      group_ctx.theme = self.theme.clone();
      group_ctx.window = self.window.clone();
      group_ctx.breakpoint = self.breakpoint.clone();
      group_ctx.app = self.app.clone();
      group_ctx.element_requests = self.element_requests.clone();
      #[cfg(feature = "tokio")]
      {
        group_ctx.runtime_future_handle = self.runtime_future_handle.clone();
      }
      #[cfg(feature = "query")]
      {
        group_ctx.query_registry = self.query_registry.clone();
      }
      group_ctx.click_outside_registry = self.click_outside_registry.clone();
      {
        group_ctx.i18n = self.i18n.clone();
      }
      group_ctx.inherit_contexts(&self.context_map);
      group_ctx.scope_id = slot_id;
      group_ctx.component_name = ForEachSlot::TYPE_NAME;
      let slot = ChildSlot {
        id: slot_id,
        key: None,
        component: Box::new(ForEachSlot),
        ctx: group_ctx,
        rendered: None,
        rendered_at: 0,
        mounted: false,
        offstage: false,
        offstage_dirty: false,
      };
      self.set_child_slot(cursor, slot);
    }

    let slot = &mut self.children[cursor];
    slot.ctx.inherit_contexts(&self.context_map);
    slot.ctx.begin_render();
    let elements = items
      .into_iter()
      .map(|item| {
        let key = format!("{}", key_fn(&item));
        slot.ctx.render_for_each_item(key, item, &component_fn)
      })
      .collect();
    slot.ctx.end_render();
    elements
  }

  fn render_for_each_item<T, CF>(&mut self, key: String, item: T, component_fn: &CF) -> Element
  where
    CF: Fn(&mut Ctx, T) -> Element,
  {
    let cursor = self.child_cursor;
    self.child_cursor += 1;

    if let Some(found) = self.children[cursor..]
      .iter()
      .position(|slot| {
        slot.key.as_deref() == Some(key.as_str()) && slot.component.type_name() == ForEachSlot::TYPE_NAME
      })
      .map(|offset| cursor + offset)
      && found != cursor
    {
      let slot = self.children.remove(found);
      self.children.insert(cursor, slot);
    }

    let can_reuse = self.children.get(cursor).is_some_and(|slot| {
      slot.key.as_deref() == Some(key.as_str()) && slot.component.type_name() == ForEachSlot::TYPE_NAME
    });

    if can_reuse {
      let slot = &mut self.children[cursor];
      slot.ctx.inherit_contexts(&self.context_map);
      #[cfg(feature = "perf_profile")]
      let _span = slot
        .ctx
        .render_span(|| Some(crate::app::profiler::RenderTrigger::ListItem));
      slot.ctx.begin_render();
      let mut element = component_fn(&mut slot.ctx, item);
      slot.ctx.end_render();
      element.node = attach_component_metadata(
        element.node,
        slot.component.tag_name(),
        slot.id,
        slot.key.as_deref(),
        #[cfg(feature = "devtools")]
        &slot.ctx,
      );
      slot.keep_rendered(&element.node);
      return element;
    }

    let slot_id = next_component_slot_id();
    let mut child_ctx = Ctx::new();
    child_ctx.inherit_dirty_ancestors_from(self, slot_id);
    child_ctx.batch = self.batch.clone();
    child_ctx.theme = self.theme.clone();
    child_ctx.window = self.window.clone();
    child_ctx.breakpoint = self.breakpoint.clone();
    child_ctx.app = self.app.clone();
    child_ctx.element_requests = self.element_requests.clone();
    #[cfg(feature = "tokio")]
    {
      child_ctx.runtime_future_handle = self.runtime_future_handle.clone();
    }
    #[cfg(feature = "query")]
    {
      child_ctx.query_registry = self.query_registry.clone();
    }
    child_ctx.click_outside_registry = self.click_outside_registry.clone();
    {
      child_ctx.i18n = self.i18n.clone();
    }
    child_ctx.inherit_contexts(&self.context_map);
    child_ctx.scope_id = slot_id;
    child_ctx.component_name = ForEachSlot::TYPE_NAME;
    #[cfg(feature = "perf_profile")]
    let _span = child_ctx.render_span(|| Some(crate::app::profiler::RenderTrigger::Mount));
    child_ctx.begin_render();
    let mut element = component_fn(&mut child_ctx, item);
    child_ctx.end_render();
    element.node = attach_component_metadata(
      element.node,
      component_tag_name::<ForEachSlot>(),
      slot_id,
      Some(key.as_str()),
      #[cfg(feature = "devtools")]
      &child_ctx,
    );

    let mut slot = ChildSlot {
      id: slot_id,
      key: Some(key),
      component: Box::new(ForEachSlot),
      ctx: child_ctx,
      rendered: None,
      rendered_at: 0,
      mounted: false,
      offstage: false,
      offstage_dirty: false,
    };
    slot.keep_rendered(&element.node);

    self.insert_child_slot(cursor, slot);

    element
  }

  // --- Error boundary ---

  pub fn error_boundary(
    &mut self,
    component_fn: impl FnOnce(&mut Ctx) -> Element,
    fallback_fn: impl FnOnce() -> Element,
  ) -> Element {
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| component_fn(self)));
    match result {
      Ok(node) => node,
      Err(_) => fallback_fn(),
    }
  }

  // --- Render lifecycle ---

  pub fn begin_render(&mut self) {
    // Values provided by the previous render are dropped; `render` provides
    // them again if it still wants to. Their map is kept while it renders:
    // a value provided again unchanged keeps its entry, and a render that
    // leaves the same entries gives the map its revision back (`end_render`).
    if self.context_map.revision() != self.base_contexts.revision() {
      self.previous_render_contexts = Some(std::mem::replace(&mut self.context_map, self.base_contexts.clone()));
    }
    self.provided_in_render = false;
    self.clear_dirty();
    #[cfg(feature = "devtools")]
    {
      self.render_started = Some(Instant::now());
    }
    self.child_cursor = 0;
    self.element_ref_cursor = 0;
    self.click_outside_cursor = 0;
    self.click_outside_active_cursors.clear();
    self.future_cursor = 0;
    self.frames.begin_render();
    #[cfg(feature = "query")]
    {
      self.query_cursor = 0;
    }
    tracking::start_tracking();
    self.rendering = true;
    // What the render builds goes through this router (`router::current_navigator`).
    #[cfg(feature = "router")]
    crate::router::navigator::enter_render(self.context_map.get::<crate::router::Navigator>());
    // What the render builds is in the component's theme (`ui::current_theme`).
    if let Some(theme) = &self.theme {
      crate::ui::theme::enter_theme(
        theme.clone(),
        self.breakpoint.clone(),
        self.app.as_ref().map(|app| app.shared.dates.clone()),
        self.app.as_ref().map(|app| app.shared.locale.clone()),
        self.app.as_ref().map(|app| app.shared.pointer.clone()),
        self.window.clone(),
      );
    }
  }

  fn set_child_slot(&mut self, cursor: usize, slot: ChildSlot) {
    if cursor < self.children.len() {
      self.children[cursor].ctx.clear_modal_entries_recursive();
      if self.children[cursor].mounted {
        self.children[cursor].component.on_unmounted();
      }
      self.children[cursor] = slot;
    } else {
      self.children.push(slot);
    }
  }

  fn insert_child_slot(&mut self, cursor: usize, slot: ChildSlot) {
    if cursor < self.children.len() {
      self.children.insert(cursor, slot);
    } else {
      self.children.push(slot);
    }
  }

  fn clear_modal_entries_recursive(&mut self) {
    self
      .click_outside_registry
      .lock()
      .retain(|entry| entry.scope_id != self.scope_id);
    for slot in &mut self.children {
      slot.ctx.clear_modal_entries_recursive();
    }
  }

  pub(crate) fn end_render(&mut self) {
    #[cfg(feature = "devtools")]
    if let Some(started) = self.render_started.take() {
      self.render_debug.count += 1;
      self.render_debug.last = started.elapsed();
    }
    self
      .click_outside_registry
      .lock()
      .retain(|entry| entry.scope_id != self.scope_id || self.click_outside_active_cursors.contains(&entry.cursor));

    for slot in &self.children[self.child_cursor..] {
      if slot.mounted {
        slot.component.on_unmounted();
      }
    }
    for slot in &mut self.children[self.child_cursor..] {
      slot.ctx.clear_modal_entries_recursive();
    }
    self.children.truncate(self.child_cursor);

    for slot in &mut self.children {
      if !slot.mounted && !slot.offstage {
        slot.component.on_mounted();
        slot.mounted = true;
      }
    }

    self.element_refs.truncate(self.element_ref_cursor);
    // Dropping a slot cancels its task.
    self.drop_unreached_future_slots();
    self.frames.end_render();
    #[cfg(feature = "query")]
    self.query_slots.truncate(self.query_cursor);
    if self.rendering && self.theme.is_some() {
      crate::ui::theme::leave_theme();
    }
    #[cfg(feature = "router")]
    if self.rendering {
      crate::router::navigator::leave_render();
    }
    self.rendering = false;
    if let Some(previous) = self.previous_render_contexts.take()
      && self.context_map.has_same_entries(&previous)
    {
      self.context_map.set_revision(previous.revision());
    }
    let deps = tracking::stop_tracking();
    let handles = deps
      .into_iter()
      .map(|dep| {
        let notifier = self.dirty_notifier(
          #[cfg(feature = "perf_profile")]
          dep.source,
        );
        let handle = (dep.subscribe_fn)(Arc::new(notifier));
        Box::new(handle) as Box<dyn Any + Send + Sync>
      })
      .collect();
    self.render_watch_handles = handles;
  }

  pub(crate) fn any_dirty(&self) -> bool {
    self.subtree_dirty.load(Ordering::Relaxed)
  }

  pub(crate) fn after_layout_recursive(&self) {
    for slot in self.children.iter().filter(|slot| !slot.offstage) {
      slot.component.after_layout();
      slot.ctx.after_layout_recursive();
    }
  }

  /// [`Self::after_layout_recursive`] in a pass a detailed recording takes:
  /// each component's span holds its hook and its descendants' spans.
  #[cfg(feature = "perf_profile")]
  pub(crate) fn after_layout_recursive_spans(&self, spans: &crate::app::profiler::detail::HookSpans) {
    for slot in self.children.iter().filter(|slot| !slot.offstage) {
      let _span = spans.enter(slot.component.type_name());
      slot.component.after_layout();
      slot.ctx.after_layout_recursive_spans(spans);
    }
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn has_active_timers(&self) -> bool {
    self.timers.iter().any(Timer::is_active)
      || self
        .children
        .iter()
        .any(|slot| !slot.offstage && slot.ctx.has_active_timers())
  }

  /// When the earliest running timer of this component or a mounted descendant fires.
  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn next_timer_fire(&self) -> Option<Instant> {
    let own = self.timers.iter().filter_map(Timer::next_fire).min();
    let children = self
      .children
      .iter()
      .filter(|slot| !slot.offstage)
      .filter_map(|slot| slot.ctx.next_timer_fire())
      .min();
    own.into_iter().chain(children).min()
  }

  /// Whether a query of this component or a mounted descendant has work the next `tick_futures` must start or
  /// finish. Other futures wake the event loop themselves.
  #[cfg(feature = "query")]
  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn has_ready_queries(&self) -> bool {
    self.query_registry.ready()
      || self
        .children
        .iter()
        .any(|slot| !slot.offstage && slot.ctx.has_ready_queries())
  }

  #[cfg_attr(not(feature = "winit"), allow(dead_code))]
  pub(crate) fn has_active_futures(&self) -> bool {
    #[cfg(feature = "query")]
    if self.query_registry.ready() {
      return true;
    }
    self.future_slots().any(|slot| slot.task.is_active())
      || self
        .children
        .iter()
        .any(|slot| !slot.offstage && slot.ctx.has_active_futures())
  }

  pub(crate) fn tick_timers(&mut self, now: Instant) -> bool {
    let mut fired = false;
    for timer in &self.timers {
      fired |= timer.tick(now);
    }
    for slot in self.children.iter_mut().filter(|slot| !slot.offstage) {
      fired |= slot.ctx.tick_timers(now);
    }
    fired
  }

  pub(crate) fn tick_futures(&mut self) -> bool {
    let waker = self.loop_waker();
    let mut cx = TaskContext::from_waker(&waker);
    #[cfg(feature = "query")]
    let query_changed = self.query_registry.tick(Instant::now(), &mut cx) | self.publish_query_updates();
    #[cfg(not(feature = "query"))]
    let query_changed = false;
    self.poll_futures(&mut cx) | query_changed
  }

  #[cfg(feature = "query")]
  pub(crate) fn next_query_deadline(&self) -> Option<Instant> {
    self.query_registry.deadline()
  }

  #[cfg(feature = "query")]
  fn publish_query_updates(&self) -> bool {
    let mut changed = false;
    for observer in &self.query_slots {
      changed |= observer.publish();
    }
    for slot in &self.children {
      changed |= slot.ctx.publish_query_updates();
    }
    changed
  }

  fn poll_futures(&mut self, cx: &mut TaskContext<'_>) -> bool {
    let mut completed = false;
    for slot in self.future_slots() {
      completed |= slot.task.poll(cx);
    }
    for slot in self.children.iter_mut().filter(|slot| !slot.offstage) {
      completed |= slot.ctx.poll_futures(cx);
    }
    completed
  }

  pub(crate) fn refresh_dirty_subtrees(&mut self) -> Vec<(u64, Box<Node>)> {
    let mut replacements = Vec::new();
    let dirty_child_slot_ids = self.take_dirty_child_slot_ids();

    for dirty_slot_id in dirty_child_slot_ids {
      let Some(index) = self.children.iter().position(|slot| slot.id == dirty_slot_id) else {
        continue;
      };
      // The children it was handed are what they were when this component last rendered: those that rendered
      // again by themselves since are what they are now, before it builds itself of them again.
      let handed = self.fresh_slot_children(index);
      let slot = &mut self.children[index];
      if !slot.ctx.any_dirty() {
        continue;
      }
      if slot.offstage {
        slot.offstage_dirty = true;
        slot.ctx.clear_dirty();
        continue;
      }
      if let Some(handed) = handed {
        slot.ctx.slot_children = Some(handed);
      }

      if slot.ctx.is_dirty() {
        #[cfg(feature = "perf_profile")]
        let _span = slot.ctx.render_span(|| None);
        let old_rendered = slot.rendered.take();
        slot.ctx.begin_render();
        let mut element = slot.component.render(&mut slot.ctx);
        slot.ctx.end_render();
        let needs_followup_refresh = slot.ctx.any_dirty();
        element.node = attach_component_metadata(
          element.node,
          slot.component.tag_name(),
          slot.id,
          slot.key.as_deref(),
          #[cfg(feature = "devtools")]
          &slot.ctx,
        );
        if let Some(old) = old_rendered.as_ref() {
          element.node.preserve_runtime_state_from(old);
        }
        slot.keep_rendered(&element.node);
        replacements.push((slot.id, element.node));
        if needs_followup_refresh {
          Self::mark_dirty_child_slot(&self.dirty_child_slots, dirty_slot_id);
        }
        continue;
      } else {
        // The caches above a component hold a placeholder for it, so its
        // fresh output only goes to the live tree.
        replacements.extend(slot.ctx.refresh_dirty_subtrees());
      }
    }

    self.update_subtree_dirty_from_children();
    replacements
  }

  /// The children handed to the component in the slot at `index`, which is about to render again by itself,
  /// with the output of every component among them that rendered again by itself since it last rendered.
  /// `None` where none did, or it holds no children, or is not about to render.
  ///
  /// A component's children are elements: the output of the components the parent mounted for it, as it was at
  /// the parent's render (`mount_with`, `Ctx::children`). A child that changes by itself goes to the live tree
  /// at once, and is not in what its holder keeps: a holder that then rendered again alone (a row that follows
  /// a finger, a sheet on its way) put the child back as it was when the parent last rendered. The components
  /// are those below this one, which mounted them; one handed down from further up is as its holder has it.
  fn fresh_slot_children(&self, index: usize) -> Option<Vec<Element>> {
    let holder = &self.children[index];
    if !holder.ctx.is_dirty() || holder.offstage {
      return None;
    }
    let handed = holder.ctx.slot_children.as_ref()?;
    // Nothing below this component rendered since the holder did: its children are as it has them.
    if !self.any_slot_rendered_after(holder.rendered_at, holder.id) {
      return None;
    }
    let mut any = false;
    let mut fresh = |root: &Node| -> Option<Node> {
      let id = root.component_slot_id()?;
      let slot = self.descendant_slot(id).filter(|slot| slot.id != holder.id)?;
      if slot.rendered_at <= holder.rendered_at {
        return None;
      }
      let mut output = slot.assemble(self, None)?;
      output.adopt_outer_decoration(root);
      any = true;
      Some(output)
    };
    let children: Vec<Element> = handed
      .iter()
      .map(|child| {
        // A child that is a component's root itself, or an element with components below it.
        let node = match fresh(&child.node) {
          Some(node) => node,
          None => child.node.clone_with_component_roots(&mut fresh),
        };
        Element::from_node(node)
      })
      .collect();
    any.then_some(children)
  }

  /// Whether a component below this one, other than the one in the slot `but` and what is in it, rendered
  /// after the render `since`.
  fn any_slot_rendered_after(&self, since: u64, but: u64) -> bool {
    self
      .children
      .iter()
      .filter(|slot| slot.id != but)
      .any(|slot| slot.rendered_at > since || slot.ctx.any_slot_rendered_after(since, but))
  }

  /// The slot of a component this one mounted, `for_each` items included.
  fn child_slot(&self, id: u64) -> Option<&ChildSlot> {
    for slot in &self.children {
      if slot.id == id {
        return Some(slot);
      }
      if slot.is_for_each_group()
        && let Some(item) = slot.ctx.children.iter().find(|item| item.id == id)
      {
        return Some(item);
      }
    }
    None
  }

  /// The slot of a component anywhere below this one.
  fn descendant_slot(&self, id: u64) -> Option<&ChildSlot> {
    for slot in &self.children {
      if slot.id == id {
        return Some(slot);
      }
      if let Some(found) = slot.ctx.descendant_slot(id) {
        return Some(found);
      }
    }
    None
  }

  #[cfg_attr(not(feature = "perf_profile"), allow(dead_code))]
  pub(crate) fn estimated_memory_bytes(&self) -> usize {
    std::mem::size_of::<Self>()
      + self
        .props
        .as_ref()
        .map(|_| std::mem::size_of::<Box<dyn Any + Send>>())
        .unwrap_or(0)
      + self.children.capacity() * std::mem::size_of::<ChildSlot>()
      + self.watch_handles.capacity() * std::mem::size_of::<Box<dyn Any + Send + Sync>>()
      + self.render_watch_handles.capacity() * std::mem::size_of::<Box<dyn Any + Send + Sync>>()
      + {
        #[cfg(feature = "devtools")]
        {
          self.memos_debug.capacity() * std::mem::size_of::<ComponentMemoDebug>()
            + self.effects_debug.capacity() * std::mem::size_of::<ComponentEffectDebug>()
        }
        #[cfg(not(feature = "devtools"))]
        {
          0
        }
      }
      + self.effects.capacity() * std::mem::size_of::<Effect>()
      + self.timers.capacity() * std::mem::size_of::<Timer>()
      + self.frames.capacity_bytes()
      + (self.future_slots.capacity() + self.stable_future_slots.capacity()) * std::mem::size_of::<FutureSlot>()
      + self.element_refs.capacity() * std::mem::size_of::<ElementRefMut>()
      + self.click_outside_active_cursors.capacity() * std::mem::size_of::<usize>()
      + self
        .children
        .iter()
        .map(ChildSlot::estimated_memory_bytes)
        .sum::<usize>()
  }
}

/// What a component found in the contexts its parent passes down.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Inherited {
  /// The parent's map is the one inherited last: nothing to take.
  Same,
  /// New values were taken, none the component renders again for; its
  /// descendants still take them (`propagate_contexts`).
  Refreshed,
  /// The component renders again: a value it read changed, or its render
  /// provides values of its own.
  Changed,
}

fn element_ref_is_click_outside(element_ref: &ElementRef, x: f32, y: f32) -> bool {
  if !element_ref.is_attached() {
    return false;
  }

  let rect = element_ref.bounds();
  x < rect.x || x > rect.x + rect.width || y < rect.y || y > rect.y + rect.height
}

struct ForEachSlot;

impl ForEachSlot {
  const TYPE_NAME: &'static str = "ForEachSlot";
}

impl AnyComponent for ForEachSlot {
  fn render(&self, _ctx: &mut Ctx) -> Element {
    Element::new()
  }
  fn after_layout(&self) {}
  fn on_mounted(&self) {}
  fn on_unmounted(&self) {}
  fn type_name(&self) -> &'static str {
    Self::TYPE_NAME
  }
  fn tag_name(&self) -> Arc<str> {
    Arc::from("ForEachSlot")
  }
}

impl ChildSlot {
  #[cfg_attr(not(feature = "perf_profile"), allow(dead_code))]
  fn estimated_memory_bytes(&self) -> usize {
    self.key.as_ref().map(|key| key.capacity()).unwrap_or(0)
      + std::mem::size_of::<Box<dyn AnyComponent>>()
      + self.ctx.estimated_memory_bytes()
  }

  fn is_for_each_group(&self) -> bool {
    self.key.is_none() && self.component.type_name() == ForEachSlot::TYPE_NAME
  }

  /// Renders what is dirty of a component that is about to leave the stage, a last time: itself, or the
  /// components below it that are. What it renders goes to no tree; it is what the component does in its
  /// render that matters (a player told to pause), and what it keeps for when it is back.
  fn render_as_it_leaves(&mut self) {
    if !self.ctx.is_dirty() {
      let _ = self.ctx.refresh_dirty_subtrees();
      return;
    }
    let previous = self.rendered.take();
    self.ctx.begin_render();
    let mut element = self.component.render(&mut self.ctx);
    self.ctx.end_render();
    element.node = attach_component_metadata(
      element.node,
      self.component.tag_name(),
      self.id,
      self.key.as_deref(),
      #[cfg(feature = "devtools")]
      &self.ctx,
    );
    if let Some(previous) = previous.as_ref() {
      element.node.preserve_runtime_state_from(previous);
    }
    self.keep_rendered(&element.node);
  }

  /// Keeps `node`, the output this slot's component just rendered, with
  /// placeholders for the components it mounted (`node/component_output.rs`).
  fn keep_rendered(&mut self, node: &Node) {
    let mut own = Vec::new();
    for child in &self.ctx.children {
      if child.is_for_each_group() {
        own.extend(child.ctx.children.iter().map(|item| item.id));
      } else {
        own.push(child.id);
      }
    }
    own.sort_unstable();
    self.rendered = Some(node.clone_own_output(&|id| own.binary_search(&id).is_ok()));
    self.rendered_at = next_render_generation();
  }

  /// The output of this slot's last render, put together again from its
  /// cache and those of the components in it, for a parent that mounts the
  /// component unchanged.
  fn assembled_output(&self) -> Option<Box<Node>> {
    self.assemble(&self.ctx, None).map(Box::new)
  }

  /// `scope` holds every slot whose component's root the output can hold:
  /// the unchanged component's own slot, which has no slot children.
  fn assemble(&self, scope: &Ctx, enclosing: Option<&SlotOwners<'_>>) -> Option<Node> {
    let rendered = self.rendered.as_deref()?;
    let owners = SlotOwners {
      ctx: &self.ctx,
      enclosing,
    };
    Some(rendered.clone_with_component_roots(&mut |root: &Node| {
      let id = root.component_slot_id()?;
      if root.is_component_slot_placeholder() {
        let mut output = self.ctx.child_slot(id)?.assemble(scope, Some(&owners))?;
        output.adopt_outer_decoration(root);
        return Some(output);
      }
      // A root this render was handed, kept whole: take its component's
      // fresh output when that component rendered again by itself since.
      let slot = enclosing
        .and_then(|owners| owners.slot(id))
        .or_else(|| scope.descendant_slot(id))?;
      if slot.rendered_at <= self.rendered_at {
        return None;
      }
      let mut output = slot.assemble(scope, Some(&owners))?;
      output.adopt_outer_decoration(root);
      Some(output)
    }))
  }
}

/// The components enclosing the one whose output is put together, nearest
/// first: the slots handed to a component are those of a component around it.
struct SlotOwners<'a> {
  ctx: &'a Ctx,
  enclosing: Option<&'a SlotOwners<'a>>,
}

impl<'a> SlotOwners<'a> {
  fn slot(&self, id: u64) -> Option<&'a ChildSlot> {
    self
      .ctx
      .child_slot(id)
      .or_else(|| self.enclosing.and_then(|owners| owners.slot(id)))
  }
}

impl Drop for Ctx {
  fn drop(&mut self) {
    for slot in &self.children {
      if slot.mounted {
        slot.component.on_unmounted();
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::Ctx;
  use crate::{
    app::component::Component,
    components::{Column, Rect},
    node::Element,
  };

  struct CachedChild;

  impl Component for CachedChild {
    type Props = ();

    fn create(_ctx: &mut Ctx) -> Self {
      Self
    }

    fn render(&self, _ctx: &mut Ctx) -> impl Into<Element> {
      Column::new()
        .child(Rect::new(1.0, 1.0))
        .child(Rect::new(2.0, 2.0))
        .child(Rect::new(3.0, 3.0))
    }
  }

  struct CachedParent;

  impl Component for CachedParent {
    type Props = ();

    fn create(_ctx: &mut Ctx) -> Self {
      Self
    }

    fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
      Column::new().child(ctx.mount::<CachedChild>(()).id("child"))
    }
  }

  /// A slot keeps the nodes of its own component only, so a child that
  /// renders again by itself touches no cache above it.
  #[test]
  fn a_slot_keeps_a_placeholder_for_each_component_it_mounted() {
    let mut root = Ctx::new_root();
    let output = root.mount::<CachedParent>(());
    assert_eq!(output.node.children()[0].children().len(), 3);

    let parent = &root.children[0];
    let kept = &parent
      .rendered
      .as_deref()
      .expect("the parent kept its output")
      .children()[0];
    assert!(kept.is_component_slot_placeholder());
    assert!(kept.children().is_empty());
    assert_eq!(kept.component_slot_id(), Some(parent.ctx.children[0].id));

    let assembled = parent.assembled_output().expect("the parent's output");
    let child = &assembled.children()[0];
    assert!(!child.is_component_slot_placeholder());
    assert_eq!(child.children().len(), 3);
    assert_eq!(child.element_id(), Some("child"), "the mounting code's id is put back");
  }

  #[test]
  fn batch_defers_dirty_marking_until_end() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(0);
    ctx.clear_dirty();

    ctx.batch(|| {
      signal.set(1);
      assert!(!ctx.is_dirty());
      assert!(!ctx.any_dirty());
    });

    assert!(ctx.is_dirty());
    assert!(ctx.any_dirty());
  }

  #[test]
  fn dirty_mark_during_render_survives_end_render() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(0);
    ctx.clear_dirty();

    ctx.begin_render();
    signal.set(1);
    ctx.end_render();

    assert!(ctx.is_dirty());
    assert!(ctx.any_dirty());
  }

  #[test]
  fn dirty_mark_for_previous_render_dependency_survives_rerender() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(0);

    ctx.begin_render();
    let _ = signal.get();
    ctx.end_render();
    ctx.clear_dirty();

    ctx.begin_render();
    let _ = signal.get();
    signal.set(1);
    ctx.end_render();

    assert!(ctx.is_dirty());
    assert!(ctx.any_dirty());
  }

  #[test]
  fn descendant_dirty_marks_ancestor_subtrees_without_marking_ancestors_dirty() {
    let root = Ctx::new_root();
    let mut child = Ctx::new();
    child.inherit_dirty_ancestors_from(&root, 10);
    let mut grandchild = Ctx::new();
    grandchild.inherit_dirty_ancestors_from(&child, 20);

    root.clear_dirty();
    child.clear_dirty();
    grandchild.clear_dirty();

    grandchild.mark_self_dirty();

    assert!(!root.is_dirty());
    assert!(!child.is_dirty());
    assert!(grandchild.is_dirty());
    assert!(root.any_dirty());
    assert!(child.any_dirty());
    assert!(grandchild.any_dirty());
    assert_eq!(*root.dirty_child_slots.lock(), vec![10]);
    assert_eq!(*child.dirty_child_slots.lock(), vec![20]);

    grandchild.clear_dirty();
    let _ = child.take_dirty_child_slot_ids();
    let _ = root.take_dirty_child_slot_ids();
    child.update_subtree_dirty_from_children();
    root.update_subtree_dirty_from_children();

    assert!(!root.any_dirty());
    assert!(!child.any_dirty());
    assert!(!grandchild.any_dirty());
  }

  #[cfg(feature = "devtools")]
  #[test]
  fn signal_debug_value_updates_when_signal_changes() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(0_i32);
    let debug = ctx.signals_debug();

    assert_eq!(debug[0].formatted_value().as_deref(), Some("0"));

    signal.set(42);

    assert_eq!(debug[0].formatted_value().as_deref(), Some("42"));
  }

  #[cfg(feature = "devtools")]
  #[test]
  fn signal_debug_history_records_value_changes() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(0_i32);
    let debug = ctx.signals_debug();

    signal.set(1);
    signal.set(2);

    let history = debug[0].history();
    assert_eq!(history.len(), 2);
    assert_eq!(history[0].from_value, "0");
    assert_eq!(history[0].to_value, "1");
    assert_eq!(history[1].from_value, "1");
    assert_eq!(history[1].to_value, "2");
  }

  #[cfg(feature = "devtools")]
  #[test]
  fn signal_debug_subscriber_count_excludes_runtime_and_debug_hooks() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(0_i32);
    let debug = ctx.signals_debug();

    assert_eq!(debug[0].subscriber_count(), 0);

    ctx.watch(&signal, |_| {});
    assert_eq!(debug[0].subscriber_count(), 1);

    let memo_signal = signal.clone();
    let _memo = ctx.memo(move || memo_signal.get() + 1);
    assert_eq!(debug[0].subscriber_count(), 2);
  }

  #[cfg(feature = "devtools")]
  #[derive(crate::DevtoolsInspectable)]
  struct DebugSignalValue {
    count: i32,
    active: bool,
  }

  #[cfg(feature = "devtools")]
  #[test]
  fn signal_debug_value_uses_devtools_inspectable_fields() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(DebugSignalValue { count: 2, active: true });
    let debug = ctx.signals_debug();

    assert_eq!(debug[0].formatted_value().as_deref(), Some("count: 2, active: true"));

    signal.set(DebugSignalValue {
      count: 3,
      active: false,
    });

    assert_eq!(debug[0].formatted_value().as_deref(), Some("count: 3, active: false"));
  }

  #[cfg(feature = "devtools")]
  #[test]
  fn memo_debug_value_updates_when_dependencies_change() {
    let mut ctx = Ctx::new_root();
    let signal = ctx.signal(2_i32);
    let memo_signal = signal.clone();
    let _memo = ctx.memo(move || memo_signal.get() * 2);
    let debug = ctx.memos_debug();

    assert_eq!(debug[0].formatted_value().as_deref(), Some("4"));

    signal.set(3);

    assert_eq!(debug[0].formatted_value().as_deref(), Some("6"));
  }
}