kui-core 0.1.0-alpha.45

kui contract: flat per-frame tree, clay-style flex layout, text stack, events as data, quad display list
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
//! [`NodeSpec`] and [`TextStyle`]: everything a node and a text declare,
//! as plain data with a builder.
//!
//! A `NodeSpec` is the contract every frontend lowers into, whether a Rust
//! builder chain, a Lua table or a JSX element. It groups the layout
//! ([`LayoutSpec`]: sizing, direction, padding, gap, alignment, overflow),
//! the look ([`VisualStyle`]: background, border, radius, shadow, opacity)
//! and, boxed because most nodes declare none of it, the events, animation,
//! accessibility and interaction styling. Every builder method sets one of
//! those fields; the field docs below say what each means.
//!
//! ```rust
//! use kui_core::{Align, Color, NodeSpec, Sizing, TextStyle, TextWrap};
//!
//! // A card: grows across its parent, fits its content down, 12 px padding
//! // and gap, rounded, with a hover background and a click payload.
//! let card = NodeSpec::column()
//!     .width(Sizing::GROW)
//!     .pad(12.0)
//!     .gap(8.0)
//!     .bg(Color::hex(0x1e2230ff))
//!     .hover_bg(Color::hex(0x262b3aff))
//!     .radius(8.0)
//!     .on_click("open-card");
//!
//! // A toolbar row: fixed height, children centred across it.
//! let toolbar = NodeSpec::row().size(Sizing::GROW, 36.0).cross_align(Align::Center);
//!
//! // A one-line title, cut with an ellipsis when it does not fit.
//! let title = TextStyle::new(16.0).ellipsis().color(Color::WHITE);
//! let code = TextStyle::new(13.0).mono().wrap(TextWrap::Glyph);
//!
//! assert_eq!(card.layout.padding.l, 12.0);
//! assert!(card.events().on_click.is_some());
//! assert_eq!(toolbar.layout.height, Sizing::Fixed(36.0));
//! assert_eq!(title.max_lines, 0); // `ellipsis` alone means one line
//! assert!(title.ellipsis && code.wrap == TextWrap::Glyph);
//! ```

use crate::anim::{Easing, Repeat, Transition};
use crate::color::Color;
use crate::cursor::CursorShape;
use crate::enter::Enter;
use crate::geom::Edges;
use crate::input::Buttons;
use crate::keyframes::Keyframe;
use crate::value::Value;
use crate::window::{WindowButton, WindowRole};

pub use crate::access::{Label, Live, Role};

/// How a node sizes one axis. A plain number converts to `Fixed`, so
/// `.width(120.0)` and `.width(Sizing::Fixed(120.0))` are the same.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Sizing {
    /// Size to content.
    #[default]
    Fit,
    /// Share leftover space, weighted by factor.
    Grow(f32),
    /// Absolute logical pixels.
    Fixed(f32),
    /// Fraction of the parent's content box (0.0..=1.0).
    Percent(f32),
    /// A size expression resolved against the parent's content box, the
    /// box a `Percent` takes its cut of: `"clamp(400px, 80%, 1000px)"`
    /// (see [`crate::calc`]). Layout treats it as it treats a `Percent`:
    /// nothing in the fit pass, its size once the parent's is known, and
    /// a parent that overflows shrinks it as it would one.
    Calc(crate::calc::Calc),
}

/// What a `min_width` / `max_width` / `min_height` / `max_height`
/// declares: px, the node's own fit size (a min only), or a size
/// expression that layout resolves against the parent's content box when
/// it sizes the node. Until then a calc bound clamps like none, as a
/// percentage clamp does in CSS's intrinsic sizing.
///
/// A calc clamp rides in the clamp's own `f32` as a negative, the way
/// [`Min::FIT`] does (`min_w` below -1, [`Min::calc`]; `max_w` below 0,
/// [`max_calc`]), and layout writes the resolved px over it. A reader
/// after layout reads a number; one before it goes through
/// [`LayoutSpec::max_w_px`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Bound {
    Px(f32),
    Fit,
    Calc(crate::calc::Calc),
}

/// A ceiling that is a size expression, as `max_w` / `max_h` hold it
/// until layout resolves it: -1 minus its number.
pub fn max_of_calc(c: crate::calc::Calc) -> f32 {
    -1.0 - c.id() as f32
}

/// A px ceiling as `max_w` / `max_h` hold it: never below zero, so a
/// negative there is only ever [`max_of_calc`]'s. A negative or `NaN`
/// ceiling is a ceiling of 0. Every binding's max clamp reaches the field
/// through [`NodeSpec::max_width`] / [`NodeSpec::max_height`], which call
/// this.
pub fn px_ceiling(px: f32) -> f32 {
    // `f32::max` takes the other operand over a `NaN`.
    px.max(0.0)
}

/// The size expression a `max_w` / `max_h` waits on, if it is one.
pub fn max_calc(v: f32) -> Option<crate::calc::Calc> {
    (v < 0.0)
        .then(|| crate::calc::Calc::from_id((-v - 1.0) as u32))
        .flatten()
}

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

impl From<Min> for Bound {
    fn from(m: Min) -> Self {
        if m.is_fit() {
            Bound::Fit
        } else if let Some(c) = m.as_calc() {
            Bound::Calc(c)
        } else if m.is_auto() {
            // Undeclared stays undeclared through `min_width`.
            Bound::Px(-0.0)
        } else {
            Bound::Px(m.resolved())
        }
    }
}

/// A lower clamp on one axis: a number of logical px, or the node's own
/// fit size on that axis ([`Min::FIT`], `minWidth: "fit"` in the
/// bindings). `FIT` is what lets a `Grow` child keep a content floor, like
/// CSS's `flex: 1 0 auto`: tabs split a bar evenly while they fit and sit
/// at their label's width, scrolling, once they do not. Layout resolves it
/// to a number in the fit pass of its axis, so every later clamp reads
/// one; until then it clamps like no floor at all.
///
/// Undeclared is [`Min::AUTO`], which clamps as 0 everywhere but one
/// place: a child giving in an overflowing row that holds a share of the
/// room, where it is CSS's `min-width: auto`, the child's min-content. A
/// declared 0 (`Min::px(0.0)`) is no floor there either, as CSS's
/// `min-width: 0` is how a flex item is let go below its content.
///
/// Stored as one `f32` with `FIT` and a calc as negatives (the form the
/// C struct's `min_w` takes too), because `LayoutSpec` is copied per node
/// per frame.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Min(f32);

impl Default for Min {
    fn default() -> Self {
        Min::AUTO
    }
}

impl Min {
    /// The node's own fit size on this axis.
    pub const FIT: Min = Min(-1.0);

    /// No floor declared: the node's min-content where a share of the room
    /// gives in CSS's way and down a column of fit children; 0 across a
    /// run of fit children alone, across a column, where a fit node is
    /// held to the column's box, and for a node that scrolls or clips.
    /// Negative zero, so it is 0 to every clamp and to `==`, and told
    /// apart from a declared 0 by its sign alone ([`Min::is_auto`]).
    pub const AUTO: Min = Min(-0.0);

    /// A floor of `v` logical px; a negative (or `NaN`) is a floor of 0,
    /// declared — no automatic one either.
    pub fn px(v: f32) -> Min {
        Min(if v > 0.0 { v } else { 0.0 })
    }

    /// Whether no floor was declared ([`Min::AUTO`]).
    pub fn is_auto(self) -> bool {
        self.0 == 0.0 && self.0.is_sign_negative()
    }

    /// Whether this is the unresolved fit floor.
    pub fn is_fit(self) -> bool {
        self.0 == Min::FIT.0
    }

    /// A floor that is a size expression, until layout resolves it: -2
    /// minus its number, below `FIT`'s -1.
    pub fn calc(c: crate::calc::Calc) -> Min {
        Min(-2.0 - c.id() as f32)
    }

    /// The size expression this floor waits on, if it is one.
    pub fn as_calc(self) -> Option<crate::calc::Calc> {
        (self.0 <= -2.0)
            .then(|| crate::calc::Calc::from_id((-self.0 - 2.0) as u32))
            .flatten()
    }

    /// Whether layout has yet to resolve this floor — a `FIT` or a calc,
    /// the negatives — without asking the table which calc it is.
    pub(crate) fn deferred(self) -> bool {
        self.0 < 0.0
    }

    /// The clamp as a number: the px it holds, or 0 for a `FIT` or a calc
    /// layout has not resolved yet (nothing to floor at).
    pub fn resolved(self) -> f32 {
        if self.0 > 0.0 { self.0 } else { 0.0 }
    }
}

impl From<f32> for Min {
    fn from(v: f32) -> Self {
        Min::px(v)
    }
}

/// A number is that many logical px, so `.width(120.0)` is
/// `.width(Sizing::Fixed(120.0))`, the way `min_width(120.0)` already read.
impl From<f32> for Sizing {
    fn from(px: f32) -> Self {
        Sizing::Fixed(px)
    }
}

impl Sizing {
    /// `Grow(1.0)`: an equal share of the leftover space, the weight
    /// nearly every grow declares.
    pub const GROW: Sizing = Sizing::Grow(1.0);
}

impl Sizing {
    /// The sizing the way a spec spells it — `fit`, `grow(1)`, `120px`,
    /// `50%` — for a reader: the devtools' inspector and a `nodes()` row.
    pub fn describe(self) -> String {
        match self {
            Sizing::Fit => "fit".into(),
            Sizing::Grow(w) => format!("grow({w})"),
            Sizing::Fixed(px) => format!("{px}px"),
            Sizing::Percent(p) => format!("{}%", p * 100.0),
            Sizing::Calc(c) => c.describe(),
        }
    }

    /// The animatable number inside: a grow factor, a px size, a fraction.
    /// None for `Fit` and a `Calc`, which have nothing to ease.
    pub fn amount(self) -> Option<f32> {
        match self {
            Sizing::Fit | Sizing::Calc(_) => None,
            Sizing::Grow(v) | Sizing::Fixed(v) | Sizing::Percent(v) => Some(v),
        }
    }

    /// The same form with a different amount (`Fit` and a `Calc` stay).
    pub fn with_amount(self, v: f32) -> Self {
        match self {
            Sizing::Fit => Sizing::Fit,
            Sizing::Calc(c) => Sizing::Calc(c),
            Sizing::Grow(_) => Sizing::Grow(v),
            Sizing::Fixed(_) => Sizing::Fixed(v),
            Sizing::Percent(_) => Sizing::Percent(v),
        }
    }
}

/// Which way a container stacks its children.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Dir {
    Row,
    #[default]
    Column,
}

impl Dir {
    /// The `dir` row's spelling.
    pub fn name(self) -> &'static str {
        match self {
            Dir::Row => "row",
            Dir::Column => "column",
        }
    }
}

/// Where children sit along an axis, and where a float attaches.
///
/// The first three apply to every axis. The rest each mean something on
/// one axis only: the three spreads on `main_align`, `Baseline` on a row's
/// `cross_align`. Anywhere else one lays out as `Start`
/// (`SpaceAround`/`SpaceEvenly` as `Center`), with an `align-ignored`
/// warning.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Align {
    #[default]
    Start,
    Center,
    End,
    /// Main axis: the free space goes between the children, none at the
    /// ends — CSS's `space-between`. One child sits at the start.
    SpaceBetween,
    /// Main axis: each child gets an equal share of the free space, half
    /// on either side, so the ends get half what a gap does — CSS's
    /// `space-around`. One child is centred.
    SpaceAround,
    /// Main axis: the free space splits into equal gaps between the
    /// children and at both ends — CSS's `space-evenly`. One child is
    /// centred.
    SpaceEvenly,
    /// A row's cross axis: the first baselines of the children's text line
    /// up, so a label and a larger value on one row read as one line. A
    /// child with no text inside it aligns by its bottom edge; a `grow` or
    /// percent height fills the line and sits at its top.
    Baseline,
}

impl Align {
    /// The `align` rows' spelling (`schema::ALIGNS`).
    pub fn name(self) -> &'static str {
        crate::schema::ALIGNS[self as usize]
    }
}

/// What a floating node is positioned against.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FloatAnchor {
    /// The parent node's border box.
    #[default]
    Parent,
    /// The whole viewport.
    Viewport,
    /// The border box of the node `Key` names, wherever it is in the
    /// tree, even after this one in preorder: such a float is laid out
    /// again in a sixth pass once its anchor is placed. What a devtools
    /// tab's content is: built in the app's part of the tree, shown over
    /// the panel's tab body. No binding spells it; the core builds it.
    Node(crate::key::Key),
}

/// Takes a node out of flex flow: it does not consume space in its parent,
/// sizes Grow/Percent against its anchor, is positioned by attach points,
/// and escapes ancestor clips unless [`FloatConfig::clip`] keeps it in its
/// parent's. It paints as a layer of its own, above the in-flow tree and
/// every float that opened before it and under every one that opened
/// after, and takes input in the same order.
///
/// ```rust
/// use kui_core::{Align, FloatConfig, NodeSpec};
///
/// let tooltip = NodeSpec::column().float(FloatConfig::below().fit());
/// let toast = NodeSpec::row().float(FloatConfig::viewport().inside(Align::End, Align::End).offset(-16.0, -16.0));
/// assert!(tooltip.layout.float.unwrap().fit);
/// assert_eq!(toast.layout.float.unwrap().offset.x, -16.0);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FloatConfig {
    pub anchor: FloatAnchor,
    /// Attach point on the anchor rect (horizontal, vertical).
    pub anchor_point: (Align, Align),
    /// Attach point on the floating node itself.
    pub self_point: (Align, Align),
    /// Extra offset applied after attaching, logical px.
    pub offset: Vec2Offset,
    /// Keep the float on screen: if the attached placement leaves the
    /// viewport on an axis, mirror the attachment across the anchor on that
    /// axis (below ↔ above, after ↔ before) when that fits better, then
    /// clamp whatever still overflows. Tooltips/menus want this.
    ///
    /// This is the in-window approximation of an OS popup: a float costs
    /// one tree, one hit list and one draw call. What it cannot do is leave
    /// the window, so a dropdown taller than the viewport, or a menu with
    /// nowhere in-window to go, is clamped rather than placed.
    pub fit: bool,
    /// Take the parent's clip, as a child does, instead of escaping every
    /// ancestor's: a node on a `clip` canvas panned past the canvas's edge
    /// is cut there, and its hit region with it, rather than drawn over
    /// and clicked through the toolbar beside it. Only a
    /// [`FloatAnchor::Parent`] float reads it; a viewport or node anchor is
    /// placed against something other than the parent, and escapes with it
    /// set or not. A declared float's paint order is unchanged: it is a
    /// layer of its own still. A `line`, `polygon` or `path` anchored in
    /// its parent's box has it set by the core, and with it paints in the
    /// parent's layer at its place in the tree, as a child does — it opens
    /// no layer (backlog F123; `Tree::opens_layer`).
    pub clip: bool,
}

