concinnity-dev 0.19.1

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
// src/editor/form_panel.rs
//
// The editor's add / edit form, in its own floating panel (separate from the
// Assets browse panel, which stays on its list while this is open). Spawned by
// clicking an asset in the browse list (or picking a type from the "+" picker):
// a draggable title bar ("Edit <type>" / "New <type>") with an "X" close button
// in its top-right corner, then a header row with the asset's editable NAME as a
// large heading and the Apply button pinned to the panel's top-right, then the
// scrollable arg-field area. Like the rest of the editor HUD it is plain
// `Sprite` / `TextLabel` / `TextInput` components at reserved ids driven each
// frame by the hook; the field model itself lives in `form.rs` and the hook owns
// all state.
//
// The field area renders a scrolling window over ALL of the type's fields into
// a fixed pool of `form::FIELD_POOL` control slots: visible slot `r` shows
// logical field `form_scroll + r`, and hit-test actions carry the LOGICAL index.
// An enum / ref field with a large variant set opens a floating value dropdown
// below the field (its own row pool here, so it can coexist with the Assets
// panel's combo).

use crate::components::TextAlign;
use crate::ecs::World;
use crate::ecs::asset_id::AssetId;

use super::form::{self, FieldKind, FormField};
use super::overrides::FieldOrigin;
use super::registry::{self, PanelKey};
use super::theme;
use super::widget::{self, place_rounded, point_in};

// An enum / ref field with this many variants or fewer cycles in place on click
// (fast for small sets); more than this opens a floating value dropdown anchored
// below the field (a long list is tedious to cycle through). A reference field's
// count includes its `(none)` option.
pub(crate) const CYCLE_MAX: usize = 5;

// Visible rows in an open field-value dropdown before it scrolls.
pub(crate) const MAX_DROP_ROWS: usize = 8;
// A field-value dropdown option row's height.
const DROP_ROW_H: f32 = 28.0;
// The most options an override / entity menu holds (Revert-all, Apply-all,
// Materialize, Minimize).
pub(crate) const MAX_OVR_ROWS: usize = 4;
const OVR_ROW_H: f32 = 26.0;
const OVR_MENU_W: f32 = 340.0;

const EDIT: u32 = registry::base(PanelKey::Edit);
pub(crate) const EDIT_BG: AssetId = AssetId(EDIT);
pub(crate) const TITLE_LABEL: AssetId = AssetId(EDIT + 2);
pub(crate) const APPLY_BG: AssetId = AssetId(EDIT + 3);
pub(crate) const APPLY_LABEL: AssetId = AssetId(EDIT + 4);
// The "X" close button in the title bar's top-right corner.
pub(crate) const CLOSE_BG: AssetId = AssetId(EDIT + 5);
pub(crate) const CLOSE_LABEL: AssetId = AssetId(EDIT + 6);
// The asset-name heading: a real editable TextInput drawn a step larger.
pub(crate) const NAME_INPUT: AssetId = AssetId(EDIT + 7);
pub(crate) const FORM_STATUS: AssetId = AssetId(EDIT + 8);
pub(crate) const FORM_TRACK: AssetId = AssetId(EDIT + 9);
pub(crate) const FORM_THUMB: AssetId = AssetId(EDIT + 10);
pub(crate) const DROP_BG: AssetId = AssetId(EDIT + 11);
pub(crate) const DROP_TRACK: AssetId = AssetId(EDIT + 12);
pub(crate) const DROP_THUMB: AssetId = AssetId(EDIT + 13);

// The per-slot control pool (`form::FIELD_POOL` of each). `form_row_label(r)` is
// the caption of visible slot `r`; `form_input(r)` its text control;
// `form_toggle_bg(r)` its checkbox / cycle-button / array-add background;
// `form_swatch(r)` its colour swatch / array-remove button;
// `form_enum_label(r)` its enum-value / array-count caption.
pub(crate) fn form_row_label(r: usize) -> AssetId {
    AssetId(EDIT + 0x20 + r as u32)
}
pub(crate) fn form_input(r: usize) -> AssetId {
    AssetId(EDIT + 0x40 + r as u32)
}
pub(crate) fn form_toggle_bg(r: usize) -> AssetId {
    AssetId(EDIT + 0x60 + r as u32)
}
pub(crate) fn form_swatch(r: usize) -> AssetId {
    AssetId(EDIT + 0x80 + r as u32)
}
pub(crate) fn form_enum_label(r: usize) -> AssetId {
    AssetId(EDIT + 0xA0 + r as u32)
}
// The value dropdown's own option rows (the Assets panel's combo pool can be in
// use at the same time now that the two are separate panels).
pub(crate) fn drop_row_bg(r: usize) -> AssetId {
    AssetId(EDIT + 0xC0 + r as u32)
}
pub(crate) fn drop_row_label(r: usize) -> AssetId {
    AssetId(EDIT + 0xE0 + r as u32)
}
// Override chrome for a template-derived asset: a per-slot accent bar +
// action button on overridden rows, a header summary chip + entity-menu
// button, and a floating Revert / Apply menu.
pub(crate) fn ovr_bar(r: usize) -> AssetId {
    AssetId(EDIT + 0x100 + r as u32)
}
pub(crate) fn ovr_btn_bg(r: usize) -> AssetId {
    AssetId(EDIT + 0x120 + r as u32)
}
pub(crate) fn ovr_btn_label(r: usize) -> AssetId {
    AssetId(EDIT + 0x140 + r as u32)
}
pub(crate) const OVR_CHIP_BG: AssetId = AssetId(EDIT + 0x160);
pub(crate) const OVR_CHIP_LABEL: AssetId = AssetId(EDIT + 0x161);
pub(crate) const ENT_BTN_BG: AssetId = AssetId(EDIT + 0x162);
pub(crate) const ENT_BTN_LABEL: AssetId = AssetId(EDIT + 0x163);
pub(crate) const OVR_MENU_BG: AssetId = AssetId(EDIT + 0x164);
pub(crate) fn ovr_menu_row_bg(r: usize) -> AssetId {
    AssetId(EDIT + 0x170 + r as u32)
}
pub(crate) fn ovr_menu_row_label(r: usize) -> AssetId {
    AssetId(EDIT + 0x180 + r as u32)
}

// Which of the form's inputs holds keyboard focus (re-asserted each frame so the
// opening click cannot blur it; only the focused input re-asserts, so N text
// fields do not fight).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FormFocus {
    Name,
    Field(usize),
}

// Geometry, in window pixels. A wider column than the Assets panel so field
// names and values read comfortably; every rect derives from the panel origin
// `o` (the title bar's top-left), so dragging the title bar moves the panel.
pub(crate) const EDIT_W: f32 = 480.0;
const PAD: f32 = 10.0;
const GAP: f32 = 8.0;
// The header row: the name heading and the Apply button.
const NAME_H: f32 = 34.0;
const BTN_W: f32 = 84.0;
// The validation status line reserved under the header row.
const STATUS_H: f32 = 22.0;
// One arg-field row; the caption column on its left.
const FIELD_H: f32 = 34.0;
const LABEL_COL: f32 = 190.0;
// Left inset per nesting level for a flattened nested (dotted-path) leaf caption.
const NEST_INDENT: f32 = 10.0;
const SCROLLBAR_W: f32 = 5.0;
// The name heading draws larger than the body text.
const NAME_SCALE: f32 = 1.05;

const BTN_TINT: [f32; 4] = [0.22, 0.40, 0.56, 1.0];
const BTN_TINT_HOVER: [f32; 4] = [0.28, 0.48, 0.66, 1.0];
const CYCLE_TINT: [f32; 4] = theme::BUTTON_TINT;
const OPTION_TINT: [f32; 4] = [0.16, 0.16, 0.20, 0.0];
const OPTION_TINT_HOVER: [f32; 4] = theme::HOVER_TINT;
const OPTION_TINT_SELECTED: [f32; 4] = theme::SELECTED_TINT;
const DROP_BG_TINT: [f32; 4] = [0.09, 0.09, 0.12, 1.0];
const TRACK_TINT: [f32; 4] = [0.12, 0.12, 0.15, 0.9];
const THUMB_TINT: [f32; 4] = [0.40, 0.44, 0.56, 0.95];
const CHECK_ON: [f32; 4] = [0.30, 0.66, 0.34, 1.0];
const CHECK_OFF: [f32; 4] = [0.30, 0.30, 0.34, 1.0];
const ADD_BTN_TINT: [f32; 4] = [0.24, 0.52, 0.32, 1.0];
const REMOVE_BTN_TINT: [f32; 4] = [0.52, 0.26, 0.26, 1.0];
const LABEL: [f32; 3] = [0.90, 0.90, 0.92];
const LABEL_DIM: [f32; 3] = [0.60, 0.60, 0.66];
const LABEL_WHITE: [f32; 3] = [1.0, 1.0, 1.0];
const ERROR_LABEL: [f32; 3] = [0.95, 0.55, 0.55];
// Override chrome: the accent marks an overridden row; instance-only fields
// (no template counterpart) read dimmer.
const OVERRIDE_LABEL: [f32; 3] = [0.62, 0.76, 1.0];
const INSTANCE_ONLY_TINT: [f32; 4] = [0.55, 0.58, 0.68, 1.0];

// Where the panel sits until the user drags it: to the left of the Assets
// panel's default anchor, below the top bar.
pub(crate) fn default_origin(vw: f32) -> [f32; 2] {
    [
        vw - super::panel::PANEL_W - GAP - EDIT_W,
        super::hud::body_top(),
    ]
}

