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
use crate::UiHost;
use crate::elements::{ElementContext, GlobalElementId};
use crate::overlay_placement::{Align, AnchoredPanelLayout, AnchoredPanelOptions, Side};
use fret_core::scene::{BlendMode, CustomEffectPyramidRequestV1, Mask, Paint};
use fret_core::{
    AttributedText, CaretAffinity, Color, Corners, Edges, EffectChain, EffectMode, EffectQuality,
    ImageId, KeyCode, NodeId, Px, Rect, RenderTargetId, SemanticsLive, SemanticsOrientation,
    SemanticsRole, Size, SvgFit, TextAlign, TextOverflow, TextStyle, TextStyleRefinement, TextWrap,
    UvRect, ViewportFit,
};
use fret_runtime::{CommandId, Model};
use std::sync::Arc;

use crate::{ResizablePanelGroupStyle, SvgSource, TextAreaStyle, TextInputStyle};

/// Declarative element tree node (ephemeral per frame), keyed by a stable `GlobalElementId`.
///
/// This is the authoring-layer representation described by ADR 0028 / ADR 0039.
///
/// Note: `AnyElement` is intentionally move-only. Reusing the same `AnyElement` value in multiple
/// places (e.g. via cloning) can create duplicate `GlobalElementId`s within a single frame, which
/// violates the element-tree contract and can lead to downstream traversal issues.
#[derive(Debug)]
pub struct AnyElement {
    pub id: GlobalElementId,
    pub kind: ElementKind,
    pub children: Vec<AnyElement>,
    /// Layout-transparent inherited foreground installed on this subtree root.
    ///
    /// This is the non-wrapper equivalent of `ForegroundScope`: descendants that opt into
    /// `currentColor`-style paint inheritance can resolve this value during paint without adding a
    /// new layout node.
    pub inherited_foreground: Option<Color>,
    /// Layout-transparent inherited passive-text typography installed on this subtree root.
    ///
    /// This is consumed by passive text leaves (`Text`, `StyledText`, `SelectableText`) via the
    /// runtime's inherited text-style cascade (ADR 0314) without introducing a layout wrapper.
    pub inherited_text_style: Option<TextStyleRefinement>,
    /// Layout-transparent semantics overrides applied when producing semantics snapshots.
    pub semantics_decoration: Option<SemanticsDecoration>,
    /// Layout-transparent key context identifier used by shortcut/keymap `when` expressions.
    pub key_context: Option<Arc<str>>,
}

impl AnyElement {
    pub fn new(id: GlobalElementId, kind: ElementKind, children: Vec<AnyElement>) -> Self {
        Self {
            id,
            kind,
            children,
            inherited_foreground: None,
            inherited_text_style: None,
            semantics_decoration: None,
            key_context: None,
        }
    }

    /// Attach a subtree-local inherited foreground without introducing a layout wrapper.
    ///
    /// Descendants that support `currentColor` / `IconTheme`-style paint inheritance resolve this
    /// value at paint time.
    pub fn inherit_foreground(mut self, foreground: Color) -> Self {
        self.inherited_foreground = Some(foreground);
        self
    }

    /// Attach a subtree-local inherited passive-text refinement without introducing a layout wrapper.
    ///
    /// Descendants that render passive text (`Text`, `StyledText`, `SelectableText`) resolve this
    /// refinement through the runtime's inherited text-style cascade.
    pub fn inherit_text_style(mut self, refinement: TextStyleRefinement) -> Self {
        match self.inherited_text_style.as_mut() {
            Some(existing) => existing.merge(&refinement),
            None => self.inherited_text_style = Some(refinement),
        }
        self
    }

    /// Attach layout-transparent semantics metadata to this element (ADR 0222).
    ///
    /// Prefer this over wrapping a subtree in `Semantics` when you only need to stamp
    /// `test_id` / `label` / `role` / `value` for diagnostics or UI automation, since `Semantics`
    /// introduces a real layout node.
    ///
    /// ```ignore
    /// use fret_core::SemanticsRole;
    /// use fret_ui::element::SemanticsDecoration;
    ///
    /// // `some_element` is any `AnyElement` produced by your view constructors:
    /// let el = some_element.attach_semantics(
    ///     SemanticsDecoration::default()
    ///         .role(SemanticsRole::Button)
    ///         .label("Save")
    ///         .test_id("toolbar.save"),
    /// );
    /// ```
    pub fn attach_semantics(mut self, decoration: SemanticsDecoration) -> Self {
        self.semantics_decoration = Some(match self.semantics_decoration.take() {
            Some(existing) => existing.merge(decoration),
            None => decoration,
        });
        self
    }

    /// Shorthand for attaching a [`SemanticsDecoration`] without introducing a layout node.
    ///
    /// This is a convenience wrapper over [`AnyElement::attach_semantics`].
    pub fn a11y(self, decoration: SemanticsDecoration) -> Self {
        self.attach_semantics(decoration)
    }

    /// Attach a semantics role override (ARIA `role`-like outcome).
    pub fn a11y_role(self, role: SemanticsRole) -> Self {
        self.a11y(SemanticsDecoration::default().role(role))
    }

    /// Attach a semantics label override (ARIA `aria-label`-like outcome).
    pub fn a11y_label(self, label: impl Into<Arc<str>>) -> Self {
        self.a11y(SemanticsDecoration::default().label(label))
    }

    /// Attach a debug/test-only identifier for diagnostics and deterministic UI automation.
    ///
    /// This is shorthand for attaching a [`SemanticsDecoration`] with `test_id` set.
    ///
    /// ```ignore
    /// let el = some_element.test_id("settings.theme.toggle");
    /// ```
    pub fn test_id(self, test_id: impl Into<Arc<str>>) -> Self {
        self.a11y(SemanticsDecoration::default().test_id(test_id))
    }

    /// Attach a semantics value override (ARIA `aria-valuetext`-like outcome).
    pub fn a11y_value(self, value: impl Into<Arc<str>>) -> Self {
        self.a11y(SemanticsDecoration::default().value(value))
    }

    /// Attach a disabled override (ARIA `aria-disabled`-like outcome).
    pub fn a11y_disabled(self, disabled: bool) -> Self {
        self.a11y(SemanticsDecoration::default().disabled(disabled))
    }

    /// Attach a selected override (ARIA `aria-selected`-like outcome).
    pub fn a11y_selected(self, selected: bool) -> Self {
        self.a11y(SemanticsDecoration::default().selected(selected))
    }

    /// Attach an expanded override (ARIA `aria-expanded`-like outcome).
    pub fn a11y_expanded(self, expanded: bool) -> Self {
        self.a11y(SemanticsDecoration::default().expanded(expanded))
    }

    /// Attach a tri-state checked override (ARIA `aria-checked`-like outcome).
    pub fn a11y_checked(self, checked: Option<bool>) -> Self {
        self.a11y(SemanticsDecoration::default().checked(checked))
    }

    /// Attach a key context identifier to this element for shortcut routing.
    ///
    /// This is a layout-transparent annotation used by `when` expressions via `keyctx.*`.
    pub fn key_context(mut self, key_context: impl Into<Arc<str>>) -> Self {
        self.key_context = Some(key_context.into());
        self
    }
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum ElementKind {
    Container(ContainerProps),
    Semantics(SemanticsProps),
    /// A flex container that also contributes a semantics node with a fixed role.
    ///
    /// This is used by higher-level libraries (e.g. Radix/shadcn ports) to model structural
    /// grouping (`role="group"`) without introducing an extra semantics wrapper layer that would
    /// otherwise be separated from layout.
    SemanticFlex(SemanticFlexProps),
    FocusScope(FocusScopeProps),
    /// A layout wrapper used for frame-lagged container queries (ADR 0231).
    ///
    /// This is paint- and input-transparent. It exists to provide a stable, queryable bounds
    /// snapshot for component-layer "responsive" policies that must adapt to **panel width**
    /// rather than viewport width.
    LayoutQueryRegion(LayoutQueryRegionProps),
    /// A transparent wrapper that gates subtree presence and interactivity.
    ///
    /// This is a mechanism-oriented primitive intended to support Radix-style authoring outcomes
    /// like `forceMount` while still being able to make a subtree non-interactive (click/keyboard)
    /// or fully absent from layout/paint, without deleting the subtree (so per-element state can be
    /// preserved).
    InteractivityGate(InteractivityGateProps),
    /// A transparent wrapper that gates pointer hit-testing for a subtree without affecting focus
    /// traversal or semantics.
    ///
    /// When `hit_test == false`, the subtree remains present for layout/paint and can still
    /// participate in keyboard focus traversal, but pointer hit-testing will ignore the subtree
    /// (click-through behavior).
    ///
    /// This is intended to support editor-grade "peek through" surfaces (ImGui-style
    /// `NoMouseInputs`) without making the subtree inert for keyboard navigation.
    HitTestGate(HitTestGateProps),
    /// A transparent wrapper that gates focus traversal for a subtree without affecting pointer
    /// hit-testing or semantics.
    ///
    /// When `traverse == false`, the subtree remains present for layout/paint and pointer
    /// hit-testing, but focus traversal will not recurse into the subtree.
    ///
    /// This is intended to support editor-grade "disabled but hoverable" surfaces (e.g. tooltips
    /// over disabled items) without requiring authors to restructure hit-testing.
    FocusTraversalGate(FocusTraversalGateProps),
    /// A paint- and input-transparent wrapper that installs a subtree-local foreground color.
    ///
    /// This is the declarative equivalent of CSS `currentColor` inheritance or Flutter's
    /// `IconTheme`/`DefaultTextStyle` *foreground* behavior: descendants that opt into inheriting
    /// foreground color can resolve it from the nearest `ForegroundScope`.
    ///
    /// Note: v2 only covers foreground color. A richer text-style stack (font/size/weight/etc.)
    /// can be layered on later without changing the element tree contract.
    ForegroundScope(ForegroundScopeProps),
    Opacity(OpacityProps),
    /// A scoped post-processing effect group wrapper (ADR 0117).
    EffectLayer(EffectLayerProps),
    /// A scoped backdrop source group wrapper (ADR 0305).
    BackdropSourceGroup(BackdropSourceGroupProps),
    /// A scoped alpha mask layer wrapper (ADR 0239).
    ///
    /// This emits a `SceneOp::PushMask/PopMask` pair around the subtree during painting. The
    /// mask's computation bounds are the wrapper's final layout bounds.
    MaskLayer(MaskLayerProps),
    /// A scoped isolated compositing group wrapper (ADR 0247).
    ///
    /// This emits a `SceneOp::PushCompositeGroup/PopCompositeGroup` pair around the subtree during
    /// painting. The compositing group's computation bounds are the wrapper's final layout bounds.
    CompositeGroup(CompositeGroupProps),
    /// Experimental view-level cache boundary wrapper.
    ///
    /// When enabled by the runtime, this marks a subtree as a cache root for range-replay and
    /// invalidation containment experiments (see `docs/workstreams/gpui-parity-refactor/gpui-parity-refactor.md`).
    ViewCache(ViewCacheProps),
    VisualTransform(VisualTransformProps),
    RenderTransform(RenderTransformProps),
    FractionalRenderTransform(FractionalRenderTransformProps),
    Anchored(AnchoredProps),
    Pressable(PressableProps),
    PointerRegion(PointerRegionProps),
    /// A focusable, text-input-capable event region primitive.
    ///
    /// Unlike `TextInput` / `TextArea`, this does not own an internal text model. It exists as a
    /// mechanism-only building block for ecosystem text surfaces (e.g. code editors) that need
    /// to receive `Event::TextInput` / `Event::Ime` / clipboard events while owning their own
    /// buffer and rendering pipeline.
    TextInputRegion(TextInputRegionProps),
    /// An internal drag event listener region primitive.
    ///
    /// This is a mechanism-only building block: it does not own policy for any particular drag
    /// kind, and is intended to be used by higher-level layers (workspace, docking, etc.).
    InternalDragRegion(InternalDragRegionProps),
    /// An external OS drag-and-drop event listener region primitive.
    ///
    /// This receives `Event::ExternalDrag` (Enter/Over/Drop/Leave) events and is intended to be
    /// used by higher-level layers to implement portable file-drop workflows (ADR 0053).
    ExternalDragRegion(ExternalDragRegionProps),
    RovingFlex(RovingFlexProps),
    Stack(StackProps),
    Column(ColumnProps),
    Row(RowProps),
    Spacer(SpacerProps),
    Text(TextProps),
    StyledText(StyledTextProps),
    SelectableText(SelectableTextProps),
    TextInput(TextInputProps),
    TextArea(TextAreaProps),
    ResizablePanelGroup(ResizablePanelGroupProps),
    VirtualList(VirtualListProps),
    Flex(FlexProps),
    Grid(GridProps),
    Image(ImageProps),
    /// A declarative, leaf canvas element for custom scene emission (ADR 0141).
    Canvas(CanvasProps),
    /// Unstable bridge element for hosting a retained subtree under declarative mount.
    #[cfg(feature = "unstable-retained-bridge")]
    RetainedSubtree(crate::retained_bridge::RetainedSubtreeProps),
    /// Composites an app-owned render target (Tier A; ADR 0007 / ADR 0038 / ADR 0123).
    ViewportSurface(ViewportSurfaceProps),
    SvgIcon(SvgIconProps),
    Spinner(SpinnerProps),
    HoverRegion(HoverRegionProps),
    /// An event-only wheel listener that updates an imperative scroll handle.
    ///
    /// Unlike `Scroll`, this element does not translate its children; it only mutates the provided
    /// `ScrollHandle` and invalidates an optional target.
    WheelRegion(WheelRegionProps),
    Scroll(ScrollProps),
    Scrollbar(ScrollbarProps),
}

#[derive(Debug, Clone, Copy)]
pub struct SemanticFlexProps {
    pub role: SemanticsRole,
    pub flex: FlexProps,
}

/// Per-element pointer state for `PointerRegion`.
#[derive(Debug, Default, Clone)]
pub struct PointerRegionState {
    pub last_down: Option<crate::action::PointerDownCx>,
}

/// A pointer event listener region primitive.
///
/// This is a mechanism-only building block: it does not imply click/activation semantics.
#[derive(Debug, Clone, Copy)]
pub struct PointerRegionProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
    /// When set, `PointerEvent::Move` is dispatched to this region during the Capture phase
    /// (root → target) rather than Bubble.
    ///
    /// This is a mechanism-only knob intended for "gesture arena" style arbitration where a
    /// parent wrapper must observe pointer moves even when a descendant would otherwise stop
    /// bubbling (e.g. pressables capturing/stopping on pointer down).
    ///
    /// When enabled, Bubble-phase handling for `PointerEvent::Move` is skipped to avoid
    /// double-dispatch.
    pub capture_phase_pointer_moves: bool,
}