/// Plain offset pair (kept separate from geometry to stay `Copy` + FFI-flat).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vec2Offset {
    pub x: f32,
    pub y: f32,
}

impl Default for FloatConfig {
    fn default() -> Self {
        Self {
            anchor: FloatAnchor::Parent,
            anchor_point: (Align::Start, Align::Start),
            self_point: (Align::Start, Align::Start),
            offset: Vec2Offset::default(),
            fit: false,
            clip: false,
        }
    }
}

impl FloatConfig {
    /// Anchored to the parent's top-left corner.
    pub fn parent() -> Self {
        Self::default()
    }

    /// Anchored to the viewport's top-left corner.
    pub fn viewport() -> Self {
        Self {
            anchor: FloatAnchor::Viewport,
            ..Self::default()
        }
    }

    /// Tooltip-style: hang below the parent, centered.
    pub fn below() -> Self {
        Self {
            anchor: FloatAnchor::Parent,
            anchor_point: (Align::Center, Align::End),
            self_point: (Align::Center, Align::Start),
            offset: Vec2Offset { x: 0.0, y: 6.0 },
            ..Self::default()
        }
    }

    /// Tooltip-style: hover above the parent, centered.
    pub fn above() -> Self {
        Self {
            anchor: FloatAnchor::Parent,
            anchor_point: (Align::Center, Align::Start),
            self_point: (Align::Center, Align::End),
            offset: Vec2Offset { x: 0.0, y: -6.0 },
            ..Self::default()
        }
    }

    /// The attach point on the anchor.
    pub fn at(mut self, x: Align, y: Align) -> Self {
        self.anchor_point = (x, y);
        self
    }

    /// The attach point on the float itself.
    pub fn self_at(mut self, x: Align, y: Align) -> Self {
        self.self_point = (x, y);
        self
    }

    /// [`Self::at`] and [`Self::self_at`] at the same point: the float sits
    /// inside the anchor against that edge or corner — `(End, End)` is a
    /// toast in the viewport's bottom-right, `(Center, Center)` a dialog.
    #[inline]
    pub fn inside(self, x: Align, y: Align) -> Self {
        self.at(x, y).self_at(x, y)
    }

    /// An extra offset after attaching, logical px.
    pub fn offset(mut self, x: f32, y: f32) -> Self {
        self.offset = Vec2Offset { x, y };
        self
    }

    /// Flip across the anchor / clamp as needed to stay in the viewport;
    /// see [`FloatConfig::fit`] for where that stops being enough.
    pub fn fit(mut self) -> Self {
        self.fit = true;
        self
    }

    /// Cut by the parent's clip instead of escaping it; see
    /// [`FloatConfig::clip`] for which anchors read it.
    pub fn clipped(mut self) -> Self {
        self.clip = true;
        self
    }

    /// Whether this float takes its parent's clip: [`FloatConfig::clip`]
    /// declared on a parent-anchored float. The one reading both paint
    /// passes and the hit regions share.
    pub fn clipped_by_parent(&self) -> bool {
        self.clip && self.anchor == FloatAnchor::Parent
    }

    /// A preset by its wire index — its position in [`FLOAT_PRESETS`], which
    /// is what the binary protocol carries and what `KUI_FLOAT_*` counts
    /// from. `None` for an index no preset claims.
    pub fn preset_at(i: usize) -> Option<Self> {
        Some(match i {
            0 => Self::parent(),
            1 => Self::viewport(),
            2 => Self::below(),
            3 => Self::above(),
            _ => return None,
        })
    }

    /// A preset by name. Every binding that spells a float as a word —
    /// `float="below"`, `float = "above"`, `kui_spec_float_preset` — resolves
    /// it here, so "below" cannot mean one thing in JS and another in Lua.
    pub fn preset(name: &str) -> Option<Self> {
        Self::preset_at(FLOAT_PRESETS.iter().position(|p| *p == name)?)
    }

    /// One config from the pieces a binding can extract without deciding
    /// anything: a `base` preset (from [`FloatConfig::preset`] or
    /// [`FloatConfig::preset_at`]) and the overrides that were actually
    /// declared. `None` leaves the base's own value — that is what lets
    /// `float="below"` keep its 6px gap while `{ anchor: "below", dx: 2 }`
    /// moves it sideways without flattening the gap to zero. `fit` and
    /// `clip` are ORed in: no preset sets either.
    pub fn build(
        base: FloatConfig,
        anchor_at: Option<(Align, Align)>,
        self_at: Option<(Align, Align)>,
        dx: Option<f32>,
        dy: Option<f32>,
        fit: bool,
        clip: bool,
    ) -> Self {
        let mut cfg = base;
        if let Some((x, y)) = anchor_at {
            cfg.anchor_point = (x, y);
        }
        if let Some((x, y)) = self_at {
            cfg.self_point = (x, y);
        }
        if let Some(x) = dx {
            cfg.offset.x = x;
        }
        if let Some(y) = dy {
            cfg.offset.y = y;
        }
        cfg.fit |= fit;
        cfg.clip |= clip;
        cfg
    }
}

/// The float preset names, in wire order: the index of a name here is what
/// the binary protocol writes for it and what `KUI_FLOAT_*` counts from.
pub const FLOAT_PRESETS: &[&str] = &["parent", "viewport", "below", "above"];

/// `overflow` as bits: the C struct's field, the binary wire's payload and
/// what the `clip` / `scrollX` / `scrollY` booleans OR together. One set of
/// values so a binding cannot invent its own numbering.
pub const OVERFLOW_CLIP: u32 = 1 << 0;
pub const OVERFLOW_SCROLL_X: u32 = 1 << 1;
pub const OVERFLOW_SCROLL_Y: u32 = 1 << 2;

/// The `pad` shorthand family as declared — any subset of the seven names,
/// each `None` when the frontend did not see it. [`PadShorthand::resolve`]
/// decides what a missing edge falls back to; a binding only reports what
/// it found.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PadShorthand {
    /// `pad`: all four edges.
    pub all: Option<f32>,
    /// `padX`: left and right.
    pub x: Option<f32>,
    /// `padY`: top and bottom.
    pub y: Option<f32>,
    pub l: Option<f32>,
    pub r: Option<f32>,
    pub t: Option<f32>,
    pub b: Option<f32>,
}

impl PadShorthand {
    /// True when the frontend saw any of the seven names.
    pub fn declared(self) -> bool {
        [self.all, self.x, self.y, self.l, self.r, self.t, self.b]
            .iter()
            .any(Option::is_some)
    }

    /// Four edges: an edge falls back to its axis, an axis to the all-round
    /// `pad`, and `pad` to zero. The specific value always wins.
    pub fn resolve(self) -> Edges {
        let all = self.all.unwrap_or(0.0);
        let (x, y) = (self.x.unwrap_or(all), self.y.unwrap_or(all));
        Edges {
            l: self.l.unwrap_or(x),
            r: self.r.unwrap_or(x),
            t: self.t.unwrap_or(y),
            b: self.b.unwrap_or(y),
        }
    }
}

/// The layout half of a [`NodeSpec`]: sizing, clamps, direction, padding,
/// gap, alignment, overflow and floating. Set through the `NodeSpec`
/// builders; read by the solver.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayoutSpec {
    pub width: Sizing,
    pub height: Sizing,
    /// Clamps applied after `width`/`height` resolve (Fit, Grow, Percent and
    /// Fixed alike), so "grow but at most N" and "fit but at least N" work.
    /// A min may also be [`Min::FIT`]: "grow but never below my content".
    pub min_w: Min,
    /// A ceiling in px, or, as a negative, a size expression layout has
    /// yet to resolve ([`max_of_calc`]); set it through
    /// [`NodeSpec::max_width`], which keeps a px one at or above zero
    /// ([`px_ceiling`]). `max_h` is the same.
    pub max_w: f32,
    pub min_h: Min,
    pub max_h: f32,
    pub dir: Dir,
    pub padding: Edges,
    pub gap: f32,
    /// Row children that don't fit the main-axis content box start a new
    /// line instead of overflowing (or shrinking). Rows only: breaking
    /// needs a definite main size, and the pass order gives a row one —
    /// its width is final before its height is measured — where a column
    /// would need its height first. Ignored on a column and on a
    /// `scroll_x` row, both with a warning (`diag::WRAP_IGNORED`).
    pub wrap: bool,
    /// A column whose rows' children line up in columns: the nth in-flow
    /// child of every in-flow row is a cell of column n, and
    /// a column is as wide as its widest cell — its cells' own `width`s
    /// say how the column sizes (a `Fixed` or `Fit` cell is content that
    /// sets the column's fit width, a `Grow` cell makes the column grow,
    /// a `Percent` one takes its cut of the row) and their `minWidth` /
    /// `maxWidth` clamp it. The rows are ordinary rows — a row's `gap` is
    /// the space between its cells, its `padding` its own, and it takes
    /// its background, its click and its hover as any row does — except
    /// that a row of a table never wraps (`diag::WRAP_IGNORED`). Set by
    /// [`NodeSpec::table`], which is a column; `dir` stays `Column`, and
    /// the flag is read on a column only ([`LayoutSpec::is_table`]): a
    /// `Row` carrying it — a shape only these public fields can build —
    /// is the row it says it is. The rows are the in-flow `Row` children;
    /// a column, a table or a leaf straight under the table is a child
    /// with its own width and no cells.
    pub table: bool,
    /// Space between wrap lines, across the main axis. `gap` is still the
    /// space between children along it.
    pub cross_gap: f32,
    /// Alignment of children along the main axis, the spreads
    /// (`SpaceBetween` / `SpaceAround` / `SpaceEvenly`) included.
    pub main_align: Align,
    /// Alignment of children across the main axis; `Baseline` on a row.
    pub cross_align: Align,
    /// Width over height (CSS's `aspect-ratio`); 0 = none.
    /// It sizes the axis whose sizing is `Fit`: a fit height is the final
    /// width over the ratio, and a fit width under a `Fixed` height is
    /// that height times it. With both axes declared it has nothing to set.
    /// The derived axis is neither shrunk nor fitted to the children,
    /// which overflow it — `min_h: Min::FIT` floors it at them.
    pub aspect: f32,
    /// Clip children to this node's rect.
    pub clip: bool,
    /// Overflowing content scrolls (implies clipping). Offsets are retained
    /// across frames in the core, keyed by this node's `Key`.
    pub scroll_x: bool,
    pub scroll_y: bool,
    /// Scroll anchoring (CSS's `overflow-anchor`): the
    /// first child in view keeps its place on screen when the content
    /// before it changes size — a chat that prepends history, a log that
    /// inserts above the viewport, a row whose estimate was corrected.
    /// On the scroll axis that is the container's main axis only.
    pub anchor: bool,
    /// Out-of-flow positioning; see [`FloatConfig`].
    pub float: Option<FloatConfig>,
}

impl Default for LayoutSpec {
    fn default() -> Self {
        Self {
            width: Sizing::Fit,
            height: Sizing::Fit,
            min_w: Min::AUTO,
            max_w: f32::INFINITY,
            min_h: Min::AUTO,
            max_h: f32::INFINITY,
            dir: Dir::Column,
            padding: Edges::default(),
            gap: 0.0,
            wrap: false,
            table: false,
            cross_gap: 0.0,
            main_align: Align::Start,
            cross_align: Align::Start,
            aspect: 0.0,
            clip: false,
            scroll_x: false,
            scroll_y: false,
            anchor: false,
            float: None,
        }
    }
}

impl LayoutSpec {
    /// Whether this node clips its children.
    pub fn clips(&self) -> bool {
        self.clip || self.scroll_x || self.scroll_y
    }

    /// Whether this node is a table: the flag, on a column. Every reader
    /// asks this and not the field, so a `Row` with the field set is a row
    /// everywhere.
    pub fn is_table(&self) -> bool {
        self.table && self.dir == Dir::Column
    }
}

impl LayoutSpec {
    /// The width a declared aspect ratio gives a `Fit` width: its `Fixed`
    /// height times the ratio. `None` when the ratio has no say over the
    /// width.
    pub(crate) fn aspect_width(&self) -> Option<f32> {
        match (self.width, self.height) {
            (Sizing::Fit, Sizing::Fixed(h)) if self.aspect > 0.0 => {
                Some(self.clamp_h(h) * self.aspect)
            }
            _ => None,
        }
    }

    /// Whether a declared aspect ratio sizes the height: a `Fit` height,
    /// read off the final width. `aspect_width`'s pair.
    pub(crate) fn aspect_height(&self) -> bool {
        self.aspect > 0.0 && self.height == Sizing::Fit
    }

    pub(crate) fn clamp_w(&self, w: f32) -> f32 {
        let min = self.min_w.resolved();
        w.clamp(min, self.max_w_px().max(min))
    }

    pub(crate) fn clamp_h(&self, h: f32) -> f32 {
        let min = self.min_h.resolved();
        h.clamp(min, self.max_h_px().max(min))
    }

    /// `max_w` as px: a calc layout has not resolved yet is no ceiling.
    pub fn max_w_px(&self) -> f32 {
        if self.max_w < 0.0 {
            f32::INFINITY
        } else {
            self.max_w
        }
    }

    /// `max_h` as px, as [`Self::max_w_px`].
    pub fn max_h_px(&self) -> f32 {
        if self.max_h < 0.0 {
            f32::INFINITY
        } else {
            self.max_h
        }
    }
}