// The chrome height around the field band (title bar + header row + status line
// + pads); the field rows stack below it.
const CHROME_H: f32 = widget::TITLE_H + PAD + NAME_H + 4.0 + STATUS_H + PAD;

fn panel_height(rows: usize) -> f32 {
    CHROME_H + rows as f32 * FIELD_H
}

// The default (minimum) on-screen field slots: the field count capped at the
// default window.
fn visible_rows(n_fields: usize) -> usize {
    n_fields.clamp(1, form::FIELD_POOL)
}

// The number of field slots that fit panel height `h`, capped at the pool.
pub(crate) fn rows_for_height(h: f32) -> usize {
    (((h - CHROME_H) / FIELD_H).floor() as usize).clamp(1, form::FIELD_POOL_MAX)
}

// The panel footprint for `n_fields` total fields (the field area tracks the
// count, capped at the default window; a wider form scrolls). Origin-independent;
// the hook's drag clamp uses this, and it is the minimum resize size.
pub(crate) fn size(n_fields: usize) -> [f32; 2] {
    [EDIT_W, panel_height(visible_rows(n_fields))]
}

// The tallest the panel resizes to for a form of `n_fields`: its fields shown in
// full, capped at the injected pool. Width is unbounded (capped by the screen).
pub(crate) fn max_size(n_fields: usize) -> [f32; 2] {
    [
        f32::INFINITY,
        panel_height(n_fields.clamp(1, form::FIELD_POOL_MAX)),
    ]
}

// The "X" close button, a square flush in the title bar's top-right corner. The
// hook checks this before the title-bar drag, so clicking the X closes the form
// rather than starting a drag.
pub(crate) fn close_rect(o: [f32; 2], w: f32) -> [f32; 4] {
    widget::close_rect(widget::title_rect(o, w))
}

// The header row under the title bar: name heading + the pinned Apply button.
pub(crate) fn name_rect(o: [f32; 2], w: f32) -> [f32; 4] {
    [
        o[0] + PAD,
        widget::header_y(o, PAD),
        w - 2.0 * PAD - (BTN_W + GAP),
        NAME_H,
    ]
}
pub(crate) fn apply_rect(o: [f32; 2], w: f32) -> [f32; 4] {
    [
        o[0] + w - PAD - BTN_W,
        widget::header_y(o, PAD),
        BTN_W,
        NAME_H,
    ]
}

// Where the scrollable field area begins (below the header + status line).
fn fields_top(o: [f32; 2]) -> f32 {
    widget::header_y(o, PAD) + NAME_H + 4.0 + STATUS_H
}

// The full-width rect of visible field slot `r` at the effective width `w`.
fn field_row_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    [o[0], fields_top(o) + r as f32 * FIELD_H, w, FIELD_H]
}
// The control (text field / checkbox area) on the right of slot `r`; it widens
// with the panel while the caption column stays fixed.
pub(crate) fn form_control_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    let row = field_row_rect(o, w, r);
    [
        row[0] + LABEL_COL,
        row[1] + 3.0,
        w - LABEL_COL - PAD - 2.0,
        FIELD_H - 8.0,
    ]
}
// The checkbox box for a bool field on slot `r`.
pub(crate) fn form_toggle_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    let c = form_control_rect(o, w, r);
    let s = FIELD_H - 12.0;
    [c[0], c[1], s, s]
}
// The `[+]` add and `[-]` remove buttons of an array header on slot `r`.
fn array_add_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    let c = form_control_rect(o, w, r);
    let s = FIELD_H - 12.0;
    [c[0] + c[2] - s, c[1], s, s]
}
fn array_remove_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    let a = array_add_rect(o, w, r);
    [a[0] - a[2] - 4.0, a[1], a[2], a[3]]
}

// An open value dropdown for the enum / ref field on slot `r`: it floats
// directly below that field's control, aligned to it.
fn field_option_rect(o: [f32; 2], w: f32, slot: usize, r: usize) -> [f32; 4] {
    let c = form_control_rect(o, w, slot);
    [c[0], c[1] + c[3] + r as f32 * DROP_ROW_H, c[2], DROP_ROW_H]
}
// The dropdown's opaque backing. Its height is rounded out to a field-row
// boundary: an overlay whose edge lands mid-row leaves that row's control half
// drawn, which reads as the two clashing rather than as one sitting over the
// other.
fn field_dropdown_backing(o: [f32; 2], w: f32, slot: usize, shown: usize) -> [f32; 4] {
    let c = form_control_rect(o, w, slot);
    let top = c[1] + c[3];
    let h = shown as f32 * DROP_ROW_H + 4.0;
    let rows = ((top + h - fields_top(o)) / FIELD_H).ceil();
    [
        c[0],
        top,
        c[2],
        (fields_top(o) + rows * FIELD_H - top).max(h),
    ]
}

// How many field slots are on screen at effective size `s`: the field count
// capped at the height-derived window.
fn visible_field_count(view: &FormView, s: [f32; 2]) -> usize {
    view.form_fields.len().min(rows_for_height(s[1]))
}

// The accent bar down an overridden row's left edge.
fn ovr_bar_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    let row = field_row_rect(o, w, r);
    [row[0] + 3.0, row[1] + 5.0, 3.0, FIELD_H - 10.0]
}

// The per-row override-menu button, tucked into the caption column's right
// edge (never under a control, so a text field's opaque background cannot
// cover it).
fn ovr_btn_rect(o: [f32; 2], w: f32, r: usize) -> [f32; 4] {
    let row = field_row_rect(o, w, r);
    let side = 16.0;
    [
        row[0] + LABEL_COL - side - 6.0,
        row[1] + (FIELD_H - side) * 0.5,
        side,
        side,
    ]
}

// The entity-menu button on the status line's right end.
fn ent_btn_rect(o: [f32; 2], w: f32) -> [f32; 4] {
    [
        o[0] + w - PAD - 18.0,
        widget::header_y(o, PAD) + NAME_H + 4.0,
        18.0,
        18.0,
    ]
}

// The "N overridden" summary chip to the entity button's left.
fn ovr_chip_rect(o: [f32; 2], w: f32) -> [f32; 4] {
    let ent = ent_btn_rect(o, w);
    [ent[0] - GAP - 110.0, ent[1], 110.0, 18.0]
}

// One option row of the floating override / entity menu anchored at `anchor`
// (a row button or the entity button), clamped inside the panel.
fn ovr_menu_option_rect(o: [f32; 2], w: f32, anchor: [f32; 4], r: usize) -> [f32; 4] {
    let menu_w = OVR_MENU_W.min(w - 2.0 * PAD);
    let x = (anchor[0]).min(o[0] + w - PAD - menu_w).max(o[0] + PAD);
    [
        x,
        anchor[1] + anchor[3] + 2.0 + r as f32 * OVR_ROW_H,
        menu_w,
        OVR_ROW_H,
    ]
}

// The menu's opaque backing behind `shown` option rows.
fn ovr_menu_backing(o: [f32; 2], w: f32, anchor: [f32; 4], shown: usize) -> [f32; 4] {
    let first = ovr_menu_option_rect(o, w, anchor, 0);
    [
        first[0] - 2.0,
        first[1] - 2.0,
        first[2] + 4.0,
        shown as f32 * OVR_ROW_H + 4.0,
    ]
}

// Where the open override / entity menu anchors this frame, if any: the field
// menu hangs off its row's button (gone when its row scrolls out), the entity
// menu off the header button.
fn ovr_menu_anchor(view: &FormView, o: [f32; 2], w: f32, window: usize) -> Option<[f32; 4]> {
    let ovr = view.overrides.as_ref()?;
    if let Some((field, _)) = ovr.field_menu {
        let slot = field_slot(view, window, field)?;
        return Some(ovr_btn_rect(o, w, slot));
    }
    ovr.entity_menu.is_some().then(|| ent_btn_rect(o, w))
}

// The open override / entity menu's option labels, if any.
fn ovr_menu_options<'a>(view: &'a FormView) -> Option<&'a [String]> {
    let ovr = view.overrides.as_ref()?;
    if let Some((_, options)) = ovr.field_menu {
        return Some(options);
    }
    ovr.entity_menu
}

// The slot showing logical field `j`, if it is inside the scroll window of
// `window` rows.
fn field_slot(view: &FormView, window: usize, j: usize) -> Option<usize> {
    let scroll = view.form_scroll;
    (j >= scroll && j < scroll + window).then(|| j - scroll)
}

// The element count of a vector field (0 for any other kind).
fn vec_len(kind: FieldKind) -> usize {
    match kind {
        FieldKind::Vec { len, .. } => len,
        _ => 0,
    }
}

// Whether the non-colour vector at logical field `j` is currently disclosed: its
// element leaves (`key.0` ..) follow it directly in the field list, so the next
// field carrying that prefix means it is expanded.
fn vec_expanded(fields: &[FormField], j: usize) -> bool {
    let Some(field) = fields.get(j) else {
        return false;
    };
    let prefix = format!("{}.", field.key);
    fields
        .get(j + 1)
        .is_some_and(|next| next.key.starts_with(&prefix))
}

// The display caption for a field: a disclosed vector element (`position.0`) reads
// as its axis (x / y / z / w); every other field keeps its leaf name.
fn field_caption(fields: &[FormField], field: &FormField) -> String {
    element_axis_label(fields, &field.key).unwrap_or_else(|| {
        field
            .key
            .rsplit('.')
            .next()
            .unwrap_or(&field.key)
            .to_string()
    })
}

