fret-ui 0.1.0

Mechanism-layer UI engine for Fret with tree, layout, focus, routing, and interaction contracts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::hash::Hash;
use std::panic::Location;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use smallvec::SmallVec;

use fret_core::input::PointerType;
use fret_core::window::{ColorScheme, ContrastPreference, ForcedColorsMode};
use fret_core::{
    AppWindowId, Color, Edges, EffectChain, EffectMode, EffectQuality, NodeId, Px, Rect,
};
use fret_runtime::{Effect, FrameId, Model, ModelId, ModelUpdateError, TimerToken};

use crate::action::OnHoverChange;
use crate::action::{
    ActionRouteHooks, CommandActionHooks, CommandAvailabilityActionHooks, DismissibleActionHooks,
    KeyActionHooks, OnActivate, OnCommand, OnCommandAvailability, OnDismissRequest,
    OnDismissiblePointerMove, OnKeyDown, OnPinchGesture, OnPointerCancel, OnPointerDown,
    OnPointerMove, OnPointerUp, OnPressablePointerDown, OnPressablePointerMove,
    OnPressablePointerUp, OnRovingActiveChange, OnRovingNavigate, OnRovingTypeahead,
    OnSelectableTextActivateSpan, OnTimer, OnWheel, PointerActionHooks, PressableActionHooks,
    PressableHoverActionHooks, PressablePointerUpResult, RovingActionHooks,
    SelectableTextActionHooks, TimerActionHooks,
};
use crate::canvas::{CanvasPaintHooks, CanvasPainter, OnCanvasPaint};
use crate::element::{
    AnyElement, BackdropSourceGroupProps, CanvasProps, ColumnProps, CompositeGroupProps,
    ContainerProps, EffectLayerProps, ElementKind, FlexProps, FocusTraversalGateProps,
    ForegroundScopeProps, GridProps, HitTestGateProps, HoverRegionProps, ImageProps,
    InteractivityGateProps, LayoutQueryRegionProps, LayoutStyle, MaskLayerProps, OpacityProps,
    PointerRegionProps, PressableProps, PressableState, ResizablePanelGroupProps, RowProps,
    ScrollProps, ScrollbarProps, SelectableTextProps, SpacerProps, SpinnerProps, StackProps,
    StyledTextProps, SvgIconProps, TextAreaProps, TextInputProps, TextProps, ViewportSurfaceProps,
    VirtualListOptions, VirtualListProps, VirtualListState, VisualTransformProps,
};
use crate::overlay_placement::{AnchoredPanelLayoutTrace, Side};
use crate::widget::Invalidation;
use crate::{SvgSource, Theme, UiHost};
use fret_core::window::WindowMetricsService;

use super::hash::{callsite_hash, derive_child_id, stable_hash};
use super::runtime::{EnvironmentQueryKey, LayoutQueryRegionMarker};
use super::{ContinuousFrames, ElementRuntime, GlobalElementId, WindowElementState, global_root};

/// Per-frame view construction context passed to declarative element constructors.
///
/// `ElementContext` exposes:
/// - a mutable handle to the app/host (`cx.app`) implementing [`UiHost`],
/// - the current window id and frame id,
/// - helper constructors for common element kinds (containers, text, input, overlays, etc.),
/// - access to theme and environment queries.
///
/// It is created and owned by [`UiTree`] and should be treated as an ephemeral, frame-scoped API.
pub struct ElementContext<'a, H: UiHost> {
    pub app: &'a mut H,
    pub window: AppWindowId,
    pub frame_id: FrameId,
    pub bounds: Rect,
    render_pass_id: u64,
    window_state: &'a mut WindowElementState,
    stack: Vec<GlobalElementId>,
    callsite_counters: Vec<CallsiteCounters>,
    view_cache_should_reuse: Option<&'a mut dyn FnMut(NodeId) -> bool>,
}

/// Explicit access contract for APIs that only need to land UI through an [`ElementContext`].
///
/// This keeps extracted helper/render-authoring surfaces free to accept a narrower context-access
/// capability instead of hard-coding `&mut ElementContext<...>` or relying on implicit `Deref`
/// bridges from facade types.
pub trait ElementContextAccess<'a, H: UiHost> {
    fn elements(&mut self) -> &mut ElementContext<'a, H>;
}

impl<'a, H: UiHost> ElementContextAccess<'a, H> for ElementContext<'a, H> {
    fn elements(&mut self) -> &mut ElementContext<'a, H> {
        self
    }
}

type CallsiteCounters = SmallVec<[(u64, u32); 16]>;

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

fn next_render_pass_id() -> u64 {
    NEXT_RENDER_PASS_ID.fetch_add(1, Ordering::Relaxed)
}

#[derive(Debug)]
struct ProvidedState<T> {
    value: Option<T>,
}

struct LocalModelSlot<T> {
    model: Option<Model<T>>,
}

#[cfg(debug_assertions)]
#[derive(Default)]
struct RenderEvaluationCallsiteDiagnostics {
    last_render_pass_id: u64,
    calls_in_render_pass: u32,
}

#[cfg(debug_assertions)]
fn note_call_in_render_evaluation(
    diagnostics: &mut RenderEvaluationCallsiteDiagnostics,
    render_pass_id: u64,
) -> bool {
    if diagnostics.last_render_pass_id != render_pass_id {
        diagnostics.last_render_pass_id = render_pass_id;
        diagnostics.calls_in_render_pass = 0;
    }
    diagnostics.calls_in_render_pass = diagnostics.calls_in_render_pass.saturating_add(1);
    diagnostics.calls_in_render_pass == 2
}

impl<T> Default for LocalModelSlot<T> {
    fn default() -> Self {
        Self { model: None }
    }
}

impl<T> Default for ProvidedState<T> {
    fn default() -> Self {
        Self { value: None }
    }
}

fn bump_callsite_counter(counters: &mut CallsiteCounters, callsite: u64) -> u64 {
    for (seen, next) in counters.iter_mut() {
        if *seen != callsite {
            continue;
        }
        let slot = (*next) as u64;
        *next = next.saturating_add(1);
        return slot;
    }
    counters.push((callsite, 1));
    0
}

impl<'a, H: UiHost> ElementContext<'a, H> {
    pub(crate) fn collect_children(
        &mut self,
        children: impl IntoIterator<Item = AnyElement>,
    ) -> Vec<AnyElement> {
        let iter = children.into_iter();
        let (min, _) = iter.size_hint();
        let mut out = self.window_state.take_scratch_element_children_vec(min);
        out.extend(iter);
        out
    }

    pub(crate) fn retained_virtual_list_row_any_element(
        &mut self,
        key: crate::ItemKey,
        index: usize,
        row: &crate::windowed_surface_host::RetainedVirtualListRowFn<H>,
    ) -> AnyElement {
        self.keyed(key, |cx| (row)(cx, index))
    }

    pub fn new(
        app: &'a mut H,
        runtime: &'a mut ElementRuntime,
        window: AppWindowId,
        bounds: Rect,
        root: GlobalElementId,
    ) -> Self {
        let frame_id = app.frame_id();
        runtime.prepare_window_for_frame(window, frame_id);

        let window_state = runtime.for_window_mut(window);
        window_state.mark_authoring_identity_seen(root);

        Self {
            app,
            window,
            frame_id,
            bounds,
            render_pass_id: next_render_pass_id(),
            window_state,
            stack: vec![root],
            callsite_counters: vec![CallsiteCounters::new()],
            view_cache_should_reuse: None,
        }
    }

    pub(crate) fn set_view_cache_should_reuse(&mut self, f: &'a mut dyn FnMut(NodeId) -> bool) {
        self.view_cache_should_reuse = Some(f);
    }

    pub fn new_for_root_name(
        app: &'a mut H,
        runtime: &'a mut ElementRuntime,
        window: AppWindowId,
        bounds: Rect,
        root_name: &str,
    ) -> Self {
        let root = global_root(window, root_name);
        #[cfg(feature = "diagnostics")]
        {
            let cx = Self::new(app, runtime, window, bounds, root);
            cx.window_state
                .record_debug_root(cx.frame_id, root, root_name);
            cx
        }
        #[cfg(not(feature = "diagnostics"))]
        {
            Self::new(app, runtime, window, bounds, root)
        }
    }

    pub(crate) fn new_for_existing_window_state(
        app: &'a mut H,
        window: AppWindowId,
        bounds: Rect,
        root: GlobalElementId,
        window_state: &'a mut WindowElementState,
    ) -> Self {
        let frame_id = app.frame_id();
        window_state.mark_authoring_identity_seen(root);
        Self {
            app,
            window,
            frame_id,
            bounds,
            render_pass_id: next_render_pass_id(),
            window_state,
            stack: vec![root],
            callsite_counters: vec![CallsiteCounters::new()],
            view_cache_should_reuse: None,
        }
    }

    /// Framework-internal diagnostics hook for repeated same-callsite use within one render
    /// evaluation.
    ///
    /// This is not a public authoring API; it exists so higher-level facade code can reuse the
    /// kernel's identity/evaluation substrate instead of maintaining duplicate bookkeeping.
    #[cfg(debug_assertions)]
    #[doc(hidden)]
    pub fn note_repeated_call_in_render_evaluation_at(
        &mut self,
        loc: &'static Location<'static>,
    ) -> bool {
        let key = (loc.file(), loc.line(), loc.column());
        self.keyed_at(loc, key, |cx| {
            let render_pass_id = cx.render_pass_id;
            cx.root_state(
                RenderEvaluationCallsiteDiagnostics::default,
                |diagnostics| note_call_in_render_evaluation(diagnostics, render_pass_id),
            )
        })
    }

    #[cfg(not(debug_assertions))]
    #[doc(hidden)]
    pub fn note_repeated_call_in_render_evaluation_at(
        &mut self,
        _loc: &'static Location<'static>,
    ) -> bool {
        false
    }

    pub fn root_id(&self) -> GlobalElementId {
        *self.stack.last().expect("root exists")
    }

    fn new_any_element(
        &mut self,
        id: GlobalElementId,
        kind: ElementKind,
        children: Vec<AnyElement>,
    ) -> AnyElement {
        AnyElement::new(id, kind, children)
    }

    /// Returns the nearest ancestor state value of type `S` in the current element scope stack.
    ///
    /// This is a lightweight building block for component-layer "provider" patterns (e.g. Radix
    /// `DirectionProvider`) without requiring a dedicated runtime context mechanism.
    pub fn inherited_state<S: Any>(&self) -> Option<&S> {
        self.inherited_state_where(|_state: &S| true)
    }

    /// Like `inherited_state`, but allows skipping "inactive" states while continuing to search.
    ///
    /// This is useful when a state entry remains allocated but temporarily holds no active value
    /// (e.g. an `Option<T>` that is `None` outside of a scope).
    pub fn inherited_state_where<S: Any>(&self, predicate: impl Fn(&S) -> bool) -> Option<&S> {
        let ty = TypeId::of::<S>();
        for &id in self.stack.iter().rev() {
            let key = (id, ty);
            let Some(any) = self.window_state.state_any_ref(&key) else {
                continue;
            };
            let Some(state) = any.downcast_ref::<S>() else {
                continue;
            };
            if predicate(state) {
                return Some(state);
            }
        }
        None
    }

    /// Returns the nearest value installed via [`Self::provide`] for type `S`.
    pub fn provided<S: Any>(&self) -> Option<&S> {
        self.provided_where(|_state: &S| true)
    }

    /// Like [`Self::provided`], but allows filtering values while continuing the ancestor search.
    pub fn provided_where<S: Any>(&self, predicate: impl Fn(&S) -> bool) -> Option<&S> {
        self.inherited_state_where::<ProvidedState<S>>(|slot| {
            slot.value.as_ref().is_some_and(&predicate)
        })
        .and_then(|slot| slot.value.as_ref())
    }

    /// Returns the last known `NodeId` for a declarative element, if available.
    ///
    /// This is intentionally a last-known query surface: authoritative render-time correctness
    /// paths should prefer live window-frame or attached-tree resolution instead of treating this
    /// as the current attached node.
    ///
    /// It remains safe to call during element rendering because it reads from the `ElementCx`'s
    /// already borrowed window state, avoiding re-entrant `UiHost::with_global_mut` leases.
    pub fn node_for_element(&self, element: GlobalElementId) -> Option<NodeId> {
        self.window_state.node_entry(element).map(|e| e.node)
    }

    /// Returns the current-frame node mapping for `element`, if available.
    ///
    /// The authoritative liveness signal is the retained `node_entry` record being touched in the
    /// current frame (`last_seen_frame == self.frame_id`).
    pub fn live_node_for_element(&mut self, element: GlobalElementId) -> Option<NodeId> {
        self.window_state
            .node_entry(element)
            .and_then(|entry| (entry.last_seen_frame == self.frame_id).then_some(entry.node))
    }

    pub fn focused_element(&self) -> Option<GlobalElementId> {
        self.window_state.focused_element
    }

    pub fn is_focused_element(&self, element: GlobalElementId) -> bool {
        self.window_state.focused_element == Some(element)
    }

    /// Returns `true` when the currently focused element is `element` itself or any descendant in
    /// the declarative element tree for this window.
    pub fn is_focus_within_element(&mut self, element: GlobalElementId) -> bool {
        let Some(focused) = self.focused_element() else {
            return false;
        };
        if focused == element {
            return true;
        }

        let root_node = crate::declarative::node_for_element_in_window_frame(
            &mut *self.app,
            self.window,
            element,
        )
        .or_else(|| self.window_state.node_entry(element).map(|e| e.node));
        let Some(root_node) = root_node else {
            return false;
        };
        let focused_node = crate::declarative::node_for_element_in_window_frame(
            &mut *self.app,
            self.window,
            focused,
        )
        .or_else(|| self.window_state.node_entry(focused).map(|e| e.node));
        let Some(focused_node) = focused_node else {
            return false;
        };

        crate::declarative::node_contains_in_window_frame(
            &mut *self.app,
            self.window,
            root_node,
            focused_node,
        )
    }

    pub fn has_active_text_selection(&self) -> bool {
        self.window_state.active_text_selection().is_some()
    }

    pub fn has_active_text_selection_in_root(&self, root: GlobalElementId) -> bool {
        self.window_state
            .active_text_selection()
            .is_some_and(|selection| selection.root == root)
    }

    pub(crate) fn sync_focused_element_from_focused_node(&mut self, focused: Option<NodeId>) {
        self.window_state.focused_element = focused.and_then(|node| {
            crate::declarative::frame::element_record_for_node(&mut *self.app, self.window, node)
                .map(|record| record.element)
                .or_else(|| self.window_state.element_for_node(node))
        });
    }