/// The paint half of a [`NodeSpec`]: background, border, corner radii,
/// opacity, shadow and pixel snapping.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VisualStyle {
    pub bg: Color,
    pub border_color: Color,
    pub border_w: f32,
    /// Corner radii (logical px), clockwise from the top-left:
    /// `[tl, tr, br, bl]`. `NodeSpec::radius` sets all four; the per-corner
    /// builders (`radius_tl`, ...) override one — later calls win, like CSS
    /// `border-radius` followed by `border-top-left-radius`.
    pub radius: [f32; 4],
    /// Group opacity, 0..=1 and 1 by default: multiplied into the alpha of
    /// every quad this node and its subtree emit, and into every
    /// descendant's own opacity. This is the *cheap* group opacity — a
    /// per-quad alpha multiply, not an offscreen composite — so a subtree
    /// whose own pieces overlap shows its seams through the fade where a
    /// compositing implementation would not. Nothing else changes: an
    /// invisible subtree still lays out, still takes clicks and is still
    /// read by assistive technology, exactly like CSS `opacity: 0`.
    pub opacity: f32,
    /// The drop shadow cast behind this node (see [`Shadow`]).
    pub shadow: Shadow,
    /// Paint the background, border, shadow and fragment with each edge on
    /// a whole physical pixel (`pixelSnap`). Off by default: a box is drawn where
    /// layout put it, so a gap between two boxes is there at any scale.
    /// On, its edges land where a text's backgrounds' do and where every
    /// other snapped box's do, so snapped boxes that share an edge in
    /// layout, and a snapped box beside a text's background, meet without
    /// a seam. Layout, hit-testing and the children are untouched.
    pub pixel_snap: bool,
}

impl Default for VisualStyle {
    fn default() -> Self {
        Self {
            bg: Color::TRANSPARENT,
            border_color: Color::TRANSPARENT,
            border_w: 0.0,
            radius: [0.0; 4],
            opacity: 1.0,
            shadow: Shadow::default(),
            pixel_snap: false,
        }
    }
}

/// One outer drop shadow: the node's rounded rect, moved by `dx`/`dy`,
/// grown by `spread` and its edge blurred over `blur`, painted in `color`
/// behind the node. CSS's `box-shadow` without the inset and multi-shadow
/// forms.
///
/// It draws whenever `color` is visible, so `shadowColor` alone is a hard
/// shadow sitting exactly behind the node. The shape is not knocked out of
/// the middle the way CSS knocks it out, so a translucent background shows
/// the shadow through itself.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Shadow {
    pub color: Color,
    /// Offset (logical px); positive `dy` casts downward.
    pub dx: f32,
    pub dy: f32,
    /// Blur radius (logical px): the edge ramps over this distance and the
    /// shadow reaches this far past its shape. 0 = a hard edge.
    pub blur: f32,
    /// Grows (or, negative, shrinks) the shape before blurring.
    pub spread: f32,
}

impl Shadow {
    /// Whether anything would be painted.
    pub fn is_visible(&self) -> bool {
        self.color.is_visible()
    }
}

/// Corner indices into `VisualStyle::radius` / `Quad::radius`.
pub mod corner {
    pub const TL: usize = 0;
    pub const TR: usize = 1;
    pub const BR: usize = 2;
    pub const BL: usize = 3;
}

/// Everything one node declares. This, not any Rust trait, is the contract
/// every frontend (Rust builders, Lua, JSX, C) lowers into. Start from
/// [`NodeSpec::row`], [`NodeSpec::column`] or [`NodeSpec::table`] and
/// chain builders; see the [module docs](self) for an example.
#[derive(Clone, Debug, Default)]
pub struct NodeSpec {
    pub layout: LayoutSpec,
    pub style: VisualStyle,
    /// Track pointer hover for this node (`Ui::is_hovered`) without making
    /// it clickable — tooltips on passive badges. Nodes with `on_click` /
    /// `on_key` / `window` are always hover-tracked; clicks on a merely
    /// hoverable node emit nothing.
    pub hoverable: bool,
    /// Ask the driver for another frame after this one, every frame this
    /// node is declared (`animate`). What a `fragment` reading `time`
    /// needs; opt-in, because it takes the loop off input-driven.
    pub animate: bool,
    /// Paint this node's background in the theme's accent: the OS's where
    /// the host reported one, the app's where it pinned one, kui's blue
    /// otherwise. A view says *that* this node is the accented one and the
    /// palette says which colour that is. The stock button also repaints
    /// its hover, pressed shade and label from the same accent.
    pub accent: bool,
    /// Window-chrome role (drag handle / window button). A chrome node's
    /// interactions become `WindowCommand`s for the frame driver instead of
    /// `UiEvent`s; `on_click` is ignored on such nodes.
    pub window: Option<WindowRole>,
    /// Eases this node's sizing amounts, colors and radius toward what the
    /// view declares instead of snapping (see [`crate::anim`]). Keyed by
    /// node identity, so the node needs a stable key across frames.
    pub transition: Option<Transition>,
    /// With `transition`: also ease this node's laid-out *position*, moving
    /// its whole subtree — reordered siblings slide into their new slots.
    /// Opt-in because a node whose position follows an already-easing
    /// sibling (a split's second half) would lag twice.
    pub slide: bool,
    /// Reachable by Tab, and focused by a click or an assistive-technology
    /// request, without a click payload or a control role — a list row
    /// that opens on Enter, a card. Controls (editors, key sinks,
    /// `on_click` boxes, the control roles) are focusable already.
    pub focusable: bool,
    /// Where focus lands when the `modal` scope containing this node is
    /// entered: the first node in the modal's Tab ring declaring it,
    /// instead of simply the ring's first — a destructive confirm opening
    /// on its Cancel rather than on whichever control is declared first.
    /// Read on entry only, so a Tab press afterwards stands; a node the
    /// ring skips (disabled, decoration, not focusable) is not a
    /// candidate, and with no candidate the entry is the ring's first
    /// node as before.
    pub initial_focus: bool,
    /// Inert: keeps its hit region (so a tooltip can say why) and loses
    /// everything else — no click, drag or key sink, no hover / pressed /
    /// focus background, no place in the Tab ring; the access tree
    /// reports it disabled.
    pub disabled: bool,
    /// The pointer shape over this node (see [`crate::cursor`]). Unset,
    /// the pointer is the I-beam over an editor or a selection scope and
    /// the plain arrow over everything else — a clickable or draggable
    /// node included — so a hand over a button, a grab over a handle
    /// (`grabbing` while its drag runs), a splitter's resize arrows and a
    /// disabled control's `notAllowed` are all the view's to declare. The
    /// stock button declares `Pointer` itself.
    pub cursor: Option<CursorShape>,

    /// See [`EventSpec`]. `None` when the node declares none of it.
    pub events: Option<Box<EventSpec>>,

    /// See [`AnimSpec`]. `None` when the node declares none of it.
    pub anim: Option<Box<AnimSpec>>,

    /// See [`AccessSpec`]. `None` when the node declares none of it.
    pub access: Option<Box<AccessSpec>>,

    /// See [`InteractSpec`]. `None` when the node declares none of it.
    pub interact: Option<Box<InteractSpec>>,
}

/// Event payloads a node declares. Boxed on `NodeSpec` because most
/// nodes declare none.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EventSpec {
    /// Payload emitted as a `UiEvent` when this node is clicked.
    pub on_click: Option<Value>,
    /// Makes this node draggable: pressing it starts a pointer-captured
    /// drag, and cursor motion until release emits `UiEvent`s of the form
    /// `{kind="drag", phase="start"|"move"|"end", x, y, dx, dy, tag}` with
    /// this payload merged in under `tag`. A drag past the click slop
    /// suppresses the node's `on_click`, so both can coexist.
    pub on_drag: Option<Value>,
    /// Marks this node as a key sink: while it holds key focus, key
    /// presses arrive as `UiEvent`s on it as `{kind="key", phase="down",
    /// code, ...}`, with this payload merged in under `tag`. Clicking the
    /// node takes key focus. Releases are not delivered unless the sink
    /// also declares [`key_up`](Self::key_up): a keymap is the common
    /// case, and a keymap that heard both halves would run every binding
    /// twice.
    pub on_key: Option<Value>,
    /// With `on_key`: the sink hears releases too, as the same payload
    /// with `phase="up"` (`text` null, `repeat` false). For a held-key
    /// interaction — WASD, press-and-hold to preview, a key that arms a
    /// mode while it is down. A key only comes up where it went down: a
    /// release whose press the sink never got is dropped, and focus
    /// leaving while a key is held delivers the `up` first, so nothing is
    /// left stuck down. Without it a sink hears presses only, which is
    /// what a keymap wants.
    pub key_up: bool,
    /// With `on_key`: the modifier and lock keys themselves arrive too
    /// (Shift, Ctrl, Alt, Super, Caps Lock, Num Lock, Scroll Lock), as
    /// codes of their own with their side in `location`.
    /// Without it a modifier is only ever held — in the next key's
    /// `shift` / `ctrl` / … and the `modifiers` event — so a keymap
    /// mid-sequence does not read Shift as a key between two others. A
    /// terminal speaking kitty's keyboard protocol asks, and so does a
    /// game that binds a lone Shift.
    pub modifier_keys: bool,
    /// Asks for a context menu: a secondary-button press over this node
    /// emits `{kind="contextmenu", x, y, tag}` on it with this payload
    /// under `tag`, and does nothing else — the press moves no focus,
    /// places no caret and produces no click, so right-clicking a
    /// selection leaves it selected. `x`/`y` are the press in logical
    /// viewport coordinates, which is where the menu goes. Asked of the
    /// topmost node under the pointer; when that node offers no menu the
    /// press reaches the nearest enclosing node that does, the way an
    /// unclaimed key reaches the enclosing sink:
    /// the event carries the owner's key and tag, a nested declaration
    /// wins over its ancestor's, a disabled node's own is skipped, and
    /// the walk stops at the modal boundary. Null = the behaviour without
    /// a tag.
    pub on_context_menu: Option<Value>,
    /// Force-click events: a press that deepened past the second stage of
    /// a Force Touch trackpad over this node emits `{kind="forceclick",
    /// x, y, tag}` with this payload under `tag`. Routed as a secondary
    /// press is — no focus moved, no caret, no click — but asked of the
    /// topmost node only, with no walk to an enclosing declaration — and
    /// the ordinary click the press produces still follows,
    /// which is what macOS does.
    ///
    /// Text does not need this: a force click over an editor or a
    /// `selectable` scope selects the word and asks the host to look it
    /// up, which is what the gesture means on that platform. This is for
    /// what the core cannot guess — a force click on a chart, a map, a
    /// timeline.
    pub on_force_click: Option<Value>,
    /// The non-primary buttons as events: a press of a
    /// button in [`buttons`](Self::buttons) over this node emits
    /// `{kind="button", phase="press", button, x, y, clicks, tag}` on it
    /// with this payload under `tag`, and the button is then captured by
    /// the node — every pointer move while it is held arrives as
    /// `phase="move"` and its release as `phase="release"`, on this node
    /// wherever the pointer is. `button` is `"secondary"`, `"middle"` or,
    /// for a button past those, its [`crate::MouseButton::code`]; `x`/`y`
    /// are logical viewport coordinates, and on a `cells` grid the events
    /// carry `cell: {row, col}` as a click does. Several buttons may be
    /// held at once, each its own capture; a primary drag is untouched.
    ///
    /// Asked of the topmost node under the pointer, and when that node
    /// claims no such button the press reaches the nearest enclosing node
    /// that does, as a context menu's does: a disabled node's own is
    /// skipped and the walk stops at the modal boundary. A claimed
    /// secondary press is this event *instead of* a `contextmenu` event
    /// and the stock menu — a nearer `on_context_menu` still wins, being
    /// the nested declaration. Like every non-primary press it moves no
    /// focus, places no caret and touches no selection or scrollbar. What
    /// it is for: a terminal's middle-click paste, and the mouse reports a
    /// program in it asked for. Null = the behaviour without a tag.
    pub on_button: Option<Value>,
    /// Which non-primary buttons [`on_button`](Self::on_button) claims:
    /// all three kinds unless the node says otherwise. A pane that wants
    /// the middle button and leaves the secondary one to its context menu
    /// says [`Buttons::MIDDLE`].
    pub buttons: Buttons,
    /// Scroll events: the wheel over this node emits `{kind="scroll", x,
    /// y, dx, dy, lines, tag}` with this payload under `tag` — the delta
    /// in logical px as the driver reported it (positive `dy` is the wheel
    /// rolling up, toward earlier content), the pointer's position, and
    /// on a `cells` grid the whole lines the delta covers (`null` on any
    /// other node), the fraction carried to the next notch. The node
    /// *takes* the wheel on the axes [`scroll_axes`](Self::scroll_axes)
    /// names: a scroll gesture that starts over it is its own, and stays
    /// its own until it ends wherever the pointer goes, except on an axis
    /// it also scrolls as a container (`scroll_x`, `scroll_y`, the offset
    /// the app sets from what it hears), where it is answered by its room
    /// as a container is: at its edge, a gesture that way passes to the
    /// scroller around it; it
    /// reaches no scroll container above it, and a container inside it
    /// still takes the axes it scrolls while it can move that way,
    /// passing this node the rest: the other axis, and a gesture that
    /// begins with the container at its limit (unless it says
    /// [`Overscroll::Contain`]). The core moves nothing — a grid's
    /// `origin_line` and a canvas's zoom are the app's to change. A
    /// drag-select held past a grid's top or bottom edge arrives here
    /// too, as the lines the frame scrolled by.
    pub on_scroll: Option<Value>,
    /// Which axes [`on_scroll`](Self::on_scroll) takes: both unless the
    /// node says otherwise. A scroll gesture on an axis
    /// the node does not take passes it by, to the scroller around it —
    /// a terminal that scrolls its history on `y` says
    /// [`ScrollAxes::Y`], and a sideways swipe that meets it goes on
    /// moving the strip it sits in. Meaningless without `on_scroll`.
    pub scroll_axes: ScrollAxes,
    /// The modifiers [`on_scroll`](Self::on_scroll) is for (backlog
    /// F122): with any named, the node hears only a scroll gesture that
    /// began with one of them held — and hears it *first*, wherever in
    /// the tree under the pointer the gesture began: ahead of every
    /// scroll container and every handler that names none, the innermost
    /// such node winning. A wheel with none of them held passes it by as
    /// if it declared no `on_scroll` — a node that is a scroll container
    /// too scrolls for it as any other does. What a Ctrl-wheel zoom is declared
    /// with, on the window's root or on the one canvas it zooms: a
    /// modified wheel is the more specific ask, and no list under the
    /// pointer scrolls for it. Its events carry `mods`, the modifiers
    /// held when the gesture began — the gesture stays this node's to
    /// its end, glide included, whatever is let go meanwhile. None named
    /// (the default): a handler like any other. Meaningless without
    /// `on_scroll`.
    pub scroll_mods: crate::input::KeyMods,
    /// Hover events: the pointer entering or leaving this node emits
    /// `{kind="hover", phase="enter"|"leave", tag}` with this payload under
    /// `tag` — for hover-dependent *layout* (a close button that appears)
    /// where a color swap isn't enough. Implies hover tracking.
    pub on_hover: Option<Value>,
    /// Drop-zone events: files dragged in from the OS over this node emit
    /// `{kind="drop", phase="enter"|"move"|"leave"|"drop", paths, x, y,
    /// tag}` with this payload under `tag` — `paths` the OS paths as
    /// strings, `x`/`y` the pointer in viewport coordinates (absent on
    /// `leave`). The zone under the files is the topmost *zone* by paint
    /// order: a node inside a zone resolves to it, and a node that is no
    /// zone and has none enclosing it is looked past, so an overlay shown
    /// on `enter` cannot make the zone lose the files. No `leave` follows
    /// a `drop`. Implies hover tracking.
    pub on_drop: Option<Value>,
    /// Layout events: the rect layout gave this node arrives as
    /// `{kind="layout", x, y, w, h, parent: {x, y, w, h}, tag}` (logical px,
    /// viewport coordinates, after scrolling and position easing) — on the
    /// node's first frame and again whenever the rect changes, never on a
    /// frame that left it alone. The view reads the numbers layout already
    /// produced instead of re-deriving them; a transition that moves the
    /// node reports every frame it moves. Needs a stable key across frames.
    pub on_layout: Option<Value>,
    /// Slider changes: on a node whose role is `Slider`, the core turns a
    /// press into the value under the pointer, a drag into the value under
    /// it, the arrows and assistive technology's Increment / Decrement
    /// into one `value_step`, PageUp / PageDown into ten, Home / End into
    /// the range's ends — clamped to `value_min..value_max`, snapped to the
    /// step — and emits `{kind="change", value, phase="move"|"end", tag}`
    /// with this payload under `tag`. The value is proposed, never
    /// applied: nothing moves until the view declares it as `value_now`.
    /// Without it a slider's keys reach the app as the `access` nudge.
    /// Ignored on any other role.
    pub on_change: Option<Value>,
    /// Modal: while this node is declared, the Tab ring is its subtree,
    /// everything outside it is inert to the pointer, the wheel and
    /// assistive technology, and Escape or a press outside emits
    /// `{kind="dismiss", reason, tag}` on it with this payload under
    /// `tag`. The last node declaring it in tree order is the one in
    /// effect (a confirm inside a dialog). Null = modal without a tag.
    pub modal: Option<Value>,
    /// A press on this node, or anywhere inside it, leaves keyboard focus
    /// where it was (`keepFocus`): a toolbar button, a tab, a divider
    /// that acts without taking the keyboard from the editor beside it.
    /// Its click, drag and hover are unchanged, and Tab
    /// and assistive technology still reach a focusable node in it — it
    /// is the pointer's press alone that stops moving focus.
    pub keep_focus: bool,
    /// Keyboard focus entering or leaving this node's subtree — the node
    /// itself or anything focused inside it — emits `{kind="focus",
    /// phase="in"|"out", by, tag}` with this payload under `tag`, where
    /// `by` is `"pointer"`, `"keyboard"`, `"assistive"` or `"program"`:
    /// what moved it. Reported once the move has settled —
    /// after the input that made it, or at the end of the frame that
    /// declared it — so a view reads a change instead of diffing
    /// `key_focus` every frame. Declares nothing interactive.
    pub on_focus: Option<Value>,
}