// The axis label for `key` when it is an element leaf of a non-colour vector
// (`parent.<idx>` with `parent` a non-colour vector field), else `None`.
fn element_axis_label(fields: &[FormField], key: &str) -> Option<String> {
    let (parent, last) = key.rsplit_once('.')?;
    let idx: usize = last.parse().ok()?;
    let is_vec_parent = fields
        .iter()
        .any(|f| f.key == parent && matches!(f.kind, FieldKind::Vec { color: false, .. }));
    is_vec_parent.then(|| axis_letter(idx))
}

// A vector element's axis label: x / y / z / w for the first four, else `[i]`.
fn axis_letter(i: usize) -> String {
    ["x", "y", "z", "w"]
        .get(i)
        .map(|s| s.to_string())
        .unwrap_or_else(|| format!("[{i}]"))
}

// A resolved form-panel click. Field actions carry the LOGICAL field index.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FormAction {
    // Focus the name heading, or arg text field `i`.
    FocusName,
    FocusField(usize),
    // Toggle the bool arg field `i`.
    ToggleField(usize),
    // Advance the enum / ref arg field `i` to its next variant (small sets).
    CycleField(usize),
    // Open (or, if already open, close) the value dropdown for field `i`.
    OpenFieldDropdown(usize),
    // Pick option `i` from the open field-value dropdown.
    PickFieldOption(usize),
    // Append / drop the last element of array arg field `i`.
    AddArrayElement(usize),
    RemoveArrayElement(usize),
    // Expand / collapse the disclosure of non-colour vector arg field `i` (its
    // per-element leaves).
    ToggleVecExpand(usize),
    // Open (or close) the override menu of the marked field `i`.
    OpenOverrideMenu(usize),
    // Pick option `i` from the open per-field override menu.
    PickOverrideOption(usize),
    // Open (or close) the entity-level override menu in the header.
    OpenEntityMenu,
    // Pick option `i` from the open entity-level menu.
    PickEntityOption(usize),
    // The header summary chip: scroll to the next overridden field.
    JumpOverride,
    // The Apply / Add button: validate + commit.
    Confirm,
    // The Cancel button: close the panel, discarding the form.
    Close,
    // Dismiss the open value dropdown without picking.
    CloseOverlays,
    // A click inside the panel that hits no control (swallowed).
    Consume,
}

// Override state for a template-derived asset's form, borrowed from the
// hook's per-tick data.
pub(crate) struct OverridesView<'a> {
    // Per-field origin, parallel to `form_fields`.
    pub marks: &'a [FieldOrigin],
    // How many fields diverge from the template.
    pub count: usize,
    // The open per-field menu: (logical field index, option labels).
    pub field_menu: Option<(usize, &'a [String])>,
    // The open entity-level menu's option labels.
    pub entity_menu: Option<&'a [String]>,
}

// The per-frame data the hook hands to `apply` / `hit_test`.
pub(crate) struct FormView<'a> {
    // The title-bar heading ("Edit Camera3D" / "New PointLight").
    pub title: &'a str,
    // Whether an existing entry is being edited (confirm says "Apply", and the
    // hook highlights the entry's browse row) vs a new asset ("Add").
    pub editing: bool,
    // The editable arg fields; the panel renders a `form::FIELD_POOL` window.
    pub form_fields: &'a [FormField],
    // First visible field of the scroll window.
    pub form_scroll: usize,
    // Which input holds keyboard focus.
    pub form_focus: FormFocus,
    // The field whose value dropdown is open, and its scroll offset.
    pub field_dropdown: Option<usize>,
    pub field_dropdown_scroll: usize,
    // A validation error from the last rejected commit.
    pub form_error: Option<&'a str>,
    // Per-field override state when the form edits a template-derived asset.
    pub overrides: Option<OverridesView<'a>>,
    pub mouse: [f32; 2],
}

// Whether the cursor is over the panel (for wheel-scrolling the field window).
pub(crate) fn cursor_over(mx: f32, my: f32, o: [f32; 2], s: [f32; 2]) -> bool {
    point_in(mx, my, widget::outer_rect(o, s))
}

// Resolve a click against the open form panel at origin `o`, effective size `s`.
// `None` means the click missed the panel (the caller lets it fall through).
// Title-bar presses never reach this: the hook intercepts them first to drag.
pub(crate) fn hit_test(
    view: &FormView,
    mx: f32,
    my: f32,
    o: [f32; 2],
    s: [f32; 2],
) -> Option<FormAction> {
    let w = s[0];
    let window = rows_for_height(s[1]);
    // An open override / entity menu is modal over the panel: its option rows
    // pick, anything else dismisses it.
    if let (Some(anchor), Some(options)) =
        (ovr_menu_anchor(view, o, w, window), ovr_menu_options(view))
    {
        let picking_field = view
            .overrides
            .as_ref()
            .is_some_and(|ovr| ovr.field_menu.is_some());
        for k in 0..options.len().min(MAX_OVR_ROWS) {
            if point_in(mx, my, ovr_menu_option_rect(o, w, anchor, k)) {
                return Some(if picking_field {
                    FormAction::PickOverrideOption(k)
                } else {
                    FormAction::PickEntityOption(k)
                });
            }
        }
        return Some(FormAction::CloseOverlays);
    }
    // An open value dropdown is modal over the panel: its option rows pick,
    // anything else dismisses it.
    if let Some(open) = view.field_dropdown
        && let Some(field) = view.form_fields.get(open)
        && let Some(slot) = field_slot(view, window, open)
    {
        let total = field.variants.len();
        let scroll = view.field_dropdown_scroll.min(total.saturating_sub(1));
        for r in 0..MAX_DROP_ROWS {
            let idx = scroll + r;
            if idx >= total {
                break;
            }
            if point_in(mx, my, field_option_rect(o, w, slot, r)) {
                return Some(FormAction::PickFieldOption(idx));
            }
        }
        return Some(FormAction::CloseOverlays);
    }

    if !point_in(mx, my, widget::outer_rect(o, s)) {
        return None;
    }
    // The "X" in the title bar closes the form. (The hook checks this before the
    // title-bar drag; resolved here too so the pure hit test stays complete.)
    if point_in(mx, my, close_rect(o, w)) {
        return Some(FormAction::Close);
    }
    if point_in(mx, my, apply_rect(o, w)) {
        return Some(FormAction::Confirm);
    }
    if point_in(mx, my, name_rect(o, w)) {
        return Some(FormAction::FocusName);
    }
    // The override chrome of a template-derived asset: the entity-menu button,
    // the summary chip, and each marked row's menu button (in the caption
    // column, so it never contends with a control).
    if let Some(ovr) = &view.overrides {
        if point_in(mx, my, ent_btn_rect(o, w)) {
            return Some(FormAction::OpenEntityMenu);
        }
        if ovr.count > 0 && point_in(mx, my, ovr_chip_rect(o, w)) {
            return Some(FormAction::JumpOverride);
        }
        for r in 0..visible_field_count(view, s) {
            let j = view.form_scroll + r;
            let marked = ovr
                .marks
                .get(j)
                .is_some_and(|m| *m != FieldOrigin::Inherited);
            if marked && point_in(mx, my, ovr_btn_rect(o, w, r)) {
                return Some(FormAction::OpenOverrideMenu(j));
            }
        }
    }

    // Arg field controls over the visible window: slot `r` is logical field
    // `form_scroll + r`. A bool toggles, an enum cycles / opens a dropdown, an
    // array grows / shrinks, a text field takes focus.
    let scroll = view.form_scroll;
    for r in 0..visible_field_count(view, s) {
        let j = scroll + r;
        let Some(f) = view.form_fields.get(j) else {
            break;
        };
        match f.kind {
            FieldKind::Bool => {
                if point_in(mx, my, form_toggle_rect(o, w, r)) {
                    return Some(FormAction::ToggleField(j));
                }
            }
            FieldKind::Enum | FieldKind::Ref { .. } => {
                if point_in(mx, my, form_control_rect(o, w, r)) {
                    // A small variant set cycles in place; a large one opens a
                    // floating dropdown instead of forcing many clicks.
                    if f.variants.len() > CYCLE_MAX {
                        return Some(FormAction::OpenFieldDropdown(j));
                    }
                    return Some(FormAction::CycleField(j));
                }
            }
            FieldKind::Array => {
                if point_in(mx, my, array_add_rect(o, w, r)) {
                    return Some(FormAction::AddArrayElement(j));
                }
                if point_in(mx, my, array_remove_rect(o, w, r)) {
                    return Some(FormAction::RemoveArrayElement(j));
                }
            }
            FieldKind::Vec { color: false, .. } => {
                // The disclosure button toggles the per-element leaves.
                if point_in(mx, my, form_control_rect(o, w, r)) {
                    return Some(FormAction::ToggleVecExpand(j));
                }
            }
            _ => {
                if point_in(mx, my, form_control_rect(o, w, r)) {
                    return Some(FormAction::FocusField(j));
                }
            }
        }
    }
    // Empty panel space: swallow so it does not fall through to the world.
    Some(FormAction::Consume)
}