/// A focusable event region that participates in text input / IME routing.
#[derive(Debug, Clone)]
pub struct TextInputRegionProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
    pub text_boundary_mode_override: Option<fret_runtime::TextBoundaryMode>,
    /// Optional IME cursor area in window visual space.
    ///
    /// When set, this is forwarded to `WindowTextInputSnapshot.ime_cursor_area` while the region
    /// is focused. This is a data-only escape hatch for editor ecosystems that own the geometry
    /// mapping (buffer ↔ rows ↔ caret rect) outside the mechanism layer.
    pub ime_cursor_area: Option<fret_core::Rect>,
    /// Optional accessibility label for this text input region.
    pub a11y_label: Option<Arc<str>>,
    /// Optional accessibility value text for this text input region.
    ///
    /// When present, selection and composition ranges are interpreted as UTF-8 byte offsets within
    /// this value (ADR 0071).
    pub a11y_value: Option<Arc<str>>,
    pub a11y_required: bool,
    pub a11y_invalid: Option<fret_core::SemanticsInvalid>,
    /// Optional selection range (anchor, focus) in UTF-8 byte offsets within `a11y_value`.
    pub a11y_text_selection: Option<(u32, u32)>,
    /// Optional IME composition range (start, end) in UTF-8 byte offsets within `a11y_value`.
    pub a11y_text_composition: Option<(u32, u32)>,
    /// Best-effort surrounding text excerpt for IME backends that support it.
    ///
    /// This SHOULD exclude any active preedit/composing text and SHOULD be limited to
    /// `WindowImeSurroundingText::MAX_TEXT_BYTES`.
    pub ime_surrounding_text: Option<fret_runtime::WindowImeSurroundingText>,
}

/// An internal drag event listener region primitive.
///
/// This is a mechanism-only building block for cross-window and internal drag flows.
#[derive(Debug, Clone, Copy)]
pub struct InternalDragRegionProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
}

/// An external drag event listener region primitive.
///
/// This is a mechanism-only building block for external file drop workflows.
#[derive(Debug, Clone, Copy)]
pub struct ExternalDragRegionProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
}

impl Default for InternalDragRegionProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
        }
    }
}

impl Default for ExternalDragRegionProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
        }
    }
}

impl Default for PointerRegionProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
            capture_phase_pointer_moves: false,
        }
    }
}