impl EventSpec {
    /// The group as a node that declares none of it — what
    /// `NodeSpec`'s accessor hands back when the box is `None`.
    pub const EMPTY: Self = Self {
        on_click: None,
        on_drag: None,
        on_key: None,
        key_up: false,
        modifier_keys: false,
        on_context_menu: None,
        on_force_click: None,
        on_button: None,
        buttons: Buttons::ALL,
        on_scroll: None,
        scroll_axes: ScrollAxes::Both,
        scroll_mods: crate::input::KeyMods::NONE,
        on_hover: None,
        on_drop: None,
        on_layout: None,
        on_change: None,
        modal: None,
        keep_focus: false,
        on_focus: None,
    };
}

/// Per-node animation declarations. Boxed on `NodeSpec`: `enter` and
/// `exit` are 60 bytes each and almost every node has neither.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AnimSpec {
    /// CSS-style stops for the animatable slots (see [`crate::keyframes`]):
    /// with a `transition`, the slots a stop names cycle through the stops
    /// over the transition's duration, in its `repeat` direction, offset by
    /// its `delay_ms` — forever, and without the view redrawing. Slots no
    /// stop names still tween toward what the view declares. Empty = none.
    pub keyframes: Vec<Keyframe>,
    /// Where this node's slots start the first frame it is seen (see
    /// [`crate::enter`]): with a `transition`, the slots it names ease in
    /// from there instead of snapping — `dx`/`dy` slide the node in from
    /// that far away, `bg` fades it in. A node that vanishes and returns
    /// enters again. None = first sight snaps.
    pub enter: Option<Enter>,
    /// Where this node's slots *end* the frame after the view stops
    /// declaring it (see [`crate::depart`]). An exit is an [`Enter`] read
    /// the other way: with a `transition`, the departing subtree is copied
    /// out of the last frame that had it and replayed — frozen where
    /// layout left it, on top, inert — while the slots this names ease
    /// from where they were toward what it declares. Needs a stable key
    /// across frames, and a `transition` with a duration; without both, a
    /// removed node vanishes at once as it always did.
    pub exit: Option<Enter>,
}

impl AnimSpec {
    /// The group as a node that declares none of it — what
    /// `NodeSpec`'s accessor hands back when the box is `None`.
    pub const EMPTY: Self = Self {
        keyframes: Vec::new(),
        enter: None,
        exit: None,
    };
}

/// Accessibility properties a view states outright, as opposed to the
/// ones the core derives (see [`crate::access`]). Boxed on `NodeSpec`:
/// read only while an access tree is being built, and unset on nearly
/// every node.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AccessSpec {
    /// What this node is to assistive technology (see [`crate::access`]).
    /// Unset, the core derives one: a node with `on_click` is a button,
    /// an editor a text input, a scrolling container a scroll view, and
    /// a plain box is structure that leaves no trace. `Role::None` hides
    /// the node and its subtree from the access tree (decoration).
    pub role: Option<Role>,
    /// The accessible name. Without one a button, link, tab or heading is
    /// named by the text inside it; an image or an icon button has no
    /// name at all, and the core says so (`control-without-name`,
    /// `image-without-label` warnings).
    pub label: Option<Label>,
    /// The accessible description, read after the name — what the
    /// `description` prop sets, and what the `tooltip` prop sets on the way
    /// to drawing the same string.
    pub description: Option<Label>,
    /// For checkbox / radio / switch roles: the on state.
    pub checked: bool,
    /// For a checkbox: neither on nor off, like the select-all box over a
    /// list some of whose rows are selected. Wins over `checked`, which it
    /// leaves as it was.
    pub mixed: bool,
    /// The current one of a set: a `Role::Tab`, a picked `Role::ListItem`,
    /// the `Role::Link` for the page you are on. A tab reports the state
    /// either way; a row or a link reports it only where it is set (see
    /// [`crate::access`]).
    pub selected: bool,
    /// For a node that shows and hides something: expanded, or collapsed.
    /// None = it does not expand, and says nothing about it.
    pub expanded: Option<bool>,
    /// For a slider role: the current value and its range, so assistive
    /// technology can read the position (the drawing stays the view's).
    pub value_now: Option<f32>,
    pub value_min: Option<f32>,
    pub value_max: Option<f32>,
    /// For a slider role: what the position *reads as* (ARIA's
    /// `aria-valuetext`). Without one a reader has only the three numbers
    /// above and says a percentage — 25 in [5..60] is "36 percent" — so a
    /// value whose unit matters says it here: "25 minutes". It replaces
    /// the number rather than joining it (see [`crate::access`]), and a
    /// nudge announces the new text, not the new number.
    pub value_text: Option<Label>,
    /// For a slider role: how far one arrow key moves it, and the grid a
    /// value set by the pointer snaps to. None = a hundredth of the range.
    pub value_step: Option<f32>,
    /// On a `Role::Line` of a custom editor: the caret's byte offset into
    /// the line's text, and the byte offset of the selection's other end
    /// (see [`crate::access`]).
    pub caret: Option<u32>,
    pub selection_anchor: Option<u32>,
    /// With `caret`: the caret this line declares does not blink — a
    /// block caret in a modal editor's normal mode — so a driver's blink
    /// clock is not armed on it (`Core::has_caret` leaves it out) while
    /// the offset still anchors the IME and reads to assistive
    /// technology. Without it a declared caret is a caret to blink.
    pub caret_solid: bool,
    /// Float `description` below the node while it is hovered — the
    /// `tooltip` prop's third effect, set by [`NodeSpec::tooltip`]. The core
    /// reads it as the node opens (`Core::hint`); a binding that lowers the
    /// prop onto a box floats the hint itself and leaves this off. A leaf
    /// reads it as it is pushed and floats the hint beside itself, anchored
    /// to it, since it holds no children for the hint to be the last of —
    /// which is how a binding asks it of a leaf (`PropsOut::for_leaf`,
    /// backlog RG113).
    pub tooltip: bool,
    /// When the text inside this node changes, a reader reads the change
    /// without being asked (ARIA's `aria-live`). Off by default; a node
    /// that declares it is semantic, so a plain box marked live is not
    /// elided.
    pub live: Live,
}

impl AccessSpec {
    /// The group as a node that declares none of it — what
    /// `NodeSpec`'s accessor hands back when the box is `None`.
    pub const EMPTY: Self = Self {
        role: None,
        label: None,
        description: None,
        checked: false,
        mixed: false,
        selected: false,
        expanded: None,
        value_now: None,
        value_min: None,
        value_max: None,
        value_text: None,
        value_step: None,
        caret: None,
        selection_anchor: None,
        caret_solid: false,
        tooltip: false,
        live: Live::Off,
    };
}

/// Hover / pressed / focus styling and the sounds that go with them.
/// Boxed on `NodeSpec` so the common node — which declares none of it —
/// costs one null check in `resolve_hover_style` instead of reading
/// several `Option`s spread across the struct.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InteractSpec {
    /// Background while the pointer hovers this node (or any node sharing
    /// its `hover_group`). Resolved by the core when the node opens, so a
    /// data-only view gets hover styling without querying `is_hovered` —
    /// and with `transition` the swap eases. Implies hover tracking.
    pub hover_bg: Option<Color>,
    /// Background while this node (or its group) is pressed. Implies hover
    /// tracking. Without a `hover_bg`, hover keeps the plain `bg`. An
    /// `on_drag` node holds this state for the whole captured drag, even
    /// while the cursor is off it.
    pub pressed_bg: Option<Color>,
    /// Hover group: nodes sharing an id count as one for `hover_bg` /
    /// `pressed_bg` — a two-piece elbow, a split button, a row whose cells
    /// highlight together. The id is a hash of a name (`hover_group`).
    /// Implies hover tracking.
    pub hover_group: Option<u64>,
    /// A registered sound played when this node is clicked (see
    /// [`crate::audio`]); the click itself still emits `on_click` if one is
    /// declared. Implies hover tracking.
    pub click_sound: Option<crate::resources::SoundId>,
    /// A registered sound played when the pointer enters this node.
    /// Implies hover tracking.
    pub hover_sound: Option<crate::resources::SoundId>,
    /// Background while this node holds keyboard-visible focus (focus
    /// moved by Tab or by assistive technology, not by a click).
    /// Declaring one replaces the ring the core draws by default. Pressed
    /// wins over focus wins over hover; eases with `transition`.
    pub focus_bg: Option<Color>,
    /// Background while files dragged in from the OS are over this node.
    /// Wins over pressed, focus and hover — a press
    /// cannot be held while the OS holds a drag — and eases with
    /// `transition`; clears when the files leave, land or the drag is
    /// cancelled. Implies hover tracking.
    pub drop_bg: Option<Color>,
    /// Makes this node a *selection scope*: the text of every node inside
    /// it is one selectable run of text, in tree order, and a press-drag
    /// inside it selects across all of them. Declared on the container
    /// rather than on each label, because what a reader selects is a
    /// paragraph or a card, not one run of it.
    ///
    /// Scopes do not nest: the innermost one containing a run owns it, and
    /// an outer one is warned about (`nested-selection-scope`). An `edit`
    /// is already its own scope and ignores this.
    pub selectable: bool,
    /// Makes this node's subtree a *focus region*: a Tab ring of its own
    /// that the ring outside never enters, and that never leaves — a
    /// devtools dock, an inspector beside the app. Entered on purpose:
    /// `Ui::focus_region`, a press inside it, or an explicit focus on a
    /// node in it. Nothing else about the node changes — it lays out,
    /// paints, takes the pointer and appears in the access tree as before,
    /// and keys bubble through it to the sink above.
    pub focus_region: bool,
    /// How this node's scrollbars look, when it scrolls (see
    /// [`Scrollbar`]). Cold: read once per scroller when its layer's
    /// chrome is emitted, which is why it lives in this box rather than
    /// beside `scroll_y` on every node.
    pub scrollbar: Scrollbar,
    /// Whether a scroll gesture that starts over this scroller while it
    /// is at its limit that way goes on to the scroller around it (see
    /// [`Overscroll`]). Cold like `scrollbar`: read once
    /// per scroller a gesture starts over.
    pub overscroll: Overscroll,
    /// On a table: lines of this colour between its columns and between
    /// its rows, drawn with the table's own box, under its cells, down the
    /// middle of each gap, so a table with a `gap` of at least `rule_w`
    /// gets a grid with no rule cells. The
    /// columns come from the row with the most cells; the lines run the
    /// table's content box. Ignored on anything that is not a table.
    pub rules: Option<Color>,
    /// The rules' width in logical px; 0 is 1.
    pub rule_w: f32,
    /// A gradient painted over the node's `bg` and under its border and
    /// its children (`docs/adr/0042-a-gradient-is-an-image-the-core-paints.md`):
    /// one image quad from the atlas, rounded by the node's radius. It
    /// does not tween, and the state backgrounds replace `bg`, not it.
    pub gradient: Option<crate::gradient::Gradient>,
    /// Blur what the app drew beneath this node, inside its rounded rect,
    /// by this radius in logical px — CSS's `backdrop-filter: blur()`
    /// (backlog F129). The blurred pixels are what was painted before the
    /// node (earlier siblings, ancestors, the window's backdrop), never
    /// the node's own `bg` or children, which paint over them; give it a
    /// translucent `bg` for frosted glass. Clipped as the node is; faded
    /// by its group opacity. 0 is none. A renderer with no way to read
    /// back its frame (the CPU raster) draws the node unblurred.
    pub backdrop_blur: f32,
}