// Position + show the panel's elements for this frame at origin `o`, effective
// size `s`, or hide them all when the form is closed (`view` is `None`).
pub(crate) fn apply(world: &mut World, view: Option<&FormView>, o: [f32; 2], s: [f32; 2]) {
    let Some(view) = view else {
        hide_all(world);
        return;
    };

    // Blank everything, then re-show what this frame needs.
    hide_all(world);

    let w = s[0];
    let window = rows_for_height(s[1]);
    widget::place_panel(world, EDIT_BG, widget::outer_rect(o, s));
    widget::place_heading(world, TITLE_LABEL, widget::title_rect(o, w), view.title);

    // The "X" close button in the title bar's top-right corner (blends into the
    // title bar until hovered; shared look across every panel).
    let close_hover = point_in(view.mouse[0], view.mouse[1], close_rect(o, w));
    widget::place_close(
        world,
        CLOSE_BG,
        CLOSE_LABEL,
        widget::title_rect(o, w),
        close_hover,
    );

    // The header row: the asset-name heading (drawn larger) and the pinned Apply
    // button at the panel's top right.
    show_name_heading(world, o, w, view.form_focus == FormFocus::Name);
    let apply_btn = apply_rect(o, w);
    let hover = point_in(view.mouse[0], view.mouse[1], apply_btn);
    place_rounded(
        world,
        APPLY_BG,
        apply_btn,
        if hover { BTN_TINT_HOVER } else { BTN_TINT },
        theme::CONTROL_RADIUS,
        true,
    );
    let confirm = if view.editing { "Apply" } else { "Add" };
    place_center_label(world, APPLY_LABEL, apply_btn, confirm, LABEL_WHITE, true);

    // A validation error, if the last commit was rejected (a reserved line, so
    // showing it never shifts the fields below).
    if let Some(err) = view.form_error {
        widget::place_left_label(
            world,
            FORM_STATUS,
            [o[0] + PAD, widget::header_y(o, PAD) + NAME_H + 6.0],
            err,
            ERROR_LABEL,
            true,
        );
    }

    // The arg fields over the visible window, drawn into the slot-indexed pool.
    let scroll = view.form_scroll;
    for r in 0..visible_field_count(view, s) {
        let j = scroll + r;
        let Some(field) = view.form_fields.get(j) else {
            break;
        };
        let row = field_row_rect(o, w, r);
        // A nested (dotted-path) field shows its indented caption; a disclosed
        // vector element reads as its axis (x / y / z / w).
        let depth = field.key.matches('.').count();
        let caption = field_caption(view.form_fields, field);
        widget::place_left_label(
            world,
            form_row_label(r),
            [
                row[0] + PAD + depth as f32 * NEST_INDENT,
                row[1] + FIELD_H * 0.5 - theme::TEXT_HALF,
            ],
            &caption,
            LABEL,
            true,
        );
        match field.kind {
            FieldKind::Bool => {
                let t = form_toggle_rect(o, w, r);
                let tint = if field.boolval { CHECK_ON } else { CHECK_OFF };
                place_rounded(world, form_toggle_bg(r), t, tint, 4.0, true);
            }
            FieldKind::Enum | FieldKind::Ref { .. } => {
                // A cycling button spanning the control, captioned with the
                // current selection.
                let c = form_control_rect(o, w, r);
                let hover = point_in(view.mouse[0], view.mouse[1], c);
                let tint = if hover { OPTION_TINT_HOVER } else { CYCLE_TINT };
                place_rounded(
                    world,
                    form_toggle_bg(r),
                    c,
                    tint,
                    theme::CONTROL_RADIUS,
                    true,
                );
                let value = field
                    .variants
                    .get(field.variant_idx)
                    .map(String::as_str)
                    .unwrap_or("");
                place_center_label(world, form_enum_label(r), c, value, LABEL, true);
            }
            FieldKind::Array => {
                // A header for a variable-length array: its element count and a
                // red `[-]` remove + green `[+]` add button.
                let c = form_control_rect(o, w, r);
                widget::place_left_label(
                    world,
                    form_enum_label(r),
                    [c[0], c[1] + c[3] * 0.5 - theme::TEXT_HALF],
                    &format!("({})", field.variant_idx),
                    LABEL_DIM,
                    true,
                );
                place_rounded(
                    world,
                    form_swatch(r),
                    array_remove_rect(o, w, r),
                    REMOVE_BTN_TINT,
                    4.0,
                    true,
                );
                place_rounded(
                    world,
                    form_toggle_bg(r),
                    array_add_rect(o, w, r),
                    ADD_BTN_TINT,
                    4.0,
                    true,
                );
            }
            FieldKind::Vec { color: false, .. } => {
                // A disclosure button spanning the control, captioned with the
                // element count and a caret (`>` collapsed, `v` expanded). Clicking
                // it toggles the per-element leaves below.
                let c = form_control_rect(o, w, r);
                let hover = point_in(view.mouse[0], view.mouse[1], c);
                let tint = if hover { OPTION_TINT_HOVER } else { CYCLE_TINT };
                place_rounded(
                    world,
                    form_toggle_bg(r),
                    c,
                    tint,
                    theme::CONTROL_RADIUS,
                    true,
                );
                let open = vec_expanded(view.form_fields, j);
                let caption = format!("[{}] {}", vec_len(field.kind), if open { "v" } else { ">" });
                widget::place_left_label(
                    world,
                    form_enum_label(r),
                    [c[0] + 8.0, c[1] + c[3] * 0.5 - theme::TEXT_HALF],
                    &caption,
                    LABEL_DIM,
                    true,
                );
            }
            kind => {
                let control = form_control_rect(o, w, r);
                // A colour vector reserves a right-hand strip for a live preview
                // swatch and narrows its field to clear it. The swatch must sit
                // OUTSIDE the field rect: a `TextInput`'s opaque background box
                // is synthesised after every authored sprite (the swatch
                // included), so a swatch drawn under the field would be painted
                // over.
                let swatch = matches!(kind, FieldKind::Vec { color: true, .. }).then(|| {
                    let s = FIELD_H - 14.0;
                    [
                        control[0] + control[2] - s,
                        control[1] + (control[3] - s) * 0.5,
                        s,
                        s,
                    ]
                });
                let rect = match swatch {
                    Some(sw) => [control[0], control[1], sw[0] - control[0] - 4.0, control[3]],
                    None => control,
                };
                widget::show_field(
                    world,
                    form_input(r),
                    rect,
                    view.form_focus == FormFocus::Field(j),
                );
                if let Some(sw) = swatch {
                    let rgb = swatch_rgb(&widget::field_text(world, form_input(r)));
                    place_rounded(world, form_swatch(r), sw, rgb, 4.0, true);
                }
            }
        }
    }

    // Override chrome for a template-derived asset: per-row accent bars +
    // menu buttons, and the header summary chip + entity-menu button.
    if let Some(ovr) = &view.overrides {
        for r in 0..visible_field_count(view, s) {
            let j = scroll + r;
            let Some(mark) = ovr.marks.get(j) else {
                break;
            };
            if *mark == FieldOrigin::Inherited {
                continue;
            }
            let tint = match mark {
                FieldOrigin::InstanceOnly => INSTANCE_ONLY_TINT,
                _ => theme::ACCENT_TINT,
            };
            place_rounded(world, ovr_bar(r), ovr_bar_rect(o, w, r), tint, 1.5, true);
            let btn = ovr_btn_rect(o, w, r);
            let hover = point_in(view.mouse[0], view.mouse[1], btn);
            let open_here = view
                .overrides
                .as_ref()
                .and_then(|v| v.field_menu)
                .is_some_and(|(f, _)| f == j);
            let bg = if hover || open_here {
                theme::HOVER_TINT
            } else {
                CYCLE_TINT
            };
            place_rounded(world, ovr_btn_bg(r), btn, bg, 4.0, true);
            place_center_label(world, ovr_btn_label(r), btn, "*", OVERRIDE_LABEL, true);
        }

        let ent = ent_btn_rect(o, w);
        let hover = point_in(view.mouse[0], view.mouse[1], ent);
        let bg = if hover || ovr.entity_menu.is_some() {
            theme::HOVER_TINT
        } else {
            CYCLE_TINT
        };
        place_rounded(world, ENT_BTN_BG, ent, bg, 4.0, true);
        place_center_label(world, ENT_BTN_LABEL, ent, "...", LABEL, true);
        if ovr.count > 0 {
            let chip = ovr_chip_rect(o, w);
            let hover = point_in(view.mouse[0], view.mouse[1], chip);
            let bg = if hover { theme::HOVER_TINT } else { CYCLE_TINT };
            place_rounded(world, OVR_CHIP_BG, chip, bg, 4.0, true);
            let caption = format!("{} overridden", ovr.count);
            place_center_label(world, OVR_CHIP_LABEL, chip, &caption, OVERRIDE_LABEL, true);
        }
    }

    // A scrollbar down the field region's right edge when the form overflows the
    // visible window.
    layout_form_scrollbar(world, view.form_fields.len(), scroll, o, w, window);

    // The open value dropdown draws last so it floats over the slots below it.
    if let Some(open) = view.field_dropdown {
        layout_field_dropdown(world, view, o, w, window, open);
    }

    // The open override / entity menu draws over everything else.
    if let (Some(anchor), Some(options)) =
        (ovr_menu_anchor(view, o, w, window), ovr_menu_options(view))
    {
        let shown = options.len().min(MAX_OVR_ROWS);
        place_rounded(
            world,
            OVR_MENU_BG,
            ovr_menu_backing(o, w, anchor, shown),
            DROP_BG_TINT,
            theme::CONTROL_RADIUS,
            true,
        );
        for (k, option) in options.iter().take(MAX_OVR_ROWS).enumerate() {
            let rect = ovr_menu_option_rect(o, w, anchor, k);
            let hovered = point_in(view.mouse[0], view.mouse[1], rect);
            let tint = if hovered {
                OPTION_TINT_HOVER
            } else {
                OPTION_TINT
            };
            place_rounded(
                world,
                ovr_menu_row_bg(k),
                theme::highlight_rect(rect),
                tint,
                theme::CONTROL_RADIUS,
                true,
            );
            widget::place_left_label(
                world,
                ovr_menu_row_label(k),
                [rect[0] + PAD, rect[1] + OVR_ROW_H * 0.5 - theme::TEXT_HALF],
                option,
                LABEL,
                true,
            );
        }
    }
}