impl Default for TextInputRegionProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
            text_boundary_mode_override: None,
            ime_cursor_area: None,
            a11y_label: None,
            a11y_value: None,
            a11y_required: false,
            a11y_invalid: None,
            a11y_text_selection: None,
            a11y_text_composition: None,
            ime_surrounding_text: None,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct LayoutStyle {
    pub size: SizeStyle,
    pub flex: FlexItemStyle,
    pub overflow: Overflow,
    pub margin: MarginEdges,
    pub position: PositionStyle,
    pub inset: InsetStyle,
    pub aspect_ratio: Option<f32>,
    pub grid: GridItemStyle,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MarginEdge {
    Px(Px),
    Fill,
    Fraction(f32),
    Auto,
}

impl Default for MarginEdge {
    fn default() -> Self {
        Self::Px(Px(0.0))
    }
}

impl From<Px> for MarginEdge {
    fn from(px: Px) -> Self {
        Self::Px(px)
    }
}

impl From<Option<Px>> for MarginEdge {
    fn from(px: Option<Px>) -> Self {
        match px {
            Some(px) => Self::Px(px),
            None => Self::Auto,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct MarginEdges {
    pub top: MarginEdge,
    pub right: MarginEdge,
    pub bottom: MarginEdge,
    pub left: MarginEdge,
}

impl MarginEdges {
    pub fn all(edge: MarginEdge) -> Self {
        Self {
            top: edge,
            right: edge,
            bottom: edge,
            left: edge,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Overflow {
    #[default]
    Visible,
    Clip,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PositionStyle {
    /// Default flow position; inset offsets are ignored.
    #[default]
    Static,
    /// Inset offsets tweak the final position without affecting siblings.
    Relative,
    /// Removed from flow and positioned via inset offsets.
    Absolute,
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct InsetStyle {
    pub top: InsetEdge,
    pub right: InsetEdge,
    pub bottom: InsetEdge,
    pub left: InsetEdge,
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum InsetEdge {
    Px(Px),
    Fill,
    Fraction(f32),
    #[default]
    Auto,
}

impl From<Px> for InsetEdge {
    fn from(px: Px) -> Self {
        Self::Px(px)
    }
}

impl From<Option<Px>> for InsetEdge {
    fn from(px: Option<Px>) -> Self {
        match px {
            Some(px) => Self::Px(px),
            None => Self::Auto,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct GridItemStyle {
    pub column: GridLine,
    pub row: GridLine,
    pub align_self: Option<CrossAlign>,
    pub justify_self: Option<CrossAlign>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct GridLine {
    pub start: Option<i16>,
    pub span: Option<u16>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SizeStyle {
    pub width: Length,
    pub height: Length,
    /// Minimum width constraint.
    ///
    /// Percent sizing semantics follow `Length` rules: `Fill`/`Fraction` only resolve under a
    /// definite containing block; otherwise they should behave like `auto` in measurement paths.
    pub min_width: Option<Length>,
    /// Minimum height constraint.
    pub min_height: Option<Length>,
    /// Maximum width constraint.
    pub max_width: Option<Length>,
    /// Maximum height constraint.
    pub max_height: Option<Length>,
}

impl Default for SizeStyle {
    fn default() -> Self {
        Self {
            width: Length::Auto,
            height: Length::Auto,
            min_width: None,
            min_height: None,
            max_width: None,
            max_height: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FlexItemStyle {
    /// Visual order within a flex container.
    ///
    /// This matches the web flexbox `order` property: it affects layout order only and does not
    /// change tree order (e.g. focus navigation that follows element order).
    pub order: i32,
    pub grow: f32,
    pub shrink: f32,
    pub basis: Length,
    pub align_self: Option<CrossAlign>,
}

impl Default for FlexItemStyle {
    fn default() -> Self {
        Self {
            order: 0,
            grow: 0.0,
            // Tailwind/DOM default is `flex-shrink: 1`. Recipes should opt out via
            // `LayoutRefinement::flex_shrink_0()` when needed.
            shrink: 1.0,
            basis: Length::Auto,
            align_self: None,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum Length {
    #[default]
    Auto,
    Px(Px),
    /// Fraction of the containing block size (percent sizing).
    ///
    /// This is expressed as a ratio (e.g. `0.5` for 50%). When the containing block size is not
    /// definite, this should behave like `Auto` (CSS-like percent sizing semantics).
    Fraction(f32),
    Fill,
}

/// A length type for spacing (padding/gap) that can express percent sizing but has no `auto`.
///
/// Taffy resolves percent padding/border against the containing block *width* (inline size),
/// including vertical edges (CSS-like). We mirror that behavior in the declarative bridge by
/// resolving percent spacing only when the containing block width is definite; otherwise it
/// resolves to `0` (definite-only).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SpacingLength {
    Px(Px),
    /// Fraction of the containing block size (percent spacing).
    ///
    /// Expressed as a ratio (e.g. `0.5` for 50%).
    Fraction(f32),
    /// Shorthand for 100% (equivalent intent to `Fraction(1.0)`).
    Fill,
}

impl Default for SpacingLength {
    fn default() -> Self {
        Self::Px(Px(0.0))
    }
}

impl SpacingLength {
    pub const fn px(px: Px) -> Self {
        Self::Px(px)
    }

    pub const fn fraction(fraction: f32) -> Self {
        Self::Fraction(fraction)
    }

    pub const fn fill() -> Self {
        Self::Fill
    }
}

impl From<Px> for SpacingLength {
    fn from(value: Px) -> Self {
        Self::Px(value)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SpacingEdges {
    pub top: SpacingLength,
    pub right: SpacingLength,
    pub bottom: SpacingLength,
    pub left: SpacingLength,
}

impl Default for SpacingEdges {
    fn default() -> Self {
        Self::all(SpacingLength::Px(Px(0.0)))
    }
}

impl SpacingEdges {
    pub const fn all(value: SpacingLength) -> Self {
        Self {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }

    pub const fn symmetric(horizontal: SpacingLength, vertical: SpacingLength) -> Self {
        Self {
            top: vertical,
            right: horizontal,
            bottom: vertical,
            left: horizontal,
        }
    }
}

impl From<Edges> for SpacingEdges {
    fn from(value: Edges) -> Self {
        Self {
            top: SpacingLength::Px(value.top),
            right: SpacingLength::Px(value.right),
            bottom: SpacingLength::Px(value.bottom),
            left: SpacingLength::Px(value.left),
        }
    }
}

/// A low-opinionated container primitive for declarative authoring.
///
/// This is intentionally small and composable: it provides padding and an optional quad background
/// (including border and corner radii) so component-layer recipes can build shadcn-like widgets
/// via composition.
#[derive(Debug, Clone, Copy)]
pub struct ContainerProps {
    pub layout: LayoutStyle,
    pub padding: SpacingEdges,
    pub background: Option<Color>,
    /// Optional paint override for the container background (ADR 0233).
    ///
    /// When set, this takes precedence over `background` and enables gradients/materials for
    /// declarative container chrome.
    pub background_paint: Option<Paint>,
    pub shadow: Option<ShadowStyle>,
    pub border: Edges,
    pub border_color: Option<Color>,
    /// Optional paint override for the container border (ADR 0233).
    ///
    /// When set, this takes precedence over `border_color`.
    pub border_paint: Option<Paint>,
    /// Optional dashed border pattern (v1).
    pub border_dash: Option<fret_core::scene::DashPatternV1>,
    /// Optional focus-visible ring decoration.
    pub focus_ring: Option<RingStyle>,
    /// When true, paint the focus ring even when the element is not focused.
    ///
    /// This is intended for component-layer animation parity with CSS `transition` outcomes
    /// (e.g. `transition-[color,box-shadow]`), where the focus ring can animate out after focus
    /// moves away.
    ///
    /// When `false` (default), the focus ring is painted only while focus-visible is active.
    pub focus_ring_always_paint: bool,
    /// Optional border-color override applied when focus-visible is active.
    ///
    /// This is primarily used for shadcn-style `focus-visible:border-ring` outcomes without
    /// requiring a dedicated "border state" API at the layout layer.
    pub focus_border_color: Option<Color>,
    /// When true, focus state is derived from any focused descendant (focus-within).
    pub focus_within: bool,
    pub corner_radii: Corners,
    /// When true, snap paint bounds to device pixels (policy-only).
    pub snap_to_device_pixels: bool,
}

impl Default for ContainerProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            padding: SpacingEdges::all(SpacingLength::Px(Px(0.0))),
            background: None,
            background_paint: None,
            shadow: None,
            border: Edges::all(Px(0.0)),
            border_color: None,
            border_paint: None,
            border_dash: None,
            focus_ring: None,
            focus_ring_always_paint: false,
            focus_border_color: None,
            focus_within: false,
            corner_radii: Corners::all(Px(0.0)),
            snap_to_device_pixels: false,
        }
    }
}

/// Layout-transparent semantics overrides attached to an existing element (ADR 0222).
///
/// This is primarily intended for diagnostics and UI automation (`test_id`) and for restricted
/// a11y stamping on typed elements without introducing a layout wrapper.
///
/// ```ignore
/// use fret_core::SemanticsRole;
/// use fret_ui::element::SemanticsDecoration;
///
/// let decoration = SemanticsDecoration::default()
///     .role(SemanticsRole::Checkbox)
///     .label("Enable autosave")
///     .checked(Some(true))
///     .test_id("settings.autosave");
///
/// let el = some_element.attach_semantics(decoration);
/// ```
#[derive(Debug, Default, Clone)]
pub struct SemanticsDecoration {
    pub role: Option<SemanticsRole>,
    pub label: Option<Arc<str>>,
    /// Optional role description override (ARIA `aria-roledescription`-like outcome).
    pub role_description: Option<Arc<str>>,
    /// Debug/test-only identifier for deterministic automation.
    ///
    /// This MUST NOT be mapped into platform accessibility name/label fields by default.
    pub test_id: Option<Arc<str>>,
    pub value: Option<Arc<str>>,
    pub disabled: Option<bool>,
    pub read_only: Option<bool>,
    pub required: Option<bool>,
    pub invalid: Option<fret_core::SemanticsInvalid>,
    pub hidden: Option<bool>,
    pub visited: Option<bool>,
    pub multiselectable: Option<bool>,
    pub busy: Option<bool>,
    /// Live region setting (ARIA `aria-live`), applied as a semantics flags override.
    ///
    /// `Some(None)` clears any live region semantics from the underlying element.
    pub live: Option<Option<SemanticsLive>>,
    pub live_atomic: Option<bool>,
    pub selected: Option<bool>,
    pub expanded: Option<bool>,
    /// Tri-state checked override (Some(None) clears; Some(Some(v)) sets to v).
    pub checked: Option<Option<bool>>,
    pub placeholder: Option<Arc<str>>,
    pub url: Option<Arc<str>>,
    /// Optional hierarchy level for outline/tree semantics (1-based).
    pub level: Option<u32>,
    pub orientation: Option<SemanticsOrientation>,
    pub numeric_value: Option<f64>,
    pub min_numeric_value: Option<f64>,
    pub max_numeric_value: Option<f64>,
    pub numeric_value_step: Option<f64>,
    pub numeric_value_jump: Option<f64>,
    pub scroll_x: Option<f64>,
    pub scroll_x_min: Option<f64>,
    pub scroll_x_max: Option<f64>,
    pub scroll_y: Option<f64>,
    pub scroll_y_min: Option<f64>,
    pub scroll_y_max: Option<f64>,
    /// Declarative-only: element ID of the active descendant for composite widgets.
    pub active_descendant_element: Option<u64>,
    /// Declarative-only: element ID of a node which labels this node (`aria-labelledby`).
    pub labelled_by_element: Option<u64>,
    /// Declarative-only: element ID of a node which describes this node (`aria-describedby`).
    pub described_by_element: Option<u64>,
    /// Declarative-only: element ID of a node which this node controls (`aria-controls`).
    pub controls_element: Option<u64>,
    /// Overrides whether this node supports the platform "invoke"/click action.
    ///
    /// This is useful for modeling ARIA patterns like Radix Accordion's `aria-disabled` trigger
    /// state, where the element remains focusable but should not expose an "activate" action.
    pub invokable: Option<bool>,
}

impl SemanticsDecoration {
    /// Merges two decorations, with `other` taking precedence.
    pub fn merge(self, other: Self) -> Self {
        Self {
            role: other.role.or(self.role),
            label: other.label.or(self.label),
            role_description: other.role_description.or(self.role_description),
            test_id: other.test_id.or(self.test_id),
            value: other.value.or(self.value),
            disabled: other.disabled.or(self.disabled),
            read_only: other.read_only.or(self.read_only),
            required: other.required.or(self.required),
            invalid: other.invalid.or(self.invalid),
            hidden: other.hidden.or(self.hidden),
            visited: other.visited.or(self.visited),
            multiselectable: other.multiselectable.or(self.multiselectable),
            busy: other.busy.or(self.busy),
            live: other.live.or(self.live),
            live_atomic: other.live_atomic.or(self.live_atomic),
            selected: other.selected.or(self.selected),
            expanded: other.expanded.or(self.expanded),
            checked: other.checked.or(self.checked),
            placeholder: other.placeholder.or(self.placeholder),
            url: other.url.or(self.url),
            level: other.level.or(self.level),
            orientation: other.orientation.or(self.orientation),
            numeric_value: other.numeric_value.or(self.numeric_value),
            min_numeric_value: other.min_numeric_value.or(self.min_numeric_value),
            max_numeric_value: other.max_numeric_value.or(self.max_numeric_value),
            numeric_value_step: other.numeric_value_step.or(self.numeric_value_step),
            numeric_value_jump: other.numeric_value_jump.or(self.numeric_value_jump),
            scroll_x: other.scroll_x.or(self.scroll_x),
            scroll_x_min: other.scroll_x_min.or(self.scroll_x_min),
            scroll_x_max: other.scroll_x_max.or(self.scroll_x_max),
            scroll_y: other.scroll_y.or(self.scroll_y),
            scroll_y_min: other.scroll_y_min.or(self.scroll_y_min),
            scroll_y_max: other.scroll_y_max.or(self.scroll_y_max),
            active_descendant_element: other
                .active_descendant_element
                .or(self.active_descendant_element),
            labelled_by_element: other.labelled_by_element.or(self.labelled_by_element),
            described_by_element: other.described_by_element.or(self.described_by_element),
            controls_element: other.controls_element.or(self.controls_element),
            invokable: other.invokable.or(self.invokable),
        }
    }

    pub fn role(mut self, role: SemanticsRole) -> Self {
        self.role = Some(role);
        self
    }

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

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

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

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

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

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

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

    pub fn invalid(mut self, invalid: fret_core::SemanticsInvalid) -> Self {
        self.invalid = Some(invalid);
        self
    }

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

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

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

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

    pub fn live(mut self, live: Option<SemanticsLive>) -> Self {
        self.live = Some(live);
        self
    }

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

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

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

    pub fn checked(mut self, checked: Option<bool>) -> Self {
        self.checked = Some(checked);
        self
    }

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

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

    pub fn level(mut self, level: u32) -> Self {
        self.level = Some(level);
        self
    }

    pub fn orientation(mut self, orientation: SemanticsOrientation) -> Self {
        self.orientation = Some(orientation);
        self
    }

    pub fn numeric_value(mut self, value: f64) -> Self {
        self.numeric_value = Some(value);
        self
    }

    pub fn numeric_range(mut self, min: f64, max: f64) -> Self {
        self.min_numeric_value = Some(min);
        self.max_numeric_value = Some(max);
        self
    }

    pub fn numeric_step(mut self, step: f64) -> Self {
        self.numeric_value_step = Some(step);
        self
    }

    pub fn numeric_jump(mut self, jump: f64) -> Self {
        self.numeric_value_jump = Some(jump);
        self
    }

    pub fn scroll_x(mut self, x: f64, min: f64, max: f64) -> Self {
        self.scroll_x = Some(x);
        self.scroll_x_min = Some(min);
        self.scroll_x_max = Some(max);
        self
    }

    pub fn scroll_y(mut self, y: f64, min: f64, max: f64) -> Self {
        self.scroll_y = Some(y);
        self.scroll_y_min = Some(min);
        self.scroll_y_max = Some(max);
        self
    }

    pub fn active_descendant_element(mut self, element: u64) -> Self {
        self.active_descendant_element = Some(element);
        self
    }

    pub fn labelled_by_element(mut self, element: u64) -> Self {
        self.labelled_by_element = Some(element);
        self
    }

    pub fn described_by_element(mut self, element: u64) -> Self {
        self.described_by_element = Some(element);
        self
    }

    pub fn controls_element(mut self, element: u64) -> Self {
        self.controls_element = Some(element);
        self
    }

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

/// A transparent semantics wrapper for structuring the accessibility tree.
///
/// This is intentionally input-transparent (hit-test passes through) and paint-transparent: it
/// only contributes layout and semantics.
///
/// Note: `Semantics` is a real layout wrapper. Do not use it only to stamp `test_id` / labels for
/// UI automation; prefer `AnyElement::attach_semantics` (`SemanticsDecoration`) to avoid subtle
/// layout regressions.
#[derive(Debug, Clone)]
pub struct SemanticsProps {
    pub layout: LayoutStyle,
    pub role: SemanticsRole,
    pub label: Option<Arc<str>>,
    /// Debug/test-only identifier for deterministic automation.
    ///
    /// This MUST NOT be mapped into platform accessibility name/label fields by default.
    pub test_id: Option<Arc<str>>,
    pub value: Option<Arc<str>>,
    pub placeholder: Option<Arc<str>>,
    pub url: Option<Arc<str>>,
    /// Optional hierarchy level for outline/tree semantics (1-based).
    pub level: Option<u32>,
    pub orientation: Option<SemanticsOrientation>,
    pub numeric_value: Option<f64>,
    pub min_numeric_value: Option<f64>,
    pub max_numeric_value: Option<f64>,
    pub numeric_value_step: Option<f64>,
    pub numeric_value_jump: Option<f64>,
    pub scroll_x: Option<f64>,
    pub scroll_x_min: Option<f64>,
    pub scroll_x_max: Option<f64>,
    pub scroll_y: Option<f64>,
    pub scroll_y_min: Option<f64>,
    pub scroll_y_max: Option<f64>,
    /// Whether this semantics wrapper participates in focus traversal.
    ///
    /// Note: this is intentionally separate from pointer hit-testing. `Semantics` remains
    /// input-transparent; use `Pressable` when you need pointer-driven focus.
    pub focusable: bool,
    /// Overrides whether this node supports `SetValue` actions (text or numeric).
    ///
    /// For `TextField` roles, this surfaces as the platform's "set value" action surface.
    ///
    /// For `Slider` roles, this is interpreted as stepper semantics and maps to
    /// Increment/Decrement actions. `SetValue` for sliders is derived conservatively by the
    /// runtime when sufficient numeric metadata is present.
    pub value_editable: Option<bool>,
    pub disabled: bool,
    pub read_only: bool,
    pub required: bool,
    pub invalid: Option<fret_core::SemanticsInvalid>,
    pub hidden: bool,
    pub visited: bool,
    pub multiselectable: bool,
    pub busy: bool,
    pub live: Option<SemanticsLive>,
    pub live_atomic: bool,
    pub selected: bool,
    pub expanded: Option<bool>,
    pub checked: Option<bool>,
    pub active_descendant: Option<NodeId>,
    /// Declarative-only: element ID of a node which labels this node.
    ///
    /// This is an authoring convenience for relationships like `aria-labelledby` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub labelled_by_element: Option<u64>,
    /// Declarative-only: element ID of a node which describes this node.
    ///
    /// This is an authoring convenience for relationships like `aria-describedby` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub described_by_element: Option<u64>,
    /// Declarative-only: element ID of a node which this node controls.
    ///
    /// This is an authoring convenience for relationships like `aria-controls` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub controls_element: Option<u64>,
}

impl Default for SemanticsProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            role: SemanticsRole::Generic,
            label: None,
            test_id: None,
            value: None,
            placeholder: None,
            url: None,
            level: None,
            orientation: None,
            numeric_value: None,
            min_numeric_value: None,
            max_numeric_value: None,
            numeric_value_step: None,
            numeric_value_jump: None,
            scroll_x: None,
            scroll_x_min: None,
            scroll_x_max: None,
            scroll_y: None,
            scroll_y_min: None,
            scroll_y_max: None,
            focusable: false,
            value_editable: None,
            disabled: false,
            read_only: false,
            required: false,
            invalid: None,
            hidden: false,
            visited: false,
            multiselectable: false,
            busy: false,
            live: None,
            live_atomic: false,
            selected: false,
            expanded: None,
            checked: None,
            active_descendant: None,
            labelled_by_element: None,
            described_by_element: None,
            controls_element: None,
        }
    }
}

/// A paint- and input-transparent layout wrapper that records a queryable bounds snapshot.
///
/// This is a mechanism-only primitive: breakpoint tables and hysteresis policies live in the
/// component ecosystem (ADR 0066 / ADR 0231).
#[derive(Debug, Default, Clone)]
pub struct LayoutQueryRegionProps {
    pub layout: LayoutStyle,
    /// Optional name used for diagnostics and audit readability.
    ///
    /// This is not a stable identifier and must not be used for equality.
    pub name: Option<Arc<str>>,
}

/// A transparent focus-scope wrapper that can trap focus traversal within its subtree.
///
/// This is a small, mechanism-oriented primitive intended to support component-owned focus scopes
/// (ADR 0068). It does not imply modal barriers or pointer blocking; it only affects `focus.next`
/// / `focus.previous` command routing when focus is inside the subtree.
#[derive(Debug, Default, Clone, Copy)]
pub struct FocusScopeProps {
    pub layout: LayoutStyle,
    pub trap_focus: bool,
}

/// Gate subtree presence (layout/paint) and interactivity (hit-testing + focus traversal).
///
/// When `present == false`, the subtree remains mounted but is treated like `display: none`:
/// it does not participate in layout, paint, hit-testing, or focus traversal.
///
/// When `present == true` and `interactive == false`, the subtree is still laid out/painted but is
/// inert for pointer and focus traversal (useful for close animations).
#[derive(Debug, Clone, Copy)]
pub struct InteractivityGateProps {
    pub layout: LayoutStyle,
    pub present: bool,
    pub interactive: bool,
}

impl Default for InteractivityGateProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            present: true,
            interactive: true,
        }
    }
}

/// Gate pointer hit-testing for a subtree without affecting focus traversal.
///
/// This is intentionally narrower than `InteractivityGateProps`: it does not change whether the
/// subtree participates in focus traversal or semantics snapshots.
#[derive(Debug, Clone, Copy)]
pub struct HitTestGateProps {
    pub layout: LayoutStyle,
    pub hit_test: bool,
}

impl Default for HitTestGateProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            hit_test: true,
        }
    }
}

/// Gate focus traversal for a subtree without affecting pointer hit-testing.
///
/// This is intentionally narrower than `InteractivityGateProps`: it does not change whether the
/// subtree participates in pointer hit-testing or semantics snapshots.
#[derive(Debug, Clone, Copy)]
pub struct FocusTraversalGateProps {
    pub layout: LayoutStyle,
    pub traverse: bool,
}

impl Default for FocusTraversalGateProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            traverse: true,
        }
    }
}

/// A paint-only opacity group wrapper (ADR 0019).
///
/// This is intentionally layout-only + paint-only: it does not imply semantics beyond its
/// children, and it is input-transparent (hit-test passes through).
#[derive(Debug, Clone, Copy)]
pub struct OpacityProps {
    pub layout: LayoutStyle,
    pub opacity: f32,
}

impl Default for OpacityProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            opacity: 1.0,
        }
    }
}

/// A paint-only foreground scope wrapper (v2).
///
/// This is intentionally layout-only + paint-only: it does not imply semantics beyond its
/// children, and it is input-transparent (hit-test passes through).
#[derive(Debug, Clone, Copy, Default)]
pub struct ForegroundScopeProps {
    pub layout: LayoutStyle,
    pub foreground: Option<Color>,
}

/// Scoped post-processing effect wrapper for declarative element subtrees (ADR 0117).
///
/// This emits a `SceneOp::PushEffect/PopEffect` pair around the subtree during painting. The
/// effect's computation bounds are the wrapper's final layout bounds.
#[derive(Debug, Clone, Copy)]
pub struct EffectLayerProps {
    pub layout: LayoutStyle,
    pub mode: EffectMode,
    pub chain: EffectChain,
    pub quality: EffectQuality,
}

impl Default for EffectLayerProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            mode: EffectMode::FilterContent,
            chain: EffectChain::EMPTY,
            quality: EffectQuality::Auto,
        }
    }
}

/// Scoped backdrop source group wrapper for declarative element subtrees (ADR 0305).
///
/// This emits a `SceneOp::PushBackdropSourceGroupV1/PopBackdropSourceGroup` pair around the
/// subtree during painting. The group's computation bounds are the wrapper's final layout bounds.
#[derive(Debug, Clone, Copy)]
pub struct BackdropSourceGroupProps {
    pub layout: LayoutStyle,
    pub pyramid: Option<CustomEffectPyramidRequestV1>,
    pub quality: EffectQuality,
}

impl Default for BackdropSourceGroupProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            pyramid: None,
            quality: EffectQuality::Auto,
        }
    }
}