/// A scrolling node's bars, per node. Every field's default is the stock
/// bar — the theme's `scrollbar` / `scrollbar_active` colours, 4 px at
/// rest and 6 px under the pointer, always drawn while the content
/// overflows — so a binding that sets none of the four rows gets exactly
/// what it always had. The bars are overlays and take no layout space
/// whatever their width; the grabbable track is at least as wide as the
/// active thumb plus its inset.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Scrollbar {
    /// Whether the bars are drawn at all, and when (see [`ScrollbarMode`]).
    pub mode: ScrollbarMode,
    /// The thumb's width at rest, logical px; under the pointer or dragged
    /// it is 2 px wider. `None` is the stock 4.
    pub width: Option<f32>,
    /// The thumb at rest; `None` is `theme.scrollbar`.
    pub color: Option<Color>,
    /// The thumb under the pointer or dragged; `None` is
    /// `theme.scrollbar_active`.
    pub active_color: Option<Color>,
}

impl Scrollbar {
    /// The stock bar: visible, 4 px, in the theme's colours.
    pub const DEFAULT: Self = Self {
        mode: ScrollbarMode::Visible,
        width: None,
        color: None,
        active_color: None,
    };
}

/// When a scrolling node's bars are drawn. Spelled by the `scrollbar` row
/// (`crate::schema::SCROLLBARS`, in this order).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollbarMode {
    /// The stock bar: drawn whenever the content overflows.
    #[default]
    Visible,
    /// No thumb is drawn and no track takes the press. The wheel, the
    /// keyboard, `reveal` and the caret still scroll the node — a list
    /// drawing its own indicator, or one whose bar would sit on a border.
    Hidden,
    /// The bar shows while the scroll state is changing — the offset or
    /// the content's extent moved since the last frame, the pointer is on
    /// its track, or a thumb is being dragged — and for a second after,
    /// then fades out over a quarter of one. A node first seen shows its
    /// bar the same second. What an overlay bar does on macOS. Needs the
    /// driver's clock (`Core::set_time`); without one it is `Visible`,
    /// since a fade with no clock could never end.
    Auto,
}

impl ScrollbarMode {
    /// Every mode, in the `scrollbar` row's order: what a binding that
    /// spells modes as numbers indexes (C's `KUI_SCROLLBAR_*` are these
    /// plus one).
    pub const ALL: [ScrollbarMode; 3] = [
        ScrollbarMode::Visible,
        ScrollbarMode::Hidden,
        ScrollbarMode::Auto,
    ];
}

/// What a scroll gesture that starts over a scroller already at its limit
/// does: CSS's `overscroll-behavior`, spelled by the `overscroll` row.
///
/// A gesture picks its target when it starts: the innermost scroller
/// under the pointer that can still move the way it goes. One at its
/// limit is passed by, to the scroller around it — *chaining* — and
/// `Contain` stops that: the gesture is this scroller's, and moves
/// nothing until it turns back. Only on the axes the node scrolls, so a
/// `scroll_y` list that contains still passes a sideways swipe to the
/// strip it sits in, where CSS would stop that too. Decided at
/// the start only: a gesture that reaches a limit midway stops there
/// whatever this says, as a browser's does.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Overscroll {
    /// The gesture goes on to the scroller around this one when this one
    /// is at its limit that way.
    #[default]
    Auto,
    /// A gesture that starts here stays here: a panel, a popup's list or
    /// a sheet whose scrolling must never move the page behind it.
    Contain,
}

impl Overscroll {
    /// Every value, in the `overscroll` row's order (C's
    /// `KUI_OVERSCROLL_*` are these plus one).
    pub const ALL: [Overscroll; 2] = [Overscroll::Auto, Overscroll::Contain];
}

/// Which axes an `on_scroll` node takes, spelled by the `scrollAxes` row.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollAxes {
    /// Both: the node hears every scroll gesture that starts over it.
    #[default]
    Both,
    /// Only sideways; a vertical gesture passes it by.
    X,
    /// Only vertical; a sideways gesture passes it by — a terminal's
    /// history, a log.
    Y,
}

impl ScrollAxes {
    /// Every value, in the `scrollAxes` row's order (C's
    /// `KUI_SCROLL_AXES_*` are these plus one).
    pub const ALL: [ScrollAxes; 3] = [ScrollAxes::Both, ScrollAxes::X, ScrollAxes::Y];

    /// Whether the node takes `x` (true) or `y` (false).
    pub fn takes(self, x: bool) -> bool {
        match self {
            ScrollAxes::Both => true,
            ScrollAxes::X => x,
            ScrollAxes::Y => !x,
        }
    }
}

impl InteractSpec {
    /// The group as a node that declares none of it — what
    /// `NodeSpec`'s accessor hands back when the box is `None`.
    pub const EMPTY: Self = Self {
        hover_bg: None,
        pressed_bg: None,
        hover_group: None,
        click_sound: None,
        hover_sound: None,
        focus_bg: None,
        drop_bg: None,
        selectable: false,
        focus_region: false,
        scrollbar: Scrollbar::DEFAULT,
        overscroll: Overscroll::Auto,
        rules: None,
        rule_w: 0.0,
        gradient: None,
        backdrop_blur: 0.0,
    };
}

impl NodeSpec {
    // -- Boxed groups ------------------------------------------------------
    // The four cold groups are behind a pointer each: a node that
    // declares none of a group pays 8 bytes for it rather than its full
    // width. Reads go through the `&` accessor, which hands back a shared
    // empty group instead of allocating, so a caller reads
    // `spec.events().on_click` exactly as it used to read `spec.on_click`.
    // Writes go through the `_mut` accessor, which allocates on first use.

    /// Event payloads this node declares, empty if it declares none.
    #[inline]
    pub fn events(&self) -> &EventSpec {
        static EMPTY: EventSpec = EventSpec::EMPTY;
        self.events.as_deref().unwrap_or(&EMPTY)
    }

    /// Allocates the group on first write.
    #[inline]
    pub fn events_mut(&mut self) -> &mut EventSpec {
        self.events.get_or_insert_with(Box::default)
    }

    /// Animation declarations, empty if this node has none.
    #[inline]
    pub fn anim(&self) -> &AnimSpec {
        static EMPTY: AnimSpec = AnimSpec::EMPTY;
        self.anim.as_deref().unwrap_or(&EMPTY)
    }

    /// Allocates the group on first write.
    #[inline]
    pub fn anim_mut(&mut self) -> &mut AnimSpec {
        self.anim.get_or_insert_with(Box::default)
    }

    /// Declared accessibility properties, empty if this node declares none.
    #[inline]
    pub fn access(&self) -> &AccessSpec {
        static EMPTY: AccessSpec = AccessSpec::EMPTY;
        self.access.as_deref().unwrap_or(&EMPTY)
    }

    /// Allocates the group on first write.
    #[inline]
    pub fn access_mut(&mut self) -> &mut AccessSpec {
        self.access.get_or_insert_with(Box::default)
    }

    /// Hover / pressed / focus styling, empty if this node declares none.
    #[inline]
    pub fn interact(&self) -> &InteractSpec {
        static EMPTY: InteractSpec = InteractSpec::EMPTY;
        self.interact.as_deref().unwrap_or(&EMPTY)
    }

    /// Allocates the group on first write.
    #[inline]
    pub fn interact_mut(&mut self) -> &mut InteractSpec {
        self.interact.get_or_insert_with(Box::default)
    }

    /// Whether the core registers a hit region for this node (any of the
    /// interaction props, or an explicit `hoverable`).
    pub fn hover_tracked(&self) -> bool {
        // Asked of every node at emission; the inline flags first, then
        // each boxed group once — a node that declares neither group is
        // answered by two null checks rather than a read per field.
        self.hoverable
            || self.focusable
            || self.window.is_some()
            // A `cursor` override has to be found under the pointer to be
            // read, even on an otherwise inert box.
            || self.cursor.is_some()
            || self.events.as_deref().is_some_and(|e| {
                // A modal's own background is not "outside" it: a press
                // there must find a region.
                e.modal.is_some()
                    || e.on_click.is_some()
                    || e.on_drag.is_some()
                    || e.on_key.is_some()
                    || e.on_context_menu.is_some()
                    || e.on_force_click.is_some()
                    || e.on_button.is_some()
                    || e.on_hover.is_some()
                    || e.on_drop.is_some()
                    || e.on_change.is_some()
            })
            || self.interact.as_deref().is_some_and(|i| {
                i.hover_bg.is_some()
                    || i.pressed_bg.is_some()
                    || i.drop_bg.is_some()
                    || i.hover_group.is_some()
                    || i.click_sound.is_some()
                    || i.hover_sound.is_some()
                    // A selection scope has to be found under the pointer:
                    // the press that starts a drag-select lands on it.
                    || i.selectable
                    // So does a focus region: a press on its dead space
                    // settles the ring there.
                    || i.focus_region
            })
    }

    /// The group id `hover_group(name)` assigns — reproducible from any
    /// binding (the same FNV mix as `Key`).
    pub fn hover_group_id(name: &str) -> u64 {
        crate::key::Key::ROOT.str(name).0
    }