    /// Returns the last frame's bounds for a declarative element, if available.
    ///
    /// This is safe to call during element rendering: it reads from the `ElementCx`'s already
    /// borrowed window state, avoiding re-entrant `UiHost::with_global_mut` leases.
    pub fn last_bounds_for_element(&self, element: GlobalElementId) -> Option<Rect> {
        self.window_state.last_bounds(element)
    }

    /// Returns the last frame's **visual** bounds (post-`render_transform` AABB) for a declarative
    /// element, if available.
    ///
    /// This is intended for anchored overlay policies that must track render transforms (ADR 0083)
    /// without mixing layout transforms into the layout solver.
    pub fn last_visual_bounds_for_element(&self, element: GlobalElementId) -> Option<Rect> {
        self.window_state
            .last_visual_bounds(element)
            .or_else(|| self.window_state.last_bounds(element))
    }

    /// Returns the last recorded root bounds for the element's root, if available.
    ///
    /// This is safe to call during element rendering for the same reason as
    /// `last_bounds_for_element`.
    pub fn root_bounds_for_element(&self, element: GlobalElementId) -> Option<Rect> {
        let root = self.window_state.node_entry(element).map(|e| e.root)?;
        self.window_state.root_bounds(root)
    }

    /// Consume a transient event flag for the current element.
    ///
    /// This returns `true` at most once per recorded event (clear-on-read).
    pub fn take_transient(&mut self, key: u64) -> bool {
        let element = self.root_id();
        self.take_transient_for(element, key)
    }

    /// Consume a transient event flag for the specified element.
    ///
    /// This returns `true` at most once per recorded event (clear-on-read).
    pub fn take_transient_for(&mut self, element: GlobalElementId, key: u64) -> bool {
        self.window_state.take_transient_event(element, key)
    }

    pub fn with_root_name<R>(&mut self, root_name: &str, f: impl FnOnce(&mut Self) -> R) -> R {
        let root = global_root(self.window, root_name);

        let prev_stack = std::mem::take(&mut self.stack);
        let prev_counters = std::mem::take(&mut self.callsite_counters);

        self.stack = vec![root];
        self.callsite_counters = vec![CallsiteCounters::new()];
        self.window_state.mark_authoring_identity_seen(root);

        let out = f(self);

        self.stack = prev_stack;
        self.callsite_counters = prev_counters;

        out
    }

    /// Runs `f` and then restores the current callsite counters to their previous state.
    ///
    /// This is useful when you need to "probe-render" a subtree (e.g. to compute derived
    /// information like `focus_within`) without consuming callsite slots and disturbing
    /// subsequent element identity in the real render pass.
    pub fn with_callsite_counters_snapshot<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
        let prev_stack = self.stack.clone();
        let prev_counters = self.callsite_counters.clone();

        let out = f(self);

        debug_assert_eq!(
            self.stack.len(),
            prev_stack.len(),
            "element stack depth must be balanced"
        );
        debug_assert_eq!(
            self.callsite_counters.len(),
            prev_counters.len(),
            "callsite counters stack depth must be balanced"
        );