/// Scoped alpha mask wrapper for declarative element subtrees (ADR 0239).
///
/// This emits a `SceneOp::PushMask/PopMask` pair around the subtree during painting. The mask's
/// computation bounds are the wrapper's final layout bounds.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MaskLayerProps {
    pub layout: LayoutStyle,
    pub mask: Mask,
}

/// Scoped isolated compositing group wrapper for declarative element subtrees (ADR 0247).
///
/// This emits a `SceneOp::PushCompositeGroup/PopCompositeGroup` pair around the subtree during
/// painting. The group's computation bounds are the wrapper's final layout bounds.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CompositeGroupProps {
    pub layout: LayoutStyle,
    pub mode: BlendMode,
    pub quality: EffectQuality,
}

impl Default for CompositeGroupProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            mode: BlendMode::Over,
            quality: EffectQuality::Auto,
        }
    }
}

/// Experimental cache boundary wrapper for declarative element subtrees.
///
/// This is a mechanism-only primitive intended to support GPUI-style view caching experiments
/// without committing to a stable authoring API.
#[derive(Debug, Clone, Copy, Default)]
pub struct ViewCacheProps {
    pub layout: LayoutStyle,
    /// Whether the subtree should be treated as layout-contained by the runtime when view caching is enabled.
    pub contained_layout: bool,
    /// Explicit cache key for view-cache reuse (experimental).
    ///
    /// The runtime will reuse cached output for this view-cache root only when the computed key is
    /// unchanged. This mirrors GPUI's `ViewCacheKey` gating behavior.
    pub cache_key: u64,
}

/// Paint-only transform wrapper for declarative element subtrees.
///
/// This applies a `SceneOp::PushTransform` / `PopTransform` around the subtree during painting,
/// without affecting layout, hit-testing, or pointer event coordinates.
///
/// This is intentionally similar to GPUI's `with_transformation(...)` semantics for elements like
/// `Svg`: it is useful for spinners and decorative animations, and is cheap to optimize because it
/// does not require inverse mapping during hit-testing.
#[derive(Debug, Clone, Copy, Default)]
pub struct VisualTransformProps {
    pub layout: LayoutStyle,
    /// A transform expressed in the element's local coordinate space.
    ///
    /// The runtime composes this around the element's bounds origin so that local transforms can be
    /// expressed in px relative to the element (e.g. rotate around `Point(Px(w/2), Px(h/2))`).
    pub transform: fret_core::Transform2D,
}

/// Render transform wrapper for declarative element subtrees.
///
/// This applies `Widget::render_transform(...)` for the subtree rooted at this element:
/// - Paint and hit-testing are both transformed.
/// - Pointer event coordinates are mapped through the inverse transform (when invertible).
/// - Layout bounds remain authoritative (this is not a layout transform).
///
/// This is useful for interactive translations (e.g. drag-to-dismiss surfaces) that must keep input
/// aligned with the rendered output.
#[derive(Debug, Clone, Copy, Default)]
pub struct RenderTransformProps {
    pub layout: LayoutStyle,
    pub transform: fret_core::Transform2D,
}

/// Render transform wrapper for declarative element subtrees.
///
/// This is a convenience wrapper for cases where the desired translation is best expressed as a
/// fraction of the element's own laid-out bounds, similar to CSS percentage translate operations.
///
/// This is computed during layout so the first painted frame can use the correct pixel offset.
#[derive(Debug, Clone, Copy, Default)]
pub struct FractionalRenderTransformProps {
    pub layout: LayoutStyle,
    /// Translation in units of the element's own width (e.g. `-1.0` shifts left by one full width).
    pub translate_x_fraction: f32,
    /// Translation in units of the element's own height.
    pub translate_y_fraction: f32,
}