    /// A container that lays its children out left to right.
    pub fn row() -> Self {
        Self {
            layout: LayoutSpec {
                dir: Dir::Row,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// A container that lays its children out top to bottom (the default).
    pub fn column() -> Self {
        Self {
            layout: LayoutSpec {
                dir: Dir::Column,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// A table: a column whose rows' children line up in columns. Its
    /// in-flow `Row` children are the rows and each row's in-flow children
    /// its cells; the nth cell of every row is column n, and a column is
    /// as wide as its widest cell, so a label column sits at its longest
    /// label with no width picked by hand.
    ///
    /// A cell's `width` says how its column sizes: `Fit` (the default) and
    /// `Fixed` are content the column's fit width is the max of, `Grow`
    /// makes the whole column grow with the table, and a column's
    /// `min_width` / `max_width` are the strictest its cells declared.
    /// Give the rows `width: grow` for the columns to grow into; a `Fit`
    /// row sits at the columns' fit width. Rows keep their own `gap`,
    /// padding, background, click and hover, and never wrap. A bare text
    /// or image straight inside a row is a cell too. A text, a column or a
    /// table straight under the table is a child with its own width and no
    /// cells. Everything else is a column's: `gap` is the space between
    /// rows, `scroll_y` scrolls them.
    ///
    /// ```rust
    /// use kui_core::{NodeSpec, Sizing};
    /// let table = NodeSpec::table().gap(4.0).rules(kui_core::Color::hex(0x80808080));
    /// let row = NodeSpec::row().width(Sizing::GROW).gap(12.0);
    /// assert!(table.layout.is_table() && !row.layout.is_table());
    /// ```
    pub fn table() -> Self {
        Self {
            layout: LayoutSpec {
                dir: Dir::Column,
                table: true,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// A [`Sizing`], or a number of px (`.width(120.0)`).
    #[inline]
    pub fn width(mut self, s: impl Into<Sizing>) -> Self {
        self.layout.width = s.into();
        self
    }

    /// A [`Sizing`], or a number of px (`.height(24.0)`).
    #[inline]
    pub fn height(mut self, s: impl Into<Sizing>) -> Self {
        self.layout.height = s.into();
        self
    }

    /// Both axes at once: `.size(20.0, 20.0)` for a fixed box,
    /// `.size(Sizing::GROW, 24.0)` for a strip.
    #[inline]
    pub fn size(self, w: impl Into<Sizing>, h: impl Into<Sizing>) -> Self {
        self.width(w).height(h)
    }

    /// An equal share of the leftover width: `.width(Sizing::GROW)`.
    #[inline]
    pub fn grow_width(self) -> Self {
        self.width(Sizing::GROW)
    }

    /// An equal share of the leftover height: `.height(Sizing::GROW)`.
    #[inline]
    pub fn grow_height(self) -> Self {
        self.height(Sizing::GROW)
    }

    /// Grow along both axes.
    #[inline]
    pub fn fill(self) -> Self {
        self.grow_width().grow_height()
    }

    /// A number of px, [`Min::FIT`] for the node's own fit width, or a
    /// [`Bound::Calc`].
    pub fn min_width(mut self, v: impl Into<Bound>) -> Self {
        self.layout.min_w = match v.into() {
            Bound::Px(px) if px == 0.0 && px.is_sign_negative() => Min::AUTO,
            Bound::Px(px) => Min::px(px),
            Bound::Fit => Min::FIT,
            Bound::Calc(c) => Min::calc(c),
        };
        self
    }

    /// A number of px, or a [`Bound::Calc`]; a max has no fit size, so
    /// [`Bound::Fit`] is no clamp. A px ceiling below zero, or `NaN`, is
    /// a ceiling of 0 ([`px_ceiling`]).
    pub fn max_width(mut self, v: impl Into<Bound>) -> Self {
        self.layout.max_w = match v.into() {
            Bound::Px(px) => px_ceiling(px),
            Bound::Fit => f32::INFINITY,
            Bound::Calc(c) => max_of_calc(c),
        };
        self
    }

    /// A number of px, [`Min::FIT`] for the node's own fit height, or a
    /// [`Bound::Calc`].
    pub fn min_height(mut self, v: impl Into<Bound>) -> Self {
        self.layout.min_h = match v.into() {
            Bound::Px(px) if px == 0.0 && px.is_sign_negative() => Min::AUTO,
            Bound::Px(px) => Min::px(px),
            Bound::Fit => Min::FIT,
            Bound::Calc(c) => Min::calc(c),
        };
        self
    }

    /// The four clamps where each is given, a transport's shape (C's
    /// `*_size` fields): `None` leaves that clamp as it is.
    pub fn with_bounds(
        self,
        min_w: Option<Bound>,
        max_w: Option<Bound>,
        min_h: Option<Bound>,
        max_h: Option<Bound>,
    ) -> Self {
        let mut s = self;
        if let Some(b) = min_w {
            s = s.min_width(b);
        }
        if let Some(b) = max_w {
            s = s.max_width(b);
        }
        if let Some(b) = min_h {
            s = s.min_height(b);
        }
        if let Some(b) = max_h {
            s = s.max_height(b);
        }
        s
    }

    /// Clip children to this node's rect without scrolling. A `radius` on
    /// the same node rounds the clip, so children stay inside its corners
    /// (see `display::Clip`).
    pub fn clip(mut self) -> Self {
        self.layout.clip = true;
        self
    }

    /// Vertical scrolling (and clipping) for overflowing content.
    pub fn scroll_y(mut self) -> Self {
        self.layout.scroll_y = true;
        self
    }

    /// Horizontal scrolling (and clipping) for overflowing content.
    pub fn scroll_x(mut self) -> Self {
        self.layout.scroll_x = true;
        self
    }

    /// Scroll anchoring on this container (see [`LayoutSpec::anchor`]):
    /// the first child in view stays where it is on screen when the
    /// content before it changes size. Needs `scroll_y` on a column or
    /// `scroll_x` on a row.
    pub fn anchor(mut self) -> Self {
        self.layout.anchor = true;
        self
    }

    /// Take this node out of flex flow; see [`FloatConfig`].
    pub fn float(mut self, cfg: FloatConfig) -> Self {
        self.layout.float = Some(cfg);
        self
    }

    /// Apply the overflow bits ([`OVERFLOW_CLIP`] and friends). What a bit
    /// means is decided here: a binding ORs together whatever its own
    /// surface spells (`clip`, `scrollX`, `overflow`) and hands the number
    /// over, rather than each one re-deciding that scrolling clips too.
    pub fn overflow_bits(mut self, bits: u32) -> Self {
        if bits & OVERFLOW_CLIP != 0 {
            self = self.clip();
        }
        if bits & OVERFLOW_SCROLL_X != 0 {
            self = self.scroll_x();
        }
        if bits & OVERFLOW_SCROLL_Y != 0 {
            self = self.scroll_y();
        }
        self
    }

    /// A tooltip: the node tracks hover, `hint` is its accessible
    /// description, and the core floats the hint below it while it is
    /// hovered. On a box or a fragment the float is the node's last child;
    /// on a leaf — an image, an editor, a cells grid, a line, a polygon, a
    /// path — which holds no children, it floats beside the leaf, anchored
    /// to it ([`FloatAnchor::Node`]), and lands below the leaf's box all
    /// the same (backlog RG113).
    #[inline]
    pub fn tooltip(self, hint: &str) -> Self {
        let mut spec = self.apply_tooltip(hint);
        spec.access_mut().tooltip = true;
        spec
    }

    /// The spec half of the `tooltip` prop: the hint is hover-gated, so the
    /// node tracks hover, and it is what assistive technology should say, so
    /// it is the accessible description too — and nothing floats. For a
    /// caller that floats the hint itself: [`crate::schema::PropsOut::apply_tooltip`]
    /// for the parsers, `kui_close` for C, a widget that draws its own. A
    /// Rust view wants [`Self::tooltip`], which is all three.
    pub fn apply_tooltip(self, hint: &str) -> Self {
        self.hoverable().description(hint)
    }

    /// A number of px, or a [`Bound::Calc`]; [`Bound::Fit`] is no clamp.
    /// A px ceiling below zero, or `NaN`, is a ceiling of 0.
    pub fn max_height(mut self, v: impl Into<Bound>) -> Self {
        self.layout.max_h = match v.into() {
            Bound::Px(px) => px_ceiling(px),
            Bound::Fit => f32::INFINITY,
            Bound::Calc(c) => max_of_calc(c),
        };
        self
    }

    /// The same padding on all four edges, logical px.
    pub fn pad(mut self, v: f32) -> Self {
        self.layout.padding = Edges::all(v);
        self
    }

    /// Padding `x` on the left and right, `y` on the top and bottom.
    pub fn pad_xy(mut self, x: f32, y: f32) -> Self {
        self.layout.padding = Edges::xy(x, y);
        self
    }

    /// Padding per edge.
    pub fn padding(mut self, e: Edges) -> Self {
        self.layout.padding = e;
        self
    }

    /// Space between children along the main axis, logical px.
    pub fn gap(mut self, v: f32) -> Self {
        self.layout.gap = v;
        self
    }

    /// Wrap overflowing children onto more lines; see [`LayoutSpec::wrap`].
    pub fn wrap(mut self) -> Self {
        self.layout.wrap = true;
        self
    }

    /// Space between wrap lines (across the main axis).
    pub fn cross_gap(mut self, v: f32) -> Self {
        self.layout.cross_gap = v;
        self
    }

    /// Where children sit along the main axis; the spreads are allowed.
    pub fn main_align(mut self, a: Align) -> Self {
        self.layout.main_align = a;
        self
    }

    /// Where children sit across the main axis; `Baseline` on a row.
    pub fn cross_align(mut self, a: Align) -> Self {
        self.layout.cross_align = a;
        self
    }

    /// Width over height (CSS's `aspect-ratio`): see
    /// [`LayoutSpec::aspect`]. `16.0 / 9.0` for a video, `1.0` for a
    /// square. A ratio that is not positive and finite clears it.
    pub fn aspect_ratio(mut self, ratio: f32) -> Self {
        self.layout.aspect = if ratio.is_finite() && ratio > 0.0 {
            ratio
        } else {
            0.0
        };
        self
    }

    /// Center children on both axes.
    pub fn center(self) -> Self {
        self.main_align(Align::Center).cross_align(Align::Center)
    }

    /// The background colour.
    pub fn bg(mut self, c: Color) -> Self {
        self.style.bg = c;
        self
    }

    /// Rounds all four corners by `r`. On a node that also clips or
    /// scrolls it rounds the clip too, so its children are cut to the same
    /// corners rather than poking square out of them.
    pub fn radius(mut self, r: f32) -> Self {
        self.style.radius = [r; 4];
        self
    }

    /// Per-corner radii, clockwise from the top-left.
    pub fn radii(mut self, tl: f32, tr: f32, br: f32, bl: f32) -> Self {
        self.style.radius = [tl, tr, br, bl];
        self
    }

    pub fn radius_tl(mut self, r: f32) -> Self {
        self.style.radius[corner::TL] = r;
        self
    }

    pub fn radius_tr(mut self, r: f32) -> Self {
        self.style.radius[corner::TR] = r;
        self
    }

    pub fn radius_br(mut self, r: f32) -> Self {
        self.style.radius[corner::BR] = r;
        self
    }

    pub fn radius_bl(mut self, r: f32) -> Self {
        self.style.radius[corner::BL] = r;
        self
    }

    /// Rounds the two top corners (tabs, headers).
    pub fn radius_top(self, r: f32) -> Self {
        self.radius_tl(r).radius_tr(r)
    }

    /// Rounds the two bottom corners.
    pub fn radius_bottom(self, r: f32) -> Self {
        self.radius_br(r).radius_bl(r)
    }

    /// A border `w` px wide in `c`, inside the node's box.
    pub fn border(mut self, w: f32, c: Color) -> Self {
        self.style.border_w = w;
        self.style.border_color = c;
        self
    }

    /// Paints this node's background, border, shadow and fragment on whole pixels
    /// (see `VisualStyle::pixel_snap`).
    pub fn pixel_snap(mut self) -> Self {
        self.style.pixel_snap = true;
        self
    }

    /// Fades this node and everything under it (see `VisualStyle::opacity`);
    /// clamped to 0..=1.
    pub fn opacity(mut self, o: f32) -> Self {
        self.style.opacity = o.clamp(0.0, 1.0);
        self
    }

    /// The whole drop shadow at once: color, offset, blur, spread.
    pub fn shadow(mut self, shadow: Shadow) -> Self {
        self.style.shadow = shadow;
        self
    }

    /// The shadow's color — on its own, a hard shadow exactly behind the
    /// node. Nothing else about a shadow draws without it.
    pub fn shadow_color(mut self, c: Color) -> Self {
        self.style.shadow.color = c;
        self
    }

    pub fn shadow_blur(mut self, blur: f32) -> Self {
        self.style.shadow.blur = blur;
        self
    }

    pub fn shadow_offset(mut self, dx: f32, dy: f32) -> Self {
        self.style.shadow.dx = dx;
        self.style.shadow.dy = dy;
        self
    }

    pub fn shadow_x(mut self, dx: f32) -> Self {
        self.style.shadow.dx = dx;
        self
    }

    pub fn shadow_y(mut self, dy: f32) -> Self {
        self.style.shadow.dy = dy;
        self
    }

    pub fn shadow_spread(mut self, spread: f32) -> Self {
        self.style.shadow.spread = spread;
        self
    }

    /// Hover-track this node without making it clickable; see the
    /// `hoverable` field.
    pub fn hoverable(mut self) -> Self {
        self.hoverable = true;
        self
    }

    /// Ask for another frame after this one, for as long as this node is
    /// declared. See the `animate` prop.
    pub fn animate(mut self) -> Self {
        self.animate = true;
        self
    }

    /// Background from the OS accent colour where the host knows it; see
    /// the field.
    pub fn accent(mut self) -> Self {
        self.accent = true;
        self
    }

    /// Makes this node clickable: a click emits `payload` as a
    /// [`UiEvent`](crate::input::UiEvent), and the node joins the Tab ring
    /// and reads as a button to assistive technology.
    pub fn on_click(mut self, payload: impl Into<Value>) -> Self {
        self.events_mut().on_click = Some(payload.into());
        self
    }

    /// Background while hovered (see the `hover_bg` field).
    pub fn hover_bg(mut self, c: Color) -> Self {
        self.interact_mut().hover_bg = Some(c);
        self
    }

    /// Background while dragged files are over this node (see the
    /// `drop_bg` field).
    pub fn drop_bg(mut self, c: Color) -> Self {
        self.interact_mut().drop_bg = Some(c);
        self
    }

    /// Paints `gradient` over this node's `bg`, under its border and
    /// its children (see the `gradient` field).
    pub fn gradient(mut self, gradient: crate::gradient::Gradient) -> Self {
        self.interact_mut().gradient = Some(gradient);
        self
    }

    /// Blurs what was drawn beneath this node, inside its rounded rect,
    /// by `radius` logical px (see the `backdrop_blur` field). A
    /// translucent `bg` over it makes frosted glass:
    ///
    /// ```
    /// # use kui_core::{Color, NodeSpec};
    /// let bar = NodeSpec::row().backdrop_blur(16.0).bg(Color::hex(0xffffff40));
    /// assert_eq!(bar.interact().backdrop_blur, 16.0);
    /// ```
    pub fn backdrop_blur(mut self, radius: f32) -> Self {
        self.interact_mut().backdrop_blur = radius.max(0.0);
        self
    }

    /// A table's grid rules in `c` (see the `rules` field).
    pub fn rules(mut self, c: Color) -> Self {
        self.interact_mut().rules = Some(c);
        self
    }

    /// The rules' width in logical px; 1 when unset (see `rules`).
    pub fn rule_width(mut self, w: f32) -> Self {
        self.interact_mut().rule_w = w;
        self
    }

    /// Makes this node a selection scope (see the `selectable` field):
    /// the text inside it becomes one selectable run.
    pub fn selectable(mut self) -> Self {
        self.interact_mut().selectable = true;
        self
    }

    /// Makes this node's subtree a focus region (see the `focus_region`
    /// field): a Tab ring of its own, entered on purpose.
    pub fn focus_region(mut self) -> Self {
        self.interact_mut().focus_region = true;
        self
    }

    /// Whether a scroll gesture starting over this scroller at its limit
    /// goes on to the one around it (see [`Overscroll`]):
    /// `Overscroll::Contain` keeps it here.
    pub fn overscroll(mut self, o: Overscroll) -> Self {
        self.interact_mut().overscroll = o;
        self
    }

    /// When this node's scrollbars are drawn (see [`ScrollbarMode`]).
    /// Scrolling itself is unchanged whatever the mode.
    pub fn scrollbar(mut self, mode: ScrollbarMode) -> Self {
        self.interact_mut().scrollbar.mode = mode;
        self
    }

    /// The thumb's width at rest, logical px (see [`Scrollbar::width`]).
    pub fn scrollbar_width(mut self, w: f32) -> Self {
        self.interact_mut().scrollbar.width = Some(w);
        self
    }

    /// The thumb's colour at rest (see [`Scrollbar::color`]).
    pub fn scrollbar_color(mut self, c: Color) -> Self {
        self.interact_mut().scrollbar.color = Some(c);
        self
    }

    /// The thumb's colour under the pointer or dragged (see
    /// [`Scrollbar::active_color`]).
    pub fn scrollbar_active_color(mut self, c: Color) -> Self {
        self.interact_mut().scrollbar.active_color = Some(c);
        self
    }

    /// Background while pressed (see the `pressed_bg` field).
    pub fn pressed_bg(mut self, c: Color) -> Self {
        self.interact_mut().pressed_bg = Some(c);
        self
    }

    /// Background while keyboard-visibly focused (see the `focus_bg`
    /// field); replaces the default focus ring.
    pub fn focus_bg(mut self, c: Color) -> Self {
        self.interact_mut().focus_bg = Some(c);
        self
    }

    /// Puts this node in the Tab ring (see the `focusable` field).
    pub fn focusable(mut self) -> Self {
        self.focusable = true;
        self
    }

    /// Hears focus entering and leaving this subtree (see the `on_focus`
    /// field).
    pub fn on_focus(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_focus = Some(tag.into());
        self
    }

    /// A press here leaves keyboard focus where it was (see the
    /// `keep_focus` field).
    pub fn keep_focus(mut self) -> Self {
        self.events_mut().keep_focus = true;
        self
    }

    /// Makes this node the modal scope's entry focus (see the
    /// `initial_focus` field).
    pub fn initial_focus(mut self) -> Self {
        self.initial_focus = true;
        self
    }

    /// Makes this node inert (see the `disabled` field).
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Makes this node the frame's modal surface (see the `modal` field).
    #[inline]
    pub fn modal(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().modal = Some(tag.into());
        self
    }

    /// Joins the hover group `name` (see the `hover_group` field).
    pub fn hover_group(mut self, name: &str) -> Self {
        self.interact_mut().hover_group = Some(Self::hover_group_id(name));
        self
    }

    /// Emits enter/leave events for this node (see the `on_hover` field).
    /// Pass a tag the handler can match on; `Value::Null` if the node key
    /// is identification enough.
    pub fn on_hover(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_hover = Some(tag.into());
        self
    }

    /// Makes this node a drop zone for files dragged in from the OS (see
    /// the `on_drop` field).
    pub fn on_drop(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_drop = Some(tag.into());
        self
    }

    /// Plays a registered sound when this node is clicked (see the
    /// `click_sound` field).
    pub fn click_sound(mut self, sound: crate::resources::SoundId) -> Self {
        self.interact_mut().click_sound = Some(sound);
        self
    }

    /// Plays a registered sound when the pointer enters this node (see the
    /// `hover_sound` field).
    pub fn hover_sound(mut self, sound: crate::resources::SoundId) -> Self {
        self.interact_mut().hover_sound = Some(sound);
        self
    }

    /// Makes this node draggable (see the `on_drag` field). Pass a tag the
    /// handler can match on; `Value::Null` if the node key is enough.
    pub fn on_drag(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_drag = Some(tag.into());
        self
    }

    /// Reports this node's laid-out rect as an event whenever it changes
    /// (see the `on_layout` field). Pass a tag the handler can match on;
    /// `Value::Null` if the node key is identification enough.
    pub fn on_layout(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_layout = Some(tag.into());
        self
    }

    /// What this node is to assistive technology (see the `role` field).
    pub fn role(mut self, role: Role) -> Self {
        self.access_mut().role = Some(role);
        self
    }

    /// The accessible name (see the `label` field). Takes an `Arc<str>`
    /// as well as a `&str`, so a view can keep one and hand it out every
    /// frame without allocating.
    pub fn label(mut self, label: impl Into<Label>) -> Self {
        self.access_mut().label = Some(label.into());
        self
    }

    /// The accessible description (see the `description` field).
    pub fn description(mut self, description: impl Into<Label>) -> Self {
        self.access_mut().description = Some(description.into());
        self
    }

    /// The on state for a checkbox / radio / switch role.
    pub fn checked(mut self, checked: bool) -> Self {
        self.access_mut().checked = checked;
        self
    }

    /// A checkbox that is neither on nor off (see the `mixed` field).
    pub fn mixed(mut self, mixed: bool) -> Self {
        self.access_mut().mixed = mixed;
        self
    }

    /// The current one of a set (see the `selected` field).
    pub fn selected(mut self, selected: bool) -> Self {
        self.access_mut().selected = selected;
        self
    }

    /// A disclosure's state (see the `expanded` field).
    pub fn expanded(mut self, expanded: bool) -> Self {
        self.access_mut().expanded = Some(expanded);
        self
    }

    /// Marks this node a live region (see the `live` field).
    pub fn live(mut self, live: Live) -> Self {
        self.access_mut().live = live;
        self
    }

    /// A slider role's current value.
    pub fn value_now(mut self, v: f32) -> Self {
        self.access_mut().value_now = Some(v);
        self
    }

    pub fn value_min(mut self, v: f32) -> Self {
        self.access_mut().value_min = Some(v);
        self
    }

    pub fn value_max(mut self, v: f32) -> Self {
        self.access_mut().value_max = Some(v);
        self
    }

    /// How far one arrow key moves a slider (see the `value_step` field).
    /// A step that is not positive and finite clears it.
    pub fn value_step(mut self, v: f32) -> Self {
        self.access_mut().value_step = (v.is_finite() && v > 0.0).then_some(v);
        self
    }

    /// Asks the core for a slider's changes (see the `on_change` field).
    pub fn on_change(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_change = Some(tag.into());
        self
    }

    /// What a slider's position reads as (see the `value_text` field).
    pub fn value_text(mut self, text: impl Into<Label>) -> Self {
        self.access_mut().value_text = Some(text.into());
        self
    }

    /// On a `Role::Line` of a custom editor: the caret's byte offset into
    /// this line's text (see the `caret` field).
    pub fn caret(mut self, offset: u32) -> Self {
        self.access_mut().caret = Some(offset);
        self
    }

    /// On a `Role::Line` of a custom editor: the byte offset where the
    /// selection's other end sits (see the `selection_anchor` field).
    pub fn selection_anchor(mut self, offset: u32) -> Self {
        self.access_mut().selection_anchor = Some(offset);
        self
    }

    /// On a `Role::Line` declaring `caret`: the caret is solid, not a
    /// caret to blink (see the `caret_solid` field). A block caret in a
    /// modal editor's normal mode — the one thing that otherwise asks an
    /// idle app for a frame twice a second.
    pub fn caret_solid(mut self) -> Self {
        self.access_mut().caret_solid = true;
        self
    }

    /// Makes this node a key sink (see `NodeSpec::on_key` field). Pass a
    /// tag the handler can match on; `Value::Null` if the node key is
    /// identification enough.
    pub fn on_key(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_key = Some(tag.into());
        self
    }

    /// A key sink with no tag — `on_key(Value::Null)`, for a handler that
    /// knows the node by its key.
    #[inline]
    pub fn key_sink(self) -> Self {
        self.on_key(Value::Null)
    }

    /// Delivers releases to this key sink as well as presses (see the
    /// `key_up` field). Meaningless without `on_key`.
    pub fn key_up(mut self) -> Self {
        self.events_mut().key_up = true;
        self
    }

    /// Delivers the modifier and lock keys to this key sink as keys of
    /// their own (see the `modifier_keys` field). Meaningless without
    /// `on_key`.
    pub fn modifier_keys(mut self) -> Self {
        self.events_mut().modifier_keys = true;
        self
    }

    /// Asks for force-click events on this node (see the
    /// `on_force_click` field).
    pub fn on_force_click(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_force_click = Some(tag.into());
        self
    }

    /// Asks for the non-primary buttons pressed over this node as events,
    /// each captured by it until its release (see the `on_button` field):
    /// `{kind="button", phase, button, x, y, tag}`. Every such button
    /// unless [`NodeSpec::buttons`] narrows it.
    pub fn on_button(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_button = Some(tag.into());
        self
    }

    /// Which non-primary buttons `on_button` claims (see the `buttons`
    /// field): `Buttons::MIDDLE`, `Buttons::SECONDARY | Buttons::MIDDLE`.
    /// Meaningless without `on_button`.
    pub fn buttons(mut self, buttons: Buttons) -> Self {
        self.events_mut().buttons = buttons;
        self
    }

    /// Asks for the wheel over this node as events (see the `on_scroll`
    /// field): `{kind="scroll", x, y, dx, dy, lines, tag}`.
    pub fn on_scroll(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_scroll = Some(tag.into());
        self
    }

    /// Which axes `on_scroll` takes (see the `scroll_axes` field):
    /// `ScrollAxes::Y` for a terminal's history, so a sideways gesture
    /// passes it by. Meaningless without `on_scroll`.
    pub fn scroll_axes(mut self, axes: ScrollAxes) -> Self {
        self.events_mut().scroll_axes = axes;
        self
    }

    /// The modifiers `on_scroll` is for (see the `scroll_mods` field):
    /// `KeyMods::NONE.with_ctrl().with_super()` hears a wheel turned with
    /// Ctrl or ⌘ held, ahead of every scroller under the pointer, and no
    /// other wheel. Meaningless without `on_scroll`.
    pub fn scroll_mods(mut self, mods: crate::input::KeyMods) -> Self {
        self.events_mut().scroll_mods = mods;
        self
    }

    /// Asks for a context menu on this node (see the `on_context_menu`
    /// field). Pass a tag the handler can match on; `Value::Null` if the
    /// node key is identification enough.
    pub fn on_context_menu(mut self, tag: impl Into<Value>) -> Self {
        self.events_mut().on_context_menu = Some(tag.into());
        self
    }

    /// Animates changes to this node's sizing amounts, colors and radius
    /// over `duration_ms` (cubic ease-out); see [`crate::anim`]. Only the
    /// duration: an easing or repeat already declared survives, so the
    /// transition props compose in any order.
    ///
    /// On a scroll container it also eases the offset a `reveal` or a
    /// `set_scroll` moves it to; the wheel, the thumb and a drag past the
    /// edge still land whole.
    ///
    /// ```rust
    /// use kui_core::{Easing, NodeSpec, Sizing};
    /// // Eases toward whatever width the view declares next frame.
    /// let pane = NodeSpec::column().width(Sizing::Fixed(240.0)).transition(180.0).easing(Easing::Smooth);
    /// assert_eq!(pane.transition.unwrap().duration_ms, 180.0);
    /// ```
    pub fn transition(mut self, duration_ms: f32) -> Self {
        let t = self.transition.get_or_insert(Transition::ms(duration_ms));
        t.duration_ms = duration_ms;
        self
    }

    /// The whole [`Transition`] at once, replacing any declared so far.
    pub fn transition_with(mut self, t: Transition) -> Self {
        self.transition = Some(t);
        self
    }

    /// Also ease this node's position (see the `slide` field); sets a
    /// default 200ms transition if none was declared yet.
    pub fn slide(mut self) -> Self {
        self.transition.get_or_insert(Transition::ms(200.0));
        self.slide = true;
        self
    }

    /// Easing for the node's transition (sets a default 200ms one if none
    /// was declared yet).
    pub fn easing(mut self, easing: Easing) -> Self {
        let t = self.transition.get_or_insert(Transition::ms(200.0));
        t.easing = easing;
        self
    }

    /// How far the node's spring overshoots, 0 (glides in) to
    /// [`crate::anim::MAX_BOUNCE`] — in place of the spring easing's own
    /// bounce, and on a timed easing in place of the curve, making it a
    /// spring (see [`Transition::bounce`]). Sets a default 200ms
    /// transition if none was declared yet.
    pub fn bounce(mut self, bounce: f32) -> Self {
        let t = self.transition.get_or_insert(Transition::ms(200.0));
        *t = t.bounce(bounce);
        self
    }

    /// How this node's `keyframes` cycle (CSS's `animation-direction`);
    /// sets a default 200ms transition if none was declared yet.
    pub fn repeat(mut self, repeat: Repeat) -> Self {
        let t = self.transition.get_or_insert(Transition::ms(200.0));
        t.repeat = repeat;
        self
    }

    /// Holds this node's keyframe cycle back by `delay_ms` (CSS's
    /// `animation-delay`), so siblings given different delays run out of
    /// phase — a cascade, a chase light. Sets a default 200ms transition if
    /// none was declared yet.
    pub fn delay(mut self, delay_ms: f32) -> Self {
        let t = self.transition.get_or_insert(Transition::ms(200.0));
        t.delay_ms = delay_ms;
        self
    }

    /// Cycles the slots these stops name (see the `keyframes` field); sets
    /// a default 200ms transition if none was declared yet.
    pub fn keyframes(mut self, stops: Vec<Keyframe>) -> Self {
        self.transition.get_or_insert(Transition::ms(200.0));
        self.anim_mut().keyframes = stops;
        self
    }

    /// Eases this node in from `enter` on its first sight (see the `enter`
    /// field); sets a default 200ms transition if none was declared yet.
    pub fn enter(mut self, enter: Enter) -> Self {
        self.transition.get_or_insert(Transition::ms(200.0));
        self.anim_mut().enter = Some(enter);
        self
    }

    /// Eases this node out to `exit` after the view stops declaring it
    /// (see the `exit` field); sets a default 200ms transition if none was
    /// declared yet.
    pub fn exit(mut self, exit: Enter) -> Self {
        self.transition.get_or_insert(Transition::ms(200.0));
        self.anim_mut().exit = Some(exit);
        self
    }

    /// Pressing this node starts an OS window drag (drivers promote a quick
    /// second press to a maximize toggle).
    pub fn window_drag(mut self) -> Self {
        self.window = Some(WindowRole::Drag);
        self
    }

    /// Clicking this node emits the button's `WindowCommand`.
    pub fn window_button(mut self, button: WindowButton) -> Self {
        self.window = Some(WindowRole::Button(button));
        self
    }

    /// The pointer shape over this node (see the `cursor` field).
    pub fn cursor(mut self, shape: CursorShape) -> Self {
        self.cursor = Some(shape);
        self
    }
}

/// Which face a text shapes with: one of the three stock families, or a
/// font registered with the core.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FontFamily {
    #[default]
    Sans,
    Serif,
    Mono,
    /// A font registered with the core (`Core::add_font_data` from file
    /// bytes, or `Core::add_system_font` by installed family name). A
    /// stale handle shapes as sans-serif. Not on the wire as a family:
    /// the `font` row carries the handle.
    Custom(crate::resources::FontId),
}

impl FontFamily {
    /// The three stock families, in wire order: a binding sends the index.
    /// `Custom` is not a family on the wire; the `font` row is.
    pub const ALL: &'static [FontFamily] = &[FontFamily::Sans, FontFamily::Serif, FontFamily::Mono];

    /// The spelling every binding uses; a registered font has none.
    pub fn name(self) -> Option<&'static str> {
        match self {
            FontFamily::Sans => Some("sans"),
            FontFamily::Serif => Some("serif"),
            FontFamily::Mono => Some("mono"),
            FontFamily::Custom(_) => None,
        }
    }

    /// The variant `schema::FAMILIES` index `i` names; `Sans` for an
    /// index this build lacks.
    pub fn from_index(i: usize) -> FontFamily {
        Self::ALL.get(i).copied().unwrap_or_default()
    }
}

/// How a text node breaks lines at its width.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextWrap {
    /// Break between words; a word wider than the line breaks by glyph.
    #[default]
    Word,
    /// Break anywhere (URLs, hashes, code).
    Glyph,
    /// Never break at the width: one line per paragraph, clipped to the
    /// node's box (explicit newlines still break).
    None,
    /// `Word`, but whitespace takes its room like any glyph — CSS's
    /// `white-space: break-spaces`: a space that does not fit starts the
    /// next row instead of hanging past the edge or vanishing at the
    /// break, so every byte has a place inside the box. An editor's
    /// wrapped line, whose caret stands on each space. A text with line
    /// breaks of its own, a `max_lines` or an `ellipsis` wraps as `Word`.
    BreakSpaces,
}

/// The OpenType features a style asks the shaper for: up to
/// [`FontFeatures::MAX`] four-letter tags with a value each. `liga` 0
/// keeps a coding font from joining `->`, `tnum` 1 gives tabular figures,
/// `ss01` 1 turns on a stylistic set. Plain data and `Copy`, since a
/// `TextStyle` is; the spelling every binding shares is
/// [`FontFeatures::parse`]'s.
///
/// ```rust
/// use kui_core::{FontFeatures, TextStyle};
/// let code = TextStyle::new(13.0).mono().features(FontFeatures::parse("-liga -calt tnum"));
/// assert_eq!(code.features.len(), 3);
/// assert_eq!(code.features.to_string_spelling(), "liga=0 calt=0 tnum=1");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct FontFeatures {
    tags: [[u8; 4]; FontFeatures::MAX],
    values: [u32; FontFeatures::MAX],
    len: u8,
}

impl FontFeatures {
    /// How many features a style can carry. Eight is more than any one
    /// text asks for and keeps the style small.
    pub const MAX: usize = 8;

    /// No features: the font's own defaults.
    pub const fn new() -> Self {
        Self {
            tags: [[b' '; 4]; Self::MAX],
            values: [0; Self::MAX],
            len: 0,
        }
    }

    /// Adds or replaces `tag` (four ASCII characters; shorter is padded
    /// with spaces, longer is cut) with `value`. Past `MAX` the feature is
    /// dropped rather than the style refused.
    pub fn set(mut self, tag: &str, value: u32) -> Self {
        let mut t = [b' '; 4];
        for (i, b) in tag.bytes().take(4).enumerate() {
            t[i] = b;
        }
        let n = self.len as usize;
        if let Some(i) = self.tags[..n].iter().position(|x| *x == t) {
            self.values[i] = value;
        } else if n < Self::MAX {
            self.tags[n] = t;
            self.values[n] = value;
            self.len += 1;
        }
        self
    }

    /// The spelling every binding shares: tags separated by whitespace or
    /// commas, each `tag=value`, a bare `tag` meaning 1 and `-tag` meaning
    /// 0 — `"liga=0 calt=0 tnum"`, `"-liga,-calt"`. Anything else in the
    /// string is skipped.
    pub fn parse(s: &str) -> Self {
        let mut out = Self::new();
        for item in s.split(|c: char| c.is_whitespace() || c == ',') {
            if item.is_empty() {
                continue;
            }
            let (tag, value) = if let Some((t, v)) = item.split_once('=') {
                (t, v.trim().parse::<u32>().unwrap_or(0))
            } else if let Some(t) = item.strip_prefix('-') {
                (t, 0)
            } else if let Some(t) = item.strip_prefix('+') {
                (t, 1)
            } else {
                (item, 1)
            };
            let tag = tag.trim();
            if !tag.is_empty() {
                out = out.set(tag, value);
            }
        }
        out
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    pub fn len(&self) -> usize {
        self.len as usize
    }

    /// Every feature, in the order set, as `(tag, value)`.
    pub fn iter(&self) -> impl Iterator<Item = (&[u8; 4], u32)> + '_ {
        let n = self.len as usize;
        self.tags[..n].iter().zip(self.values[..n].iter().copied())
    }

    /// What `parse` reads: `tag=value` pairs joined by spaces.
    pub fn to_string_spelling(&self) -> String {
        self.iter()
            .map(|(t, v)| format!("{}={}", String::from_utf8_lossy(t).trim_end(), v))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// How a run of text is shaped and painted: size, line height, colour,
/// family, wrapping, line limits, OpenType features and decorations.
///
/// [`TextStyle::new`] takes the font size and derives a line height; the
/// rest are builders. A style with no colour paints in the theme's
/// foreground, so plain text is legible on both the light and dark base.
///
/// ```rust
/// use kui_core::{Color, FontFamily, TextStyle, TextWrap};
///
/// let body = TextStyle::new(15.0).line_height(22.0);
/// let caption = TextStyle::new(12.0).color(Color::hex(0x8a8fa3ff)).max_lines(2).ellipsis();
/// let code = TextStyle::new(13.0).family(FontFamily::Mono).wrap(TextWrap::None);
/// let link = TextStyle::new(15.0).underline().color(Color::hex(0x3b5bd4ff));
///
/// assert_eq!(body.color, None); // the theme's foreground
/// assert_eq!(caption.max_lines, 2);
/// assert!(code.wrap == TextWrap::None && link.underline);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextStyle {
    pub size: f32,
    pub line_height: f32,
    /// `None` is the theme's foreground, filled in as the text enters the
    /// tree so nothing downstream of that ever sees a `None`.
    pub color: Option<Color>,
    pub family: FontFamily,
    pub wrap: TextWrap,
    /// At most this many lines are laid out; 0 = unlimited.
    pub max_lines: u32,
    /// End the last line with "…" when the text was cut off. Alone it
    /// means a single line (`max_lines` 1); with `max_lines` it clamps.
    pub ellipsis: bool,
    /// OpenType features for the shaper; none by default, which is the
    /// font's own defaults (ligatures on, where it has them).
    pub features: FontFeatures,
    /// A line under every glyph, where the face puts its underline. Paint
    /// only: not part of what the text is shaped as.
    pub underline: bool,
    /// The underline's own colour; `None` is the text's.
    pub underline_color: Option<Color>,
    /// The underline's shape: a line, a wave, dots.
    pub underline_style: UnderlineStyle,
    /// A line through every glyph, where the face puts its strikeout.
    pub strikethrough: bool,
}

/// The shape of an underline: the face's line, a wave under a diagnostic,
/// dots. Where it goes and how thick it is are the face's
/// recommendation either way; a wave is three strokes tall around the
/// line's centre with a six-stroke period, dots two strokes across and
/// four apart (`crate::deco`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UnderlineStyle {
    #[default]
    Solid,
    Wavy,
    Dotted,
}

impl UnderlineStyle {
    /// The spellings, in discriminant order (`underlineStyle` /
    /// `underline_style`; C's `KUI_UNDERLINE_*`).
    pub const NAMES: &[&str] = &["solid", "wavy", "dotted"];

    pub fn from_index(i: u32) -> Self {
        match i {
            1 => Self::Wavy,
            2 => Self::Dotted,
            _ => Self::Solid,
        }
    }

    pub fn name(self) -> &'static str {
        Self::NAMES[self as usize]
    }
}

impl Default for TextStyle {
    fn default() -> Self {
        Self::new(16.0)
    }
}

impl TextStyle {
    /// A style at `size` logical px, sans, in the theme's foreground, with
    /// a line height of 1.35 times the size, rounded.
    pub fn new(size: f32) -> Self {
        Self {
            size,
            line_height: (size * 1.35).round(),
            color: None,
            family: FontFamily::Sans,
            wrap: TextWrap::Word,
            max_lines: 0,
            ellipsis: false,
            features: FontFeatures::new(),
            underline: false,
            underline_color: None,
            underline_style: UnderlineStyle::Solid,
            strikethrough: false,
        }
    }

    /// Underlines the text in its own colour.
    pub fn underline(mut self) -> Self {
        self.underline = true;
        self
    }

    /// An underline in its own colour rather than the text's (a
    /// diagnostic's red under keyword-coloured text). Turns the underline
    /// on.
    pub fn underline_color(mut self, c: Color) -> Self {
        self.underline = true;
        self.underline_color = Some(c);
        self
    }

    /// An underline of this shape. Turns the underline on.
    pub fn underline_style(mut self, s: UnderlineStyle) -> Self {
        self.underline = true;
        self.underline_style = s;
        self
    }

    /// A line through the text.
    pub fn strikethrough(mut self) -> Self {
        self.strikethrough = true;
        self
    }

    /// OpenType features for the shaper; see [`FontFeatures`].
    pub fn features(mut self, f: FontFeatures) -> Self {
        self.features = f;
        self
    }

    /// The face to shape with.
    pub fn family(mut self, f: FontFamily) -> Self {
        self.family = f;
        self
    }

    /// The stock monospace family.
    pub fn mono(self) -> Self {
        self.family(FontFamily::Mono)
    }

    /// Shape with a registered font (see `FontFamily::Custom`).
    pub fn font(self, id: crate::resources::FontId) -> Self {
        self.family(FontFamily::Custom(id))
    }

    /// The line height in logical px, replacing the derived one.
    pub fn line_height(mut self, lh: f32) -> Self {
        self.line_height = lh;
        self
    }

    /// How lines break at the node's width.
    pub fn wrap(mut self, wrap: TextWrap) -> Self {
        self.wrap = wrap;
        self
    }

    /// One line per paragraph, clipped to the node (`TextWrap::None`).
    pub fn nowrap(self) -> Self {
        self.wrap(TextWrap::None)
    }

    /// Lay out at most `n` lines (0 = unlimited).
    pub fn max_lines(mut self, n: u32) -> Self {
        self.max_lines = n;
        self
    }

    /// Truncate with "…" instead of overflowing: a single line unless
    /// `max_lines` says otherwise.
    pub fn ellipsis(mut self) -> Self {
        self.ellipsis = true;
        self
    }

    /// The text colour, instead of the theme's foreground.
    pub fn color(mut self, c: Color) -> Self {
        self.color = Some(c);
        self
    }

    /// This style with `fg` where it named no colour of its own: what the
    /// core stamps on as the text enters the tree, so the shaping caches,
    /// the display list and every binding see a resolved colour.
    pub fn or_fg(mut self, fg: Color) -> Self {
        self.color = Some(self.color.unwrap_or(fg));
        self
    }

    /// The colour this style paints in, falling back to what kui painted
    /// before there were themes. For the handful of places that hold a
    /// style the core never stamped.
    pub fn color_or_default(&self) -> Color {
        self.color.unwrap_or(crate::theme::Theme::DEFAULT_FG)
    }
}

/// Hand-written so that a group whose box was allocated but left at its
/// defaults — `.checked(false)` on a fresh spec — equals one whose box was
/// never allocated at all. The derived version compared `None` against
/// `Some(EMPTY)` and called them different, which is a difference the boxing
/// introduced rather than one a caller declared.
impl PartialEq for NodeSpec {
    fn eq(&self, other: &Self) -> bool {
        self.layout == other.layout
            && self.style == other.style
            && self.hoverable == other.hoverable
            && self.animate == other.animate
            && self.accent == other.accent
            && self.window == other.window
            && self.transition == other.transition
            && self.slide == other.slide
            && self.focusable == other.focusable
            && self.initial_focus == other.initial_focus
            && self.disabled == other.disabled
            && self.cursor == other.cursor
            && self.events() == other.events()
            && self.anim() == other.anim()
            && self.access() == other.access()
            && self.interact() == other.interact()
    }
}

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

    /// `NodeSpec` is moved by value for every node a frame builds — through
    /// the builder chain, `Core::open`, `open_with_key` and into
    /// `Vec<NodeSpec>` in `Tree::push` — so its size is a per-node cost that
    /// every app pays whether or not it declares the fields. It reached 728
    /// bytes one feature at a time and cost ~2.5x on the frame benches before
    /// anyone measured it.
    ///
    /// This is the number a review can fail. Adding a prop is fine; adding it
    /// *inline* past this bound is the thing to notice. Put cold fields in one
    /// of the boxed groups instead, and only raise this if the field is read
    /// on every node of every frame.
    #[test]
    fn node_spec_stays_small() {
        const BOUND: usize = 256;
        let size = std::mem::size_of::<NodeSpec>();
        assert!(
            size <= BOUND,
            "NodeSpec is {size} bytes, over the {BOUND}-byte bound. It is copied \
             per node per frame; put cold fields in EventSpec / AnimSpec / \
             AccessSpec / InteractSpec rather than inline. See C15."
        );
    }

    /// The groups exist to be absent: a node declaring none of them carries
    /// four null pointers, not four structs.
    #[test]
    fn an_undeclared_group_costs_a_pointer() {
        let spec = NodeSpec::default();
        assert!(spec.events.is_none() && spec.anim.is_none());
        assert!(spec.access.is_none() && spec.interact.is_none());
        // and reads still work, without allocating
        assert!(spec.events().on_click.is_none());
        assert_eq!(spec.access().role, None);
    }

    /// An allocated-but-default group is still equal to no group at all.
    #[test]
    fn an_empty_group_equals_no_group() {
        assert_eq!(NodeSpec::default().checked(false), NodeSpec::default());
    }
}