// The name heading: the editable TextInput under the title bar, drawn larger
// than the body text.
fn show_name_heading(world: &mut World, o: [f32; 2], w: f32, focused: bool) {
    widget::show_field(world, NAME_INPUT, name_rect(o, w), focused);
    if let Some(t) = widget::input_mut(world, NAME_INPUT) {
        t.scale = NAME_SCALE;
    }
}

// The form's scrollbar thumb, sizing the visible window against the total field
// count. Shown only when the form overflows the visible window of `window` rows.
fn layout_form_scrollbar(
    world: &mut World,
    total: usize,
    scroll: usize,
    o: [f32; 2],
    w: f32,
    window: usize,
) {
    if total <= window {
        return;
    }
    let region_top = fields_top(o);
    let track_h = window as f32 * FIELD_H;
    let track = [o[0] + w - SCROLLBAR_W, region_top, SCROLLBAR_W, track_h];
    place_rounded(
        world,
        FORM_TRACK,
        track,
        TRACK_TINT,
        SCROLLBAR_W * 0.5,
        true,
    );
    let frac_visible = window as f32 / total as f32;
    let thumb_h = (track_h * frac_visible).max(20.0);
    let max_scroll = (total - window) as f32;
    let t = if max_scroll > 0.0 {
        scroll.min(total - window) as f32 / max_scroll
    } else {
        0.0
    };
    let thumb_y = region_top + t * (track_h - thumb_h);
    place_rounded(
        world,
        FORM_THUMB,
        [track[0], thumb_y, SCROLLBAR_W, thumb_h],
        THUMB_TINT,
        SCROLLBAR_W * 0.5,
        true,
    );
}

// The floating value dropdown for an open enum / ref field: an opaque backing
// plus its option rows (the current selection highlighted) and, when it
// overflows, its own thin scrollbar.
fn layout_field_dropdown(
    world: &mut World,
    view: &FormView,
    o: [f32; 2],
    w: f32,
    window: usize,
    open: usize,
) {
    let Some(field) = view.form_fields.get(open) else {
        return;
    };
    let Some(slot) = field_slot(view, window, open) else {
        return;
    };
    let total = field.variants.len();
    let scroll = view.field_dropdown_scroll.min(total.saturating_sub(1));
    let shown = total.saturating_sub(scroll).clamp(1, MAX_DROP_ROWS);
    place_rounded(
        world,
        DROP_BG,
        field_dropdown_backing(o, w, slot, shown),
        DROP_BG_TINT,
        theme::CONTROL_RADIUS,
        true,
    );
    for r in 0..MAX_DROP_ROWS {
        let idx = scroll + r;
        if idx >= total {
            break;
        }
        let rect = field_option_rect(o, w, slot, r);
        let hovered = point_in(view.mouse[0], view.mouse[1], rect);
        let tint = if hovered {
            OPTION_TINT_HOVER
        } else if idx == field.variant_idx {
            OPTION_TINT_SELECTED
        } else {
            OPTION_TINT
        };
        place_rounded(
            world,
            drop_row_bg(r),
            theme::highlight_rect(rect),
            tint,
            theme::CONTROL_RADIUS,
            true,
        );
        widget::place_left_label(
            world,
            drop_row_label(r),
            [rect[0] + PAD, rect[1] + DROP_ROW_H * 0.5 - theme::TEXT_HALF],
            &field.variants[idx],
            LABEL,
            true,
        );
    }
    if total > MAX_DROP_ROWS {
        let back = field_dropdown_backing(o, w, slot, shown);
        let track = [
            back[0] + back[2] - SCROLLBAR_W,
            back[1],
            SCROLLBAR_W,
            back[3],
        ];
        place_rounded(
            world,
            DROP_TRACK,
            track,
            TRACK_TINT,
            SCROLLBAR_W * 0.5,
            true,
        );
        let frac = MAX_DROP_ROWS as f32 / total as f32;
        let thumb_h = (back[3] * frac).max(20.0);
        let max_scroll = (total - MAX_DROP_ROWS) as f32;
        let t = if max_scroll > 0.0 {
            scroll as f32 / max_scroll
        } else {
            0.0
        };
        let thumb_y = back[1] + t * (back[3] - thumb_h);
        place_rounded(
            world,
            DROP_THUMB,
            [track[0], thumb_y, SCROLLBAR_W, thumb_h],
            THUMB_TINT,
            SCROLLBAR_W * 0.5,
            true,
        );
    }
}

// Parse a colour field's live text ("r, g, b" / "r, g, b, a") into an opaque RGB
// tint for its preview swatch, clamped to the displayable 0..=1 range. Falls
// back to a neutral dark swatch until three components parse.
fn swatch_rgb(text: &str) -> [f32; 4] {
    let nums: Vec<f32> = text
        .split(|c: char| c == ',' || c.is_whitespace())
        .filter(|s| !s.is_empty())
        .filter_map(|s| s.parse::<f32>().ok())
        .take(3)
        .collect();
    if nums.len() < 3 {
        return [0.15, 0.15, 0.18, 1.0];
    }
    [
        nums[0].clamp(0.0, 1.0),
        nums[1].clamp(0.0, 1.0),
        nums[2].clamp(0.0, 1.0),
        1.0,
    ]
}

fn place_center_label(
    world: &mut World,
    id: AssetId,
    rect: [f32; 4],
    content: &str,
    color: [f32; 3],
    visible: bool,
) {
    if let Some(l) = widget::label_mut(world, id) {
        l.x = rect[0] + rect[2] * 0.5;
        l.y = rect[1] + rect[3] * 0.5 - theme::TEXT_HALF;
        l.align = TextAlign::Center;
        l.color = color;
        l.visible = visible;
        l.content = content.to_string();
    }
}

// Hide every panel element, including the typed fields (and blur them so a
// hidden field cannot keep keyboard focus).
pub(crate) fn hide_all(world: &mut World) {
    widget::hide_all(world, &all_sprite_ids(), &all_label_ids(), &all_field_ids());
}

// Every panel sprite id. THE ORDER OF THIS VEC IS THE DRAW ORDER (inject.rs
// inserts in this sequence; the overlay draws in insertion order): background,
// title, buttons, per-slot chrome, then the floating overlays (scrollbar, value
// dropdown) which must sit above the slot chrome.
// The value dropdown's own elements, which draw above the rest of the panel
// while it is open so its backing occludes the field rows it covers.
pub(crate) fn dropdown_ids() -> Vec<AssetId> {
    let mut ids = vec![DROP_BG, DROP_TRACK, DROP_THUMB];
    ids.extend((0..MAX_DROP_ROWS).map(drop_row_bg));
    ids.extend((0..MAX_DROP_ROWS).map(drop_row_label));
    ids
}

// The open override / entity menu's elements, raised above the rest of the
// panel while one is open (same contract as `dropdown_ids`).
pub(crate) fn override_menu_ids() -> Vec<AssetId> {
    let mut ids = vec![OVR_MENU_BG];
    ids.extend((0..MAX_OVR_ROWS).map(ovr_menu_row_bg));
    ids.extend((0..MAX_OVR_ROWS).map(ovr_menu_row_label));
    ids
}