/// Layout-driven anchored placement wrapper for declarative element subtrees (ADR 0103).
///
/// This wrapper computes a placement transform during layout (based on the child's intrinsic
/// size) and applies it via the retained runtime's `Widget::render_transform` hook.
///
/// Unlike `VisualTransformProps`, this affects hit-testing and pointer coordinate mapping.
#[derive(Debug, Clone)]
pub struct AnchoredProps {
    pub layout: LayoutStyle,
    /// Insets applied to the wrapper bounds before placement.
    pub outer_margin: Edges,
    /// Anchor rect in the same coordinate space as the wrapper bounds.
    pub anchor: fret_core::Rect,
    /// Optional anchor element ID to resolve during layout (ADR 0103).
    ///
    /// When set, the layout pass attempts to resolve the element's current-frame bounds and uses
    /// that rect as the anchor. This avoids cross-frame geometry jitter from
    /// `bounds_for_element(...)` / `last_bounds_for_element(...)` queries and better matches GPUI's
    /// layout-driven placement model.
    ///
    /// If the element cannot be resolved (e.g. not mounted yet), `anchor` is used as a fallback.
    pub anchor_element: Option<u64>,
    pub side: Side,
    pub align: Align,
    /// Gap between the anchor and the placed subtree.
    pub side_offset: Px,
    pub options: AnchoredPanelOptions,
    /// Optional output model updated with the computed layout during layout.
    pub layout_out: Option<Model<AnchoredPanelLayout>>,
}

impl Default for AnchoredProps {
    fn default() -> Self {
        let mut layout = LayoutStyle::default();
        layout.size.width = Length::Fill;
        layout.size.height = Length::Fill;

        Self {
            layout,
            outer_margin: Edges::all(Px(0.0)),
            anchor: fret_core::Rect::default(),
            anchor_element: None,
            side: Side::Bottom,
            align: Align::Start,
            side_offset: Px(0.0),
            options: AnchoredPanelOptions::default(),
            layout_out: None,
        }
    }
}

/// One `box-shadow` layer (CSS-style) for component-level elevation recipes.
///
/// This is renderer-friendly: runtimes can approximate blur by drawing multiple expanded quads with
/// alpha falloff (ADR 0060) until we have a true blur pipeline.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShadowLayerStyle {
    pub color: Color,
    pub offset_x: Px,
    pub offset_y: Px,
    /// Blur radius in pixels.
    pub blur: Px,
    /// Spread radius in pixels (can be negative).
    pub spread: Px,
}

/// A low-level drop shadow primitive for component-level elevation recipes.
///
/// Many Tailwind/shadcn recipes are multi-layer shadows (e.g. `shadow-md`), so we support up to two
/// layers without forcing heap allocation (keeps `ContainerProps` `Copy`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShadowStyle {
    pub primary: ShadowLayerStyle,
    pub secondary: Option<ShadowLayerStyle>,
    pub corner_radii: Corners,
}

#[derive(Clone)]
pub struct PressableProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
    /// Whether this pressable is a focus traversal stop (Tab order).
    ///
    /// When `false`, the node can still be focused programmatically (e.g. roving focus),
    /// but it is skipped by the default focus traversal.
    pub focusable: bool,
    pub focus_ring: Option<RingStyle>,
    /// When true, paint the focus ring even when the pressable is not focused.
    ///
    /// This is intended for component-layer animation parity with CSS `transition` outcomes where
    /// focus ring (box-shadow-like) decorations can animate out after focus changes.
    ///
    /// When `false` (default), the focus ring is painted only while focus-visible is active on the
    /// pressable.
    pub focus_ring_always_paint: bool,
    /// Optional override for the bounds used when painting the focus ring.
    ///
    /// Coordinates are **local** to the pressable's origin (i.e. `0,0` is the pressable's top-left),
    /// and are translated into absolute coordinates at paint time.
    ///
    /// This is useful when the pressable is wider than the visual control chrome (e.g. a "row"
    /// pressable that should paint focus ring only around an icon-sized control).
    pub focus_ring_bounds: Option<Rect>,
    pub key_activation: PressableKeyActivation,
    pub a11y: PressableA11y,
}

impl std::fmt::Debug for PressableProps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut out = f.debug_struct("PressableProps");
        out.field("layout", &self.layout)
            .field("enabled", &self.enabled)
            .field("focusable", &self.focusable);

        out.field("focus_ring", &self.focus_ring)
            .field("focus_ring_always_paint", &self.focus_ring_always_paint)
            .field("focus_ring_bounds", &self.focus_ring_bounds)
            .field("key_activation", &self.key_activation)
            .field("a11y", &self.a11y)
            .finish()
    }
}

impl Default for PressableProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
            focusable: true,
            focus_ring: None,
            focus_ring_always_paint: false,
            focus_ring_bounds: None,
            key_activation: PressableKeyActivation::default(),
            a11y: PressableA11y::default(),
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum PressableKeyActivation {
    /// Activate on Enter/NumpadEnter and Space (button-like default).
    #[default]
    EnterAndSpace,
    /// Activate on Enter/NumpadEnter only (link-like).
    EnterOnly,
}

impl PressableKeyActivation {
    pub fn allows(self, key: KeyCode) -> bool {
        match self {
            Self::EnterAndSpace => {
                matches!(key, KeyCode::Enter | KeyCode::NumpadEnter | KeyCode::Space)
            }
            Self::EnterOnly => matches!(key, KeyCode::Enter | KeyCode::NumpadEnter),
        }
    }
}

#[derive(Clone, Default)]
pub struct RovingFlexProps {
    pub flex: FlexProps,
    pub roving: RovingFocusProps,
}

impl std::fmt::Debug for RovingFlexProps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RovingFlexProps")
            .field("flex", &self.flex)
            .field("roving", &self.roving)
            .finish()
    }
}

#[derive(Debug, Clone)]
pub struct RovingFocusProps {
    pub enabled: bool,
    pub wrap: bool,
    pub disabled: Arc<[bool]>,
}