        self.stack = prev_stack;
        self.callsite_counters = prev_counters;
        debug_assert_eq!(self.callsite_counters.len(), self.stack.len());
        out
    }

    /// Request a window redraw (one-shot).
    ///
    /// Use this after mutating state/models to schedule a repaint.
    ///
    /// Notes:
    /// - This does not guarantee frame-driven progression. If you need to advance without input
    ///   events (animations, progressive rendering), prefer `request_animation_frame()` or
    ///   `begin_continuous_frames()`.
    /// - This is not a timer: callers that need continuous progression must keep requesting frames.
    pub fn request_frame(&mut self) {
        self.app.request_redraw(self.window);
    }

    /// Mark the nearest cache root as needing a paint notification on the next mount.
    ///
    /// This is a lightweight way to force paint-cache roots to rerun paint (e.g. while animating
    /// opacity/transform) without necessarily requesting a new animation frame from the runner.
    pub fn notify_for_animation_frame(&mut self) {
        // Drive invalidation from the current element, letting propagation and cache-root
        // truncation pick the appropriate boundary (e.g. nearest view-cache root when enabled).
        self.window_state
            .request_notify_for_animation_frame(self.root_id());
    }

    /// Request the next animation frame for this window.
    ///
    /// Use this for frame-driven updates that must advance without input events.
    ///
    /// This is a one-shot request. Prefer `begin_continuous_frames()` when driving animations from
    /// declarative UI code.
    pub fn request_animation_frame(&mut self) {
        self.notify_for_animation_frame();
        self.app
            .push_effect(Effect::RequestAnimationFrame(self.window));
    }

    /// Begin a "continuous frames" lease for this window.
    ///
    /// This is the preferred way for declarative UI to drive animations: while the returned
    /// lease is held, the mount pass will continue requesting animation frames.
    pub fn begin_continuous_frames(&mut self) -> ContinuousFrames {
        let lease = self
            .window_state
            .begin_continuous_frames(Some(self.root_id()));
        self.request_animation_frame();
        lease
    }

    /// Request a one-shot timer event routed to the given element.
    ///
    /// This records the timer target in the current window element runtime, enabling
    /// `Event::Timer { token }` to be dispatched to the element's `on_timer` hook.
    pub fn set_timer_for(&mut self, element: GlobalElementId, token: TimerToken, after: Duration) {
        self.window_state.timer_targets.insert(
            token,
            crate::elements::runtime::TimerTarget::Element(element),
        );
        self.app.push_effect(Effect::SetTimer {
            window: Some(self.window),
            token,
            after,
            repeat: None,
        });
    }

    /// Request a one-shot timer event routed to the current element.
    pub fn set_timer(&mut self, token: TimerToken, after: Duration) {
        let element = self.root_id();
        self.set_timer_for(element, token, after);
    }

    /// Cancel a previously requested timer and clear its routing entry for this window.
    pub fn cancel_timer(&mut self, token: TimerToken) {
        self.window_state.timer_targets.remove(&token);
        self.app.push_effect(Effect::CancelTimer { token });
    }

    #[track_caller]
    pub fn scope<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
        let loc = Location::caller();
        let callsite = callsite_hash(loc);
        self.enter_with_callsite(loc, callsite, None, None, f)
    }

    #[doc(hidden)]
    pub fn scope_at<R>(
        &mut self,
        loc: &'static Location<'static>,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let callsite = callsite_hash(loc);
        self.enter_with_callsite(loc, callsite, None, None, f)
    }

    #[track_caller]
    pub fn keyed<K: Hash, R>(&mut self, key: K, f: impl FnOnce(&mut Self) -> R) -> R {
        let loc = Location::caller();
        self.keyed_at(loc, key, f)
    }

    #[doc(hidden)]
    pub fn keyed_at<K: Hash, R>(
        &mut self,
        loc: &'static Location<'static>,
        key: K,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let caller = callsite_hash(loc);
        let key_hash = stable_hash(&key);
        self.enter_with_callsite(loc, caller, Some(key_hash), None, f)
    }

    #[track_caller]
    pub fn named<R>(&mut self, name: &str, f: impl FnOnce(&mut Self) -> R) -> R {
        let loc = Location::caller();
        let caller = callsite_hash(loc);
        let key_hash = stable_hash(&name);
        self.enter_with_callsite(loc, caller, Some(key_hash), Some(name), f)
    }

    /// Component/internal identity lane: accesses root-scoped state stored under the current
    /// `root_id()`.
    ///
    /// This is keyed by `(root_id, TypeId)`, so it is a shared slot per element root.
    /// Repeated calls with the same state type under the same root intentionally see the same
    /// state. If you need multiple independent slots of the same type, create a child scope first
    /// via [`Self::scope`], [`Self::keyed`], or another helper that allocates a distinct root id.
    pub fn root_state<S: Any, R>(
        &mut self,
        init: impl FnOnce() -> S,
        f: impl FnOnce(&mut S) -> R,
    ) -> R {
        let id = self.root_id();
        self.state_for(id, init, f)
    }

    /// Compatibility alias for [`Self::root_state`].
    ///
    /// Prefer [`Self::root_state`] in new first-party code. Keep this alias for migration and
    /// downstream compatibility only.
    #[deprecated(note = "use root_state(...) for root-scoped shared element state")]
    pub fn with_state<S: Any, R>(
        &mut self,
        init: impl FnOnce() -> S,
        f: impl FnOnce(&mut S) -> R,
    ) -> R {
        self.root_state(init, f)
    }

    /// Component/internal identity lane: accesses helper-local state stored under a synthetic
    /// callsite-derived slot.
    ///
    /// Unlike [`Self::root_state`], this does not use the current `root_id()` directly. The slot is
    /// derived from `(current_root, caller_location, call_index_at_that_location)` so distinct
    /// callsites of the same state type do not collide.
    ///
    /// This is the correct primitive for helper-owned internals that want React hook-like slot
    /// semantics without allocating a visible child scope in the element stack. The derived slot is
    /// intentionally **not** pushed onto the inherited-state stack, so descendants cannot observe
    /// it via [`Self::inherited_state`].
    ///
    /// If a helper needs to touch the same slot more than once during one render pass, either do
    /// all work inside a single closure or allocate the slot once via [`Self::slot_id`] and then
    /// use [`Self::state_for`] for repeated accesses.
    ///
    /// When the helper may be invoked from a reorderable collection, prefer wrapping the caller in
    /// [`Self::keyed`] (or use [`Self::keyed_slot_state`]) so the surrounding identity stays stable
    /// across insertions and reordering.
    #[track_caller]
    pub fn slot_state<S: Any, R>(
        &mut self,
        init: impl FnOnce() -> S,
        f: impl FnOnce(&mut S) -> R,
    ) -> R {
        let loc = Location::caller();
        let id = self.callsite_state_slot_id(loc, None);
        self.state_for(id, init, f)
    }

    /// Like [`Self::slot_state`], but derives the synthetic slot from `(callsite, key)`.
    ///
    /// This mirrors [`Self::keyed`]: repeated renders with the same key reuse the same state slot
    /// even if sibling order changes.
    #[track_caller]
    pub fn keyed_slot_state<K: Hash, S: Any, R>(
        &mut self,
        key: K,
        init: impl FnOnce() -> S,
        f: impl FnOnce(&mut S) -> R,
    ) -> R {
        let loc = Location::caller();
        let id = self.callsite_state_slot_id(loc, Some(stable_hash(&key)));
        self.state_for(id, init, f)
    }

    /// Allocates a synthetic callsite-derived state slot id without pushing a child scope.
    ///
    /// Use this when one helper invocation needs to read/write the same helper-local slot multiple
    /// times during a single render pass.
    #[track_caller]
    pub fn slot_id(&mut self) -> GlobalElementId {
        let loc = Location::caller();
        self.slot_id_at(loc)
    }

    /// Like [`Self::slot_id`], but keys the synthetic slot by `(callsite, key)`.
    ///
    /// This is useful for helper-local state inside reorderable collections where sibling order is
    /// not stable across renders.
    #[track_caller]
    pub fn keyed_slot_id<K: Hash>(&mut self, key: K) -> GlobalElementId {
        let loc = Location::caller();
        self.keyed_slot_id_at(loc, key)
    }

    /// Like [`Self::slot_id`], but anchors the synthetic slot at an explicit caller location.
    #[doc(hidden)]
    pub fn slot_id_at(&mut self, loc: &'static Location<'static>) -> GlobalElementId {
        self.callsite_state_slot_id(loc, None)
    }

    /// Like [`Self::keyed_slot_id`], but anchors the synthetic slot at an explicit caller
    /// location.
    #[doc(hidden)]
    pub fn keyed_slot_id_at<K: Hash>(
        &mut self,
        loc: &'static Location<'static>,
        key: K,
    ) -> GlobalElementId {
        self.callsite_state_slot_id(loc, Some(stable_hash(&key)))
    }

    /// Component/internal identity lane: returns a helper-local model handle stored under a
    /// synthetic callsite-derived slot.
    ///
    /// This is the model-handle counterpart to [`Self::slot_state`]: the slot identity is local to
    /// this helper invocation and stable across frames, so callers can create copy-paste-friendly
    /// local `Model<T>` state without abusing root-scoped [`Self::with_state`].
    #[track_caller]
    pub fn local_model<T: Any>(&mut self, init: impl FnOnce() -> T) -> Model<T> {
        let slot = self.slot_id();
        self.local_model_for(slot, init)
    }

    /// Like [`Self::local_model`], but anchors the synthetic slot at an explicit caller location.
    #[doc(hidden)]
    pub fn local_model_at<T: Any>(
        &mut self,
        loc: &'static Location<'static>,
        init: impl FnOnce() -> T,
    ) -> Model<T> {
        let slot = self.slot_id_at(loc);
        self.local_model_for(slot, init)
    }

    /// Like [`Self::local_model`], but keys the synthetic slot by `(callsite, key)`.
    ///
    /// Prefer this when one helper is invoked from a reorderable collection or when several local
    /// models are authored through a shared helper and need explicit, stable names.
    #[track_caller]
    pub fn local_model_keyed<K: Hash, T: Any>(
        &mut self,
        key: K,
        init: impl FnOnce() -> T,
    ) -> Model<T> {
        let slot = self.keyed_slot_id(key);
        self.local_model_for(slot, init)
    }

    /// Like [`Self::local_model_keyed`], but anchors the synthetic slot at an explicit caller
    /// location.
    #[doc(hidden)]
    pub fn local_model_keyed_at<K: Hash, T: Any>(
        &mut self,
        loc: &'static Location<'static>,
        key: K,
        init: impl FnOnce() -> T,
    ) -> Model<T> {
        let slot = self.keyed_slot_id_at(loc, key);
        self.local_model_for(slot, init)
    }

    /// Accesses state stored under an explicit element identity.
    pub fn state_for<S: Any, R>(
        &mut self,
        element: GlobalElementId,
        init: impl FnOnce() -> S,
        f: impl FnOnce(&mut S) -> R,
    ) -> R {
        self.window_state.with_state_mut(element, init, f)
    }

    /// Compatibility alias for [`Self::state_for`].
    ///
    /// Prefer [`Self::state_for`] in new first-party code. Keep this alias for migration and
    /// downstream compatibility only.
    #[deprecated(note = "use state_for(...) for explicit-identity element state")]
    pub fn with_state_for<S: Any, R>(
        &mut self,
        element: GlobalElementId,
        init: impl FnOnce() -> S,
        f: impl FnOnce(&mut S) -> R,
    ) -> R {
        self.state_for(element, init, f)
    }

    /// Component/internal identity lane: returns a model handle stored under an explicit element
    /// identity.
    ///
    /// This is the explicit-identity counterpart to [`Self::local_model`] and
    /// [`Self::local_model_keyed`]. Prefer it when a helper must bind a `Model<T>` to a stable
    /// overlay/portal/root id instead of a callsite-derived slot.
    ///
    /// Like [`Self::state_for`], storage is keyed by `(element, TypeId)`. Different model value
    /// types may therefore share one explicit element id, while multiple models of the same type
    /// still need distinct explicit ids.
    pub fn model_for<T: Any>(
        &mut self,
        element: GlobalElementId,
        init: impl FnOnce() -> T,
    ) -> Model<T> {
        self.local_model_for(element, init)
    }

    fn local_model_for<T: Any>(
        &mut self,
        slot: GlobalElementId,
        init: impl FnOnce() -> T,
    ) -> Model<T> {
        let model = self.state_for(slot, LocalModelSlot::<T>::default, |st| st.model.clone());
        match model {
            Some(model) => model,
            None => {
                let model = self.app.models_mut().insert(init());
                self.state_for(slot, LocalModelSlot::<T>::default, |st| {
                    st.model = Some(model.clone());
                });
                model
            }
        }
    }

    /// Installs `value` as an inherited provider value for the current subtree.
    ///
    /// This is the preferred authoring surface for provider-style patterns. It keeps provider
    /// semantics separate from raw root state while still using the same element-state substrate.
    pub fn provide<S: Any, R>(&mut self, value: S, f: impl FnOnce(&mut Self) -> R) -> R {
        let prev = self.root_state(ProvidedState::<S>::default, |slot| {
            slot.value.replace(value)
        });
        let out = f(self);
        self.root_state(ProvidedState::<S>::default, |slot| {
            slot.value = prev;
        });
        out
    }

    pub fn observe_model<T>(&mut self, model: &Model<T>, invalidation: Invalidation) {
        self.observe_model_id(model.id(), invalidation);
    }

    pub fn read_model<T: Any, R>(
        &mut self,
        model: &Model<T>,
        invalidation: Invalidation,
        f: impl FnOnce(&mut H, &T) -> R,
    ) -> Result<R, ModelUpdateError> {
        self.observe_model(model, invalidation);
        model.read(&mut *self.app, f)
    }

    pub fn read_model_ref<T: Any, R>(
        &mut self,
        model: &Model<T>,
        invalidation: Invalidation,
        f: impl FnOnce(&T) -> R,
    ) -> Result<R, ModelUpdateError> {
        self.observe_model(model, invalidation);
        self.app.models().read(model, f)
    }

    pub fn get_model_copied<T: Any + Copy>(
        &mut self,
        model: &Model<T>,
        invalidation: Invalidation,
    ) -> Option<T> {
        self.read_model_ref(model, invalidation, |v| *v).ok()
    }

    pub fn get_model_cloned<T: Any + Clone>(
        &mut self,
        model: &Model<T>,
        invalidation: Invalidation,
    ) -> Option<T> {
        self.read_model_ref(model, invalidation, Clone::clone).ok()
    }

    pub fn observe_model_id(&mut self, model: ModelId, invalidation: Invalidation) {
        let id = self
            .window_state
            .current_view_cache_root()
            .unwrap_or_else(|| self.root_id());
        let list = self
            .window_state
            .observed_models_next
            .entry(id)
            .or_default();
        if list
            .iter()
            .any(|(m, inv)| *m == model && *inv == invalidation)
        {
            return;
        }
        list.push((model, invalidation));
    }

    pub fn observe_global<T: Any>(&mut self, invalidation: Invalidation) {
        self.observe_global_id(TypeId::of::<T>(), invalidation);
    }

    pub fn observe_global_id(&mut self, global: TypeId, invalidation: Invalidation) {
        let id = self
            .window_state
            .current_view_cache_root()
            .unwrap_or_else(|| self.root_id());
        let list = self
            .window_state
            .observed_globals_next
            .entry(id)
            .or_default();
        if list
            .iter()
            .any(|(g, inv)| *g == global && *inv == invalidation)
        {
            return;
        }
        list.push((global, invalidation));
    }

    fn observe_environment_query(&mut self, key: EnvironmentQueryKey, invalidation: Invalidation) {
        let id = self
            .window_state
            .current_view_cache_root()
            .unwrap_or_else(|| self.root_id());
        let list = self
            .window_state
            .observed_environment_next
            .entry(id)
            .or_default();
        if list
            .iter()
            .any(|(k, inv)| *k == key && *inv == invalidation)
        {
            return;
        }
        list.push((key, invalidation));
    }

    pub fn observe_layout_query_region(
        &mut self,
        region: GlobalElementId,
        invalidation: Invalidation,
    ) {
        let id = self
            .window_state
            .current_view_cache_root()
            .unwrap_or_else(|| self.root_id());
        let list = self
            .window_state
            .observed_layout_queries_next
            .entry(id)
            .or_default();
        if list
            .iter()
            .any(|(r, inv)| *r == region && *inv == invalidation)
        {
            return;
        }
        list.push((region, invalidation));
    }

    pub fn layout_query_bounds(
        &mut self,
        region: GlobalElementId,
        invalidation: Invalidation,
    ) -> Option<Rect> {
        self.observe_layout_query_region(region, invalidation);
        self.last_bounds_for_element(region)
    }

    pub fn environment_viewport_bounds(&mut self, invalidation: Invalidation) -> Rect {
        self.observe_environment_query(EnvironmentQueryKey::ViewportSize, invalidation);
        self.window_state.committed_viewport_bounds()
    }

    pub fn environment_viewport_width(&mut self, invalidation: Invalidation) -> Px {
        self.environment_viewport_bounds(invalidation).size.width
    }

    pub fn environment_viewport_height(&mut self, invalidation: Invalidation) -> Px {
        self.environment_viewport_bounds(invalidation).size.height
    }

    pub fn environment_scale_factor(&mut self, invalidation: Invalidation) -> f32 {
        self.observe_environment_query(EnvironmentQueryKey::ScaleFactor, invalidation);
        self.window_state.committed_scale_factor()
    }

    pub fn environment_color_scheme(&mut self, invalidation: Invalidation) -> Option<ColorScheme> {
        self.observe_environment_query(EnvironmentQueryKey::ColorScheme, invalidation);
        self.window_state.committed_color_scheme()
    }

    pub fn environment_prefers_reduced_motion(
        &mut self,
        invalidation: Invalidation,
    ) -> Option<bool> {
        self.observe_environment_query(EnvironmentQueryKey::PrefersReducedMotion, invalidation);
        self.window_state.committed_prefers_reduced_motion()
    }

    pub fn environment_text_scale_factor(&mut self, invalidation: Invalidation) -> Option<f32> {
        self.observe_environment_query(EnvironmentQueryKey::TextScaleFactor, invalidation);
        self.window_state.committed_text_scale_factor()
    }

    pub fn environment_prefers_reduced_transparency(
        &mut self,
        invalidation: Invalidation,
    ) -> Option<bool> {
        self.observe_environment_query(
            EnvironmentQueryKey::PrefersReducedTransparency,
            invalidation,
        );
        self.window_state.committed_prefers_reduced_transparency()
    }

    pub fn environment_accent_color(&mut self, invalidation: Invalidation) -> Option<Color> {
        self.observe_environment_query(EnvironmentQueryKey::AccentColor, invalidation);
        self.window_state.committed_accent_color()
    }

    pub fn environment_prefers_contrast(
        &mut self,
        invalidation: Invalidation,
    ) -> Option<ContrastPreference> {
        self.observe_environment_query(EnvironmentQueryKey::PrefersContrast, invalidation);
        self.window_state.committed_contrast_preference()
    }

    pub fn environment_forced_colors_mode(
        &mut self,
        invalidation: Invalidation,
    ) -> Option<ForcedColorsMode> {
        self.observe_environment_query(EnvironmentQueryKey::ForcedColorsMode, invalidation);
        self.window_state.committed_forced_colors_mode()
    }

    pub fn environment_safe_area_insets(&mut self, invalidation: Invalidation) -> Option<Edges> {
        self.observe_environment_query(EnvironmentQueryKey::SafeAreaInsets, invalidation);
        self.window_state.committed_safe_area_insets()
    }

    pub fn environment_occlusion_insets(&mut self, invalidation: Invalidation) -> Option<Edges> {
        self.observe_environment_query(EnvironmentQueryKey::OcclusionInsets, invalidation);
        self.window_state.committed_occlusion_insets()
    }

    pub fn environment_primary_pointer_type(&mut self, invalidation: Invalidation) -> PointerType {
        self.observe_environment_query(EnvironmentQueryKey::PrimaryPointerType, invalidation);
        self.window_state.committed_primary_pointer_type()
    }

    pub fn environment_primary_pointer_can_hover(
        &mut self,
        invalidation: Invalidation,
        default_when_unknown: bool,
    ) -> bool {
        match self.environment_primary_pointer_type(invalidation) {
            PointerType::Touch => false,
            PointerType::Unknown => default_when_unknown,
            PointerType::Mouse | PointerType::Pen => true,
        }
    }

    pub fn environment_primary_pointer_is_coarse(
        &mut self,
        invalidation: Invalidation,
        default_when_unknown: bool,
    ) -> bool {
        match self.environment_primary_pointer_type(invalidation) {
            PointerType::Touch => true,
            PointerType::Unknown => default_when_unknown,
            PointerType::Mouse | PointerType::Pen => false,
        }
    }

    pub fn diagnostics_record_overlay_placement_anchored_panel(
        &mut self,
        overlay_root_name: Option<&str>,
        anchor_element: Option<GlobalElementId>,
        content_element: Option<GlobalElementId>,
        trace: AnchoredPanelLayoutTrace,
    ) {
        #[cfg(feature = "diagnostics")]
        self.window_state.record_overlay_placement_anchored_panel(
            self.frame_id,
            overlay_root_name.map(Arc::<str>::from),
            anchor_element,
            content_element,
            trace,
        );
        #[cfg(not(feature = "diagnostics"))]
        let _ = (overlay_root_name, anchor_element, content_element, trace);
    }

    #[allow(clippy::too_many_arguments)]
    pub fn diagnostics_record_overlay_placement_placed_rect(
        &mut self,
        overlay_root_name: Option<&str>,
        anchor_element: Option<GlobalElementId>,
        content_element: Option<GlobalElementId>,
        outer: Rect,
        anchor: Rect,
        placed: Rect,
        side: Option<Side>,
    ) {
        #[cfg(feature = "diagnostics")]
        self.window_state.record_overlay_placement_placed_rect(
            self.frame_id,
            overlay_root_name.map(Arc::<str>::from),
            anchor_element,
            content_element,
            outer,
            anchor,
            placed,
            side,
        );
        #[cfg(not(feature = "diagnostics"))]
        let _ = (
            overlay_root_name,
            anchor_element,
            content_element,
            outer,
            anchor,
            placed,
            side,
        );
    }

    pub fn theme(&mut self) -> &Theme {
        self.observe_global::<Theme>(Invalidation::Layout);
        Theme::global(&*self.app)
    }

    #[track_caller]
    pub fn for_each_keyed<T, K: Hash>(
        &mut self,
        items: &[T],
        mut key: impl FnMut(&T) -> K,
        mut f: impl FnMut(&mut Self, usize, &T),
    ) {
        let loc = Location::caller();
        self.scope(|cx| {
            let mut first_dup: Option<(u64, usize, usize)> = None;
            let mut seen: HashMap<u64, usize> = HashMap::new();
            for (index, item) in items.iter().enumerate() {
                let k = key(item);
                let key_hash = stable_hash(&k);
                if first_dup.is_none()
                    && let Some(prev) = seen.insert(key_hash, index)
                {
                    first_dup = Some((key_hash, prev, index));
                }
                cx.keyed(k, |cx| f(cx, index, item));
            }

            if let Some((key_hash, a, b)) = first_dup
                && cfg!(debug_assertions)
                && items.len() > 1
            {
                let element_path: Option<String> = {
                    #[cfg(feature = "diagnostics")]
                    {
                        cx.window_state.debug_path_for_element(cx.root_id())
                    }
                    #[cfg(not(feature = "diagnostics"))]
                    {
                        None
                    }
                };

                tracing::warn!(
                    file = loc.file(),
                    line = loc.line(),
                    column = loc.column(),
                    key_hash = format_args!("{key_hash:#x}"),
                    first_index = a,
                    second_index = b,
                    element_path = element_path.as_deref().unwrap_or("<unknown>"),
                    "duplicate keyed list item key hash; element state may collide"
                );
            }
        });
    }

    #[track_caller]
    pub fn for_each_unkeyed<T: Hash>(
        &mut self,
        items: &[T],
        mut f: impl FnMut(&mut Self, usize, &T),
    ) {
        let loc = Location::caller();
        let list_id = callsite_hash(loc);
        let fingerprints: Vec<u64> = items.iter().map(stable_hash).collect();
        self.window_state
            .cur_unkeyed_fingerprints
            .insert(list_id, fingerprints.clone());

        if let Some(prev) = self.window_state.prev_unkeyed_fingerprints.get(&list_id)
            && prev != &fingerprints
            && items.len() > 1
            && cfg!(debug_assertions)
        {
            let element_path: Option<String> = {
                #[cfg(feature = "diagnostics")]
                {
                    self.window_state.debug_path_for_element(self.root_id())
                }
                #[cfg(not(feature = "diagnostics"))]
                {
                    None
                }
            };
            tracing::warn!(
                list_id = format_args!("{list_id:#x}"),
                file = loc.file(),
                line = loc.line(),
                column = loc.column(),
                element_path = element_path.as_deref().unwrap_or("<unknown>"),
                "unkeyed element list order changed; add explicit keys to preserve state"
            );
        }

        self.scope(|cx| {
            for (index, item) in items.iter().enumerate() {
                let index_key = index as u64;
                cx.enter_with_callsite(loc, list_id, Some(index_key), None, |cx| {
                    f(cx, index, item)
                });
            }
        });
    }

    fn enter_with_callsite<R>(
        &mut self,
        _loc: &'static Location<'static>,
        callsite: u64,
        key_hash: Option<u64>,
        _debug_name: Option<&str>,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let parent = self.root_id();
        let counters = self
            .callsite_counters
            .last_mut()
            .expect("callsite counters exist");
        let slot = bump_callsite_counter(counters, callsite);

        let child_salt = key_hash.unwrap_or(slot);
        let id = derive_child_id(parent, callsite, child_salt);
        self.window_state.mark_authoring_identity_seen(id);

        #[cfg(feature = "diagnostics")]
        self.window_state.record_debug_child(
            self.frame_id,
            parent,
            id,
            _loc.file(),
            _loc.line(),
            _loc.column(),
            key_hash,
            _debug_name,
            slot,
        );

        self.stack.push(id);
        self.callsite_counters.push(CallsiteCounters::new());
        let out = f(self);
        self.callsite_counters.pop();
        self.stack.pop();
        out
    }

    fn callsite_state_slot_id(
        &mut self,
        loc: &'static Location<'static>,
        key_hash: Option<u64>,
    ) -> GlobalElementId {
        let parent = self.root_id();
        let callsite = callsite_hash(loc);
        let counters = self
            .callsite_counters
            .last_mut()
            .expect("callsite counters exist");
        let slot = bump_callsite_counter(counters, callsite);
        let child_salt = key_hash.unwrap_or(slot);
        derive_child_id(parent, callsite, child_salt)
    }

    #[track_caller]
    pub fn container<I>(
        &mut self,
        props: ContainerProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Container(props), children)
        })
    }

    /// Creates a `Semantics` layout wrapper around the subtree.
    ///
    /// `Semantics` is intentionally input- and paint-transparent, but it **does** participate in
    /// layout via `SemanticsProps.layout`. Use it when you need a semantics node boundary (tree
    /// structure) or wrapper-only semantics features (e.g. a focusable semantics node).
    ///
    /// If you only need to stamp `test_id` / `label` / `role` / `value` for diagnostics or UI
    /// automation, prefer attaching `SemanticsDecoration` to an existing element via
    /// `AnyElement::attach_semantics(...)` to avoid introducing a layout node.
    #[track_caller]
    pub fn semantics<I>(
        &mut self,
        props: crate::element::SemanticsProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Semantics(props), children)
        })
    }

    #[track_caller]
    pub fn semantic_flex<I>(
        &mut self,
        props: crate::element::SemanticFlexProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::SemanticFlex(props), children)
        })
    }

    #[track_caller]
    pub fn focus_scope<I>(
        &mut self,
        props: crate::element::FocusScopeProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::FocusScope(props), children)
        })
    }

    #[track_caller]
    pub fn view_cache<I>(
        &mut self,
        props: crate::element::ViewCacheProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let should_reuse = cx
                .window_state
                .node_entry(id)
                .map(|e| e.node)
                .and_then(|node| cx.view_cache_should_reuse.as_mut().map(|f| f(node)))
                .unwrap_or(false);

            let theme_revision = Theme::global(&*cx.app).revision();
            let scale_factor = cx
                .app
                .global::<WindowMetricsService>()
                .and_then(|svc| svc.scale_factor(cx.window))
                .unwrap_or(1.0);

            // View-cache keys must incorporate any "external" dependencies that can affect the
            // cached subtree without triggering a normal invalidation walk (e.g. environment
            // queries, layout queries).
            //
            // When reusing, depend on the previously-recorded deps for this cache root. When
            // re-rendering, the key is refreshed from `*_next` after the closure runs.
            let scale_bits = scale_factor.to_bits();
            let deps_key_rendered = if should_reuse {
                (
                    cx.window_state.environment_deps_fingerprint_rendered(id),
                    cx.window_state.layout_query_deps_fingerprint_rendered(id),
                )
            } else {
                (0, 0)
            };
            let key = stable_hash(&(
                theme_revision,
                scale_bits,
                props.cache_key,
                deps_key_rendered.0,
                deps_key_rendered.1,
            ));

            let key_matches = if should_reuse {
                let matches = cx.window_state.view_cache_key_matches_and_touch(id, key);
                if !matches {
                    cx.window_state.record_view_cache_key_mismatch(id);
                }
                matches
            } else {
                false
            };

            let reuse = should_reuse && key_matches;

            let children: Vec<AnyElement> = if reuse {
                cx.window_state.mark_view_cache_reuse_root(id);
                cx.window_state.touch_view_cache_state_keys_if_recorded(id);
                cx.window_state
                    .touch_observed_models_for_element_if_recorded(id);
                cx.window_state
                    .touch_observed_globals_for_element_if_recorded(id);
                cx.window_state
                    .touch_observed_environment_for_element_if_recorded(id);
                cx.window_state
                    .touch_observed_layout_queries_for_element_if_recorded(id);
                Vec::new()
            } else {
                cx.window_state.begin_view_cache_scope(id);
                let built = f(cx);
                let children = cx.collect_children(built);
                cx.window_state.end_view_cache_scope(id);

                let deps_key_next = (
                    cx.window_state.environment_deps_fingerprint_next(id),
                    cx.window_state.layout_query_deps_fingerprint_next(id),
                );
                let key = stable_hash(&(
                    theme_revision,
                    scale_bits,
                    props.cache_key,
                    deps_key_next.0,
                    deps_key_next.1,
                ));
                cx.window_state.set_view_cache_key(id, key);
                children
            };
            cx.new_any_element(id, ElementKind::ViewCache(props), children)
        })
    }

    /// Explicit keep-alive cache root for cases where the element producer may be skipped by view caching.
    ///
    /// This mirrors the "reuse" side of `view_cache(...)`, but makes the decision explicit:
    /// - When `keep_alive=true`, the subtree is kept alive even if `f` is not executed.
    /// - When `keep_alive=false`, `f` is always executed (no implicit reuse).
    ///
    /// This is a mechanism-layer escape hatch intended for overlay synthesis and similar systems
    /// that must preserve subtree liveness when the normal authoring closure does not run.
    #[track_caller]
    pub fn view_cache_keep_alive<I>(
        &mut self,
        props: crate::element::ViewCacheProps,
        keep_alive: bool,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();

            let theme_revision = Theme::global(&*cx.app).revision();
            let scale_factor = cx
                .app
                .global::<WindowMetricsService>()
                .and_then(|svc| svc.scale_factor(cx.window))
                .unwrap_or(1.0);
            let scale_bits = scale_factor.to_bits();

            if keep_alive {
                cx.window_state.mark_view_cache_reuse_root(id);
                cx.window_state.touch_view_cache_state_keys_if_recorded(id);
                cx.window_state
                    .touch_observed_models_for_element_if_recorded(id);
                cx.window_state
                    .touch_observed_globals_for_element_if_recorded(id);
                cx.window_state
                    .touch_observed_environment_for_element_if_recorded(id);
                cx.window_state
                    .touch_observed_layout_queries_for_element_if_recorded(id);

                // Preserve the previously-recorded key (if any); this root is being kept alive
                // explicitly rather than via normal key-matched reuse.
                let _ = (theme_revision, scale_bits);
                return cx.new_any_element(id, ElementKind::ViewCache(props), Vec::new());
            }

            cx.window_state.begin_view_cache_scope(id);
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.window_state.end_view_cache_scope(id);

            let deps_key_next = (
                cx.window_state.environment_deps_fingerprint_next(id),
                cx.window_state.layout_query_deps_fingerprint_next(id),
            );
            let key = stable_hash(&(
                theme_revision,
                scale_bits,
                props.cache_key,
                deps_key_next.0,
                deps_key_next.1,
            ));
            cx.window_state.set_view_cache_key(id, key);

            cx.new_any_element(id, ElementKind::ViewCache(props), children)
        })
    }

    #[track_caller]
    pub fn focus_scope_with_id<I>(
        &mut self,
        props: crate::element::FocusScopeProps,
        f: impl FnOnce(&mut Self, GlobalElementId) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx, id);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::FocusScope(props), children)
        })
    }

    #[track_caller]
    pub fn layout_query_region_with_id<I>(
        &mut self,
        props: LayoutQueryRegionProps,
        f: impl FnOnce(&mut Self, GlobalElementId) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let name = props.name.clone();
            cx.state_for(id, LayoutQueryRegionMarker::default, |marker| {
                marker.name = name.clone();
            });
            let built = f(cx, id);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::LayoutQueryRegion(props), children)
        })
    }

    #[track_caller]
    pub fn layout_query_region<I>(
        &mut self,
        props: LayoutQueryRegionProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.layout_query_region_with_id(props, |cx, _id| f(cx))
    }

    /// Creates a `Semantics` layout wrapper around the subtree and passes its element id.
    ///
    /// See [`Self::semantics`] for guidance on when to use `Semantics` vs `attach_semantics`
    /// (`SemanticsDecoration`).
    #[track_caller]
    pub fn semantics_with_id<I>(
        &mut self,
        props: crate::element::SemanticsProps,
        f: impl FnOnce(&mut Self, GlobalElementId) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx, id);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Semantics(props), children)
        })
    }

    #[track_caller]
    pub fn opacity<I>(&mut self, opacity: f32, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        let props = OpacityProps {
            opacity: opacity.clamp(0.0, 1.0),
            ..Default::default()
        };
        self.opacity_props(props, f)
    }

    #[track_caller]
    pub fn opacity_props<I>(
        &mut self,
        props: OpacityProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Opacity(props), children)
        })
    }

    #[track_caller]
    pub fn foreground_scope<I>(
        &mut self,
        foreground: fret_core::Color,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.foreground_scope_props(
            ForegroundScopeProps {
                foreground: Some(foreground),
                ..Default::default()
            },
            f,
        )
    }

    #[track_caller]
    pub fn foreground_scope_props<I>(
        &mut self,
        props: ForegroundScopeProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::ForegroundScope(props), children)
        })
    }

    #[track_caller]
    pub fn effect_layer<I>(
        &mut self,
        mode: EffectMode,
        chain: EffectChain,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.effect_layer_props(
            EffectLayerProps {
                mode,
                chain,
                ..Default::default()
            },
            f,
        )
    }

    #[track_caller]
    pub fn effect_layer_props<I>(
        &mut self,
        props: EffectLayerProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::EffectLayer(props), children)
        })
    }

    #[track_caller]
    pub fn backdrop_source_group_v1<I>(
        &mut self,
        pyramid: Option<fret_core::scene::CustomEffectPyramidRequestV1>,
        quality: EffectQuality,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.backdrop_source_group_v1_props(
            BackdropSourceGroupProps {
                pyramid,
                quality,
                ..Default::default()
            },
            f,
        )
    }

    #[track_caller]
    pub fn backdrop_source_group_v1_props<I>(
        &mut self,
        props: BackdropSourceGroupProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::BackdropSourceGroup(props), children)
        })
    }

    #[track_caller]
    pub fn mask_layer<I>(
        &mut self,
        mask: fret_core::scene::Mask,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.mask_layer_props(
            MaskLayerProps {
                layout: LayoutStyle::default(),
                mask,
            },
            f,
        )
    }

    #[track_caller]
    pub fn mask_layer_props<I>(
        &mut self,
        props: MaskLayerProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::MaskLayer(props), children)
        })
    }

    #[track_caller]
    pub fn composite_group<I>(
        &mut self,
        mode: fret_core::scene::BlendMode,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.composite_group_props(
            CompositeGroupProps {
                layout: LayoutStyle::default(),
                mode,
                quality: EffectQuality::Auto,
            },
            f,
        )
    }

    #[track_caller]
    pub fn composite_group_props<I>(
        &mut self,
        props: CompositeGroupProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::CompositeGroup(props), children)
        })
    }

    #[track_caller]
    pub fn visual_transform<I>(
        &mut self,
        transform: fret_core::Transform2D,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.visual_transform_props(
            VisualTransformProps {
                layout: LayoutStyle::default(),
                transform,
            },
            f,
        )
    }

    #[track_caller]
    pub fn render_transform<I>(
        &mut self,
        transform: fret_core::Transform2D,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.render_transform_props(
            crate::element::RenderTransformProps {
                layout: LayoutStyle::default(),
                transform,
            },
            f,
        )
    }

    #[track_caller]
    pub fn fractional_render_transform<I>(
        &mut self,
        translate_x_fraction: f32,
        translate_y_fraction: f32,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.fractional_render_transform_props(
            crate::element::FractionalRenderTransformProps {
                layout: LayoutStyle::default(),
                translate_x_fraction,
                translate_y_fraction,
            },
            f,
        )
    }

    #[track_caller]
    pub fn visual_transform_props<I>(
        &mut self,
        props: VisualTransformProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::VisualTransform(props), children)
        })
    }

    #[track_caller]
    pub fn render_transform_props<I>(
        &mut self,
        props: crate::element::RenderTransformProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::RenderTransform(props), children)
        })
    }

    #[track_caller]
    pub fn fractional_render_transform_props<I>(
        &mut self,
        props: crate::element::FractionalRenderTransformProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::FractionalRenderTransform(props), children)
        })
    }

    #[track_caller]
    pub fn anchored_props<I>(
        &mut self,
        props: crate::element::AnchoredProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Anchored(props), children)
        })
    }

    #[track_caller]
    pub fn interactivity_gate<I>(
        &mut self,
        present: bool,
        interactive: bool,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.interactivity_gate_props(
            InteractivityGateProps {
                present,
                interactive,
                ..Default::default()
            },
            f,
        )
    }

    #[track_caller]
    pub fn interactivity_gate_props<I>(
        &mut self,
        props: InteractivityGateProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::InteractivityGate(props), children)
        })
    }

    #[track_caller]
    pub fn hit_test_gate<I>(&mut self, hit_test: bool, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.hit_test_gate_props(
            HitTestGateProps {
                hit_test,
                ..Default::default()
            },
            f,
        )
    }

    #[track_caller]
    pub fn hit_test_gate_props<I>(
        &mut self,
        props: HitTestGateProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::HitTestGate(props), children)
        })
    }

    #[track_caller]
    pub fn focus_traversal_gate<I>(
        &mut self,
        traverse: bool,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.focus_traversal_gate_props(
            FocusTraversalGateProps {
                traverse,
                ..Default::default()
            },
            f,
        )
    }

    #[track_caller]
    pub fn focus_traversal_gate_props<I>(
        &mut self,
        props: FocusTraversalGateProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::FocusTraversalGate(props), children)
        })
    }

    #[track_caller]
    pub fn pressable<I>(
        &mut self,
        props: PressableProps,
        f: impl FnOnce(&mut Self, PressableState) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let hovered = cx.window_state.hovered_pressable == Some(id);
            let hovered_raw = cx.window_state.hovered_pressable_raw == Some(id);
            let hovered_raw_below_barrier =
                cx.window_state.hovered_pressable_raw_below_barrier == Some(id);
            let pressed = cx.window_state.pressed_pressable == Some(id);
            let focused = cx.window_state.focused_element == Some(id);
            cx.pressable_clear_on_activate();
            cx.pressable_clear_on_clipboard_write_completed();
            cx.pressable_clear_on_hover_change();
            let built = f(
                cx,
                PressableState {
                    hovered,
                    hovered_raw,
                    hovered_raw_below_barrier,
                    pressed,
                    focused,
                },
            );
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Pressable(props), children)
        })
    }

    #[track_caller]
    pub fn pressable_with_id<I>(
        &mut self,
        props: PressableProps,
        f: impl FnOnce(&mut Self, PressableState, GlobalElementId) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let hovered = cx.window_state.hovered_pressable == Some(id);
            let hovered_raw = cx.window_state.hovered_pressable_raw == Some(id);
            let hovered_raw_below_barrier =
                cx.window_state.hovered_pressable_raw_below_barrier == Some(id);
            let pressed = cx.window_state.pressed_pressable == Some(id);
            let focused = cx.window_state.focused_element == Some(id);
            cx.pressable_clear_on_activate();
            cx.pressable_clear_on_clipboard_write_completed();
            cx.pressable_clear_on_hover_change();
            let built = f(
                cx,
                PressableState {
                    hovered,
                    hovered_raw,
                    hovered_raw_below_barrier,
                    pressed,
                    focused,
                },
                id,
            );
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Pressable(props), children)
        })
    }

    #[track_caller]
    pub fn pressable_with_id_props<I>(
        &mut self,
        f: impl FnOnce(&mut Self, PressableState, GlobalElementId) -> (PressableProps, I),
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let hovered = cx.window_state.hovered_pressable == Some(id);
            let hovered_raw = cx.window_state.hovered_pressable_raw == Some(id);
            let hovered_raw_below_barrier =
                cx.window_state.hovered_pressable_raw_below_barrier == Some(id);
            let pressed = cx.window_state.pressed_pressable == Some(id);
            let focused = cx.window_state.focused_element == Some(id);
            cx.pressable_clear_on_activate();
            cx.pressable_clear_on_clipboard_write_completed();
            cx.pressable_clear_on_pointer_down();
            cx.pressable_clear_on_hover_change();
            let (props, children) = f(
                cx,
                PressableState {
                    hovered,
                    hovered_raw,
                    hovered_raw_below_barrier,
                    pressed,
                    focused,
                },
                id,
            );
            let children = cx.collect_children(children);
            cx.new_any_element(id, ElementKind::Pressable(props), children)
        })
    }

    /// Register a component-owned activation handler for the current pressable element.
    ///
    /// This is a policy hook mechanism (ADR 0074): components decide what activation does (model
    /// writes, overlay requests, command dispatch), while the runtime remains mechanism-only.
    pub fn pressable_on_activate(&mut self, handler: OnActivate) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_activate = Some(handler);
        });
    }

    pub fn pressable_on_activate_for(&mut self, element: GlobalElementId, handler: OnActivate) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_activate = Some(handler);
        });
    }

    pub fn pressable_add_on_activate(&mut self, handler: OnActivate) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_activate = match hooks.on_activate.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, reason| {
                        prev(host, cx, reason);
                        next(host, cx, reason);
                    }))
                }
            };
        });
    }

    pub fn pressable_add_on_activate_for(&mut self, element: GlobalElementId, handler: OnActivate) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_activate = match hooks.on_activate.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, reason| {
                        prev(host, cx, reason);
                        next(host, cx, reason);
                    }))
                }
            };
        });
    }

    pub fn pressable_clear_on_activate(&mut self) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_activate = None;
        });
    }

    /// Register a component-owned activation handler for interactive spans in the current
    /// selectable text element.
    ///
    /// This is a policy hook mechanism (ADR 0074): components decide what activation does
    /// (open URL, dispatch command, etc.), while the runtime remains mechanism-only.
    pub fn selectable_text_on_activate_span(&mut self, handler: OnSelectableTextActivateSpan) {
        self.root_state(SelectableTextActionHooks::default, |hooks| {
            hooks.on_activate_span = Some(handler);
        });
    }

    pub fn selectable_text_on_activate_span_for(
        &mut self,
        element: GlobalElementId,
        handler: OnSelectableTextActivateSpan,
    ) {
        self.state_for(element, SelectableTextActionHooks::default, |hooks| {
            hooks.on_activate_span = Some(handler);
        });
    }

    pub fn selectable_text_clear_on_activate_span(&mut self) {
        self.root_state(SelectableTextActionHooks::default, |hooks| {
            hooks.on_activate_span = None;
        });
    }

    pub fn selectable_text_clear_on_activate_span_for(&mut self, element: GlobalElementId) {
        self.state_for(element, SelectableTextActionHooks::default, |hooks| {
            hooks.on_activate_span = None;
        });
    }

    /// Register a component-owned pointer down handler for the current pressable element.
    ///
    /// This is a policy hook mechanism (ADR 0074): components can opt into Radix-style "select on
    /// mouse down" semantics without changing the default click-like activation behavior.
    pub fn pressable_on_pointer_down(&mut self, handler: OnPressablePointerDown) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_down = Some(handler);
        });
    }

    pub fn pressable_on_pointer_move(&mut self, handler: OnPressablePointerMove) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_move = Some(handler);
        });
    }

    pub fn pressable_on_pointer_up(&mut self, handler: OnPressablePointerUp) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_up = Some(handler);
        });
    }

    pub fn pressable_on_clipboard_write_completed(
        &mut self,
        handler: crate::action::OnPressableClipboardWriteCompleted,
    ) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_clipboard_write_completed = Some(handler);
        });
    }

    pub fn pressable_on_pointer_down_for(
        &mut self,
        element: GlobalElementId,
        handler: OnPressablePointerDown,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_pointer_down = Some(handler);
        });
    }

    pub fn pressable_on_pointer_move_for(
        &mut self,
        element: GlobalElementId,
        handler: OnPressablePointerMove,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_pointer_move = Some(handler);
        });
    }

    pub fn pressable_on_pointer_up_for(
        &mut self,
        element: GlobalElementId,
        handler: OnPressablePointerUp,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_pointer_up = Some(handler);
        });
    }

    pub fn pressable_on_clipboard_write_completed_for(
        &mut self,
        element: GlobalElementId,
        handler: crate::action::OnPressableClipboardWriteCompleted,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_clipboard_write_completed = Some(handler);
        });
    }

    pub fn pressable_add_on_pointer_down(&mut self, handler: OnPressablePointerDown) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_down = match hooks.on_pointer_down.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        let prev_result = prev(host, cx, down);
                        let next_result = next(host, cx, down);
                        use crate::action::PressablePointerDownResult as R;
                        match (prev_result, next_result) {
                            (R::SkipDefaultAndStopPropagation, _)
                            | (_, R::SkipDefaultAndStopPropagation) => {
                                R::SkipDefaultAndStopPropagation
                            }
                            (R::SkipDefault, _) | (_, R::SkipDefault) => R::SkipDefault,
                            _ => R::Continue,
                        }
                    }))
                }
            };
        });
    }

    pub fn pressable_add_on_pointer_move(&mut self, handler: OnPressablePointerMove) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_move = match hooks.on_pointer_move.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, mv| {
                        let prev_handled = prev(host, cx, mv);
                        let next_handled = next(host, cx, mv);
                        prev_handled || next_handled
                    }))
                }
            };
        });
    }

    pub fn pressable_add_on_pointer_up(&mut self, handler: OnPressablePointerUp) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_up = match hooks.on_pointer_up.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, up| {
                        let prev_result = prev(host, cx, up);
                        let next_result = next(host, cx, up);
                        match (prev_result, next_result) {
                            (PressablePointerUpResult::SkipActivate, _)
                            | (_, PressablePointerUpResult::SkipActivate) => {
                                PressablePointerUpResult::SkipActivate
                            }
                            _ => PressablePointerUpResult::Continue,
                        }
                    }))
                }
            };
        });
    }

    pub fn pressable_add_on_pointer_down_for(
        &mut self,
        element: GlobalElementId,
        handler: OnPressablePointerDown,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_pointer_down = match hooks.on_pointer_down.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        let prev_result = prev(host, cx, down);
                        let next_result = next(host, cx, down);
                        use crate::action::PressablePointerDownResult as R;
                        match (prev_result, next_result) {
                            (R::SkipDefaultAndStopPropagation, _)
                            | (_, R::SkipDefaultAndStopPropagation) => {
                                R::SkipDefaultAndStopPropagation
                            }
                            (R::SkipDefault, _) | (_, R::SkipDefault) => R::SkipDefault,
                            _ => R::Continue,
                        }
                    }))
                }
            };
        });
    }

    pub fn pressable_add_on_pointer_move_for(
        &mut self,
        element: GlobalElementId,
        handler: OnPressablePointerMove,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_pointer_move = match hooks.on_pointer_move.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, mv| {
                        let prev_handled = prev(host, cx, mv);
                        let next_handled = next(host, cx, mv);
                        prev_handled || next_handled
                    }))
                }
            };
        });
    }

    pub fn pressable_add_on_pointer_up_for(
        &mut self,
        element: GlobalElementId,
        handler: OnPressablePointerUp,
    ) {
        self.state_for(element, PressableActionHooks::default, |hooks| {
            hooks.on_pointer_up = match hooks.on_pointer_up.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, up| {
                        let prev_result = prev(host, cx, up);
                        let next_result = next(host, cx, up);
                        match (prev_result, next_result) {
                            (PressablePointerUpResult::SkipActivate, _)
                            | (_, PressablePointerUpResult::SkipActivate) => {
                                PressablePointerUpResult::SkipActivate
                            }
                            _ => PressablePointerUpResult::Continue,
                        }
                    }))
                }
            };
        });
    }

    pub fn pressable_clear_on_pointer_down(&mut self) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_down = None;
        });
    }

    pub fn pressable_clear_on_pointer_move(&mut self) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_move = None;
        });
    }

    pub fn pressable_clear_on_pointer_up(&mut self) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_pointer_up = None;
        });
    }

    pub fn pressable_clear_on_clipboard_write_completed(&mut self) {
        self.root_state(PressableActionHooks::default, |hooks| {
            hooks.on_clipboard_write_completed = None;
        });
    }

    /// Register a component-owned hover change handler for the current pressable element.
    ///
    /// This is a mechanism-only hook: the runtime tracks hover deterministically and invokes
    /// component code on hover transitions, without baking hover policy into `fret-ui`.
    pub fn pressable_on_hover_change(&mut self, handler: OnHoverChange) {
        self.root_state(PressableHoverActionHooks::default, |hooks| {
            hooks.on_hover_change = Some(handler);
        });
    }

    pub fn pressable_add_on_hover_change(&mut self, handler: OnHoverChange) {
        self.root_state(PressableHoverActionHooks::default, |hooks| {
            hooks.on_hover_change = match hooks.on_hover_change.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, hovered| {
                        prev(host, cx, hovered);
                        next(host, cx, hovered);
                    }))
                }
            };
        });
    }

    pub fn pressable_clear_on_hover_change(&mut self) {
        self.root_state(PressableHoverActionHooks::default, |hooks| {
            hooks.on_hover_change = None;
        });
    }

    #[track_caller]
    pub fn pointer_region<I>(
        &mut self,
        props: PointerRegionProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.pointer_region_clear_on_pointer_down();
            cx.pointer_region_clear_on_pointer_move();
            cx.pointer_region_clear_on_pointer_up();
            cx.pointer_region_clear_on_wheel();
            cx.pointer_region_clear_on_pinch_gesture();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::PointerRegion(props), children)
        })
    }

    #[track_caller]
    pub fn text_input_region<I>(
        &mut self,
        props: crate::element::TextInputRegionProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.text_input_region_clear_on_text_input();
            cx.text_input_region_clear_on_ime();
            cx.text_input_region_clear_on_clipboard_read_text();
            cx.text_input_region_clear_on_clipboard_read_failed();
            cx.text_input_region_clear_on_set_selection();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::TextInputRegion(props), children)
        })
    }

    pub fn internal_drag_region<I>(
        &mut self,
        props: crate::element::InternalDragRegionProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.internal_drag_region_clear_on_internal_drag();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::InternalDragRegion(props), children)
        })
    }

    pub fn internal_drag_region_on_internal_drag(
        &mut self,
        handler: crate::action::OnInternalDrag,
    ) {
        self.root_state(crate::action::InternalDragActionHooks::default, |hooks| {
            hooks.on_internal_drag = Some(handler);
        });
    }

    pub fn internal_drag_region_clear_on_internal_drag(&mut self) {
        self.root_state(crate::action::InternalDragActionHooks::default, |hooks| {
            hooks.on_internal_drag = None;
        });
    }

    pub fn external_drag_region<I>(
        &mut self,
        props: crate::element::ExternalDragRegionProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.external_drag_region_clear_on_external_drag();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::ExternalDragRegion(props), children)
        })
    }

    pub fn external_drag_region_on_external_drag(
        &mut self,
        handler: crate::action::OnExternalDrag,
    ) {
        self.root_state(crate::action::ExternalDragActionHooks::default, |hooks| {
            hooks.on_external_drag = Some(handler);
        });
    }

    pub fn external_drag_region_clear_on_external_drag(&mut self) {
        self.root_state(crate::action::ExternalDragActionHooks::default, |hooks| {
            hooks.on_external_drag = None;
        });
    }

    /// Register a component-owned pointer down handler for the current pointer region element.
    ///
    /// This is a mechanism-only hook point: components decide what a pointer down does (open a
    /// context menu, start a drag, request focus, etc.), while the runtime remains policy-free.
    pub fn pointer_region_on_pointer_down(&mut self, handler: OnPointerDown) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_down = Some(handler);
        });
    }

    pub fn pointer_region_add_on_pointer_down(&mut self, handler: OnPointerDown) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_down = match hooks.on_pointer_down.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        prev(host, cx, down) || next(host, cx, down)
                    }))
                }
            };
        });
    }

    pub fn pointer_region_clear_on_pointer_down(&mut self) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_down = None;
        });
    }

    /// Register a component-owned pointer move handler for the current pointer region element.
    ///
    /// This hook is invoked when the pointer region receives `PointerEvent::Move` events via
    /// normal hit-testing or pointer capture.
    pub fn pointer_region_on_pointer_move(&mut self, handler: OnPointerMove) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_move = Some(handler);
        });
    }

    pub fn pointer_region_add_on_pointer_move(&mut self, handler: OnPointerMove) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_move = match hooks.on_pointer_move.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, mv| {
                        prev(host, cx, mv) || next(host, cx, mv)
                    }))
                }
            };
        });
    }

    pub fn pointer_region_clear_on_pointer_move(&mut self) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_move = None;
        });
    }

    /// Register a component-owned pointer up handler for the current pointer region element.
    ///
    /// This hook is invoked when the pointer region receives `PointerEvent::Up` events via
    /// normal hit-testing or pointer capture.
    pub fn pointer_region_on_pointer_up(&mut self, handler: OnPointerUp) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_up = Some(handler);
        });
    }

    /// Register a component-owned pointer cancel handler for the current pointer region element.
    ///
    /// This hook is invoked when the runtime receives `Event::PointerCancel` for a pointer stream
    /// that was previously interacting with this region (typically via pointer capture).
    pub fn pointer_region_on_pointer_cancel(&mut self, handler: OnPointerCancel) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_cancel = Some(handler);
        });
    }

    pub fn pointer_region_on_wheel(&mut self, handler: OnWheel) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_wheel = Some(handler);
        });
    }

    pub fn pointer_region_on_pinch_gesture(&mut self, handler: OnPinchGesture) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pinch_gesture = Some(handler);
        });
    }

    pub fn pointer_region_add_on_pointer_up(&mut self, handler: OnPointerUp) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_up = match hooks.on_pointer_up.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, up| {
                        prev(host, cx, up) || next(host, cx, up)
                    }))
                }
            };
        });
    }

    pub fn pointer_region_add_on_wheel(&mut self, handler: OnWheel) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_wheel = match hooks.on_wheel.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, wheel| {
                        prev(host, cx, wheel) || next(host, cx, wheel)
                    }))
                }
            };
        });
    }

    pub fn pointer_region_add_on_pinch_gesture(&mut self, handler: OnPinchGesture) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pinch_gesture = match hooks.on_pinch_gesture.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, pinch| {
                        prev(host, cx, pinch) || next(host, cx, pinch)
                    }))
                }
            };
        });
    }

    pub fn pointer_region_clear_on_pointer_up(&mut self) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pointer_up = None;
        });
    }

    pub fn pointer_region_clear_on_wheel(&mut self) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_wheel = None;
        });
    }

    pub fn pointer_region_clear_on_pinch_gesture(&mut self) {
        self.root_state(PointerActionHooks::default, |hooks| {
            hooks.on_pinch_gesture = None;
        });
    }

    pub fn text_input_region_on_text_input(
        &mut self,
        handler: crate::action::OnTextInputRegionTextInput,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_text_input = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_text_input(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_text_input = None;
            },
        );
    }

    pub fn text_input_region_on_ime(&mut self, handler: crate::action::OnTextInputRegionIme) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_ime = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_ime(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_ime = None;
            },
        );
    }

    pub fn text_input_region_on_clipboard_read_text(
        &mut self,
        handler: crate::action::OnTextInputRegionClipboardReadText,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_clipboard_read_text = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_clipboard_read_text(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_clipboard_read_text = None;
            },
        );
    }

    pub fn text_input_region_on_clipboard_read_failed(
        &mut self,
        handler: crate::action::OnTextInputRegionClipboardReadFailed,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_clipboard_read_failed = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_clipboard_read_failed(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_clipboard_read_failed = None;
            },
        );
    }

    pub fn text_input_region_on_set_selection(
        &mut self,
        handler: crate::action::OnTextInputRegionSetSelection,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_set_selection = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_set_selection(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_set_selection = None;
            },
        );
    }

    pub fn text_input_region_on_platform_text_input_query(
        &mut self,
        handler: crate::action::OnTextInputRegionPlatformTextInputQuery,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_platform_text_input_query = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_platform_text_input_query(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_platform_text_input_query = None;
            },
        );
    }

    pub fn text_input_region_on_platform_text_input_replace_text_in_range_utf16(
        &mut self,
        handler: crate::action::OnTextInputRegionPlatformTextInputReplaceTextInRangeUtf16,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_platform_text_input_replace_text_in_range_utf16 = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_platform_text_input_replace_text_in_range_utf16(&mut self) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_platform_text_input_replace_text_in_range_utf16 = None;
            },
        );
    }

    pub fn text_input_region_on_platform_text_input_replace_and_mark_text_in_range_utf16(
        &mut self,
        handler: crate::action::OnTextInputRegionPlatformTextInputReplaceAndMarkTextInRangeUtf16,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_platform_text_input_replace_and_mark_text_in_range_utf16 = Some(handler);
            },
        );
    }

    pub fn text_input_region_clear_on_platform_text_input_replace_and_mark_text_in_range_utf16(
        &mut self,
    ) {
        self.root_state(
            crate::action::TextInputRegionActionHooks::default,
            |hooks| {
                hooks.on_platform_text_input_replace_and_mark_text_in_range_utf16 = None;
            },
        );
    }

    pub fn key_on_key_down_for(&mut self, element: GlobalElementId, handler: OnKeyDown) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down = Some(handler);
        });
    }

    pub fn key_on_key_down_focused_for(&mut self, element: GlobalElementId, handler: OnKeyDown) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down_focused = Some(handler);
        });
    }

    pub fn key_add_on_key_down_for(&mut self, element: GlobalElementId, handler: OnKeyDown) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down = match hooks.on_key_down.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        prev(host, cx, down) || next(host, cx, down)
                    }))
                }
            };
        });
    }

    pub fn key_prepend_on_key_down_for(&mut self, element: GlobalElementId, handler: OnKeyDown) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down = match hooks.on_key_down.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        next(host, cx, down) || prev(host, cx, down)
                    }))
                }
            };
        });
    }

    pub fn key_clear_on_key_down_for(&mut self, element: GlobalElementId) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down = None;
        });
    }

    pub fn key_clear_on_key_down_focused_for(&mut self, element: GlobalElementId) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down_focused = None;
        });
    }

    pub fn key_on_key_down_capture_for(&mut self, element: GlobalElementId, handler: OnKeyDown) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down_capture = Some(handler);
        });
    }

    pub fn key_add_on_key_down_capture_for(
        &mut self,
        element: GlobalElementId,
        handler: OnKeyDown,
    ) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down_capture = match hooks.on_key_down_capture.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        prev(host, cx, down) || next(host, cx, down)
                    }))
                }
            };
        });
    }

    pub fn key_prepend_on_key_down_capture_for(
        &mut self,
        element: GlobalElementId,
        handler: OnKeyDown,
    ) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down_capture = match hooks.on_key_down_capture.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, down| {
                        next(host, cx, down) || prev(host, cx, down)
                    }))
                }
            };
        });
    }

    pub fn key_clear_on_key_down_capture_for(&mut self, element: GlobalElementId) {
        self.state_for(element, KeyActionHooks::default, |hooks| {
            hooks.on_key_down_capture = None;
        });
    }

    pub fn command_on_command_for(&mut self, element: GlobalElementId, handler: OnCommand) {
        self.state_for(element, CommandActionHooks::default, |hooks| {
            hooks.on_command = Some(handler);
        });
    }

    pub fn action_on_command_for_owner<Owner: Any>(
        &mut self,
        element: GlobalElementId,
        handler: OnCommand,
    ) {
        let owner = TypeId::of::<Owner>();
        self.state_for(element, ActionRouteHooks::default, |hooks| {
            hooks.set_on_command(owner, handler);
        });
    }

    pub fn action_add_on_command_for_owner<Owner: Any>(
        &mut self,
        element: GlobalElementId,
        handler: OnCommand,
    ) {
        let owner = TypeId::of::<Owner>();
        self.state_for(element, ActionRouteHooks::default, |hooks| {
            hooks.add_on_command(owner, handler);
        });
    }

    pub fn action_clear_on_command_for_owner<Owner: Any>(&mut self, element: GlobalElementId) {
        let owner = TypeId::of::<Owner>();
        self.state_for(element, ActionRouteHooks::default, |hooks| {
            hooks.clear_on_command(owner);
        });
    }

    pub fn command_add_on_command_for(&mut self, element: GlobalElementId, handler: OnCommand) {
        self.state_for(element, CommandActionHooks::default, |hooks| {
            hooks.on_command = match hooks.on_command.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, command| {
                        prev(host, cx, command.clone()) || next(host, cx, command)
                    }))
                }
            };
        });
    }

    pub fn command_prepend_on_command_for(&mut self, element: GlobalElementId, handler: OnCommand) {
        self.state_for(element, CommandActionHooks::default, |hooks| {
            hooks.on_command = match hooks.on_command.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, command| {
                        next(host, cx, command.clone()) || prev(host, cx, command)
                    }))
                }
            };
        });
    }

    pub fn command_clear_on_command_for(&mut self, element: GlobalElementId) {
        self.state_for(element, CommandActionHooks::default, |hooks| {
            hooks.on_command = None;
        });
    }

    pub fn command_on_command_availability_for(
        &mut self,
        element: GlobalElementId,
        handler: OnCommandAvailability,
    ) {
        self.state_for(element, CommandAvailabilityActionHooks::default, |hooks| {
            hooks.on_command_availability = Some(handler);
        });
    }

    pub fn action_on_command_availability_for_owner<Owner: Any>(
        &mut self,
        element: GlobalElementId,
        handler: OnCommandAvailability,
    ) {
        let owner = TypeId::of::<Owner>();
        self.state_for(element, ActionRouteHooks::default, |hooks| {
            hooks.set_on_command_availability(owner, handler);
        });
    }

    pub fn action_add_on_command_availability_for_owner<Owner: Any>(
        &mut self,
        element: GlobalElementId,
        handler: OnCommandAvailability,
    ) {
        let owner = TypeId::of::<Owner>();
        self.state_for(element, ActionRouteHooks::default, |hooks| {
            hooks.add_on_command_availability(owner, handler);
        });
    }

    pub fn action_clear_on_command_availability_for_owner<Owner: Any>(
        &mut self,
        element: GlobalElementId,
    ) {
        let owner = TypeId::of::<Owner>();
        self.state_for(element, ActionRouteHooks::default, |hooks| {
            hooks.clear_on_command_availability(owner);
        });
    }

    pub fn command_add_on_command_availability_for(
        &mut self,
        element: GlobalElementId,
        handler: OnCommandAvailability,
    ) {
        self.state_for(element, CommandAvailabilityActionHooks::default, |hooks| {
            hooks.on_command_availability = match hooks.on_command_availability.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, command| {
                        let availability = prev(host, cx.clone(), command.clone());
                        if availability != crate::widget::CommandAvailability::NotHandled {
                            return availability;
                        }
                        next(host, cx, command)
                    }))
                }
            };
        });
    }

    pub fn command_prepend_on_command_availability_for(
        &mut self,
        element: GlobalElementId,
        handler: OnCommandAvailability,
    ) {
        self.state_for(element, CommandAvailabilityActionHooks::default, |hooks| {
            hooks.on_command_availability = match hooks.on_command_availability.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, command| {
                        let availability = next(host, cx.clone(), command.clone());
                        if availability != crate::widget::CommandAvailability::NotHandled {
                            return availability;
                        }
                        prev(host, cx, command)
                    }))
                }
            };
        });
    }

    pub fn command_clear_on_command_availability_for(&mut self, element: GlobalElementId) {
        self.state_for(element, CommandAvailabilityActionHooks::default, |hooks| {
            hooks.on_command_availability = None;
        });
    }

    pub fn timer_on_timer_for(&mut self, element: GlobalElementId, handler: OnTimer) {
        self.state_for(element, TimerActionHooks::default, |hooks| {
            hooks.on_timer = Some(handler);
        });
    }

    pub fn timer_add_on_timer_for(&mut self, element: GlobalElementId, handler: OnTimer) {
        self.state_for(element, TimerActionHooks::default, |hooks| {
            hooks.on_timer = match hooks.on_timer.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, token| {
                        prev(host, cx, token) || next(host, cx, token)
                    }))
                }
            };
        });
    }

    pub fn timer_clear_on_timer_for(&mut self, element: GlobalElementId) {
        self.state_for(element, TimerActionHooks::default, |hooks| {
            hooks.on_timer = None;
        });
    }

    /// Register a component-owned dismiss handler for the current dismissible root element.
    ///
    /// This is intended for overlay policy code that composes
    /// `render_dismissible_root_with_hooks(...)` and
    /// wants full control over dismissal semantics (ADR 0074).
    pub fn dismissible_on_dismiss_request(&mut self, handler: OnDismissRequest) {
        self.root_state(DismissibleActionHooks::default, |hooks| {
            hooks.on_dismiss_request = Some(handler);
        });
    }

    /// Register a component-owned pointer-move observer for the current dismissible root element.
    ///
    /// This is used for overlay policies that need global pointer movement (e.g. submenu
    /// safe-hover corridors) without making the overlay hit-testable outside its content.
    pub fn dismissible_on_pointer_move(&mut self, handler: OnDismissiblePointerMove) {
        self.root_state(DismissibleActionHooks::default, |hooks| {
            hooks.on_pointer_move = Some(handler);
        });
    }

    pub fn dismissible_add_on_dismiss_request(&mut self, handler: OnDismissRequest) {
        self.root_state(DismissibleActionHooks::default, |hooks| {
            hooks.on_dismiss_request = match hooks.on_dismiss_request.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, req| {
                        prev(host, cx, req);
                        next(host, cx, req);
                    }))
                }
            };
        });
    }

    pub fn dismissible_add_on_pointer_move(&mut self, handler: OnDismissiblePointerMove) {
        self.root_state(DismissibleActionHooks::default, |hooks| {
            hooks.on_pointer_move = match hooks.on_pointer_move.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, mv| {
                        prev(host, cx, mv) || next(host, cx, mv)
                    }))
                }
            };
        });
    }

    pub fn dismissible_clear_on_dismiss_request(&mut self) {
        self.root_state(DismissibleActionHooks::default, |hooks| {
            hooks.on_dismiss_request = None;
        });
    }

    pub fn dismissible_clear_on_pointer_move(&mut self) {
        self.root_state(DismissibleActionHooks::default, |hooks| {
            hooks.on_pointer_move = None;
        });
    }

    /// Register a component-owned roving active-change handler for the current roving element.
    ///
    /// This hook is invoked when the roving container changes focus among its children due to
    /// keyboard navigation (arrow keys, Home/End, or typeahead).
    ///
    /// Components can implement “automatic activation” (e.g. Tabs) by updating selection models
    /// here, keeping selection policy out of the runtime (ADR 0074).
    pub fn roving_on_active_change(&mut self, handler: OnRovingActiveChange) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_active_change = Some(handler);
        });
    }

    pub fn roving_add_on_active_change(&mut self, handler: OnRovingActiveChange) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_active_change = match hooks.on_active_change.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, idx| {
                        prev(host, cx, idx);
                        next(host, cx, idx);
                    }))
                }
            };
        });
    }

    pub fn roving_clear_on_active_change(&mut self) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_active_change = None;
        });
    }

    /// Register a component-owned roving typeahead handler for the current roving element.
    ///
    /// When set, the runtime forwards alphanumeric key presses to this handler so components can
    /// decide how typeahead should work (buffering, prefix matching, wrapping, etc.).
    pub fn roving_on_typeahead(&mut self, handler: OnRovingTypeahead) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_typeahead = Some(handler);
        });
    }

    pub fn roving_add_on_typeahead(&mut self, handler: OnRovingTypeahead) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_typeahead = match hooks.on_typeahead.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, it| {
                        prev(host, cx, it.clone()).or_else(|| next(host, cx, it))
                    }))
                }
            };
        });
    }

    pub fn roving_clear_on_typeahead(&mut self) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_typeahead = None;
        });
    }

    pub fn roving_on_key_down(&mut self, handler: OnKeyDown) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_key_down.clear();
            hooks.on_key_down.push(handler);
        });
    }

    pub fn roving_add_on_key_down(&mut self, handler: OnKeyDown) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_key_down.push(handler);
        });
    }

    pub fn roving_clear_on_key_down(&mut self) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_key_down.clear();
        });
    }

    /// Register a component-owned roving navigation handler for the current roving element.
    ///
    /// This is invoked for key down events that bubble through the roving container so component
    /// code can decide which child should become focused (arrow keys, Home/End, etc.).
    pub fn roving_on_navigate(&mut self, handler: OnRovingNavigate) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_navigate = Some(handler);
        });
    }

    pub fn roving_add_on_navigate(&mut self, handler: OnRovingNavigate) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_navigate = match hooks.on_navigate.clone() {
                None => Some(handler),
                Some(prev) => {
                    let next = handler.clone();
                    Some(Arc::new(move |host, cx, it| {
                        match prev(host, cx, it.clone()) {
                            crate::action::RovingNavigateResult::NotHandled => next(host, cx, it),
                            other => other,
                        }
                    }))
                }
            };
        });
    }

    pub fn roving_clear_on_navigate(&mut self) {
        self.root_state(RovingActionHooks::default, |hooks| {
            hooks.on_navigate = None;
        });
    }

    #[track_caller]
    pub fn stack<I>(&mut self, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.stack_props(StackProps::default(), f)
    }

    #[track_caller]
    pub fn stack_props<I>(
        &mut self,
        props: StackProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Stack(props), children)
        })
    }

    #[track_caller]
    pub fn column<I>(&mut self, props: ColumnProps, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Column(props), children)
        })
    }

    #[track_caller]
    pub fn row<I>(&mut self, props: RowProps, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Row(props), children)
        })
    }

    #[track_caller]
    pub fn spacer(&mut self, props: SpacerProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Spacer(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn text(&mut self, text: impl Into<std::sync::Arc<str>>) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Text(TextProps::new(text)), Vec::new())
        })
    }

    #[track_caller]
    pub fn text_props(&mut self, props: TextProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Text(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn styled_text(&mut self, rich: fret_core::AttributedText) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(
                id,
                ElementKind::StyledText(StyledTextProps::new(rich)),
                Vec::new(),
            )
        })
    }

    #[track_caller]
    pub fn styled_text_props(&mut self, props: StyledTextProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::StyledText(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn selectable_text(&mut self, rich: fret_core::AttributedText) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.selectable_text_clear_on_activate_span();
            cx.new_any_element(
                id,
                ElementKind::SelectableText(SelectableTextProps::new(rich)),
                Vec::new(),
            )
        })
    }

    #[track_caller]
    pub fn selectable_text_with_id_props(
        &mut self,
        f: impl FnOnce(&mut Self, GlobalElementId) -> SelectableTextProps,
    ) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.selectable_text_clear_on_activate_span();
            let props = f(cx, id);
            cx.new_any_element(id, ElementKind::SelectableText(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn selectable_text_props(&mut self, props: SelectableTextProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.selectable_text_clear_on_activate_span();
            cx.new_any_element(id, ElementKind::SelectableText(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn text_input(&mut self, props: TextInputProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::TextInput(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn text_input_with_id_props(
        &mut self,
        f: impl FnOnce(&mut Self, GlobalElementId) -> TextInputProps,
    ) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            let props = f(cx, id);
            cx.new_any_element(id, ElementKind::TextInput(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn text_area(&mut self, props: TextAreaProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::TextArea(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn text_area_with_id_props(
        &mut self,
        f: impl FnOnce(&mut Self, GlobalElementId) -> TextAreaProps,
    ) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            let props = f(cx, id);
            cx.new_any_element(id, ElementKind::TextArea(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn resizable_panel_group<I>(
        &mut self,
        props: ResizablePanelGroupProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::ResizablePanelGroup(props), children)
        })
    }

    #[track_caller]
    pub fn image(&mut self, image: fret_core::ImageId) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Image(ImageProps::new(image)), Vec::new())
        })
    }

    #[track_caller]
    pub fn image_props(&mut self, props: ImageProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Image(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn canvas(
        &mut self,
        props: CanvasProps,
        paint: impl for<'p> Fn(&mut CanvasPainter<'p>) + 'static,
    ) -> AnyElement {
        let on_paint: OnCanvasPaint = Arc::new(paint);
        self.scope(|cx| {
            let id = cx.root_id();
            cx.state_for(id, CanvasPaintHooks::default, |hooks| {
                hooks.on_paint = Some(on_paint.clone());
            });
            cx.new_any_element(id, ElementKind::Canvas(props), Vec::new())
        })
    }

    #[cfg(feature = "unstable-retained-bridge")]
    #[track_caller]
    pub fn retained_subtree(
        &mut self,
        props: crate::retained_bridge::RetainedSubtreeProps,
    ) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::RetainedSubtree(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn viewport_surface(&mut self, target: fret_core::RenderTargetId) -> AnyElement {
        self.viewport_surface_props(ViewportSurfaceProps::new(target))
    }

    #[track_caller]
    pub fn viewport_surface_mapped(
        &mut self,
        target: fret_core::RenderTargetId,
        target_px_size: (u32, u32),
        fit: fret_core::ViewportFit,
    ) -> AnyElement {
        self.viewport_surface_props(ViewportSurfaceProps {
            target_px_size,
            fit,
            ..ViewportSurfaceProps::new(target)
        })
    }

    #[track_caller]
    pub fn viewport_surface_props(&mut self, props: ViewportSurfaceProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::ViewportSurface(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn svg_icon(&mut self, svg: SvgSource) -> AnyElement {
        self.svg_icon_props(SvgIconProps::new(svg))
    }

    #[track_caller]
    pub fn svg_icon_props(&mut self, props: SvgIconProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::SvgIcon(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn spinner(&mut self) -> AnyElement {
        self.spinner_props(SpinnerProps::default())
    }

    #[track_caller]
    pub fn spinner_props(&mut self, props: SpinnerProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Spinner(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn hover_region<I>(
        &mut self,
        props: HoverRegionProps,
        f: impl FnOnce(&mut Self, bool) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let hovered = cx.window_state.hovered_hover_region == Some(id);
            let built = f(cx, hovered);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::HoverRegion(props), children)
        })
    }

    #[track_caller]
    pub fn wheel_region<I>(
        &mut self,
        props: crate::element::WheelRegionProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::WheelRegion(props), children)
        })
    }

    #[track_caller]
    pub fn scroll<I>(&mut self, props: ScrollProps, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Scroll(props), children)
        })
    }

    #[track_caller]
    pub fn scrollbar(&mut self, props: ScrollbarProps) -> AnyElement {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.new_any_element(id, ElementKind::Scrollbar(props), Vec::new())
        })
    }

    #[track_caller]
    pub fn virtual_list<F, I>(
        &mut self,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        f: F,
    ) -> AnyElement
    where
        F: FnOnce(&mut Self, &[crate::virtual_list::VirtualItem]) -> I,
        I: IntoIterator<Item = AnyElement>,
    {
        self.virtual_list_with_layout(LayoutStyle::default(), len, options, scroll_handle, f)
    }

    #[track_caller]
    pub fn virtual_list_with_range_extractor<F, I>(
        &mut self,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        range_extractor: impl FnOnce(crate::virtual_list::VirtualRange) -> Vec<usize>,
        f: F,
    ) -> AnyElement
    where
        F: FnOnce(&mut Self, &[crate::virtual_list::VirtualItem]) -> I,
        I: IntoIterator<Item = AnyElement>,
    {
        self.virtual_list_with_layout_and_range_extractor(
            LayoutStyle::default(),
            len,
            options,
            scroll_handle,
            range_extractor,
            f,
        )
    }

    #[track_caller]
    pub fn virtual_list_with_layout<F, I>(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        f: F,
    ) -> AnyElement
    where
        F: FnOnce(&mut Self, &[crate::virtual_list::VirtualItem]) -> I,
        I: IntoIterator<Item = AnyElement>,
    {
        self.virtual_list_with_layout_and_range_extractor(
            layout,
            len,
            options,
            scroll_handle,
            crate::virtual_list::default_range_extractor,
            f,
        )
    }

    #[track_caller]
    pub fn virtual_list_with_layout_and_range_extractor<F, I>(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        range_extractor: impl FnOnce(crate::virtual_list::VirtualRange) -> Vec<usize>,
        f: F,
    ) -> AnyElement
    where
        F: FnOnce(&mut Self, &[crate::virtual_list::VirtualItem]) -> I,
        I: IntoIterator<Item = AnyElement>,
    {
        self.virtual_list_with_layout_and_keys(
            layout,
            len,
            options,
            scroll_handle,
            |i| i as crate::ItemKey,
            range_extractor,
            f,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn virtual_list_with_layout_and_keys<F, I>(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        mut item_key_at: impl FnMut(usize) -> crate::ItemKey,
        range_extractor: impl FnOnce(crate::virtual_list::VirtualRange) -> Vec<usize>,
        f: F,
    ) -> AnyElement
    where
        F: FnOnce(&mut Self, &[crate::virtual_list::VirtualItem]) -> I,
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();

            let scroll_handle = scroll_handle.clone();
            scroll_handle.set_items_count(len);

            let key_cache = match options.measure_mode {
                crate::element::VirtualListMeasureMode::Measured => {
                    crate::element::VirtualListKeyCacheMode::AllKeys
                }
                crate::element::VirtualListMeasureMode::Fixed => options.key_cache,
                crate::element::VirtualListMeasureMode::Known => options.key_cache,
            };

            let range = cx.root_state(VirtualListState::default, |state| {
                let axis = options.axis;
                let (viewport, offset) = match axis {
                    fret_core::Axis::Vertical => (state.viewport_h, state.offset_y),
                    fret_core::Axis::Horizontal => (state.viewport_w, state.offset_x),
                };

                // For large scroll jumps, rendering the full overscan window can produce a
                // one-frame layout spike (we're attaching and solving many item roots at once).
                //
                // Prefer rendering the true visible window for the jump frame and let overscan
                // catch up on subsequent frames.
                let mut overscan_for_range = if scroll_handle.deferred_scroll_to_item().is_some() {
                    0
                } else {
                    options.overscan
                };

                let prev_anchor = if viewport.0 > 0.0 && len > 0 {
                    state.metrics.visible_range(offset, viewport, 0).map(|r| {
                        let idx = r.start_index;
                        let key = if idx >= len {
                            idx as crate::ItemKey
                        } else {
                            match key_cache {
                                crate::element::VirtualListKeyCacheMode::AllKeys => state
                                    .keys
                                    .get(idx)
                                    .copied()
                                    .unwrap_or_else(|| item_key_at(idx)),
                                crate::element::VirtualListKeyCacheMode::VisibleOnly => {
                                    item_key_at(idx)
                                }
                            }
                        };
                        let start = state.metrics.offset_for_index(idx);
                        let offset_in_viewport = Px((offset.0 - start.0).max(0.0));
                        (key, offset_in_viewport)
                    })
                } else {
                    None
                };

                let prev_cfg = (
                    state.metrics.estimate(),
                    state.metrics.gap(),
                    state.metrics.scroll_margin(),
                );
                let cfg = (
                    options.estimate_row_height,
                    options.gap,
                    options.scroll_margin,
                );

                state.metrics.ensure_with_mode(
                    options.measure_mode,
                    len,
                    options.estimate_row_height,
                    options.gap,
                    options.scroll_margin,
                );

                let needs_rebuild = state.items_revision != options.items_revision
                    || state.items_len != len
                    || state.key_cache != key_cache
                    || prev_cfg != cfg;

                if needs_rebuild {
                    state.items_revision = options.items_revision;
                    state.items_len = len;
                    state.key_cache = key_cache;

                    match key_cache {
                        crate::element::VirtualListKeyCacheMode::AllKeys => {
                            state.keys.clear();
                            state.keys.reserve(len);

                            for i in 0..len {
                                let key = item_key_at(i);
                                state.keys.push(key);
                            }
                        }
                        crate::element::VirtualListKeyCacheMode::VisibleOnly => {
                            state.keys.clear();
                        }
                    }

                    state.metrics.sync_keys(&state.keys, options.items_revision);

                    if options.measure_mode == crate::element::VirtualListMeasureMode::Known
                        && let Some(height_at) = options.known_row_height_at.as_ref()
                    {
                        let heights = (0..len).map(|i| height_at(i)).collect::<Vec<_>>();
                        state.metrics.rebuild_from_known_heights(
                            heights,
                            options.estimate_row_height,
                            options.gap,
                            options.scroll_margin,
                        );
                    }

                    if key_cache == crate::element::VirtualListKeyCacheMode::AllKeys {
                        let has_deferred_scroll = scroll_handle.deferred_scroll_to_item().is_some();
                        if !has_deferred_scroll
                            && let Some((key, offset_in_viewport)) = prev_anchor
                            && let Some(index) = state.keys.iter().position(|&k| k == key)
                        {
                            let start = state.metrics.offset_for_index(index);
                            let desired = Px(start.0 + offset_in_viewport.0);
                            let prev = scroll_handle.offset();
                            let clamped = state.metrics.clamp_offset(desired, viewport);
                            match axis {
                                fret_core::Axis::Vertical => {
                                    scroll_handle
                                        .set_offset(fret_core::Point::new(prev.x, clamped));
                                    state.offset_y = clamped;
                                }
                                fret_core::Axis::Horizontal => {
                                    scroll_handle
                                        .set_offset(fret_core::Point::new(clamped, prev.y));
                                    state.offset_x = clamped;
                                }
                            }
                        }
                    }
                }

                let viewport = Px(viewport.0.max(0.0));
                let offset = state.metrics.clamp_offset(offset, viewport);

                state.deferred_scroll_offset_hint = None;

                let mut range = state.render_window_range.filter(|r| {
                    r.count == len && r.overscan == options.overscan && r.start_index <= r.end_index
                });
                if range.is_none() {
                    range = state.window_range.filter(|r| {
                        r.count == len
                            && r.overscan == options.overscan
                            && r.start_index <= r.end_index
                    });
                }

                // When a scroll handle offset changes out-of-band (wheel, inertial scroll, or a
                // component-driven `set_offset`), the handle's current offset may lead the
                // element-local `state.offset_*` which is only updated during layout.
                //
                // If we are rerendering this frame, compute the visible range against the latest
                // scroll handle offset so "window jump" frames can rebuild the correct visible
                // items without requiring a follow-up rerender.
                let mut preview_offset = offset;
                if state.has_final_viewport && viewport.0 > 0.0 && len > 0 {
                    let handle_offset = scroll_handle.offset();
                    let handle_axis = match axis {
                        fret_core::Axis::Vertical => handle_offset.y,
                        fret_core::Axis::Horizontal => handle_offset.x,
                    };
                    let handle_axis = state.metrics.clamp_offset(handle_axis, viewport);
                    if (handle_axis.0 - offset.0).abs() > 0.01 {
                        // If the handle jumps far outside the previously committed visible range,
                        // skip overscan for this render so we don't attach/solve a large window of
                        // off-screen items in a single frame.
                        if overscan_for_range > 0 {
                            let prev_visible = state.metrics.visible_range(offset, viewport, 0);
                            let next_visible =
                                state.metrics.visible_range(handle_axis, viewport, 0);
                            let large_jump = match (prev_visible, next_visible) {
                                (Some(prev), Some(next)) => {
                                    let prev_len = prev
                                        .end_index
                                        .saturating_sub(prev.start_index)
                                        .saturating_add(1);
                                    let threshold = prev_len
                                        .saturating_mul(4)
                                        .max(options.overscan.saturating_mul(8));
                                    next.start_index.abs_diff(prev.start_index) > threshold
                                }
                                _ => {
                                    let delta_px = (handle_axis.0 - offset.0).abs();
                                    delta_px > (viewport.0 * 3.0)
                                }
                            };

                            if large_jump {
                                overscan_for_range = 0;
                                range = None;
                            }
                        }
                        preview_offset = handle_axis;
                    }
                }

                // Preview deferred scroll-to-item requests during render so we compute the correct
                // visible range without consuming the request. The final layout pass will apply
                // the scroll offset and clear the request.
                if state.has_final_viewport
                    && viewport.0 > 0.0
                    && len > 0
                    && let Some((index, strategy)) = scroll_handle.deferred_scroll_to_item()
                {
                    let desired = state
                        .metrics
                        .scroll_offset_for_item(index, viewport, offset, strategy);
                    let desired = state.metrics.clamp_offset(desired, viewport);
                    preview_offset = desired;
                    state.deferred_scroll_offset_hint = Some(desired);
                    range = state
                        .metrics
                        .visible_range(desired, viewport, overscan_for_range);
                }

                if state.has_final_viewport && viewport.0 > 0.0 && len > 0 {
                    let visible = state.metrics.visible_range(preview_offset, viewport, 0);
                    if let (Some(prev), Some(visible)) = (range, visible) {
                        let prev_visible_len = prev
                            .end_index
                            .saturating_sub(prev.start_index)
                            .saturating_add(1);
                        let visible_len = visible
                            .end_index
                            .saturating_sub(visible.start_index)
                            .saturating_add(1);

                        let win_start = prev.start_index.saturating_sub(prev.overscan);
                        let win_end =
                            (prev.end_index + prev.overscan).min(prev.count.saturating_sub(1));
                        let out_of_window =
                            visible.start_index < win_start || visible.end_index > win_end;

                        // If the viewport grows (e.g. after intrinsic probes settle), the stored
                        // render-derived window may under-estimate the visible span while still
                        // appearing "within overscan". Force a one-shot recompute so we don't get
                        // stuck in a too-small window forever under view-cache reuse.
                        if visible_len > prev_visible_len || out_of_window {
                            range = state.metrics.visible_range(
                                preview_offset,
                                viewport,
                                overscan_for_range,
                            );
                        }
                    } else if range.is_none() {
                        range = state.metrics.visible_range(
                            preview_offset,
                            viewport,
                            overscan_for_range,
                        );
                    }
                } else if range.is_none() {
                    range = state
                        .metrics
                        .visible_range(offset, viewport, overscan_for_range);
                }

                state.render_window_range = range;
                range
            });

            let mut indices = range
                .map(range_extractor)
                .unwrap_or_default()
                .into_iter()
                .filter(|&idx| idx < len)
                .collect::<Vec<_>>();
            indices.sort_unstable();
            indices.dedup();

            let visible_items = cx.root_state(VirtualListState::default, |state| {
                indices
                    .iter()
                    .map(|&idx| {
                        let key = if idx >= len {
                            idx as crate::ItemKey
                        } else {
                            match key_cache {
                                crate::element::VirtualListKeyCacheMode::AllKeys => state
                                    .keys
                                    .get(idx)
                                    .copied()
                                    .unwrap_or_else(|| item_key_at(idx)),
                                crate::element::VirtualListKeyCacheMode::VisibleOnly => {
                                    item_key_at(idx)
                                }
                            }
                        };
                        state.metrics.virtual_item(idx, key)
                    })
                    .collect::<Vec<_>>()
            });

            let built = f(cx, &visible_items);
            let children = cx.collect_children(built);
            cx.new_any_element(
                id,
                ElementKind::VirtualList(VirtualListProps {
                    layout,
                    axis: options.axis,
                    len,
                    items_revision: options.items_revision,
                    estimate_row_height: options.estimate_row_height,
                    measure_mode: options.measure_mode,
                    key_cache,
                    overscan: options.overscan,
                    keep_alive: options.keep_alive,
                    scroll_margin: options.scroll_margin,
                    gap: options.gap,
                    scroll_handle,
                    visible_items,
                }),
                children,
            )
        })
    }

    #[track_caller]
    pub fn flex<I>(&mut self, props: FlexProps, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Flex(props), children)
        })
    }

    #[track_caller]
    pub fn roving_flex<I>(
        &mut self,
        props: crate::element::RovingFlexProps,
        f: impl FnOnce(&mut Self) -> I,
    ) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            cx.roving_clear_on_active_change();
            cx.roving_clear_on_typeahead();
            cx.roving_clear_on_key_down();
            cx.roving_clear_on_navigate();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::RovingFlex(props), children)
        })
    }

    #[track_caller]
    pub fn grid<I>(&mut self, props: GridProps, f: impl FnOnce(&mut Self) -> I) -> AnyElement
    where
        I: IntoIterator<Item = AnyElement>,
    {
        self.scope(|cx| {
            let id = cx.root_id();
            let built = f(cx);
            let children = cx.collect_children(built);
            cx.new_any_element(id, ElementKind::Grid(props), children)
        })
    }

    /// Virtualized list helper that enforces stable element identity by entering a keyed scope
    /// for each visible row.
    ///
    /// Prefer this over index-identity list rendering for any dynamic collection that can reorder,
    /// so element-local state (caret/selection/scroll) does not “stick to positions”.
    #[track_caller]
    pub fn virtual_list_keyed(
        &mut self,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl FnMut(usize) -> crate::ItemKey,
        row: impl FnMut(&mut Self, usize) -> AnyElement,
    ) -> AnyElement {
        self.virtual_list_keyed_with_layout(
            LayoutStyle::default(),
            len,
            options,
            scroll_handle,
            key_at,
            row,
        )
    }

    /// Retained-host VirtualList helper (ADR 0192).
    ///
    /// This is an opt-in surface that stores `'static` row callbacks in element-local state so
    /// the runtime can attach/detach row subtrees when a cache root reuses without rerendering.
    #[track_caller]
    pub fn virtual_list_keyed_retained(
        &mut self,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: crate::windowed_surface_host::RetainedVirtualListKeyAtFn,
        row: crate::windowed_surface_host::RetainedVirtualListRowFn<H>,
    ) -> AnyElement
    where
        H: 'static,
    {
        self.virtual_list_keyed_retained_with_layout(
            LayoutStyle::default(),
            len,
            options,
            scroll_handle,
            key_at,
            row,
        )
    }

    #[track_caller]
    pub fn virtual_list_keyed_retained_fn(
        &mut self,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl Fn(usize) -> crate::ItemKey + 'static,
        row: impl for<'b> Fn(&mut ElementContext<'b, H>, usize) -> AnyElement + 'static,
    ) -> AnyElement
    where
        H: 'static,
    {
        self.virtual_list_keyed_retained_with_layout_fn(
            LayoutStyle::default(),
            len,
            options,
            scroll_handle,
            key_at,
            row,
        )
    }

    #[track_caller]
    pub fn virtual_list_keyed_retained_with_layout(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: crate::windowed_surface_host::RetainedVirtualListKeyAtFn,
        row: crate::windowed_surface_host::RetainedVirtualListRowFn<H>,
    ) -> AnyElement
    where
        H: 'static,
    {
        self.virtual_list_keyed_retained_with_layout_and_range_extractor(
            layout,
            len,
            options,
            scroll_handle,
            key_at,
            crate::virtual_list::default_range_extractor,
            row,
        )
    }

    #[track_caller]
    pub fn virtual_list_keyed_retained_with_layout_fn(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl Fn(usize) -> crate::ItemKey + 'static,
        row: impl for<'b> Fn(&mut ElementContext<'b, H>, usize) -> AnyElement + 'static,
    ) -> AnyElement
    where
        H: 'static,
    {
        let key_at: crate::windowed_surface_host::RetainedVirtualListKeyAtFn = Arc::new(key_at);
        let row: crate::windowed_surface_host::RetainedVirtualListRowFn<H> = Arc::new(row);
        self.virtual_list_keyed_retained_with_layout(
            layout,
            len,
            options,
            scroll_handle,
            key_at,
            row,
        )
    }

    #[track_caller]
    #[allow(clippy::too_many_arguments)]
    pub fn virtual_list_keyed_retained_with_layout_and_range_extractor(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: crate::windowed_surface_host::RetainedVirtualListKeyAtFn,
        range_extractor: crate::windowed_surface_host::RetainedVirtualListRangeExtractor,
        row: crate::windowed_surface_host::RetainedVirtualListRowFn<H>,
    ) -> AnyElement
    where
        H: 'static,
    {
        let key_at_for_keys = Arc::clone(&key_at);
        self.virtual_list_with_layout_and_keys(
            layout,
            len,
            options,
            scroll_handle,
            move |i| (key_at_for_keys)(i),
            range_extractor,
            move |cx, items| {
                cx.root_state(
                    crate::windowed_surface_host::RetainedVirtualListHostMarker::default,
                    |_| {},
                );
                // Keep the retained keep-alive bucket's element-local state alive across frames
                // (including view-cache hits) so window shifts can actually reuse previously
                // mounted item subtrees. The actual budget is controlled by `VirtualListProps`.
                cx.root_state(
                    crate::windowed_surface_host::RetainedVirtualListKeepAliveState::default,
                    |_| {},
                );
                cx.root_state(
                    || crate::windowed_surface_host::RetainedVirtualListHostCallbacks::<H> {
                        key_at: Arc::clone(&key_at),
                        row: Arc::clone(&row),
                        range_extractor,
                    },
                    |st| {
                        st.key_at = Arc::clone(&key_at);
                        st.row = Arc::clone(&row);
                        st.range_extractor = range_extractor;
                    },
                );

                items
                    .iter()
                    .copied()
                    .map(|item| {
                        cx.retained_virtual_list_row_any_element(item.key, item.index, &row)
                    })
                    .collect::<Vec<_>>()
            },
        )
    }

    #[track_caller]
    #[allow(clippy::too_many_arguments)]
    pub fn virtual_list_keyed_retained_with_layout_and_range_extractor_fn(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl Fn(usize) -> crate::ItemKey + 'static,
        range_extractor: crate::windowed_surface_host::RetainedVirtualListRangeExtractor,
        row: impl for<'b> Fn(&mut ElementContext<'b, H>, usize) -> AnyElement + 'static,
    ) -> AnyElement
    where
        H: 'static,
    {
        let key_at: crate::windowed_surface_host::RetainedVirtualListKeyAtFn = Arc::new(key_at);
        let row: crate::windowed_surface_host::RetainedVirtualListRowFn<H> = Arc::new(row);
        self.virtual_list_keyed_retained_with_layout_and_range_extractor(
            layout,
            len,
            options,
            scroll_handle,
            key_at,
            range_extractor,
            row,
        )
    }

    #[track_caller]
    pub fn virtual_list_keyed_with_range_extractor(
        &mut self,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl FnMut(usize) -> crate::ItemKey,
        range_extractor: impl FnOnce(crate::virtual_list::VirtualRange) -> Vec<usize>,
        row: impl FnMut(&mut Self, usize) -> AnyElement,
    ) -> AnyElement {
        self.virtual_list_keyed_with_layout_and_range_extractor(
            LayoutStyle::default(),
            len,
            options,
            scroll_handle,
            key_at,
            range_extractor,
            row,
        )
    }

    #[track_caller]
    pub fn virtual_list_keyed_with_layout(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl FnMut(usize) -> crate::ItemKey,
        row: impl FnMut(&mut Self, usize) -> AnyElement,
    ) -> AnyElement {
        self.virtual_list_keyed_with_layout_and_range_extractor(
            layout,
            len,
            options,
            scroll_handle,
            key_at,
            crate::virtual_list::default_range_extractor,
            row,
        )
    }

    #[track_caller]
    #[allow(clippy::too_many_arguments)]
    pub fn virtual_list_keyed_with_layout_and_range_extractor(
        &mut self,
        layout: LayoutStyle,
        len: usize,
        options: VirtualListOptions,
        scroll_handle: &crate::scroll::VirtualListScrollHandle,
        key_at: impl FnMut(usize) -> crate::ItemKey,
        range_extractor: impl FnOnce(crate::virtual_list::VirtualRange) -> Vec<usize>,
        mut row: impl FnMut(&mut Self, usize) -> AnyElement,
    ) -> AnyElement {
        let loc = Location::caller();
        self.virtual_list_with_layout_and_keys(
            layout,
            len,
            options,
            scroll_handle,
            key_at,
            range_extractor,
            |cx, items| {
                if cfg!(debug_assertions) && items.len() > 1 {
                    let mut first_dup: Option<(crate::ItemKey, usize, usize)> = None;
                    let mut seen: HashMap<crate::ItemKey, usize> = HashMap::new();
                    for (pos, item) in items.iter().enumerate() {
                        if first_dup.is_none()
                            && let Some(prev) = seen.insert(item.key, pos)
                        {
                            first_dup = Some((item.key, prev, pos));
                        }
                    }

                    if let Some((key, a, b)) = first_dup {
                        let element_path: Option<String> = {
                            #[cfg(feature = "diagnostics")]
                            {
                                cx.window_state.debug_path_for_element(cx.root_id())
                            }
                            #[cfg(not(feature = "diagnostics"))]
                            {
                                None
                            }
                        };

                        tracing::warn!(
                            file = loc.file(),
                            line = loc.line(),
                            column = loc.column(),
                            key = format_args!("{key:#x}"),
                            first_visible_pos = a,
                            second_visible_pos = b,
                            element_path = element_path.as_deref().unwrap_or("<unknown>"),
                            "duplicate virtual_list item key; element identity may collide"
                        );
                    }
                }

                items
                    .iter()
                    .copied()
                    .map(|item| cx.keyed(item.key, |cx| row(cx, item.index)))
                    .collect::<Vec<_>>()
            },
        )
    }
}