pub(crate) fn all_sprite_ids() -> Vec<AssetId> {
    let mut ids = vec![EDIT_BG, CLOSE_BG, APPLY_BG, OVR_CHIP_BG, ENT_BTN_BG];
    ids.extend((0..form::FIELD_POOL_MAX).map(form_toggle_bg));
    ids.extend((0..form::FIELD_POOL_MAX).map(form_swatch));
    ids.extend((0..form::FIELD_POOL_MAX).map(ovr_bar));
    ids.extend((0..form::FIELD_POOL_MAX).map(ovr_btn_bg));
    ids.extend([FORM_TRACK, FORM_THUMB, DROP_BG]);
    ids.extend((0..MAX_DROP_ROWS).map(drop_row_bg));
    ids.extend([DROP_TRACK, DROP_THUMB, OVR_MENU_BG]);
    ids.extend((0..MAX_OVR_ROWS).map(ovr_menu_row_bg));
    ids
}
// Same draw-order contract; the dropdown's option captions come last so they
// draw above the slot captions the dropdown floats over.
pub(crate) fn all_label_ids() -> Vec<AssetId> {
    let mut ids = vec![
        TITLE_LABEL,
        CLOSE_LABEL,
        APPLY_LABEL,
        FORM_STATUS,
        OVR_CHIP_LABEL,
        ENT_BTN_LABEL,
    ];
    ids.extend((0..form::FIELD_POOL_MAX).map(form_row_label));
    ids.extend((0..form::FIELD_POOL_MAX).map(form_enum_label));
    ids.extend((0..form::FIELD_POOL_MAX).map(ovr_btn_label));
    ids.extend((0..MAX_DROP_ROWS).map(drop_row_label));
    ids.extend((0..MAX_OVR_ROWS).map(ovr_menu_row_label));
    ids
}
// Every typed field: the name heading and the arg-field text inputs.
pub(crate) fn all_field_ids() -> Vec<AssetId> {
    let mut ids = vec![NAME_INPUT];
    ids.extend((0..form::FIELD_POOL_MAX).map(form_input));
    ids
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::{Sprite, TextInput, TextLabel};

    fn test_origin() -> [f32; 2] {
        default_origin(1280.0)
    }

    fn field(key: &str, kind: FieldKind) -> FormField {
        FormField {
            key: key.into(),
            kind,
            initial: "0".into(),
            boolval: false,
            variants: Vec::new(),
            variant_idx: 0,
        }
    }

    fn float_fields(n: usize) -> Vec<FormField> {
        (0..n)
            .map(|i| field(&format!("f{i}"), FieldKind::Float))
            .collect()
    }

    // A ref field with `n` options past `(none)`. With `n > CYCLE_MAX` it opens
    // a dropdown rather than cycling.
    fn ref_field(n: usize) -> FormField {
        let mut variants = vec![form::NONE_LABEL.to_string()];
        variants.extend((0..n).map(|i| format!("tex_{i}")));
        FormField {
            key: "texture".into(),
            kind: FieldKind::Ref { target: "Texture" },
            initial: String::new(),
            boolval: false,
            variants,
            variant_idx: 0,
        }
    }

    fn view<'a>(fields: &'a [FormField]) -> FormView<'a> {
        FormView {
            title: "New PointLight",
            editing: false,
            form_fields: fields,
            form_scroll: 0,
            form_focus: FormFocus::Name,
            field_dropdown: None,
            field_dropdown_scroll: 0,
            form_error: None,
            overrides: None,
            mouse: [0.0, 0.0],
        }
    }

    fn injected_world() -> World {
        let mut world = World::new();
        for id in all_sprite_ids() {
            world.add_component(Sprite {
                asset_id: id,
                ..Default::default()
            });
        }
        for id in all_label_ids() {
            world.add_component(TextLabel {
                asset_id: id,
                ..Default::default()
            });
        }
        for id in all_field_ids() {
            world.add_component(TextInput {
                asset_id: id,
                ..Default::default()
            });
        }
        world
    }

    fn sprite(world: &World, id: AssetId) -> Sprite {
        world
            .query::<Sprite>()
            .find(|s| s.asset_id == id)
            .cloned()
            .expect("sprite present")
    }
    fn sprite_visible(world: &World, id: AssetId) -> bool {
        sprite(world, id).visible
    }
    fn label(world: &World, id: AssetId) -> TextLabel {
        world
            .query::<TextLabel>()
            .find(|l| l.asset_id == id)
            .cloned()
            .expect("label present")
    }
    fn input(world: &World, id: AssetId) -> TextInput {
        world
            .query::<TextInput>()
            .find(|t| t.asset_id == id)
            .cloned()
            .expect("input present")
    }

    // The X close sits in the title bar's top-right corner; the header row pins the
    // name heading and the Apply button under the title bar.
    #[test]
    fn header_pins_name_and_button_under_the_title_bar() {
        let o = test_origin();
        let title = widget::title_rect(o, EDIT_W);
        assert_eq!(title, [o[0], o[1], EDIT_W, widget::TITLE_H]);
        let close = close_rect(o, EDIT_W);
        assert_eq!(close[1], o[1], "the X sits in the title bar");
        assert_eq!(
            close[0] + close[2],
            o[0] + EDIT_W,
            "the X is flush to the panel's right edge"
        );
        let name = name_rect(o, EDIT_W);
        let apply_btn = apply_rect(o, EDIT_W);
        assert_eq!(name[1], o[1] + widget::TITLE_H + PAD, "under the title bar");
        assert_eq!(
            name[1], apply_btn[1],
            "the name and Apply share the header row"
        );
        assert!(
            name[0] + name[2] <= apply_btn[0],
            "the name heading ends left of Apply"
        );
        assert_eq!(
            apply_btn[0] + apply_btn[2],
            o[0] + EDIT_W - PAD,
            "Apply flush to the panel's right pad"
        );
        // The whole panel follows its origin.
        let v = view(&[]);
        let moved = widget::outer_rect([40.0, 60.0], size(v.form_fields.len()));
        assert_eq!((moved[0], moved[1]), (40.0, 60.0));
    }

    // The panel height tracks the field count up to the pool cap; `size` is what
    // the hook's drag clamp uses.
    #[test]
    fn panel_height_tracks_fields_and_caps_at_the_pool() {
        let short = size(2);
        let tall = size(form::FIELD_POOL + 20);
        assert!(short[1] < tall[1]);
        assert_eq!(
            tall[1],
            size(form::FIELD_POOL)[1],
            "a form past the pool scrolls instead of growing"
        );
        let fields = float_fields(2);
        let v = view(&fields);
        assert_eq!(
            widget::outer_rect(test_origin(), size(v.form_fields.len()))[3],
            short[1]
        );
    }

    // Growing the panel taller reveals more field rows (up to the pool); a short
    // form is height-locked; growing it wider stretches the control column while
    // the caption column stays fixed.
    #[test]
    fn taller_reveals_more_fields_and_wider_grows_the_control_column() {
        // A form past the default window: the default height shows FIELD_POOL rows,
        // taller reveals more up to FIELD_POOL_MAX.
        assert_eq!(rows_for_height(size(40)[1]), form::FIELD_POOL);
        assert_eq!(
            rows_for_height(size(40)[1] + 5.0 * FIELD_H),
            form::FIELD_POOL + 5
        );
        assert_eq!(rows_for_height(max_size(40)[1]), form::FIELD_POOL_MAX);
        assert_eq!(
            rows_for_height(10_000.0),
            form::FIELD_POOL_MAX,
            "capped at the pool"
        );
        // A short form's height is locked (max == default): no vertical grab.
        assert_eq!(max_size(3)[1], size(3)[1]);
        // Wider widens the control column; the caption column start is fixed.
        let o = [40.0, 60.0];
        let narrow = form_control_rect(o, EDIT_W, 0);
        let wide = form_control_rect(o, EDIT_W + 200.0, 0);
        assert_eq!(narrow[0], wide[0], "the control column starts at a fixed x");
        assert!(
            wide[2] > narrow[2] + 150.0,
            "the control widens with the panel"
        );
    }

    // A taller panel draws field rows past the default window that a default one
    // would never show.
    #[test]
    fn taller_panel_draws_fields_past_the_default_window() {
        let mut world = injected_world();
        let fields = float_fields(form::FIELD_POOL_MAX);
        let tall = [EDIT_W, max_size(fields.len())[1]];
        apply(&mut world, Some(&view(&fields)), [20.0, 20.0], tall);
        assert!(
            input(&world, form_input(form::FIELD_POOL)).visible,
            "a row past the default window shows only because we grew"
        );
    }

    #[test]
    fn buttons_and_name_hit_test() {
        let fields = float_fields(1);
        let v = view(&fields);
        let o = test_origin();
        let a = apply_rect(o, EDIT_W);
        let x = close_rect(o, EDIT_W);
        let n = name_rect(o, EDIT_W);
        assert_eq!(
            hit_test(&v, a[0] + 5.0, a[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::Confirm)
        );
        assert_eq!(
            hit_test(&v, x[0] + 5.0, x[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::Close),
            "the title-bar X closes the form"
        );
        assert_eq!(
            hit_test(&v, n[0] + 5.0, n[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::FocusName)
        );
        // A title-bar click off the X is consumed (the hook grabs drags before this).
        let t = widget::title_rect(o, EDIT_W);
        assert_eq!(
            hit_test(&v, t[0] + 5.0, t[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::Consume)
        );
        // A miss falls through.
        assert_eq!(
            hit_test(&v, 10.0, 700.0, o, size(v.form_fields.len())),
            None
        );
    }

    // The title bar carries the heading, the confirm button is captioned "Apply"
    // while editing and "Add" for a new asset, and the name heading draws larger.
    #[test]
    fn apply_shows_title_confirm_caption_and_scaled_name() {
        let fields = float_fields(1);
        let mut world = injected_world();
        let o = test_origin();
        apply(&mut world, Some(&view(&fields)), o, size(fields.len()));
        assert_eq!(label(&world, TITLE_LABEL).content, "New PointLight");
        assert_eq!(label(&world, APPLY_LABEL).content, "Add");
        assert_eq!(
            label(&world, CLOSE_LABEL).content,
            "X",
            "the title-bar close"
        );
        let name = input(&world, NAME_INPUT);
        assert!(name.visible);
        assert!(name.scale > 1.0, "the name heading draws larger");
        let mut editing = view(&fields);
        editing.editing = true;
        editing.title = "Edit Camera3D";
        apply(
            &mut world,
            Some(&editing),
            o,
            size(editing.form_fields.len()),
        );
        assert_eq!(label(&world, TITLE_LABEL).content, "Edit Camera3D");
        assert_eq!(label(&world, APPLY_LABEL).content, "Apply");
    }

    // Field slots map logical fields through the scroll window; a form past the
    // pool shows its scrollbar and keeps the buttons pinned in the header.
    #[test]
    fn a_form_past_the_pool_scrolls_a_window() {
        let o = test_origin();
        let fields = float_fields(form::FIELD_POOL + 4);
        let mut world = injected_world();
        let v = view(&fields);
        apply(&mut world, Some(&v), o, size(v.form_fields.len()));
        assert!(
            sprite_visible(&world, FORM_THUMB),
            "the form scrollbar shows"
        );
        // Slot 0 resolves to logical field 0.
        let c0 = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, c0[0] + 5.0, c0[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::FocusField(0))
        );
        // Scrolled by three: slot 0 shows logical field 3; the last slot shows
        // the window's last field.
        let mut vs = view(&fields);
        vs.form_scroll = 3;
        assert_eq!(
            hit_test(&vs, c0[0] + 5.0, c0[1] + 5.0, o, size(vs.form_fields.len())),
            Some(FormAction::FocusField(3))
        );
        let last = form_control_rect(o, EDIT_W, form::FIELD_POOL - 1);
        assert_eq!(
            hit_test(
                &vs,
                last[0] + 5.0,
                last[1] + 5.0,
                o,
                size(vs.form_fields.len())
            ),
            Some(FormAction::FocusField(3 + form::FIELD_POOL - 1))
        );
        // The Apply button stays pinned in the header regardless.
        let a = apply_rect(o, EDIT_W);
        assert_eq!(
            hit_test(&vs, a[0] + 5.0, a[1] + 5.0, o, size(vs.form_fields.len())),
            Some(FormAction::Confirm)
        );
    }

    #[test]
    fn a_form_within_the_pool_has_no_scrollbar() {
        let fields = float_fields(1);
        let mut world = injected_world();
        apply(
            &mut world,
            Some(&view(&fields)),
            test_origin(),
            size(fields.len()),
        );
        assert!(!sprite_visible(&world, FORM_THUMB));
    }

    // A colour-vector arg field renders its text control plus a live preview
    // swatch tinted from the field's current text; the swatch sits outside the
    // field rect (a TextInput's opaque background box is synthesised after every
    // authored sprite, so a swatch under the field would be painted over).
    #[test]
    fn colour_vector_field_shows_a_live_swatch() {
        let mut world = injected_world();
        for t in world.query_mut::<TextInput>() {
            if t.asset_id == form_input(0) {
                t.content = "1, 0, 0".into();
            }
        }
        let fields = [FormField {
            key: "color".into(),
            kind: FieldKind::Vec {
                len: 3,
                color: true,
            },
            initial: "1, 0, 0".into(),
            boolval: false,
            variants: Vec::new(),
            variant_idx: 0,
        }];
        apply(
            &mut world,
            Some(&view(&fields)),
            test_origin(),
            size(fields.len()),
        );
        let sw = sprite(&world, form_swatch(0));
        assert!(sw.visible, "the colour field draws a swatch");
        assert_eq!(sw.tint, [1.0, 0.0, 0.0, 1.0], "swatch tint is the RGB text");
        let ti = input(&world, form_input(0));
        assert!(ti.visible, "the editable text field still shows");
        assert!(
            sw.x >= ti.x + ti.width,
            "the swatch sits outside the field's opaque background box"
        );
    }

    // A plain (non-colour) vector renders as a collapsed disclosure button, not an
    // editable text field or a swatch; clicking it toggles its per-element leaves.
    #[test]
    fn plain_vector_field_is_a_disclosure() {
        let o = test_origin();
        let mut world = injected_world();
        let fields = [FormField {
            key: "position".into(),
            kind: FieldKind::Vec {
                len: 3,
                color: false,
            },
            initial: "0, 0, 0".into(),
            boolval: false,
            variants: Vec::new(),
            variant_idx: 0,
        }];
        let v = view(&fields);
        apply(&mut world, Some(&v), o, size(v.form_fields.len()));
        assert!(!sprite_visible(&world, form_swatch(0)), "no colour swatch");
        assert!(
            !input(&world, form_input(0)).visible,
            "a collapsed vector has no editable comma field"
        );
        assert!(
            sprite_visible(&world, form_toggle_bg(0)),
            "the disclosure button shows"
        );
        let cap = label(&world, form_enum_label(0));
        assert!(
            cap.visible && cap.content == "[3] >",
            "collapsed count + caret"
        );
        let c = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, c[0] + 5.0, c[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::ToggleVecExpand(0))
        );
    }

    // An expanded vector shows its element leaves labelled by axis (x / y / z), each
    // an editable field, and the header caret flips to `v`.
    #[test]
    fn expanded_vector_shows_axis_labelled_element_fields() {
        let o = test_origin();
        let mut world = injected_world();
        let elem = |axis: &str| FormField {
            key: format!("position.{axis}"),
            kind: FieldKind::Float,
            initial: "0".into(),
            boolval: false,
            variants: Vec::new(),
            variant_idx: 0,
        };
        let fields = [
            FormField {
                key: "position".into(),
                kind: FieldKind::Vec {
                    len: 3,
                    color: false,
                },
                initial: String::new(),
                boolval: false,
                variants: Vec::new(),
                variant_idx: 0,
            },
            elem("0"),
            elem("1"),
            elem("2"),
        ];
        let v = view(&fields);
        apply(&mut world, Some(&v), o, size(v.form_fields.len()));
        // The header caret is now `v` (its element leaves follow it).
        assert_eq!(label(&world, form_enum_label(0)).content, "[3] v");
        // Slots 1..=3 are the axis-labelled element fields.
        assert_eq!(label(&world, form_row_label(1)).content, "x");
        assert_eq!(label(&world, form_row_label(2)).content, "y");
        assert_eq!(label(&world, form_row_label(3)).content, "z");
        assert!(
            input(&world, form_input(1)).visible,
            "an element leaf is an editable field"
        );
        // Clicking an element focuses it; clicking the header collapses again.
        let c1 = form_control_rect(o, EDIT_W, 1);
        assert_eq!(
            hit_test(&v, c1[0] + 5.0, c1[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::FocusField(1))
        );
        let c0 = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, c0[0] + 5.0, c0[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::ToggleVecExpand(0))
        );
    }

    // An enum / ref field renders as a cycling button captioned with the current
    // variant and hit-tests to a cycle; a large variant set opens a dropdown.
    #[test]
    fn choice_fields_cycle_or_open_a_dropdown() {
        let o = test_origin();
        let mut world = injected_world();
        let small = [FormField {
            key: "align".into(),
            kind: FieldKind::Enum,
            initial: String::new(),
            boolval: false,
            variants: vec!["left".into(), "center".into(), "right".into()],
            variant_idx: 1,
        }];
        let v = view(&small);
        apply(&mut world, Some(&v), o, size(v.form_fields.len()));
        assert!(
            sprite_visible(&world, form_toggle_bg(0)),
            "cycle button shows"
        );
        let cap = label(&world, form_enum_label(0));
        assert!(cap.visible && cap.content == "center");
        assert!(
            !input(&world, form_input(0)).visible,
            "an enum has no editable text field"
        );
        let c = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, c[0] + 5.0, c[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::CycleField(0))
        );
        let big = [ref_field(CYCLE_MAX + 1)];
        let vb = view(&big);
        assert_eq!(
            hit_test(&vb, c[0] + 5.0, c[1] + 5.0, o, size(vb.form_fields.len())),
            Some(FormAction::OpenFieldDropdown(0)),
            "a large variant set opens a dropdown"
        );
    }

    // An open value dropdown is modal: its option rows pick (through the scroll
    // offset), anything else closes it.
    #[test]
    fn open_field_dropdown_picks_options_and_is_modal() {
        let o = test_origin();
        let fields = [ref_field(CYCLE_MAX + 3)];
        let mut v = view(&fields);
        v.field_dropdown = Some(0);
        let opt = field_option_rect(o, EDIT_W, 0, 2);
        assert_eq!(
            hit_test(&v, opt[0] + 5.0, opt[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::PickFieldOption(2))
        );
        let n = name_rect(o, EDIT_W);
        assert_eq!(
            hit_test(&v, n[0] + 5.0, n[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::CloseOverlays),
            "a click off the option list dismisses it"
        );
        v.field_dropdown_scroll = 3;
        let r0 = field_option_rect(o, EDIT_W, 0, 0);
        assert_eq!(
            hit_test(&v, r0[0] + 5.0, r0[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::PickFieldOption(3)),
            "visible row 0 is option `scroll + 0`"
        );
    }

    // Laying out an open dropdown shows its backing + option rows and hides the
    // slots it floats over (their opaque TextInput boxes would paint over it).
    #[test]
    fn open_dropdown_draws_over_the_slots_it_covers() {
        let mut world = injected_world();
        let fields = [
            ref_field(CYCLE_MAX + 2),
            field("intensity", FieldKind::Float),
        ];
        let mut v = view(&fields);
        v.field_dropdown = Some(0);
        apply(
            &mut world,
            Some(&v),
            test_origin(),
            size(v.form_fields.len()),
        );
        assert!(sprite_visible(&world, DROP_BG), "dropdown backing shows");
        assert!(sprite_visible(&world, drop_row_bg(0)), "option row shows");
        let opt0 = label(&world, drop_row_label(0));
        assert!(opt0.visible && opt0.content == form::NONE_LABEL);
        assert!(
            sprite_visible(&world, form_toggle_bg(0)),
            "the open field's button stays"
        );
        // The covered rows keep drawing: the dropdown is on its own layer (see
        // `overlay_ids`) and its opaque backing hides them.
        assert!(
            label(&world, form_row_label(1)).visible,
            "the covered slot was blanked instead of being drawn under the dropdown"
        );
        let declared = dropdown_ids();
        for id in [DROP_BG, drop_row_bg(0), drop_row_label(0)] {
            assert!(declared.contains(&id), "{id:?} is not declared an overlay");
        }
    }

    // An overlay that stops mid-row leaves the row under it half drawn, which
    // reads as clashing text rather than as one thing sitting over another.
    #[test]
    fn the_dropdown_backing_ends_on_a_field_row_boundary() {
        let o = test_origin();
        let w = EDIT_W;
        for slot in 0..4 {
            for shown in 1..=MAX_DROP_ROWS {
                let b = field_dropdown_backing(o, w, slot, shown);
                let bottom = b[1] + b[3];
                let rows = (bottom - fields_top(o)) / FIELD_H;
                assert!(
                    (rows - rows.round()).abs() < 0.01,
                    "slot {slot} shown {shown}: bottom {bottom} is {rows} rows down",
                );
                // Still tall enough for every option it draws.
                assert!(b[3] >= shown as f32 * DROP_ROW_H, "{b:?}");
            }
        }
    }

    // An array header renders its element count + red remove / green add buttons,
    // and the buttons hit-test to the add / remove actions.
    #[test]
    fn array_header_renders_count_and_buttons_and_hit_tests() {
        let o = test_origin();
        let mut world = injected_world();
        let fields = [FormField {
            key: "waves".into(),
            kind: FieldKind::Array,
            initial: String::new(),
            boolval: false,
            variants: Vec::new(),
            variant_idx: 3,
        }];
        let v = view(&fields);
        apply(&mut world, Some(&v), o, size(v.form_fields.len()));
        assert!(
            sprite_visible(&world, form_toggle_bg(0)),
            "add button shows"
        );
        assert!(
            sprite_visible(&world, form_swatch(0)),
            "remove button shows"
        );
        let cap = label(&world, form_enum_label(0));
        assert!(cap.visible && cap.content == "(3)");
        assert!(!input(&world, form_input(0)).visible);
        let add = array_add_rect(o, EDIT_W, 0);
        let rem = array_remove_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, add[0] + 3.0, add[1] + 3.0, o, size(v.form_fields.len())),
            Some(FormAction::AddArrayElement(0))
        );
        assert_eq!(
            hit_test(&v, rem[0] + 3.0, rem[1] + 3.0, o, size(v.form_fields.len())),
            Some(FormAction::RemoveArrayElement(0))
        );
    }

    // A validation error shows on the reserved status line; hiding the panel
    // blanks everything including the typed fields.
    #[test]
    fn error_line_shows_and_hide_all_blanks() {
        let fields = float_fields(1);
        let mut world = injected_world();
        let mut v = view(&fields);
        v.form_error = Some("Invalid argument");
        apply(
            &mut world,
            Some(&v),
            test_origin(),
            size(v.form_fields.len()),
        );
        let status = label(&world, FORM_STATUS);
        assert!(status.visible);
        assert_eq!(status.content, "Invalid argument");
        apply(&mut world, None, [0.0, 0.0], size(0));
        assert!(world.query::<Sprite>().all(|s| !s.visible));
        assert!(world.query::<TextLabel>().all(|l| !l.visible));
        assert!(world.query::<TextInput>().all(|t| !t.visible));
    }

    // The floating value dropdown draws above the slot chrome (insertion order).
    #[test]
    fn dropdown_is_injected_after_the_slot_chrome() {
        let sprites = all_sprite_ids();
        let spos = |id: AssetId| sprites.iter().position(|&x| x == id).unwrap();
        let last_slot = (0..form::FIELD_POOL_MAX)
            .map(form_toggle_bg)
            .chain((0..form::FIELD_POOL_MAX).map(form_swatch))
            .map(spos)
            .max()
            .unwrap();
        assert!(
            spos(DROP_BG) > last_slot,
            "dropdown backing above the slots"
        );
        let first_drop_row = (0..MAX_DROP_ROWS).map(drop_row_bg).map(spos).min().unwrap();
        assert!(spos(DROP_BG) < first_drop_row, "backing under its rows");
        let labels = all_label_ids();
        let lpos = |id: AssetId| labels.iter().position(|&x| x == id).unwrap();
        let last_slot_label = (0..form::FIELD_POOL_MAX)
            .map(form_row_label)
            .chain((0..form::FIELD_POOL_MAX).map(form_enum_label))
            .map(lpos)
            .max()
            .unwrap();
        for r in 0..MAX_DROP_ROWS {
            assert!(lpos(drop_row_label(r)) > last_slot_label);
        }
    }

    // A FormView with the value dropdown for logical field `open` disclosed.
    fn view_with_dropdown<'a>(
        fields: &'a [FormField],
        open: usize,
        mouse: [f32; 2],
    ) -> FormView<'a> {
        FormView {
            field_dropdown: Some(open),
            mouse,
            ..view(fields)
        }
    }

    // An enum field with a small (cycle-in-place) variant set.
    fn enum_field(key: &str, variants: &[&str]) -> FormField {
        FormField {
            key: key.into(),
            kind: FieldKind::Enum,
            initial: String::new(),
            boolval: false,
            variants: variants.iter().map(|s| s.to_string()).collect(),
            variant_idx: 0,
        }
    }

    #[test]
    fn open_dropdown_renders_its_options_and_a_scrollbar() {
        // 11 variants ((none) + tex_0..tex_9) overflow the 8-row window, so the
        // dropdown draws its scrollbar too.
        let fields = vec![ref_field(10)];
        let mut world = injected_world();
        let o = test_origin();
        apply(
            &mut world,
            Some(&view_with_dropdown(&fields, 0, [0.0, 0.0])),
            o,
            size(fields.len()),
        );
        assert!(sprite_visible(&world, DROP_BG));
        assert_eq!(label(&world, drop_row_label(0)).content, form::NONE_LABEL);
        assert!(sprite_visible(&world, DROP_TRACK), "scrollbar track shows");
        assert!(sprite_visible(&world, DROP_THUMB), "scrollbar thumb shows");
    }

    #[test]
    fn open_dropdown_hit_test_picks_or_dismisses() {
        // A short (non-scrolling) dropdown so the option scan reaches its end.
        let fields = vec![ref_field(2)];
        let o = test_origin();
        let v = view_with_dropdown(&fields, 0, [0.0, 0.0]);
        // Clicking an option row picks that variant.
        let opt = field_option_rect(o, EDIT_W, 0, 1);
        assert_eq!(
            hit_test(&v, opt[0] + 5.0, opt[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::PickFieldOption(1))
        );
        // Clicking off every option dismisses the dropdown.
        assert_eq!(
            hit_test(&v, 0.0, 0.0, o, size(v.form_fields.len())),
            Some(FormAction::CloseOverlays)
        );
    }

    #[test]
    fn control_click_opens_a_large_variant_dropdown() {
        // A ref field with more than CYCLE_MAX options opens a dropdown rather
        // than cycling in place.
        let fields = vec![ref_field(10)];
        let o = test_origin();
        let v = view(&fields);
        let c = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, c[0] + 5.0, c[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::OpenFieldDropdown(0))
        );
    }

    #[test]
    fn bool_enum_and_array_controls_hit_test() {
        let o = test_origin();

        // A bool field toggles from its checkbox rect.
        let bools = vec![field("flag", FieldKind::Bool)];
        let vb = view(&bools);
        let t = form_toggle_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&vb, t[0] + 3.0, t[1] + 3.0, o, size(vb.form_fields.len())),
            Some(FormAction::ToggleField(0))
        );

        // A small enum cycles in place from its control rect.
        let enums = vec![enum_field("mode", &["a", "b"])];
        let ve = view(&enums);
        let c = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&ve, c[0] + 5.0, c[1] + 5.0, o, size(ve.form_fields.len())),
            Some(FormAction::CycleField(0))
        );

        // An array header grows / shrinks from its + / - buttons.
        let arrays = vec![field("waves", FieldKind::Array)];
        let va = view(&arrays);
        let add = array_add_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(
                &va,
                add[0] + 3.0,
                add[1] + 3.0,
                o,
                size(va.form_fields.len())
            ),
            Some(FormAction::AddArrayElement(0))
        );
        let rem = array_remove_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(
                &va,
                rem[0] + 3.0,
                rem[1] + 3.0,
                o,
                size(va.form_fields.len())
            ),
            Some(FormAction::RemoveArrayElement(0))
        );
    }

    #[test]
    fn hit_test_consumes_a_click_past_the_scrolled_field_window() {
        // A scroll offset past the only field leaves the visible slot empty, so a
        // click there is swallowed rather than resolving to a control.
        let fields = float_fields(1);
        let v = FormView {
            form_scroll: 1,
            ..view(&fields)
        };
        let o = test_origin();
        let c = form_control_rect(o, EDIT_W, 0);
        assert_eq!(
            hit_test(&v, c[0] + 5.0, c[1] + 5.0, o, size(v.form_fields.len())),
            Some(FormAction::Consume)
        );
    }

    #[test]
    fn swatch_rgb_falls_back_and_clamps() {
        // Fewer than three parsed components yields the neutral placeholder.
        assert_eq!(swatch_rgb("1"), [0.15, 0.15, 0.18, 1.0]);
        assert_eq!(swatch_rgb("nope"), [0.15, 0.15, 0.18, 1.0]);
        // Three components clamp into the displayable range.
        assert_eq!(swatch_rgb("2, -1, 0.5"), [1.0, 0.0, 0.5, 1.0]);
    }
}