impl Default for RovingFocusProps {
    fn default() -> Self {
        Self {
            enabled: true,
            wrap: true,
            disabled: Arc::from([]),
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct PressableA11y {
    pub role: Option<SemanticsRole>,
    pub label: Option<Arc<str>>,
    /// Optional hierarchy level for outline/tree semantics (1-based).
    pub level: Option<u32>,
    /// Debug/test-only identifier for deterministic automation.
    ///
    /// This MUST NOT be mapped into platform accessibility name/label fields by default.
    pub test_id: Option<Arc<str>>,
    /// When true, suppress exposing this pressable to assistive technologies (aria-hidden).
    ///
    /// This is useful for purely visual affordances (e.g. decorative scroll buttons in Radix
    /// Select) that should remain interactive for pointer users but should not appear in the
    /// accessibility tree.
    pub hidden: bool,
    /// Indicates that the pressable represents a visited link.
    ///
    /// This is a portable approximation of the "visited link" concept in HTML.
    pub visited: bool,
    /// Indicates that this collection supports selecting multiple items.
    ///
    /// This is a portable approximation of ARIA `aria-multiselectable`.
    pub multiselectable: bool,
    pub required: bool,
    pub invalid: Option<fret_core::SemanticsInvalid>,
    pub selected: bool,
    pub expanded: Option<bool>,
    pub checked: Option<bool>,
    pub checked_state: Option<fret_core::SemanticsCheckedState>,
    pub pressed_state: Option<fret_core::SemanticsPressedState>,
    pub active_descendant: Option<NodeId>,
    /// Declarative-only: element ID of a node which labels this node.
    ///
    /// This is an authoring convenience for relationships like `aria-labelledby` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub labelled_by_element: Option<u64>,
    /// Declarative-only: element ID of a node which describes this node.
    ///
    /// This is an authoring convenience for relationships like `aria-describedby` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub described_by_element: Option<u64>,
    /// Declarative-only: element ID of a node which this node controls.
    ///
    /// This is an authoring convenience for relationships like `aria-controls` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub controls_element: Option<u64>,
    pub pos_in_set: Option<u32>,
    pub set_size: Option<u32>,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct PressableState {
    pub hovered: bool,
    pub hovered_raw: bool,
    /// Pointer-hover signal that ignores modal/popup barrier gating.
    ///
    /// When a modal barrier is active (e.g. a popup that blocks underlay input), the UI runtime
    /// suppresses underlay hit-testing and hover for blocked layers. This flag is populated from a
    /// best-effort underlay hit-test performed only when the pointer is not currently over any
    /// active (non-blocked) layer.
    pub hovered_raw_below_barrier: bool,
    pub pressed: bool,
    pub focused: bool,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RingPlacement {
    /// Draw the ring inside the element bounds.
    Inset,
    /// Draw the ring outside the element bounds (best effort; may be clipped by parent clips).
    #[default]
    Outset,
}

/// A simple focus ring decoration, intended for component-layer recipes (e.g. shadcn-style
/// focus-visible ring).
///
/// This is intentionally small and renderer-friendly: it maps to one or two `SceneOp::Quad`
/// operations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RingStyle {
    pub placement: RingPlacement,
    pub width: Px,
    pub offset: Px,
    pub color: Color,
    pub offset_color: Option<Color>,
    pub corner_radii: Corners,
}

#[derive(Debug, Default, Clone, Copy)]
pub struct StackProps {
    pub layout: LayoutStyle,
}

#[derive(Debug, Clone, Copy)]
pub struct ColumnProps {
    pub layout: LayoutStyle,
    pub gap: SpacingLength,
    pub padding: SpacingEdges,
    pub justify: MainAlign,
    pub align: CrossAlign,
}

impl Default for ColumnProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            gap: SpacingLength::Px(Px(0.0)),
            padding: SpacingEdges::all(SpacingLength::Px(Px(0.0))),
            justify: MainAlign::Start,
            align: CrossAlign::Stretch,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct RowProps {
    pub layout: LayoutStyle,
    pub gap: SpacingLength,
    pub padding: SpacingEdges,
    pub justify: MainAlign,
    pub align: CrossAlign,
}

impl Default for RowProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            gap: SpacingLength::Px(Px(0.0)),
            padding: SpacingEdges::all(SpacingLength::Px(Px(0.0))),
            justify: MainAlign::Start,
            align: CrossAlign::Stretch,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MainAlign {
    #[default]
    Start,
    Center,
    End,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CrossAlign {
    Start,
    #[default]
    Center,
    End,
    Stretch,
}

#[derive(Debug, Clone, Copy)]
pub struct SpacerProps {
    pub layout: LayoutStyle,
    pub min: Px,
}

impl Default for SpacerProps {
    fn default() -> Self {
        let mut layout = LayoutStyle::default();
        layout.flex.grow = 1.0;
        layout.flex.shrink = 1.0;
        layout.flex.basis = Length::Px(Px(0.0));
        Self {
            layout,
            min: Px(0.0),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TextProps {
    pub layout: LayoutStyle,
    pub text: std::sync::Arc<str>,
    pub style: Option<TextStyle>,
    pub color: Option<Color>,
    pub wrap: TextWrap,
    pub overflow: TextOverflow,
    pub align: TextAlign,
    /// Policy for handling ink overflow when the line box is fixed (e.g. emoji/CJK fallback).
    ///
    /// This is a mechanism-level escape hatch to avoid visual clipping when parents clip to
    /// rounded corners or other shapes. Callers that want typography-driven layout should prefer
    /// `TextLineHeightPolicy::ExpandToFit` instead.
    pub ink_overflow: TextInkOverflow,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextInkOverflow {
    /// Do not apply any extra padding; tall glyph ink may be clipped if an ancestor clips.
    #[default]
    None,
    /// Adds top/bottom padding to accommodate first/last-line ink extents when available.
    ///
    /// Notes:
    /// - This is best-effort: if ink metrics are unavailable, no padding is applied.
    /// - If the widget is height-constrained, padding may be partially applied (or ignored).
    AutoPad,
}

#[derive(Debug, Clone)]
pub struct StyledTextProps {
    pub layout: LayoutStyle,
    pub rich: AttributedText,
    pub style: Option<TextStyle>,
    /// Base color for glyphs without a per-run override.
    pub color: Option<Color>,
    pub wrap: TextWrap,
    pub overflow: TextOverflow,
    pub align: TextAlign,
    pub ink_overflow: TextInkOverflow,
}

#[derive(Debug, Clone)]
pub struct SelectableTextProps {
    pub layout: LayoutStyle,
    pub rich: AttributedText,
    pub style: Option<TextStyle>,
    /// Base color for glyphs without a per-run override.
    pub color: Option<Color>,
    pub wrap: TextWrap,
    pub overflow: TextOverflow,
    pub align: TextAlign,
    pub ink_overflow: TextInkOverflow,
    /// Optional interactive span ranges (e.g. link spans).
    ///
    /// The runtime owns hit-testing and event routing; component/ecosystem code decides what
    /// activation does via `ElementContext::selectable_text_on_activate_span*` hooks.
    pub interactive_spans: std::sync::Arc<[SelectableTextInteractiveSpan]>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectableTextInteractiveSpan {
    pub range: std::ops::Range<usize>,
    /// A stable, component-defined tag for the span (e.g. a URL for markdown links).
    pub tag: std::sync::Arc<str>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SelectableTextInteractiveSpanBounds {
    pub range: std::ops::Range<usize>,
    pub tag: std::sync::Arc<str>,
    /// Span bounds in local widget coordinates (relative to the widget's bounds origin).
    pub bounds_local: fret_core::Rect,
}

#[derive(Debug, Clone)]
pub struct SelectableTextState {
    pub selection_anchor: usize,
    pub caret: usize,
    pub affinity: CaretAffinity,
    pub preferred_x: Option<Px>,
    pub dragging: bool,
    pub last_pointer_pos: Option<fret_core::Point>,
    pub pointer_down_pos: Option<fret_core::Point>,
    pub pending_span_activation: Option<crate::action::SelectableTextSpanActivation>,
    pub pending_span_click_count: u8,
    pub interactive_span_bounds: Vec<SelectableTextInteractiveSpanBounds>,
}

impl Default for SelectableTextState {
    fn default() -> Self {
        Self {
            selection_anchor: 0,
            caret: 0,
            affinity: CaretAffinity::Downstream,
            preferred_x: None,
            dragging: false,
            last_pointer_pos: None,
            pointer_down_pos: None,
            pending_span_activation: None,
            pending_span_click_count: 0,
            interactive_span_bounds: Vec::new(),
        }
    }
}

#[derive(Clone)]
pub struct TextInputProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
    pub focusable: bool,
    pub model: Model<String>,
    pub a11y_label: Option<std::sync::Arc<str>>,
    pub a11y_role: Option<SemanticsRole>,
    pub test_id: Option<std::sync::Arc<str>>,
    pub placeholder: Option<std::sync::Arc<str>>,
    /// When true, visually obscures the rendered text (e.g. password fields) while keeping the
    /// underlying model value unchanged.
    pub obscure_text: bool,
    pub a11y_required: bool,
    pub a11y_invalid: Option<fret_core::SemanticsInvalid>,
    pub active_descendant: Option<NodeId>,
    /// Declarative-only: element ID of the active descendant for composite widgets.
    ///
    /// This is an authoring convenience for `aria-activedescendant`-style relationships where the
    /// target is another declarative element. The runtime resolves this into a `NodeId` during
    /// semantics snapshot production.
    pub active_descendant_element: Option<u64>,
    /// Declarative-only: element ID of a node which this text input controls.
    ///
    /// This is an authoring convenience for relationships like `aria-controls` where the target
    /// is another declarative element. The runtime resolves this into a `NodeId` during semantics
    /// snapshot production.
    pub controls_element: Option<u64>,
    pub expanded: Option<bool>,
    pub chrome: TextInputStyle,
    /// When true, paints the focus ring even if focus-visible is currently false.
    ///
    /// This exists to support CSS-like `transition-[..., box-shadow]` semantics where the ring
    /// animates out after blur. Policy code is expected to drive ring alpha to zero and set this
    /// flag only while the transition is animating.
    pub focus_ring_always_paint: bool,
    pub text_style: TextStyle,
    pub submit_command: Option<CommandId>,
    pub cancel_command: Option<CommandId>,
}

impl TextInputProps {
    pub fn new(model: Model<String>) -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
            focusable: true,
            model,
            a11y_label: None,
            a11y_role: None,
            test_id: None,
            placeholder: None,
            obscure_text: false,
            a11y_required: false,
            a11y_invalid: None,
            active_descendant: None,
            active_descendant_element: None,
            controls_element: None,
            expanded: None,
            chrome: TextInputStyle::default(),
            focus_ring_always_paint: false,
            text_style: TextStyle::default(),
            submit_command: None,
            cancel_command: None,
        }
    }
}

impl std::fmt::Debug for TextInputProps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextInputProps")
            .field("layout", &self.layout)
            .field("enabled", &self.enabled)
            .field("focusable", &self.focusable)
            .field("model", &"<model>")
            .field("a11y_label", &self.a11y_label.as_ref().map(|s| s.as_ref()))
            .field("a11y_role", &self.a11y_role)
            .field("test_id", &self.test_id.as_ref().map(|s| s.as_ref()))
            .field(
                "placeholder",
                &self.placeholder.as_ref().map(|s| s.as_ref()),
            )
            .field("obscure_text", &self.obscure_text)
            .field("active_descendant_element", &self.active_descendant_element)
            .field("controls_element", &self.controls_element)
            .field("expanded", &self.expanded)
            .field("chrome", &self.chrome)
            .field("focus_ring_always_paint", &self.focus_ring_always_paint)
            .field("text_style", &self.text_style)
            .field("submit_command", &self.submit_command)
            .field("cancel_command", &self.cancel_command)
            .finish()
    }
}

#[derive(Clone)]
pub struct TextAreaProps {
    pub layout: LayoutStyle,
    pub enabled: bool,
    pub focusable: bool,
    pub model: Model<String>,
    pub placeholder: Option<std::sync::Arc<str>>,
    pub a11y_required: bool,
    pub a11y_invalid: Option<fret_core::SemanticsInvalid>,
    pub a11y_label: Option<std::sync::Arc<str>>,
    pub test_id: Option<std::sync::Arc<str>>,
    pub chrome: TextAreaStyle,
    /// When true, paints the focus ring even if focus-visible is currently false.
    ///
    /// This exists to support CSS-like `transition-[..., box-shadow]` semantics where the ring
    /// animates out after blur. Policy code is expected to drive ring alpha to zero and set this
    /// flag only while the transition is animating.
    pub focus_ring_always_paint: bool,
    pub text_style: TextStyle,
    pub min_height: Px,
}

impl TextAreaProps {
    pub fn new(model: Model<String>) -> Self {
        Self {
            layout: LayoutStyle::default(),
            enabled: true,
            focusable: true,
            model,
            placeholder: None,
            a11y_required: false,
            a11y_invalid: None,
            a11y_label: None,
            test_id: None,
            chrome: TextAreaStyle::default(),
            focus_ring_always_paint: false,
            text_style: TextStyle::default(),
            min_height: Px(80.0),
        }
    }
}

impl std::fmt::Debug for TextAreaProps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextAreaProps")
            .field("layout", &self.layout)
            .field("enabled", &self.enabled)
            .field("focusable", &self.focusable)
            .field("model", &"<model>")
            .field(
                "placeholder",
                &self.placeholder.as_ref().map(|s| s.as_ref()),
            )
            .field("a11y_label", &self.a11y_label.as_ref().map(|s| s.as_ref()))
            .field("test_id", &self.test_id.as_ref().map(|s| s.as_ref()))
            .field("chrome", &self.chrome)
            .field("focus_ring_always_paint", &self.focus_ring_always_paint)
            .field("text_style", &self.text_style)
            .field("min_height", &self.min_height)
            .finish()
    }
}

#[derive(Clone)]
pub struct ResizablePanelGroupProps {
    pub layout: LayoutStyle,
    pub axis: fret_core::Axis,
    pub model: Model<Vec<f32>>,
    pub min_px: Vec<Px>,
    pub enabled: bool,
    pub chrome: ResizablePanelGroupStyle,
}

impl ResizablePanelGroupProps {
    pub fn new(axis: fret_core::Axis, model: Model<Vec<f32>>) -> Self {
        let mut layout = LayoutStyle::default();
        layout.size.width = Length::Fill;
        layout.size.height = Length::Fill;

        Self {
            layout,
            axis,
            model,
            min_px: Vec::new(),
            enabled: true,
            chrome: ResizablePanelGroupStyle::default(),
        }
    }
}

impl std::fmt::Debug for ResizablePanelGroupProps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResizablePanelGroupProps")
            .field("layout", &self.layout)
            .field("axis", &self.axis)
            .field("model", &"<model>")
            .field("min_px_len", &self.min_px.len())
            .field("enabled", &self.enabled)
            .field("chrome", &self.chrome)
            .finish()
    }
}

#[derive(Debug, Clone, Copy)]
pub struct ImageProps {
    pub layout: LayoutStyle,
    pub image: ImageId,
    pub fit: ViewportFit,
    pub sampling: fret_core::scene::ImageSamplingHint,
    pub opacity: f32,
    pub uv: Option<UvRect>,
}

impl ImageProps {
    pub fn new(image: ImageId) -> Self {
        Self {
            layout: LayoutStyle::default(),
            image,
            fit: ViewportFit::Stretch,
            sampling: fret_core::scene::ImageSamplingHint::Default,
            opacity: 1.0,
            uv: None,
        }
    }

    pub fn sampling(mut self, sampling: fret_core::scene::ImageSamplingHint) -> Self {
        self.sampling = sampling;
        self
    }
}

#[derive(Debug, Clone, Copy)]
pub struct ViewportSurfaceProps {
    pub layout: LayoutStyle,
    pub target: RenderTargetId,
    pub target_px_size: (u32, u32),
    pub fit: ViewportFit,
    pub opacity: f32,
}

impl ViewportSurfaceProps {
    pub fn new(target: RenderTargetId) -> Self {
        Self {
            layout: LayoutStyle::default(),
            target,
            target_px_size: (1, 1),
            fit: ViewportFit::Stretch,
            opacity: 1.0,
        }
    }
}

/// A declarative leaf canvas element.
///
/// Paint handlers are registered via element-local state (not props) so the element tree can
/// remain `Clone + Debug` (see ADR 0141).
#[derive(Debug, Clone, Copy)]
pub struct CanvasProps {
    pub layout: LayoutStyle,
    pub cache_policy: CanvasCachePolicy,
}

/// Cache tuning for a single hosted resource kind (text/path/svg) within a declarative `Canvas`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CanvasCacheTuning {
    /// How long an unused entry may remain cached (in UI frames).
    pub keep_frames: u64,
    /// Hard cap on cached entries for this resource kind.
    pub max_entries: usize,
}

impl CanvasCacheTuning {
    pub const fn transient() -> Self {
        Self {
            keep_frames: 0,
            max_entries: 0,
        }
    }
}

/// Hosted cache policy for declarative `Canvas` resources.
///
/// This is intentionally numeric-only configuration: it does not encode interaction policy or
/// domain semantics (ADR 0141 / ADR 0128).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CanvasCachePolicy {
    pub text: CanvasCacheTuning,
    pub shared_text: CanvasCacheTuning,
    pub path: CanvasCacheTuning,
    pub svg: CanvasCacheTuning,
}

impl CanvasCachePolicy {
    pub const fn smooth_default() -> Self {
        Self {
            // ~1s at 60fps; reduces prepare/release thrash during scroll/pan.
            text: CanvasCacheTuning {
                keep_frames: 60,
                max_entries: 4096,
            },
            // Shared cache (keyed by content/style/constraints) is useful for repeated labels,
            // but should remain bounded and configurable for large, scroll-driven surfaces.
            //
            // Default preserves the previous hard-coded behavior in `CanvasCache`.
            shared_text: CanvasCacheTuning {
                keep_frames: 120,
                max_entries: 4096,
            },
            path: CanvasCacheTuning {
                keep_frames: 60,
                max_entries: 2048,
            },
            svg: CanvasCacheTuning {
                keep_frames: 60,
                max_entries: 256,
            },
        }
    }
}

impl Default for CanvasCachePolicy {
    fn default() -> Self {
        Self::smooth_default()
    }
}

impl Default for CanvasProps {
    fn default() -> Self {
        let mut layout = LayoutStyle::default();
        layout.size.width = Length::Fill;
        layout.size.height = Length::Fill;
        Self {
            layout,
            cache_policy: CanvasCachePolicy::default(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct SvgIconProps {
    pub layout: LayoutStyle,
    pub svg: SvgSource,
    pub fit: SvgFit,
    pub color: Color,
    /// When true, the icon will use the nearest inherited foreground (if present) during paint.
    ///
    /// When no foreground is inherited, `color` is used as the fallback.
    pub inherit_color: bool,
    pub opacity: f32,
}

impl SvgIconProps {
    pub fn new(svg: SvgSource) -> Self {
        Self {
            layout: LayoutStyle::default(),
            svg,
            fit: SvgFit::Contain,
            color: Color {
                r: 1.0,
                g: 1.0,
                b: 1.0,
                a: 1.0,
            },
            inherit_color: false,
            opacity: 1.0,
        }
    }
}

/// A simple loading spinner primitive.
///
/// This is intentionally low-opinionated and renderer-friendly: it paints a ring of small rounded
/// quads with frame-driven alpha modulation (`Effect::RequestAnimationFrame`).
#[derive(Debug, Clone, Copy)]
pub struct SpinnerProps {
    pub layout: LayoutStyle,
    pub color: Option<Color>,
    pub dot_count: u8,
    /// Phase increment per frame, in dot steps. (`0.0` disables animation.)
    pub speed: f32,
}

impl Default for SpinnerProps {
    fn default() -> Self {
        let mut layout = LayoutStyle::default();
        layout.size.width = Length::Px(Px(16.0));
        layout.size.height = Length::Px(Px(16.0));

        Self {
            layout,
            color: None,
            dot_count: 12,
            speed: 0.2,
        }
    }
}

/// A hover tracking region primitive.
///
/// This is a small substrate building block: it provides a `hovered: bool` signal to component
/// code (via `ElementCx::hover_region(...)`) without imposing click/focus semantics.
#[derive(Debug, Clone, Copy, Default)]
pub struct HoverRegionProps {
    pub layout: LayoutStyle,
}

/// A wheel listener region that mutates a scroll handle without affecting layout.
#[derive(Debug, Clone)]
pub struct WheelRegionProps {
    pub layout: LayoutStyle,
    pub axis: ScrollAxis,
    /// Declarative element id to invalidate when the scroll offset changes.
    pub scroll_target: Option<GlobalElementId>,
    pub scroll_handle: crate::scroll::ScrollHandle,
}

impl Default for WheelRegionProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            axis: ScrollAxis::Y,
            scroll_target: None,
            scroll_handle: crate::scroll::ScrollHandle::default(),
        }
    }
}

impl TextProps {
    pub fn new(text: impl Into<std::sync::Arc<str>>) -> Self {
        Self {
            layout: LayoutStyle::default(),
            text: text.into(),
            style: None,
            color: None,
            wrap: TextWrap::Word,
            overflow: TextOverflow::Clip,
            align: TextAlign::Start,
            ink_overflow: TextInkOverflow::None,
        }
    }

    pub(crate) fn resolved_text_style_with_inherited(
        &self,
        theme: crate::ThemeSnapshot,
        inherited: Option<&fret_core::TextStyleRefinement>,
    ) -> TextStyle {
        crate::text_props::resolve_text_style(theme, self.style.clone(), inherited)
    }

    pub(crate) fn build_text_input_with_style(&self, style: TextStyle) -> fret_core::TextInput {
        crate::text_props::build_text_input_plain(self.text.clone(), style)
    }
}

impl StyledTextProps {
    pub fn new(rich: AttributedText) -> Self {
        Self {
            layout: LayoutStyle::default(),
            rich,
            style: None,
            color: None,
            wrap: TextWrap::Word,
            overflow: TextOverflow::Clip,
            align: TextAlign::Start,
            ink_overflow: TextInkOverflow::None,
        }
    }

    pub(crate) fn resolved_text_style_with_inherited(
        &self,
        theme: crate::ThemeSnapshot,
        inherited: Option<&fret_core::TextStyleRefinement>,
    ) -> TextStyle {
        crate::text_props::resolve_text_style(theme, self.style.clone(), inherited)
    }

    pub(crate) fn build_text_input_with_style(&self, style: TextStyle) -> fret_core::TextInput {
        crate::text_props::build_text_input_attributed(&self.rich, style)
    }
}

impl SelectableTextProps {
    pub fn new(rich: AttributedText) -> Self {
        Self {
            layout: LayoutStyle::default(),
            rich,
            style: None,
            color: None,
            wrap: TextWrap::Word,
            overflow: TextOverflow::Clip,
            align: TextAlign::Start,
            ink_overflow: TextInkOverflow::None,
            interactive_spans: std::sync::Arc::from([]),
        }
    }

    pub(crate) fn resolved_text_style_with_inherited(
        &self,
        theme: crate::ThemeSnapshot,
        inherited: Option<&fret_core::TextStyleRefinement>,
    ) -> TextStyle {
        crate::text_props::resolve_text_style(theme, self.style.clone(), inherited)
    }

    pub(crate) fn build_text_input_with_style(&self, style: TextStyle) -> fret_core::TextInput {
        crate::text_props::build_text_input_attributed(&self.rich, style)
    }
}

#[derive(Debug, Clone, Copy)]
pub struct FlexProps {
    pub layout: LayoutStyle,
    pub direction: fret_core::Axis,
    pub gap: SpacingLength,
    pub padding: SpacingEdges,
    pub justify: MainAlign,
    pub align: CrossAlign,
    pub wrap: bool,
}

impl Default for FlexProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            direction: fret_core::Axis::Horizontal,
            gap: SpacingLength::Px(Px(0.0)),
            padding: SpacingEdges::all(SpacingLength::Px(Px(0.0))),
            justify: MainAlign::Start,
            align: CrossAlign::Stretch,
            wrap: false,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridTrackSizing {
    Auto,
    MinContent,
    MaxContent,
    Px(Px),
    Fr(f32),
    /// `minmax(0, Nfr)` style track sizing for shrinkable content columns.
    Flex(f32),
}

#[derive(Debug, Clone, PartialEq)]
pub struct GridProps {
    pub layout: LayoutStyle,
    pub cols: u16,
    pub rows: Option<u16>,
    /// Explicit per-track column sizing.
    ///
    /// When present and non-empty, this takes precedence over `cols`.
    pub template_columns: Option<Vec<GridTrackSizing>>,
    /// Explicit per-track row sizing.
    ///
    /// When present and non-empty, this takes precedence over `rows`.
    pub template_rows: Option<Vec<GridTrackSizing>>,
    pub gap: SpacingLength,
    /// Grid inline-axis gap.
    ///
    /// When `None`, the runtime falls back to the shared `gap` shorthand.
    pub column_gap: Option<SpacingLength>,
    /// Grid block-axis gap.
    ///
    /// When `None`, the runtime falls back to the shared `gap` shorthand.
    pub row_gap: Option<SpacingLength>,
    pub padding: SpacingEdges,
    pub justify: MainAlign,
    pub align: CrossAlign,
    /// Grid-only inline-axis item alignment (`justify-items`).
    ///
    /// When `None`, the runtime preserves the underlying grid default (`stretch`).
    pub justify_items: Option<CrossAlign>,
}

impl Default for GridProps {
    fn default() -> Self {
        Self {
            layout: LayoutStyle::default(),
            cols: 1,
            rows: None,
            template_columns: None,
            template_rows: None,
            gap: SpacingLength::Px(Px(0.0)),
            column_gap: None,
            row_gap: None,
            padding: SpacingEdges::all(SpacingLength::Px(Px(0.0))),
            justify: MainAlign::Start,
            align: CrossAlign::Stretch,
            justify_items: None,
        }
    }
}

impl GridProps {
    pub fn resolved_column_gap(&self) -> SpacingLength {
        self.column_gap.unwrap_or(self.gap)
    }

    pub fn resolved_row_gap(&self) -> SpacingLength {
        self.row_gap.unwrap_or(self.gap)
    }
}

#[derive(Debug, Clone)]
pub struct VirtualListProps {
    pub layout: LayoutStyle,
    pub axis: fret_core::Axis,
    pub len: usize,
    pub items_revision: u64,
    pub estimate_row_height: Px,
    pub measure_mode: VirtualListMeasureMode,
    pub key_cache: VirtualListKeyCacheMode,
    pub overscan: usize,
    /// Number of off-window items that a retained virtual-list host may keep alive for reuse.
    ///
    /// This is primarily consumed by retained/windowed host implementations (ADR 0177) so window
    /// shifts can reuse previously-mounted item subtrees without forcing the parent cache root to
    /// rerender.
    pub keep_alive: usize,
    pub scroll_margin: Px,
    pub gap: Px,
    pub scroll_handle: crate::scroll::VirtualListScrollHandle,
    pub visible_items: Vec<crate::virtual_list::VirtualItem>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VirtualListMeasureMode {
    /// Performs a measurement pass for all visible items and updates the virtualizer with the
    /// measured sizes. Correct for variable-height items.
    Measured,
    /// Skips the measurement pass and assumes all items have the estimated size.
    /// Intended for fixed-height lists/tables.
    Fixed,
    /// Skips the measurement pass and uses caller-provided per-index row heights.
    ///
    /// This mode is intended for “known-height” virtualization (e.g. fixed-height rows with
    /// occasional deterministic height changes like group headers), where measuring each visible
    /// row would be wasted work.
    ///
    /// Correctness requires that the provided height function matches the rendered row layout.
    Known,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum VirtualListKeyCacheMode {
    /// Cache the full `index -> key` mapping so we can:
    /// - restore scroll anchor across reorder
    /// - provide stable keys to measured virtualization
    #[default]
    AllKeys,
    /// Do not cache `index -> key`. Keys are computed on-demand for visible items only.
    ///
    /// This is intended for very large fixed-height lists (e.g. tables) where caching the full
    /// key map can dominate startup time and memory.
    VisibleOnly,
}

#[derive(Clone)]
pub struct VirtualListOptions {
    pub axis: fret_core::Axis,
    pub items_revision: u64,
    pub estimate_row_height: Px,
    pub measure_mode: VirtualListMeasureMode,
    pub key_cache: VirtualListKeyCacheMode,
    pub overscan: usize,
    pub keep_alive: usize,
    pub scroll_margin: Px,
    pub gap: Px,
    pub known_row_height_at: Option<Arc<dyn Fn(usize) -> Px + Send + Sync>>,
}

impl VirtualListOptions {
    pub fn new(estimate_row_height: Px, overscan: usize) -> Self {
        Self {
            axis: fret_core::Axis::Vertical,
            items_revision: 0,
            estimate_row_height,
            measure_mode: VirtualListMeasureMode::Measured,
            key_cache: VirtualListKeyCacheMode::AllKeys,
            overscan,
            keep_alive: 0,
            scroll_margin: Px(0.0),
            gap: Px(0.0),
            known_row_height_at: None,
        }
    }

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

    pub fn fixed(estimate_row_height: Px, overscan: usize) -> Self {
        Self {
            measure_mode: VirtualListMeasureMode::Fixed,
            ..Self::new(estimate_row_height, overscan)
        }
    }

    pub fn known(
        estimate_row_height: Px,
        overscan: usize,
        height_at: impl Fn(usize) -> Px + Send + Sync + 'static,
    ) -> Self {
        let mut options = Self::new(estimate_row_height, overscan);
        options.measure_mode = VirtualListMeasureMode::Known;
        options.known_row_height_at = Some(Arc::new(height_at));
        options
    }
}

impl std::fmt::Debug for VirtualListOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VirtualListOptions")
            .field("axis", &self.axis)
            .field("items_revision", &self.items_revision)
            .field("estimate_row_height", &self.estimate_row_height)
            .field("measure_mode", &self.measure_mode)
            .field("key_cache", &self.key_cache)
            .field("overscan", &self.overscan)
            .field("keep_alive", &self.keep_alive)
            .field("scroll_margin", &self.scroll_margin)
            .field("gap", &self.gap)
            .field("known_row_height_at", &self.known_row_height_at.is_some())
            .finish()
    }
}

/// Cross-frame element-local state for a virtual list (stored in the element state store).
#[derive(Debug, Default, Clone)]
pub struct VirtualListState {
    pub offset_x: Px,
    pub offset_y: Px,
    pub viewport_w: Px,
    pub viewport_h: Px,
    pub(crate) window_range: Option<crate::virtual_list::VirtualRange>,
    pub(crate) render_window_range: Option<crate::virtual_list::VirtualRange>,
    pub(crate) last_scroll_direction_forward: Option<bool>,
    pub(crate) has_final_viewport: bool,
    pub(crate) deferred_scroll_offset_hint: Option<Px>,
    pub(crate) metrics: crate::virtual_list::VirtualListMetrics,
    pub(crate) items_revision: u64,
    pub(crate) items_len: usize,
    pub(crate) key_cache: VirtualListKeyCacheMode,
    pub(crate) keys: Vec<crate::ItemKey>,
    pub(crate) layout_scratch: VirtualListLayoutScratch,
}

#[derive(Debug, Default, Clone)]
pub(crate) struct VirtualListLayoutScratch {
    pub(crate) measured_updates: Vec<(NodeId, usize, Px)>,
    pub(crate) barrier_roots: Vec<(NodeId, Rect)>,
}

#[derive(Debug, Clone)]
pub struct ScrollProps {
    pub layout: LayoutStyle,
    pub axis: ScrollAxis,
    pub scroll_handle: Option<crate::scroll::ScrollHandle>,
    pub intrinsic_measure_mode: ScrollIntrinsicMeasureMode,
    /// When true, the scroll subtree's paint output depends on the scroll offset in a
    /// windowed/virtualized way (e.g. a single `Canvas` that only paints the visible range).
    ///
    /// In this mode, scroll-handle updates must be allowed to invalidate view-cache reuse so the
    /// subtree can re-render and re-run paint handlers for the new visible window.
    ///
    /// This is a mechanism-only switch; policy lives in ecosystem layers.
    pub windowed_paint: bool,
    /// When true (default), scroll containers probe their content with a very large available size
    /// along the scroll axis to measure the full scrollable extent.
    ///
    /// When false, probing uses the viewport constraints, which allows word-wrapping content while
    /// still permitting scrolling for long unbreakable tokens.
    pub probe_unbounded: bool,
}

impl Default for ScrollProps {
    fn default() -> Self {
        let layout = LayoutStyle {
            overflow: Overflow::Clip,
            ..Default::default()
        };
        Self {
            layout,
            axis: ScrollAxis::Y,
            scroll_handle: None,
            intrinsic_measure_mode: ScrollIntrinsicMeasureMode::Content,
            windowed_paint: false,
            probe_unbounded: true,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollIntrinsicMeasureMode {
    /// Default behavior: scroll measurement probes children (potentially using MaxContent on the
    /// scroll axis when `probe_unbounded` is true).
    Content,
    /// Treat the scroll container as a viewport-sized barrier in intrinsic measurement contexts.
    ///
    /// This avoids recursively measuring large scrollable subtrees (virtualized surfaces, large
    /// tables, code views) during Min/MaxContent measurement passes.
    ///
    /// Note: this affects only `measure()` / intrinsic sizing; final layout under definite
    /// available space is unchanged.
    Viewport,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollAxis {
    X,
    Y,
    Both,
}

impl ScrollAxis {
    pub fn scroll_x(self) -> bool {
        matches!(self, Self::X | Self::Both)
    }

    pub fn scroll_y(self) -> bool {
        matches!(self, Self::Y | Self::Both)
    }
}

/// Cross-frame element-local state for scroll containers.
#[derive(Debug, Default, Clone)]
pub struct ScrollState {
    pub scroll_handle: crate::scroll::ScrollHandle,
    pub(crate) intrinsic_measure_cache: Option<ScrollIntrinsicMeasureCache>,
    pub(crate) pending_extent_probe: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ScrollIntrinsicMeasureCacheKey {
    pub avail_w: u64,
    pub avail_h: u64,
    pub axis: u8,
    pub probe_unbounded: bool,
    pub scale_bits: u32,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct ScrollIntrinsicMeasureCache {
    pub key: ScrollIntrinsicMeasureCacheKey,
    pub max_child: Size,
}

#[derive(Debug, Clone, Copy)]
pub struct ScrollbarStyle {
    pub thumb: Color,
    pub thumb_hover: Color,
    pub thumb_idle_alpha: f32,
    /// Padding (main axis) reserved at both ends of the scrollbar track.
    ///
    /// This is part of Radix ScrollArea's thumb sizing/offset math. Component libraries should set
    /// this to match the visual padding they apply to the scrollbar container (e.g. shadcn/ui v4
    /// uses `p-px`, so `Px(1.0)`).
    pub track_padding: Px,
}

impl Default for ScrollbarStyle {
    fn default() -> Self {
        Self {
            thumb: Color {
                r: 0.35,
                g: 0.38,
                b: 0.45,
                a: 1.0,
            },
            thumb_hover: Color {
                r: 0.45,
                g: 0.50,
                b: 0.60,
                a: 1.0,
            },
            thumb_idle_alpha: 0.65,
            track_padding: Px(1.0),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScrollbarAxis {
    #[default]
    Vertical,
    Horizontal,
}

/// A mechanism-only scrollbar primitive.
///
/// Component libraries decide when to show/hide scrollbars and resolve theme tokens into this
/// style. The runtime owns hit-testing, thumb/track interactions, and paints using the resolved
/// style.
#[derive(Debug, Clone, Default)]
pub struct ScrollbarProps {
    pub layout: LayoutStyle,
    pub axis: ScrollbarAxis,
    /// Declarative element id for the associated scroll container, if any.
    ///
    /// When provided, the scrollbar will invalidate the target node's layout/paint when the
    /// scroll handle offset changes (e.g. thumb drag or track paging).
    pub scroll_target: Option<GlobalElementId>,
    pub scroll_handle: crate::scroll::ScrollHandle,
    pub style: ScrollbarStyle,
}

/// Cross-frame element-local state for scrollbars.
#[derive(Debug, Default, Clone)]
pub struct ScrollbarState {
    pub dragging_thumb: bool,
    pub drag_start_pointer: Px,
    pub drag_start_offset: Px,
    pub drag_baseline_viewport: Option<Px>,
    pub drag_baseline_content: Option<Px>,
    pub hovered: bool,
}

/// Authoring conversion boundary (ADR 0039).
///
/// Most application code does not implement this directly; component crates typically expose
/// ergonomic constructors that return `AnyElement` (or helpers that build `Elements`).
pub trait IntoElement {
    fn into_element(self, id: GlobalElementId) -> AnyElement;
}

/// A small owned collection wrapper for element lists.
///
/// This is intended for authoring-facing APIs that want an "iterator-friendly" return type without
/// forcing callers into `Vec<AnyElement>` as the only option.
///
/// This type is commonly used as a view return value (e.g. `ViewElements` in `fret-bootstrap`).
#[derive(Debug, Default)]
pub struct Elements(pub Vec<AnyElement>);

impl Elements {
    pub fn new(children: impl IntoIterator<Item = AnyElement>) -> Self {
        Self(children.into_iter().collect())
    }

    pub fn into_vec(self) -> Vec<AnyElement> {
        self.0
    }
}

impl From<Vec<AnyElement>> for Elements {
    fn from(value: Vec<AnyElement>) -> Self {
        Self(value)
    }
}

impl From<AnyElement> for Elements {
    fn from(value: AnyElement) -> Self {
        Self::new([value])
    }
}

impl<const N: usize> From<[AnyElement; N]> for Elements {
    fn from(value: [AnyElement; N]) -> Self {
        Self::new(value)
    }
}

impl std::iter::FromIterator<AnyElement> for Elements {
    fn from_iter<T: IntoIterator<Item = AnyElement>>(iter: T) -> Self {
        Self::new(iter)
    }
}

impl std::ops::Deref for Elements {
    type Target = Vec<AnyElement>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for Elements {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl IntoIterator for Elements {
    type Item = AnyElement;
    type IntoIter = std::vec::IntoIter<AnyElement>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Elements {
    type Item = &'a AnyElement;
    type IntoIter = std::slice::Iter<'a, AnyElement>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a mut Elements {
    type Item = &'a mut AnyElement;
    type IntoIter = std::slice::IterMut<'a, AnyElement>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}

/// Authoring helper for collecting iterator-produced child elements.
///
/// This exists to reduce boilerplate after switching common `children: Vec<AnyElement>` APIs to
/// accept `IntoIterator<Item = AnyElement>` (e.g. `ElementContext::{row,column}`), where the target
/// collection type is no longer implied by the callee.
///
/// Example:
/// `let children = (0..10).map(|i| cx.text(format!("row-{i}"))).elements();`
pub trait AnyElementIterExt: Iterator<Item = AnyElement> + Sized {
    fn elements(self) -> Vec<AnyElement> {
        self.collect()
    }

    fn elements_owned(self) -> Elements {
        self.collect::<Elements>()
    }
}

impl<T> AnyElementIterExt for T where T: Iterator<Item = AnyElement> + Sized {}

impl IntoElement for AnyElement {
    fn into_element(self, _id: GlobalElementId) -> AnyElement {
        self
    }
}

impl IntoElement for TextProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::Text(self), Vec::new())
    }
}

impl IntoElement for StyledTextProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::StyledText(self), Vec::new())
    }
}

impl IntoElement for SelectableTextProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::SelectableText(self), Vec::new())
    }
}

impl IntoElement for ImageProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::Image(self), Vec::new())
    }
}

impl IntoElement for ViewportSurfaceProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::ViewportSurface(self), Vec::new())
    }
}

impl IntoElement for SvgIconProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::SvgIcon(self), Vec::new())
    }
}

impl IntoElement for ScrollProps {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        AnyElement::new(id, ElementKind::Scroll(self), Vec::new())
    }
}

impl IntoElement for std::sync::Arc<str> {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        TextProps::new(self).into_element(id)
    }
}

impl IntoElement for &'static str {
    fn into_element(self, id: GlobalElementId) -> AnyElement {
        TextProps::new(self).into_element(id)
    }
}

/// Stateful view authoring layer (ADR 0039).
pub trait Render {
    fn render<H: UiHost>(&mut self, cx: &mut ElementContext<'_, H>) -> AnyElement;
}

/// Stateless component authoring layer (ADR 0039).
pub trait RenderOnce {
    fn render_once<H: UiHost>(self, cx: &mut ElementContext<'_, H>) -> AnyElement;
}

#[cfg(test)]
mod default_semantics_tests {
    use super::*;

    #[test]
    fn flex_props_default_width_is_auto() {
        assert_eq!(FlexProps::default().layout.size.width, Length::Auto);
    }

    #[test]
    fn length_default_is_auto() {
        assert_eq!(Length::default(), Length::Auto);
    }

    #[test]
    fn scroll_props_default_probe_unbounded_is_true() {
        assert!(ScrollProps::default().probe_unbounded);
    }
}