BREP_app 0.2.1

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
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
//! The SHARED COLUMN-TREE widget — a table whose rows are a TREE, with
//! resizable, reorderable, hideable, sortable columns and a per-column editor
//! kind. One function draws a complete columned tree and returns what the user
//! did.
//!
//! ```text
//!   │ Item          │ Qty │ Description      │ Material │      │  ← header
//!   │ [-] Assembly  │  4  │                  │          │      │
//!   │  ├ bracket    │  2  │ [L-bracket     ] │ [6061 ▾] │ [✕]  │  ← editors
//!   │  └[-] gearbox │  1  │ [drive unit    ] │ [ ---  ▾]│ [✕]  │
//!   │     └ shaft   │  1  │ [              ] │ [4140 ▾] │ [✕]  │
//! ```
//!
//! # It is generic, and that is the point
//!
//! It knows nothing about assemblies, parts, occurrences or `EngineState`. It
//! is handed COLUMNS (a key, a label, an editor kind), ROWS (an id, a cell
//! value per column key, children) and a LAYOUT (order, hidden set, widths,
//! sort), and it hands back EDITS and CLICKS. The BOM is the first consumer;
//! the wire-harness connection list named as the second one needs no change
//! here — a connection list is a different `columns` slice and a different
//! `rows` tree, both built by its own panel.
//!
//! The rule that keeps it that way: **nothing in this module may name a
//! consumer's vocabulary.** If a behaviour cannot be expressed as "a column of
//! kind K" or "a row with children", it belongs in the consumer, not here.
//!
//! # The shape is `form_view`'s
//!
//! `(ui, spec, &mut layout, rows) -> Out` — no engine, no document, no store.
//! Intents come OUT as values ([`ColumnTreeOut`]) that the calling panel acts
//! on AFTER the draw, exactly as [`crate::form_view`] does and for the same
//! reason: a caller that has no engine (the headless docs generator; a test)
//! can still drive the real widget.
//!
//! `layout` is the ONE `&mut` input, because column order / widths / hidden /
//! sort are things the USER changes BY DRAGGING THIS WIDGET, so the widget must
//! be able to write them. It is plain data the consumer owns and persists (the
//! BOM round-trips it through a settings textarea); [`ColumnTreeOut::layout_changed`]
//! says when to save.
//!
//! # Column 0 is a real tree
//!
//! The first visible column draws through [`crate::panels::tree::node`] — the
//! same `[+]`/`[-]` boxes and `├`/`└` connector rules the history, scene,
//! settings, sketch, assembly-structure and constraint panels use — inside a
//! clipped child `Ui` sized to that column. So this widget is a SIBLING of
//! `panels::tree`, not a fork of it: the node painter is called, never copied,
//! and its six existing consumers keep a byte-identical code path.
//!
//! # Per-row ACTIONS are a declaration, not a behaviour
//!
//! A row carries [`RowNode::actions`] — a list of (id, label, enabled) the
//! CONSUMER writes. The widget renders them as a menu and reports which id
//! fired on which row ([`ColumnTreeOut::actions`]); it never learns what any of
//! them means. Availability is per ROW because that is where it varies (one
//! row's part has no source file, another's component is fixed), and a refused
//! entry is drawn GREYED with its tooltip rather than hidden: a menu that
//! changes shape row to row cannot be learned, and the tooltip is the only
//! place the reason can be told.
//!
//! The menu has TWO triggers and ONE definition. A [`CellKind::Actions`] cell
//! click and a right-click anywhere on the row both do nothing but record
//! *which row, at which point*; the menu itself is drawn once per frame from
//! that record. Two triggers cannot drift apart because there is only one of
//! them to drift.
//!
//! # Frozen columns
//!
//! [`ColumnLayout::frozen`] holds the first N columns FIXED while the rest
//! scroll horizontally (Excel's freeze-panes). The widget therefore owns its
//! horizontal scrolling — an outer scroll area would carry the frozen columns
//! away with everything else. `frozen == 0` is one plain scrolling region, i.e.
//! exactly the behaviour of a table that never heard of freezing.
//!
//! # Transient state
//!
//! Which column is mid-drag lives in egui MEMORY keyed by [`ColumnTreeSpec::id`],
//! and so does each text cell's in-progress edit buffer (a text cell commits on
//! focus-loss / Enter, never per keystroke — a consumer's commit can be
//! expensive, and the BOM's part-level one rebuilds geometry) and which row's
//! action menu is open. Expansion is the CALLER's, exactly as in `panels::tree`.

use crate::panels::tree::{self, TreeRow};
use eframe::egui;
use serde_json::Value;
use std::collections::{HashMap, HashSet};

/// Minimum column width, in points — narrow enough to park a column out of the
/// way, wide enough that its resize grip is still catchable.
pub const MIN_COLUMN_WIDTH: f32 = 28.0;

/// The default width of a column whose [`ColumnLayout`] carries none.
pub const DEFAULT_COLUMN_WIDTH: f32 = 110.0;

/// Width of the draggable divider strip at a header cell's right edge.
const GRIP: f32 = 5.0;

/// Horizontal padding inside a cell, so text does not touch the divider.
const CELL_PAD: f32 = 3.0;

/// Width of the band between the frozen columns and the scrolling ones.
const FREEZE_GAP: f32 = 4.0;

/// What a column's cells are, and therefore which editor the widget draws.
#[derive(Debug, Clone, PartialEq)]
pub enum CellKind {
    /// Free text. Committed on focus-loss / Enter, NOT per keystroke.
    Text,
    /// A number, edited with a drag-value.
    Numeric { step: f64 },
    /// A fixed set of choices — a combobox. An empty string is always
    /// offered as the "unset" choice, so a user can clear a cell.
    Choice { options: Vec<String> },
    /// An action button in every row of the column. The widget reports the
    /// click ([`ColumnTreeOut::buttons`]); the consumer acts.
    Button { label: String },
    /// The row's ACTION MENU trigger. Every row draws `label`; clicking it
    /// opens that row's [`RowNode::actions`] — the same menu a right-click on
    /// the row opens. A row that declares no action draws the trigger greyed.
    Actions { label: String },
    /// Read-only status glyphs drawn inline, from a cell value shaped
    /// `[{"glyph": "⏚", "color": "#ff9f0a", "tooltip": "…"}, …]` (`color` and
    /// `tooltip` optional). A plain text cell cannot colour part of its own
    /// content, and these glyphs carry meaning IN their colour — a constraint
    /// status, an out-of-date badge — so they get a kind rather than being
    /// flattened into a string.
    Badges,
    /// A boolean, drawn as a checkbox. The cell's value is read with
    /// [`Value::as_bool`]; a missing value reads false. A row that is not
    /// [`RowNode::editable`] still DRAWS its box (so the column stays
    /// readable) but cannot be clicked — a derived grouping row has no state
    /// of its own to toggle.
    Toggle,
    /// Displayed, never edited (a derived value — a rolled-up quantity, a
    /// computed length).
    ReadOnly,
}

/// One column: its cell key, its heading, its editor, its default width.
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnSpec {
    /// The key this column reads out of [`RowNode::cells`]. Unique per spec.
    pub key: String,
    /// The heading text.
    pub label: String,
    pub kind: CellKind,
    /// Width used when [`ColumnLayout::widths`] carries none for this key.
    pub default_width: f32,
}

impl ColumnSpec {
    /// A column with the default width.
    pub fn new(key: impl Into<String>, label: impl Into<String>, kind: CellKind) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            kind,
            default_width: DEFAULT_COLUMN_WIDTH,
        }
    }

    pub fn width(mut self, width: f32) -> Self {
        self.default_width = width;
        self
    }
}

/// One entry in a row's action menu: what to call it, whether this ROW allows
/// it, and how to draw it. Everything here is the consumer's vocabulary — the
/// widget only ever compares [`RowAction::id`] for equality when it reports the
/// click back.
#[derive(Debug, Clone, PartialEq)]
pub struct RowAction {
    /// Stable id, handed back in [`RowActionClick::action`].
    pub id: String,
    /// The menu text.
    pub label: String,
    /// Hover text. Set it on a DISABLED entry to say why it is refused — the
    /// entry is greyed, not hidden, so this is where the reason is told.
    pub tooltip: String,
    /// Whether THIS ROW allows it. A disabled entry is drawn greyed and
    /// reports nothing.
    pub enabled: bool,
    /// Draw a separator line above this entry (grouping, e.g. before a
    /// destructive tail).
    pub separator_above: bool,
    /// Draw in the error colour — an entry that destroys something.
    pub destructive: bool,
}

impl RowAction {
    /// An enabled entry.
    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            tooltip: String::new(),
            enabled: true,
            separator_above: false,
            destructive: false,
        }
    }

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

    /// Refuse this entry ON THIS ROW, saying why (the greyed entry's tooltip).
    pub fn disabled(mut self, why: impl Into<String>) -> Self {
        self.enabled = false;
        self.tooltip = why.into();
        self
    }

    pub fn separator_above(mut self) -> Self {
        self.separator_above = true;
        self
    }

    pub fn destructive(mut self) -> Self {
        self.destructive = true;
        self
    }
}

/// One row. Rows nest — this is a TREE, not a flat table — and each row's
/// cells are looked up by column key, so adding a column never touches the
/// row builder's shape.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RowNode {
    /// Stable, unique across the whole tree — the id every out-value names.
    pub id: String,
    /// Cell values by column key. A missing key draws an empty cell.
    pub cells: HashMap<String, Value>,
    /// Whether this row's cells accept edits. A read-only row still draws its
    /// values (and its buttons), it just cannot be typed into — the BOM's
    /// nested sub-assembly rows, whose data belongs to another document.
    pub editable: bool,
    /// Draw the first column's label emphasized (the selected row).
    pub selected: bool,
    /// Expansion is the CALLER's, as in `panels::tree`.
    pub expanded: bool,
    /// What this row offers, in menu order. EMPTY means the row offers
    /// nothing: its trigger cell draws greyed and a right-click on it opens
    /// nothing (the BOM's nested sub-assembly rows, which own no feature in
    /// this document).
    pub actions: Vec<RowAction>,
    pub children: Vec<RowNode>,
}

impl RowNode {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            editable: true,
            ..Default::default()
        }
    }

    /// Set one cell.
    pub fn cell(mut self, key: impl Into<String>, value: Value) -> Self {
        self.cells.insert(key.into(), value);
        self
    }

    /// Set this row's action menu.
    pub fn actions(mut self, actions: Vec<RowAction>) -> Self {
        self.actions = actions;
        self
    }
}

/// The user's column arrangement — the widget WRITES this (header drag,
/// divider drag, hide/show, sort click) and the consumer owns and persists it.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ColumnLayout {
    /// Column keys in display order. Keys absent from the spec are ignored;
    /// spec columns absent from `order` are appended in spec order, so a
    /// consumer may start with an empty layout and get the spec's order.
    pub order: Vec<String>,
    /// Column keys the user has hidden.
    pub hidden: HashSet<String>,
    /// Per-column width overrides, in points.
    pub widths: HashMap<String, f32>,
    /// `(column key, ascending)`. `None` = the consumer's own row order.
    pub sort: Option<(String, bool)>,
    /// How many LEADING columns are held fixed while the rest scroll
    /// horizontally. Counted over the arranged order INCLUDING hidden columns,
    /// so hiding a frozen column does not silently promote the next one into
    /// the frozen region. `0` = nothing frozen, one plain scrolling table.
    pub frozen: usize,
}

/// One cell was edited.
#[derive(Debug, Clone, PartialEq)]
pub struct CellEdit {
    pub row_id: String,
    pub column: String,
    pub value: Value,
}

/// A [`CellKind::Button`] cell was clicked.
#[derive(Debug, Clone, PartialEq)]
pub struct CellClick {
    pub row_id: String,
    pub column: String,
}

/// A row's action menu fired.
#[derive(Debug, Clone, PartialEq)]
pub struct RowActionClick {
    pub row_id: String,
    /// The [`RowAction::id`] the consumer declared.
    pub action: String,
}

/// Everything the consumer supplies. Borrowed; the widget holds no state of
/// its own beyond egui memory.
pub struct ColumnTreeSpec<'a> {
    /// Scope key for this tree's transient view state and widget ids. Must be
    /// STABLE and UNIQUE per tree — two trees sharing it share their drag
    /// state and their text buffers.
    pub id: &'a str,
    /// The columns, in spec order (the fallback order when `layout.order` does
    /// not name them).
    pub columns: &'a [ColumnSpec],
    /// An optional always-open root row above the tree (`"Assembly"`), drawn
    /// with its own cells taken from `root_cells`.
    pub root_label: Option<&'a str>,
    /// Cells for the root row, when there is one.
    pub root_cells: Option<&'a HashMap<String, Value>>,
    /// Text drawn in place of the body when `rows` is empty.
    pub empty_hint: Option<&'a str>,
    /// Prefix for every published hit key. `""` for a consumer that shows one
    /// tree at a time.
    pub hits_prefix: &'a str,
}

/// What the user did in one drawn frame.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct ColumnTreeOut {
    /// Cell edits, in draw order. A frame can carry at most one (egui gives
    /// one widget the focus), but the vec keeps the caller from having to care.
    pub edits: Vec<CellEdit>,
    /// Button cells clicked this frame.
    pub buttons: Vec<CellClick>,
    /// Row action-menu entries chosen this frame.
    pub actions: Vec<RowActionClick>,
    /// A row's `[+]`/`[-]` box was clicked — the caller flips its own
    /// expansion state (expansion is the caller's, as in `panels::tree`).
    pub toggled: Option<String>,
    /// A row's first-column label was clicked (select).
    pub clicked: Option<String>,
    /// The layout was changed by the user (reorder / resize / hide / sort) —
    /// the caller persists it.
    pub layout_changed: bool,
}

/// `#rrggbb` → a colour. Any other shape is ignored rather than guessed at, so
/// a malformed badge simply draws in the ambient text colour.
fn parse_hex_color(hex: &str) -> Option<egui::Color32> {
    let digits = hex.strip_prefix('#')?;
    if digits.len() != 6 {
        return None;
    }
    let byte = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).ok();
    Some(egui::Color32::from_rgb(byte(0)?, byte(2)?, byte(4)?))
}

/// Draw ONE complete column tree and return what the user did.
///
/// `hits`, when supplied, receives widget screen rects for the headed
/// verifier, all prefixed with [`ColumnTreeSpec::hits_prefix`]:
///
/// | key | what |
/// |---|---|
/// | `col:{key}` | a column heading |
/// | `grip:{key}` | a heading's resize divider |
/// | `row:{row id}` | the first column's label |
/// | `box:{row id}` | the first column's collapse box |
/// | `cell:{row id}:{col key}` | one cell's editor |
/// | `menu:{row id}` | the row's action-menu trigger cell |
/// | `menuitem:{row id}:{action id}` | one entry of the OPEN action menu |
/// | `freeze:divider` | the frozen / scrolling boundary (only when frozen) |
pub fn column_tree(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    layout: &mut ColumnLayout,
    rows: &[RowNode],
    mut hits: Option<&mut HashMap<String, egui::Rect>>,
) -> ColumnTreeOut {
    let mut out = ColumnTreeOut::default();
    // The arranged order INCLUDING the hidden columns: the freeze boundary is
    // counted over THIS, so hiding a frozen column cannot silently promote the
    // next one into the frozen band.
    let arranged = arranged_columns(spec, layout);
    let visible: Vec<&ColumnSpec> = arranged
        .iter()
        .copied()
        .filter(|column| !layout.hidden.contains(&column.key))
        .collect();
    if visible.is_empty() {
        ui.label(egui::RichText::new("(every column is hidden)").weak());
        return out;
    }

    // Column widths, in the drawn order.
    let widths: Vec<f32> = visible
        .iter()
        .map(|column| column_width(layout, column))
        .collect();

    // How many DRAWN columns are frozen. Freezing every column is meaningless
    // — there is nothing left to scroll it against — and would strand any
    // column past the pane's right edge with no way to reach it, so it reads
    // as "frozen: none".
    let mut frozen = arranged
        .iter()
        .take(layout.frozen)
        .filter(|column| !layout.hidden.contains(&column.key))
        .count();
    if frozen >= visible.len() {
        frozen = 0;
    }

    ui.spacing_mut().item_spacing.y = 2.0;
    let full = ui.available_rect_before_wrap();
    // The frozen band never eats the whole width — something has to be left to
    // scroll in.
    let frozen_width: f32 = widths[..frozen]
        .iter()
        .sum::<f32>()
        .min((full.width() - MIN_COLUMN_WIDTH).max(0.0));

    // Which row's action menu either trigger asked for, this frame.
    let mut pending: Option<MenuOpen> = None;
    // Heading bounds from BOTH panes, merged: a reorder drag that crosses the
    // freeze boundary must find its drop target, because dropping a column on
    // the other side of the boundary is how a column is frozen or unfrozen
    // with the mouse.
    let mut bounds: Vec<(String, f32, f32)> = Vec::new();
    let mut bottom = full.top();

    if frozen > 0 {
        let rect = egui::Rect::from_min_max(
            full.min,
            egui::pos2(full.min.x + frozen_width, full.max.y),
        );
        let mut pane = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(rect)
                .layout(egui::Layout::top_down(egui::Align::Min))
                .id_salt((spec.id, "column-tree-frozen")),
        );
        // Clip the frozen band HORIZONTALLY only: its height belongs to the
        // caller (an outer vertical scroll area owns that axis).
        pane.set_clip_rect(pane.clip_rect().intersect(egui::Rect::from_x_y_ranges(
            rect.x_range(),
            ui.clip_rect().y_range(),
        )));
        pane.spacing_mut().item_spacing.y = 2.0;
        draw_pane(
            &mut pane,
            spec,
            layout,
            &visible[..frozen],
            &widths[..frozen],
            0,
            frozen_width,
            rows,
            &mut hits,
            &mut out,
            &mut pending,
            &mut bounds,
        );
        bottom = bottom.max(pane.min_rect().bottom());
    }

    // The scrolling remainder. The widget owns this scroll area rather than the
    // caller, because a scroll area OUTSIDE the widget would carry the frozen
    // columns away with everything else.
    let scroll_left = full.min.x + if frozen > 0 { frozen_width + FREEZE_GAP } else { 0.0 };
    let scroll_rect = egui::Rect::from_min_max(egui::pos2(scroll_left, full.min.y), full.max);
    let viewport = scroll_rect.width();
    let mut pane = ui.new_child(
        egui::UiBuilder::new()
            .max_rect(scroll_rect)
            .layout(egui::Layout::top_down(egui::Align::Min))
            .id_salt((spec.id, "column-tree-scrolling")),
    );
    let rest: f32 = widths[frozen..].iter().sum();
    // (egui's default `ScrollSource` drags to scroll on TOUCH only, which is
    // what we want: a mouse drag-to-scroll would fight the header's reorder
    // drag and a text cell's selection drag.)
    egui::ScrollArea::horizontal()
        .id_salt((spec.id, "column-tree-hscroll"))
        .show(&mut pane, |ui: &mut egui::Ui| {
            ui.spacing_mut().item_spacing.y = 2.0;
            draw_pane(
                ui,
                spec,
                layout,
                &visible[frozen..],
                &widths[frozen..],
                frozen,
                rest.max(viewport),
                rows,
                &mut hits,
                &mut out,
                &mut pending,
                &mut bounds,
            );
            if rest > viewport {
                // A GUTTER for the horizontal scrollbar. egui's bars float over
                // the content, and this one lands on the LAST ROW — where it
                // silently eats every click on the bottom half of that row's
                // cells (found by the headed verifier: the action trigger opened
                // from its top edge and not from its centre).
                let scroll = ui.spacing().scroll;
                ui.add_space(scroll.bar_width + scroll.bar_inner_margin + scroll.bar_outer_margin);
            }
        });
    bottom = bottom.max(pane.min_rect().bottom());

    let used = egui::Rect::from_min_max(full.min, egui::pos2(full.max.x, bottom));
    ui.advance_cursor_after_rect(used);

    // The boundary, so the user can SEE which columns are pinned.
    if frozen > 0 {
        let x = full.min.x + frozen_width + FREEZE_GAP * 0.5;
        let divider = egui::Rect::from_min_max(
            egui::pos2(x - 1.0, used.top()),
            egui::pos2(x + 1.0, used.bottom()),
        );
        ui.painter()
            .rect_filled(divider, 0.0, ui.visuals().widgets.active.bg_fill);
        publish(&mut hits, spec, "freeze:divider", divider);
    }

    finish_reorder(ui, spec, layout, &arranged, &bounds, &mut out);
    // ONE menu, drawn from whatever record a trigger left. `pending` is applied
    // AFTER it — apply it first and the popup's own close-on-click would see
    // the very click that opened it and shut immediately.
    row_action_menu(ui, spec, rows, &mut hits, &mut out, &mut pending);
    out
}

/// Draw ONE pane — a contiguous run of columns, with the header and every row.
/// The frozen band and the scrolling remainder are the same code walking the
/// same rows in the same order, which is what keeps them aligned.
///
/// `offset` is the drawn index of `columns[0]`, so the pane holding column 0
/// (and only it) draws the TREE cell. `band` is the width every row spans here.
#[allow(clippy::too_many_arguments)]
fn draw_pane(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    layout: &mut ColumnLayout,
    columns: &[&ColumnSpec],
    widths: &[f32],
    offset: usize,
    band: f32,
    rows: &[RowNode],
    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
    out: &mut ColumnTreeOut,
    pending: &mut Option<MenuOpen>,
    bounds: &mut Vec<(String, f32, f32)>,
) {
    header(ui, spec, layout, columns, widths, band, hits, out, bounds);
    ui.separator();

    if let Some(label) = spec.root_label {
        let mut cells = spec.root_cells.cloned().unwrap_or_default();
        // The root's label belongs to whichever column is drawn FIRST — the
        // tree column follows the user's order, so it is not a fixed key.
        if offset == 0 {
            cells.insert(columns[0].key.clone(), Value::String(label.to_string()));
        }
        let root = RowNode {
            id: format!("{}__root", spec.id),
            cells,
            editable: false,
            selected: false,
            expanded: true,
            actions: Vec::new(),
            children: Vec::new(),
        };
        draw_row(
            ui, spec, columns, widths, offset, band, &root, &[], true, true, hits, out, pending,
        );
    }

    if rows.is_empty() {
        if let Some(hint) = spec.empty_hint {
            if offset == 0 {
                let guides = tree::child_guides(&[], true);
                tree::node(ui, TreeRow::leaf(&guides, true, hint), |_| {});
            } else {
                // The other pane still spends the same row, so the two panes
                // keep the same height.
                ui.allocate_exact_size(
                    egui::vec2(band, ui.spacing().interact_size.y),
                    egui::Sense::hover(),
                );
            }
        }
        return;
    }

    let ordered = sorted_siblings(rows, layout);
    let last = ordered.len();
    for (index, row) in ordered.iter().enumerate() {
        draw_subtree(
            ui,
            spec,
            layout,
            columns,
            widths,
            offset,
            band,
            row,
            &[],
            index + 1 == last,
            hits,
            out,
            pending,
        );
    }
}

/// Every spec column in the user's order — `layout.order` first (spec columns
/// only), then any spec column the layout has never heard of. Hidden columns
/// KEEP their slot here; the drawn set filters them out afterwards, and the
/// freeze boundary counts over this list.
fn arranged_columns<'a>(
    spec: &'a ColumnTreeSpec<'_>,
    layout: &ColumnLayout,
) -> Vec<&'a ColumnSpec> {
    let mut out: Vec<&ColumnSpec> = Vec::new();
    for key in &layout.order {
        if let Some(column) = spec.columns.iter().find(|c| &c.key == key) {
            if !out.iter().any(|c| c.key == column.key) {
                out.push(column);
            }
        }
    }
    for column in spec.columns {
        if !out.iter().any(|c| c.key == column.key) {
            out.push(column);
        }
    }
    out
}

fn column_width(layout: &ColumnLayout, column: &ColumnSpec) -> f32 {
    layout
        .widths
        .get(&column.key)
        .copied()
        .unwrap_or(column.default_width)
        .max(MIN_COLUMN_WIDTH)
}

/// One pane's header: a heading per column (click = sort, drag = reorder,
/// right-click = the show/hide checklist) with a resize grip at each right
/// edge. The drop of a reorder drag is resolved by [`finish_reorder`] once
/// BOTH panes have contributed their bounds.
#[allow(clippy::too_many_arguments)]
fn header(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    layout: &mut ColumnLayout,
    visible: &[&ColumnSpec],
    widths: &[f32],
    width: f32,
    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
    out: &mut ColumnTreeOut,
    bounds: &mut Vec<(String, f32, f32)>,
) {
    let height = ui.spacing().interact_size.y;
    let (band, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
    let drag_key = egui::Id::new((spec.id, "column-tree-drag"));
    let dragging: Option<String> = ui.data(|d| d.get_temp(drag_key));

    let mut x = band.left();
    // The reorder DROP target is decided from the pointer's x at drag end, so
    // the boundaries are collected while the headings are laid out.
    let first = bounds.len();
    for (column, width) in visible.iter().zip(widths) {
        let cell = egui::Rect::from_min_size(egui::pos2(x, band.top()), egui::vec2(*width, height));
        bounds.push((column.key.clone(), cell.left(), cell.right()));

        let resp = ui.interact(
            cell,
            ui.id().with(("column-tree-head", spec.id, &column.key)),
            egui::Sense::click_and_drag(),
        );
        let held = dragging.as_deref() == Some(column.key.as_str());
        let fill = if held {
            ui.visuals().selection.bg_fill.gamma_multiply(0.45)
        } else if resp.hovered() {
            ui.visuals().widgets.hovered.bg_fill
        } else {
            ui.visuals().widgets.noninteractive.bg_fill
        };
        ui.painter().rect_filled(cell, 0.0, fill);
        // The sort marker rides the heading text, so the sorted column is
        // obvious without a second row of chrome.
        let marker = match &layout.sort {
            Some((key, true)) if key == &column.key => " \u{25B2}",
            Some((key, false)) if key == &column.key => " \u{25BC}",
            _ => "",
        };
        let text = format!("{}{marker}", column.label);
        ui.painter().text(
            egui::pos2(cell.left() + CELL_PAD, cell.center().y),
            egui::Align2::LEFT_CENTER,
            elide(ui, &text, *width - 2.0 * CELL_PAD),
            egui::TextStyle::Body.resolve(ui.style()),
            ui.visuals().strong_text_color(),
        );
        publish(hits, spec, &format!("col:{}", column.key), cell);

        // Right-click ANY heading → the show/hide checklist. Hiding lives here
        // rather than on a toolbar because the column is the thing being
        // hidden and this is where the user's hand already is.
        resp.context_menu(|ui| {
            ui.label(egui::RichText::new("Columns").strong());
            for candidate in spec.columns {
                let mut shown = !layout.hidden.contains(&candidate.key);
                if ui.checkbox(&mut shown, &candidate.label).changed() {
                    if shown {
                        layout.hidden.remove(&candidate.key);
                    } else {
                        layout.hidden.insert(candidate.key.clone());
                    }
                    out.layout_changed = true;
                }
            }
        });

        // A CLICK sorts. egui reports `clicked()` false once a press turns
        // into a drag, so the click and the reorder drag share the heading
        // without a mode.
        if resp.clicked() {
            layout.sort = match &layout.sort {
                Some((key, true)) if key == &column.key => Some((column.key.clone(), false)),
                Some((key, false)) if key == &column.key => None,
                _ => Some((column.key.clone(), true)),
            };
            out.layout_changed = true;
        }
        if resp.drag_started() {
            ui.data_mut(|d| d.insert_temp(drag_key, column.key.clone()));
        }

        ui.painter().line_segment(
            [
                egui::pos2(cell.right(), band.top()),
                egui::pos2(cell.right(), band.bottom()),
            ],
            ui.visuals().widgets.noninteractive.bg_stroke,
        );
        x = cell.right();
    }

    // The resize grips, in a SECOND pass. A grip straddles the divider, so it
    // overlaps the heading to its right — and egui hands an overlapped point to
    // the LAST widget registered there. Interleaved with the headings, every
    // grip would therefore lose its own hit to the next heading and no column
    // would ever resize.
    for (column, (_, _, right)) in visible.iter().zip(&bounds[first..]) {
        let grip_rect = egui::Rect::from_min_max(
            egui::pos2(right - GRIP * 0.5, band.top()),
            egui::pos2(right + GRIP * 0.5, band.bottom()),
        );
        let grip = ui.interact(
            grip_rect,
            ui.id().with(("column-tree-grip", spec.id, &column.key)),
            egui::Sense::drag(),
        );
        if grip.hovered() || grip.dragged() {
            ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
        }
        if grip.dragged() {
            let next = (column_width(layout, column) + grip.drag_delta().x).max(MIN_COLUMN_WIDTH);
            layout.widths.insert(column.key.clone(), next);
            out.layout_changed = true;
        }
        publish(hits, spec, &format!("grip:{}", column.key), grip_rect);
    }
}

/// Finish a reorder: on release, the dragged column moves to whichever heading
/// the pointer is over — in EITHER pane, so dragging a column across the freeze
/// boundary is what freezes or unfreezes it.
fn finish_reorder(
    ui: &egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    layout: &mut ColumnLayout,
    arranged: &[&ColumnSpec],
    bounds: &[(String, f32, f32)],
    out: &mut ColumnTreeOut,
) {
    let drag_key = egui::Id::new((spec.id, "column-tree-drag"));
    let Some(held) = ui.data(|d| d.get_temp::<String>(drag_key)) else {
        return;
    };
    if ui.input(|i| i.pointer.any_down()) {
        return;
    }
    ui.data_mut(|d| d.remove::<String>(drag_key));
    let Some(pos) = ui.input(|i| i.pointer.latest_pos()) else {
        return;
    };
    if let Some((target, _, _)) = bounds
        .iter()
        .find(|(_, left, right)| pos.x >= *left && pos.x < *right)
    {
        if *target != held && move_column(layout, arranged, &held, target) {
            out.layout_changed = true;
        }
    }
}

/// Move `held` to `target`'s slot in the layout order, materializing the
/// current arranged order first so a layout that never named its columns still
/// reorders correctly. Returns whether anything moved.
fn move_column(
    layout: &mut ColumnLayout,
    arranged: &[&ColumnSpec],
    held: &str,
    target: &str,
) -> bool {
    let mut order: Vec<String> = layout.order.clone();
    // Seed from the drawn order so the first drag on a fresh layout is not a
    // no-op against an empty `order`.
    for column in arranged {
        if !order.iter().any(|key| key == &column.key) {
            order.push(column.key.clone());
        }
    }
    let Some(from) = order.iter().position(|key| key == held) else {
        return false;
    };
    let key = order.remove(from);
    let Some(to) = order.iter().position(|k| k == target) else {
        order.insert(from.min(order.len()), key);
        return false;
    };
    order.insert(to, key);
    layout.order = order;
    true
}

/// Draw one row and, when it is open, its children — the recursion that keeps
/// the rows a TREE.
#[allow(clippy::too_many_arguments)]
fn draw_subtree(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    layout: &ColumnLayout,
    visible: &[&ColumnSpec],
    widths: &[f32],
    offset: usize,
    band: f32,
    row: &RowNode,
    guides: &[bool],
    is_last: bool,
    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
    out: &mut ColumnTreeOut,
    pending: &mut Option<MenuOpen>,
) {
    draw_row(
        ui, spec, visible, widths, offset, band, row, guides, is_last, false, hits, out, pending,
    );
    if !row.expanded || row.children.is_empty() {
        return;
    }
    let child_guides = tree::child_guides(guides, is_last);
    let ordered = sorted_siblings(&row.children, layout);
    let last = ordered.len();
    for (index, child) in ordered.iter().enumerate() {
        draw_subtree(
            ui,
            spec,
            layout,
            visible,
            widths,
            offset,
            band,
            child,
            &child_guides,
            index + 1 == last,
            hits,
            out,
            pending,
        );
    }
}

/// Sort ONE level of siblings by the layout's sort column. Sorting is
/// per-level so the nesting survives it — a child never overtakes its parent.
/// A stable sort, so an unsorted-equal run keeps the consumer's order.
fn sorted_siblings<'a>(rows: &'a [RowNode], layout: &ColumnLayout) -> Vec<&'a RowNode> {
    let mut out: Vec<&RowNode> = rows.iter().collect();
    if let Some((key, ascending)) = &layout.sort {
        out.sort_by(|a, b| {
            let ordering = compare_cells(a.cells.get(key), b.cells.get(key));
            if *ascending {
                ordering
            } else {
                ordering.reverse()
            }
        });
    }
    out
}

/// Order two cell values: numbers numerically, everything else by its display
/// text case-insensitively, and an ABSENT/null cell last in ascending order
/// (an unfilled cell is not a small value, it is a missing one).
fn compare_cells(a: Option<&Value>, b: Option<&Value>) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    let empty = |value: Option<&Value>| match value {
        None | Some(Value::Null) => true,
        Some(Value::String(text)) => text.is_empty(),
        _ => false,
    };
    match (empty(a), empty(b)) {
        (true, true) => return Ordering::Equal,
        (true, false) => return Ordering::Greater,
        (false, true) => return Ordering::Less,
        (false, false) => {}
    }
    if let (Some(Value::Number(x)), Some(Value::Number(y))) = (a, b) {
        if let (Some(x), Some(y)) = (x.as_f64(), y.as_f64()) {
            return x.partial_cmp(&y).unwrap_or(Ordering::Equal);
        }
    }
    display_text(a).to_lowercase().cmp(&display_text(b).to_lowercase())
}

/// A cell value as the text a cell shows: a string bare (not JSON-quoted), a
/// number in its shortest form, anything else as its JSON.
fn display_text(value: Option<&Value>) -> String {
    match value {
        None | Some(Value::Null) => String::new(),
        Some(Value::String(text)) => text.clone(),
        Some(other) => other.to_string(),
    }
}

/// Draw ONE row: the tree cell in column 0, an editor in each other column.
#[allow(clippy::too_many_arguments)]
fn draw_row(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    visible: &[&ColumnSpec],
    widths: &[f32],
    offset: usize,
    band_width: f32,
    row: &RowNode,
    guides: &[bool],
    is_last: bool,
    root: bool,
    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
    out: &mut ColumnTreeOut,
    pending: &mut Option<MenuOpen>,
) {
    let height = ui.spacing().interact_size.y;
    let (band, _) = ui.allocate_exact_size(egui::vec2(band_width, height), egui::Sense::hover());
    let clip = ui.clip_rect();

    // TRIGGER 2 — a right-click ANYWHERE on the row. Read off the raw pointer
    // rather than from a `Response`, because the cell editors are registered
    // AFTER this band and egui hands an overlapped point to the LAST widget
    // registered there: a `context_menu` on the band would silently never fire
    // over a text cell. Reading the position also leaves the band's `hover`
    // sense alone, so no primary click / select / sort / drag path changes.
    let over_row = band.intersect(clip);
    if !row.actions.is_empty()
        && over_row.is_positive()
        && ui.input(|i| i.pointer.secondary_clicked())
    {
        if let Some(pos) = ui.ctx().input(|i| i.pointer.interact_pos()) {
            // ...and nothing floating (an open menu, the header's own column
            // checklist) is above that point.
            let above = ui.ctx().layer_id_at(pos);
            let ours = above.is_none() || above == Some(ui.layer_id());
            if over_row.contains(pos) && ours {
                *pending = Some(MenuOpen {
                    row: row.id.clone(),
                    pos,
                });
            }
        }
    }

    // The SELECTION band. A selected row is emphasised across its whole width,
    // not just by bolding the tree cell's text: this table is as wide as its
    // configured columns, and a picked component has to be findable at a
    // glance from anywhere in it. Painted BEFORE the cells so every editor
    // draws over it, and drawn in both panes (each calls this with its own
    // band) so the highlight does not stop at the frozen boundary.
    if row.selected && !root {
        let visible_band = band.intersect(clip);
        if visible_band.is_positive() {
            ui.painter().rect_filled(
                visible_band,
                0.0,
                ui.visuals().selection.bg_fill.gamma_multiply(0.35),
            );
        }
    }

    let mut x = band.left();
    for (index, (column, width)) in visible.iter().zip(widths).enumerate() {
        let cell = egui::Rect::from_min_size(egui::pos2(x, band.top()), egui::vec2(*width, height));
        x = cell.right();
        let Some(cell_clip) = cell.intersect(clip).is_positive().then_some(cell.intersect(clip))
        else {
            continue;
        };
        let mut child = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(cell.shrink2(egui::vec2(CELL_PAD, 0.0)))
                .layout(egui::Layout::left_to_right(egui::Align::Center))
                .id_salt(("column-tree-cell", spec.id, &row.id, &column.key)),
        );
        child.set_clip_rect(cell_clip);

        if offset + index == 0 {
            // The TREE cell — drawn by `panels::tree::node` itself, so the
            // connector rules and collapse boxes are the shared ones.
            let label = display_text(row.cells.get(&column.key));
            let expandable = !row.children.is_empty();
            let mut tree_row = TreeRow {
                guides,
                is_last,
                expandable,
                expanded: row.expanded,
                root,
                glyph: None,
                label: &label,
                selected: row.selected,
                draggable: false,
            };
            if root {
                tree_row.expandable = true;
                tree_row.expanded = true;
            }
            let resp = tree::node(&mut child, tree_row, |_| {});
            publish(hits, spec, &format!("row:{}", row.id), resp.label.rect);
            publish(hits, spec, &format!("box:{}", row.id), resp.box_rect);
            if resp.toggled {
                out.toggled = Some(row.id.clone());
            }
            if resp.label.clicked() {
                out.clicked = Some(row.id.clone());
            }
        } else {
            let rect = cell_editor(&mut child, spec, row, column, out, pending);
            publish(
                hits,
                spec,
                &format!("cell:{}:{}", row.id, column.key),
                rect,
            );
            if matches!(column.kind, CellKind::Actions { .. }) {
                publish(hits, spec, &format!("menu:{}", row.id), rect);
            }
        }
    }
}

/// Draw ONE non-tree cell's editor and return its rect. A non-editable row
/// still SHOWS its value and still offers its buttons and its action menu — it
/// just cannot be typed into.
fn cell_editor(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    row: &RowNode,
    column: &ColumnSpec,
    out: &mut ColumnTreeOut,
    pending: &mut Option<MenuOpen>,
) -> egui::Rect {
    let value = row.cells.get(&column.key);
    let width = ui.available_width();
    let mut emit = |new_value: Value| {
        out.edits.push(CellEdit {
            row_id: row.id.clone(),
            column: column.key.clone(),
            value: new_value,
        });
    };

    match &column.kind {
        CellKind::Button { label } => {
            let button = ui.add_sized([width, ui.available_height()], egui::Button::new(label));
            if button.clicked() {
                out.buttons.push(CellClick {
                    row_id: row.id.clone(),
                    column: column.key.clone(),
                });
            }
            button.rect
        }
        CellKind::Actions { label } => {
            // TRIGGER 1 — the actions cell. Like the right-click it only
            // RECORDS which row was asked for; the menu is drawn once, after
            // every row, from that record. A row that offers nothing draws the
            // trigger greyed rather than dropping it, so the column stays a
            // column.
            let offered = !row.actions.is_empty();
            let button = ui
                .add_enabled_ui(offered, |ui| {
                    ui.add_sized([width, ui.available_height()], egui::Button::new(label))
                })
                .inner;
            if button.clicked() {
                *pending = Some(MenuOpen {
                    row: row.id.clone(),
                    pos: button.rect.left_bottom(),
                });
            }
            button.rect
        }
        CellKind::ReadOnly => ui.add(egui::Label::new(display_text(value)).truncate()).rect,
        CellKind::Badges => {
            let badges = value.and_then(Value::as_array).cloned().unwrap_or_default();
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 3.0;
                for badge in &badges {
                    let glyph = badge.get("glyph").and_then(Value::as_str).unwrap_or("");
                    if glyph.is_empty() {
                        continue;
                    }
                    let color = badge
                        .get("color")
                        .and_then(Value::as_str)
                        .and_then(parse_hex_color)
                        .unwrap_or_else(|| ui.visuals().text_color());
                    // A badge glyph carries meaning IN its colour, so it is
                    // drawn from the icon catalog and tinted — there is no icon
                    // font to render the character with.
                    let label = match crate::icon_text::glyph(ui, glyph, color) {
                        Some(art) => ui.add(art),
                        None => ui.label(egui::RichText::new(glyph).color(color)),
                    };
                    if let Some(tip) = badge.get("tooltip").and_then(Value::as_str) {
                        label.on_hover_text(tip);
                    }
                }
            })
            .response
            .rect
        }
        CellKind::Toggle => {
            // Drawn for every row, clickable only on an editable one: the
            // weak-label fallback below would render a bool as the text
            // "false", which is not a checkbox.
            let mut on = value.and_then(Value::as_bool).unwrap_or(false);
            let box_ = ui
                .add_enabled_ui(row.editable, |ui| ui.checkbox(&mut on, ""))
                .inner;
            if box_.changed() {
                emit(Value::Bool(on));
            }
            box_.rect
        }
        _ if !row.editable => ui
            .add(
                egui::Label::new(egui::RichText::new(display_text(value)).weak())
                    .truncate(),
            )
            .rect,
        CellKind::Text => {
            // An in-progress edit lives in egui memory and commits on
            // focus-loss / Enter. Per-keystroke commits are wrong here: a
            // consumer's commit can be arbitrarily expensive (the BOM's
            // part-level one re-signs a part document and re-heals every
            // instance of it), and a half-typed value is not a value.
            let buffer_id = egui::Id::new(("column-tree-text", spec.id, &row.id, &column.key));
            let stored = display_text(value);
            let mut buffer: String =
                ui.data(|d| d.get_temp(buffer_id)).unwrap_or_else(|| stored.clone());
            let edit = ui.add_sized(
                [width, ui.available_height()],
                egui::TextEdit::singleline(&mut buffer),
            );
            let entered = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
            if edit.has_focus() || edit.changed() {
                ui.data_mut(|d| d.insert_temp(buffer_id, buffer.clone()));
            }
            if edit.lost_focus() || entered {
                ui.data_mut(|d| d.remove::<String>(buffer_id));
                if buffer != stored {
                    emit(Value::String(buffer));
                }
            } else if !edit.has_focus() {
                // Unfocused: track the model, so an edit made elsewhere (a
                // packed fan-out landing on a sibling row) shows immediately.
                ui.data_mut(|d| d.remove::<String>(buffer_id));
            }
            edit.rect
        }
        CellKind::Numeric { step } => {
            let mut number = value.and_then(Value::as_f64).unwrap_or(0.0);
            let drag = ui.add_sized(
                [width, ui.available_height()],
                egui::DragValue::new(&mut number).speed(*step),
            );
            if drag.changed() {
                emit(serde_json::json!(number));
            }
            drag.rect
        }
        CellKind::Choice { options } => {
            let current = display_text(value);
            let mut chosen = current.clone();
            let combo = egui::ComboBox::from_id_salt((
                "column-tree-combo",
                spec.id,
                &row.id,
                &column.key,
            ))
            .width(width)
            .selected_text(if current.is_empty() { "" } else { &current })
            .show_ui(ui, |ui| {
                // The blank choice is always offered: without it a dropdown
                // cell can be set but never cleared.
                ui.selectable_value(&mut chosen, String::new(), "");
                for option in options {
                    ui.selectable_value(&mut chosen, option.clone(), option);
                }
            });
            if chosen != current {
                emit(Value::String(chosen));
            }
            combo.response.rect
        }
    }
}

/// Which row's action menu is open, and the point it was opened at. Lives in
/// egui memory keyed by [`ColumnTreeSpec::id`] — one record, so there can only
/// ever be one open menu per tree.
#[derive(Clone)]
struct MenuOpen {
    row: String,
    pos: egui::Pos2,
}

/// THE action menu — one definition, drawn from whichever trigger recorded a
/// [`MenuOpen`]. Neither trigger renders anything itself, so the cell click and
/// the right-click cannot drift apart: there is only one menu to drift.
fn row_action_menu(
    ui: &mut egui::Ui,
    spec: &ColumnTreeSpec<'_>,
    rows: &[RowNode],
    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
    out: &mut ColumnTreeOut,
    pending: &mut Option<MenuOpen>,
) {
    let key = egui::Id::new((spec.id, "column-tree-menu"));
    let mut open: Option<MenuOpen> = ui.data(|d| d.get_temp(key));
    let was_open = open.as_ref().map(|state| state.row.clone());

    if let Some(state) = open.clone() {
        // A row that has gone (or lost every action) takes its menu with it.
        match find_row(rows, &state.row) {
            Some(row) if !row.actions.is_empty() => {
                let mut still_open = true;
                egui::Popup::new(
                    key.with("popup"),
                    ui.ctx().clone(),
                    egui::PopupAnchor::Position(state.pos),
                    ui.layer_id(),
                )
                .open_bool(&mut still_open)
                .kind(egui::PopupKind::Menu)
                .layout(egui::Layout::top_down_justified(egui::Align::Min))
                .width(160.0)
                .show(|ui| {
                    for action in &row.actions {
                        if action.separator_above {
                            ui.separator();
                        }
                        // The caption may lead with a catalogued glyph (🔒 Fix,
                        // ✖ Delete); it is drawn as artwork, not as a character.
                        // A destructive entry keeps its red — on the artwork as
                        // well as the text.
                        let color =
                            action.destructive.then(|| ui.visuals().error_fg_color);
                        let button =
                            crate::icon_text::icon_button_colored(ui, &action.label, color);
                        let entry = ui.add_enabled(action.enabled, button);
                        publish(
                            hits,
                            spec,
                            &format!("menuitem:{}:{}", row.id, action.id),
                            entry.rect,
                        );
                        if !action.tooltip.is_empty() {
                            // A greyed entry's tooltip is where its refusal is
                            // explained, so it has to be the DISABLED hover.
                            if action.enabled {
                                entry.clone().on_hover_text(&action.tooltip);
                            } else {
                                entry.clone().on_disabled_hover_text(&action.tooltip);
                            }
                        }
                        if entry.clicked() {
                            out.actions.push(RowActionClick {
                                row_id: row.id.clone(),
                                action: action.id.clone(),
                            });
                        }
                    }
                });
                if !still_open {
                    open = None;
                }
            }
            _ => open = None,
        }
    }

    // Applied AFTER the draw (see the call site): applying it first would let
    // the popup's own close-on-click see the very click that opened it. A
    // trigger fired on the row whose menu just closed itself is a TOGGLE — the
    // second click on the same trigger shuts it.
    if let Some(next) = pending.take() {
        let toggled_off = open.is_none() && was_open.as_deref() == Some(next.row.as_str());
        open = (!toggled_off).then_some(next);
    }
    match &open {
        Some(state) => ui.data_mut(|d| {
            d.insert_temp(key, state.clone());
        }),
        None => ui.data_mut(|d| d.remove::<MenuOpen>(key)),
    }
}

/// The row with `id`, anywhere in the tree.
fn find_row<'a>(rows: &'a [RowNode], id: &str) -> Option<&'a RowNode> {
    for row in rows {
        if row.id == id {
            return Some(row);
        }
        if let Some(found) = find_row(&row.children, id) {
            return Some(found);
        }
    }
    None
}

/// Truncate `text` with an ellipsis so it fits `width`.
fn elide(ui: &egui::Ui, text: &str, width: f32) -> String {
    let font = egui::TextStyle::Body.resolve(ui.style());
    let measure = |candidate: &str| {
        ui.painter()
            .layout_no_wrap(candidate.to_string(), font.clone(), egui::Color32::WHITE)
            .rect
            .width()
    };
    if width <= 0.0 || measure(text) <= width {
        return text.to_string();
    }
    let mut cut: Vec<char> = text.chars().collect();
    while !cut.is_empty() {
        cut.pop();
        let candidate: String = cut.iter().collect::<String>() + "\u{2026}";
        if measure(&candidate) <= width {
            return candidate;
        }
    }
    String::new()
}

fn publish(
    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
    spec: &ColumnTreeSpec<'_>,
    key: &str,
    rect: egui::Rect,
) {
    if let Some(map) = hits.as_deref_mut() {
        map.insert(format!("{}{key}", spec.hits_prefix), rect);
    }
}

#[cfg(test)]
mod tests {
    //! The widget is driven through REAL egui frames (the shared `run_ui`
    //! idiom), and every assertion is about behaviour a SECOND consumer would
    //! depend on — never about the BOM.
    use super::*;

    fn columns() -> Vec<ColumnSpec> {
        vec![
            ColumnSpec::new("name", "Name", CellKind::Text).width(120.0),
            ColumnSpec::new("qty", "Qty", CellKind::ReadOnly).width(40.0),
            ColumnSpec::new("note", "Note", CellKind::Text),
            ColumnSpec::new(
                "grade",
                "Grade",
                CellKind::Choice {
                    options: vec!["A".into(), "B".into()],
                },
            ),
            ColumnSpec::new("del", "", CellKind::Button { label: "x".into() }).width(30.0),
            ColumnSpec::new("on", "", CellKind::Toggle).width(26.0),
            ColumnSpec::new("flags", "", CellKind::Badges).width(52.0),
            ColumnSpec::new(
                "act",
                "",
                CellKind::Actions {
                    label: "\u{22EF}".into(),
                },
            )
            .width(30.0),
        ]
    }

    /// A consumer's action declaration — three entries, one of them refused on
    /// this row, one destructive behind a separator.
    fn actions(open_allowed: bool) -> Vec<RowAction> {
        vec![
            RowAction::new("open", "Open").tooltip("Open it"),
            RowAction::new("rename", "Rename").tooltip("Rename it"),
            RowAction::new("drop", "Drop")
                .separator_above()
                .destructive(),
        ]
        .into_iter()
        .map(|action| {
            if action.id == "open" && !open_allowed {
                action.disabled("This one has nothing to open")
            } else {
                action
            }
        })
        .collect()
    }

    /// A wire-harness-shaped tree (the named second consumer): two connectors,
    /// one with two nested pins.
    fn rows() -> Vec<RowNode> {
        vec![
            RowNode::new("J1")
                .cell("name", Value::String("J1".into()))
                .cell("qty", serde_json::json!(2))
                .cell("note", Value::String("main".into()))
                .cell("on", Value::Bool(true))
                .cell(
                    "flags",
                    serde_json::json!([
                        { "glyph": "A", "color": "#ff9f0a", "tooltip": "amber" },
                        { "glyph": "B" }
                    ]),
                )
                .actions(actions(true)),
            {
                let mut parent = RowNode::new("J2")
                    .cell("name", Value::String("J2".into()))
                    .cell("qty", serde_json::json!(1))
                    .actions(actions(false));
                parent.expanded = true;
                parent.children = vec![
                    // A pin declares NOTHING — the row offers no menu at all.
                    RowNode::new("J2-P2").cell("name", Value::String("pin2".into())),
                    RowNode::new("J2-P1").cell("name", Value::String("pin1".into())),
                ];
                parent
            },
        ]
    }

    fn spec<'a>(columns: &'a [ColumnSpec]) -> ColumnTreeSpec<'a> {
        ColumnTreeSpec {
            id: "test-tree",
            columns,
            root_label: None,
            root_cells: None,
            empty_hint: Some("(nothing)"),
            hits_prefix: "",
        }
    }

    /// Draw one frame and return `(out, hits)`.
    fn frame(
        ctx: &egui::Context,
        layout: &mut ColumnLayout,
        rows: &[RowNode],
        events: Vec<egui::Event>,
    ) -> (ColumnTreeOut, HashMap<String, egui::Rect>) {
        let cols = columns();
        let spec = spec(&cols);
        let mut hits = HashMap::new();
        let mut out = ColumnTreeOut::default();
        let raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(700.0, 500.0),
            )),
            events,
            ..Default::default()
        };
        let _ = ctx.run_ui(raw, |ui| {
            out = column_tree(ui, &spec, layout, rows, Some(&mut hits));
        });
        (out, hits)
    }

    /// Press and release at `pos` across two frames (egui fires `clicked()` on
    /// release).
    fn click_at(
        ctx: &egui::Context,
        layout: &mut ColumnLayout,
        rows: &[RowNode],
        pos: egui::Pos2,
        button: egui::PointerButton,
    ) -> ColumnTreeOut {
        frame(
            ctx,
            layout,
            rows,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        frame(
            ctx,
            layout,
            rows,
            vec![egui::Event::PointerButton {
                pos,
                button,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        )
        .0
    }

    /// Press and release the SECONDARY button at `pos`.
    fn right_click_at(
        ctx: &egui::Context,
        layout: &mut ColumnLayout,
        rows: &[RowNode],
        pos: egui::Pos2,
    ) -> ColumnTreeOut {
        click_at(ctx, layout, rows, pos, egui::PointerButton::Secondary)
    }

    /// Draw two idle frames. An egui popup's FIRST frame is a SIZING pass whose
    /// widgets are not interactable yet; it asks for a repaint, which a real app
    /// serves immediately and a test has to draw by hand.
    fn settle(ctx: &egui::Context, layout: &mut ColumnLayout, rows: &[RowNode])
        -> HashMap<String, egui::Rect>
    {
        frame(ctx, layout, rows, vec![]);
        frame(ctx, layout, rows, vec![]).1
    }

    /// The `menuitem:` keys published for `row`, sorted.
    fn menu_entries(hits: &HashMap<String, egui::Rect>, row: &str) -> Vec<String> {
        let prefix = format!("menuitem:{row}:");
        let mut keys: Vec<String> = hits
            .keys()
            .filter_map(|key| key.strip_prefix(&prefix).map(str::to_string))
            .collect();
        keys.sort();
        keys
    }

    /// Every column heads a column, every row draws a cell per column, and the
    /// nesting is preserved — the widget's basic contract.
    #[test]
    fn every_column_and_every_row_cell_is_drawn() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        for key in ["name", "qty", "note", "grade", "del", "act"] {
            assert!(hits.contains_key(&format!("col:{key}")), "heading {key}");
        }
        for row in ["J1", "J2", "J2-P1", "J2-P2"] {
            assert!(hits.contains_key(&format!("row:{row}")), "tree cell {row}");
            assert!(
                hits.contains_key(&format!("cell:{row}:note")),
                "editor cell {row}"
            );
        }
        // The tree cell is column 0, so the nested rows are INDENTED past
        // their parent — the connector geometry came from `panels::tree`.
        assert!(
            hits["row:J2-P1"].left() > hits["row:J2"].left(),
            "a child indents"
        );
    }

    /// Clicking a heading sorts ascending, then descending, then off — and the
    /// sort applies WITHIN each level, so a child never overtakes its parent.
    #[test]
    fn heading_click_cycles_sort_and_sorts_within_each_level() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        let head = hits["col:name"].center();

        let out = click_at(&ctx, &mut layout, &rows(), head, egui::PointerButton::Primary);
        assert!(out.layout_changed, "a sort click is a layout change");
        assert_eq!(layout.sort, Some(("name".into(), true)));
        // Ascending: pin1 now precedes pin2 (the caller handed them reversed),
        // and both are still UNDER J2.
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(hits["row:J2-P1"].top() < hits["row:J2-P2"].top(), "sorted");
        assert!(hits["row:J2"].top() < hits["row:J2-P1"].top(), "still nested");

        click_at(&ctx, &mut layout, &rows(), head, egui::PointerButton::Primary);
        assert_eq!(layout.sort, Some(("name".into(), false)), "then descending");
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(hits["row:J2-P2"].top() < hits["row:J2-P1"].top(), "reversed");

        click_at(&ctx, &mut layout, &rows(), head, egui::PointerButton::Primary);
        assert_eq!(layout.sort, None, "a third click clears the sort");
    }

    /// An empty cell sorts LAST ascending — an unfilled cell is a missing
    /// value, not a small one — and numbers compare numerically, not as text.
    #[test]
    fn empty_cells_sort_last_and_numbers_compare_numerically() {
        use std::cmp::Ordering;
        let ten = serde_json::json!(10);
        let nine = serde_json::json!(9);
        assert_eq!(compare_cells(Some(&ten), Some(&nine)), Ordering::Greater);
        // ...whereas as text "10" < "9".
        let ten_text = Value::String("10".into());
        let nine_text = Value::String("9".into());
        assert_eq!(
            compare_cells(Some(&ten_text), Some(&nine_text)),
            Ordering::Less
        );
        let filled = Value::String("a".into());
        assert_eq!(compare_cells(None, Some(&filled)), Ordering::Greater);
        assert_eq!(compare_cells(Some(&Value::Null), Some(&filled)), Ordering::Greater);
        assert_eq!(compare_cells(None, None), Ordering::Equal);
    }

    /// Dragging a divider resizes its column and reports the layout change.
    #[test]
    fn dragging_a_divider_resizes_the_column() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        let grip = hits["grip:name"].center();
        frame(
            &ctx,
            &mut layout,
            &rows(),
            vec![
                egui::Event::PointerMoved(grip),
                egui::Event::PointerButton {
                    pos: grip,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        let mut out = ColumnTreeOut::default();
        for step in 1..=4 {
            out = frame(
                &ctx,
                &mut layout,
                &rows(),
                vec![egui::Event::PointerMoved(egui::pos2(
                    grip.x + 10.0 * step as f32,
                    grip.y,
                ))],
            )
            .0;
        }
        assert!(out.layout_changed, "a resize is a layout change");
        assert!(
            layout.widths["name"] > 120.0,
            "widened past its default: {:?}",
            layout.widths
        );
        // It can never be dragged away to nothing.
        layout.widths.insert("name".into(), 1.0);
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(hits["col:name"].width() >= MIN_COLUMN_WIDTH);
    }

    /// A hidden column heads nothing and draws no cell; the rest close up.
    #[test]
    fn a_hidden_column_disappears_and_the_rest_close_up() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, before) = frame(&ctx, &mut layout, &rows(), vec![]);
        let note_left = before["col:note"].left();
        layout.hidden.insert("qty".into());
        let (_, after) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(!after.contains_key("col:qty"), "no heading");
        assert!(!after.contains_key("cell:J1:qty"), "no cell");
        assert!(
            after["col:note"].left() < note_left,
            "the columns to its right close up"
        );
    }

    /// The layout's `order` drives the drawn order, and a column the layout
    /// never names still appears (in spec order) rather than vanishing — so a
    /// consumer may hand in a partial layout.
    #[test]
    fn layout_order_reorders_and_unnamed_columns_still_appear() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout {
            order: vec!["note".into(), "name".into()],
            ..Default::default()
        };
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(hits["col:note"].left() < hits["col:name"].left(), "reordered");
        for key in ["qty", "grade", "del"] {
            assert!(
                hits.contains_key(&format!("col:{key}")),
                "unnamed column {key} still drawn"
            );
        }
        // Column 0 is whatever comes FIRST — the tree follows the order, it is
        // not pinned to one column key.
        assert!(hits.contains_key("row:J1"), "the tree cell moved with it");
    }

    /// `move_column` is the reorder that a header drag commits: it seeds from
    /// the DRAWN order, so the first drag on a fresh layout is not a no-op.
    #[test]
    fn move_column_seeds_from_the_drawn_order() {
        let cols = columns();
        let visible: Vec<&ColumnSpec> = cols.iter().collect();
        let mut layout = ColumnLayout::default();
        assert!(move_column(&mut layout, &visible, "grade", "name"));
        assert_eq!(
            layout.order,
            vec!["grade", "name", "qty", "note", "del", "on", "flags", "act"],
            "the held column takes the target's slot"
        );
    }

    /// A button cell reports its click by (row, column) and never edits —
    /// the widget reports, the consumer acts.
    #[test]
    fn a_button_cell_reports_the_click_and_edits_nothing() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        let out = click_at(
            &ctx,
            &mut layout,
            &rows(),
            hits["cell:J1:del"].center(),
            egui::PointerButton::Primary,
        );
        assert_eq!(
            out.buttons,
            vec![CellClick {
                row_id: "J1".into(),
                column: "del".into()
            }]
        );
        assert!(out.edits.is_empty(), "a button never writes a cell");
    }

    /// A TOGGLE cell reports a boolean edit, and reports the value it moved
    /// TO — not the one it came from.
    #[test]
    fn a_toggle_cell_reports_the_flipped_boolean() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        let out = click_at(
            &ctx,
            &mut layout,
            &rows(),
            hits["cell:J1:on"].center(),
            egui::PointerButton::Primary,
        );
        assert_eq!(
            out.edits,
            vec![CellEdit {
                row_id: "J1".into(),
                column: "on".into(),
                value: Value::Bool(false),
            }],
            "the cell was true, so the click writes false"
        );
    }

    /// A row that is not editable draws its toggle but cannot flip it — a
    /// derived grouping row has no state of its own to write.
    #[test]
    fn a_toggle_on_a_read_only_row_draws_but_does_not_write() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let mut rows = rows();
        rows[0].editable = false;
        let (_, hits) = frame(&ctx, &mut layout, &rows, vec![]);
        let cell = *hits.get("cell:J1:on").expect("the box is still DRAWN");
        let out = click_at(&ctx, &mut layout, &rows, cell.center(), egui::PointerButton::Primary);
        assert!(out.edits.is_empty(), "but it does not write");
    }

    /// A BADGES cell renders its glyphs and writes nothing. Ill-formed colours
    /// are ignored rather than guessed at, so a bad badge still draws.
    #[test]
    fn a_badges_cell_draws_glyphs_and_never_edits() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        let cell = *hits.get("cell:J1:flags").expect("a badges rect");
        let out = click_at(&ctx, &mut layout, &rows(), cell.center(), egui::PointerButton::Primary);
        assert!(out.edits.is_empty(), "badges are read-only");
        assert!(out.buttons.is_empty());
        assert_eq!(parse_hex_color("#ff9f0a"), Some(egui::Color32::from_rgb(0xff, 0x9f, 0x0a)));
        assert_eq!(parse_hex_color("nonsense"), None, "ignored, not guessed");
        assert_eq!(parse_hex_color("#fff"), None, "a short form is not a colour");
    }

    /// A collapse-box click reports a TOGGLE and nothing else — expansion is
    /// the caller's state, exactly as in `panels::tree`.
    #[test]
    fn a_collapse_box_click_reports_a_toggle_not_a_state_change() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let mut data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        let out = click_at(
            &ctx,
            &mut layout,
            &data,
            hits["box:J2"].center(),
            egui::PointerButton::Primary,
        );
        assert_eq!(out.toggled.as_deref(), Some("J2"));
        assert!(data[1].expanded, "the widget did not touch the caller's state");
        // The caller flips it, and the children go.
        data[1].expanded = false;
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        assert!(!hits.contains_key("row:J2-P1"), "collapsed children are gone");
    }

    /// A text cell commits on focus-LOSS, not per keystroke: typing produces
    /// no edit until the focus leaves. The BOM's part-level commit re-signs a
    /// part document, so a per-keystroke commit would rebuild per character.
    #[test]
    fn a_text_cell_commits_on_focus_loss_not_per_keystroke() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        let cell = hits["cell:J1:note"].center();
        click_at(&ctx, &mut layout, &data, cell, egui::PointerButton::Primary);

        let out = frame(
            &ctx,
            &mut layout,
            &data,
            vec![egui::Event::Text("XY".into())],
        )
        .0;
        assert!(out.edits.is_empty(), "typing alone commits nothing");

        // Enter commits, once, with the whole value.
        let out = frame(
            &ctx,
            &mut layout,
            &data,
            vec![
                egui::Event::Key {
                    key: egui::Key::Enter,
                    physical_key: None,
                    pressed: true,
                    repeat: false,
                    modifiers: egui::Modifiers::default(),
                },
                egui::Event::Key {
                    key: egui::Key::Enter,
                    physical_key: None,
                    pressed: false,
                    repeat: false,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        )
        .0;
        assert_eq!(
            out.edits,
            vec![CellEdit {
                row_id: "J1".into(),
                column: "note".into(),
                value: Value::String("mainXY".into()),
            }],
            "one commit carrying the finished text"
        );
    }

    /// A non-editable row still SHOWS its values and still offers its buttons
    /// — it just cannot be typed into. (The BOM's nested sub-assembly rows,
    /// whose data belongs to another document.)
    #[test]
    fn a_read_only_row_shows_values_but_takes_no_edit() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let mut data = rows();
        data[0].editable = false;
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        assert!(hits.contains_key("cell:J1:note"), "the cell is still drawn");
        let cell = hits["cell:J1:note"].center();
        click_at(&ctx, &mut layout, &data, cell, egui::PointerButton::Primary);
        let out = frame(&ctx, &mut layout, &data, vec![egui::Event::Text("Z".into())]).0;
        assert!(out.edits.is_empty(), "a read-only row takes no text");
        // ...but its button still works.
        let out = click_at(
            &ctx,
            &mut layout,
            &data,
            hits["cell:J1:del"].center(),
            egui::PointerButton::Primary,
        );
        assert_eq!(out.buttons.len(), 1, "buttons stay live on a read-only row");
    }

    /// An empty tree draws the consumer's hint rather than a bare header.
    #[test]
    fn an_empty_tree_draws_the_hint() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let (out, hits) = frame(&ctx, &mut layout, &[], vec![]);
        assert!(hits.contains_key("col:name"), "the header still stands");
        assert!(out.edits.is_empty());
    }

    /// Hiding EVERY column is survivable — it says so rather than drawing an
    /// unusable empty band.
    #[test]
    fn hiding_every_column_says_so() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        for column in columns() {
            layout.hidden.insert(column.key);
        }
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(hits.is_empty(), "nothing to publish, and no panic");
    }

    // ---------------------------------------------------------------- actions

    /// THE discriminating test for trigger 2: the right-click lands on a TEXT
    /// CELL, which is a live `TextEdit` registered after the row band. A
    /// `context_menu` hung off the band would lose that click to the text edit
    /// and never open — this asserts the menu opens anyway. It also asserts the
    /// right-click did not select the row or touch the sort.
    #[test]
    fn a_right_click_on_a_text_cell_opens_the_row_menu() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        let cell = hits["cell:J1:note"].center();

        let out = right_click_at(&ctx, &mut layout, &data, cell);
        assert!(out.clicked.is_none(), "a right-click never selects");
        assert_eq!(layout.sort, None, "and never sorts");
        assert!(!out.layout_changed);

        let hits = settle(&ctx, &mut layout, &data);
        assert_eq!(
            menu_entries(&hits, "J1"),
            vec!["drop", "open", "rename"],
            "the row's declared entries, from a right-click over a text cell"
        );
    }

    /// Both triggers render the SAME menu, because there is only one menu: the
    /// cell click and the right-click do nothing but record which row.
    #[test]
    fn both_triggers_open_one_and_the_same_menu() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);

        click_at(
            &ctx,
            &mut layout,
            &data,
            hits["menu:J1"].center(),
            egui::PointerButton::Primary,
        );
        let from_cell = settle(&ctx, &mut layout, &data);
        let by_cell = menu_entries(&from_cell, "J1");
        assert_eq!(by_cell, vec!["drop", "open", "rename"]);

        // Close it, then open the same row's menu by right-clicking its tree cell.
        click_at(
            &ctx,
            &mut layout,
            &data,
            hits["menu:J1"].center(),
            egui::PointerButton::Primary,
        );
        let closed = settle(&ctx, &mut layout, &data);
        assert!(
            menu_entries(&closed, "J1").is_empty(),
            "a second click on the trigger shuts it"
        );

        right_click_at(&ctx, &mut layout, &data, hits["row:J1"].center());
        let from_row = settle(&ctx, &mut layout, &data);
        assert_eq!(menu_entries(&from_row, "J1"), by_cell, "the same menu");
    }

    /// Choosing an entry reports `(row, action id)` and closes the menu; a
    /// DISABLED entry reports nothing at all but is still drawn (greyed, with
    /// its reason) rather than hidden.
    #[test]
    fn an_entry_reports_its_row_and_a_disabled_one_reports_nothing() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);

        // J2 refuses "open" — but still lists it.
        click_at(
            &ctx,
            &mut layout,
            &data,
            hits["menu:J2"].center(),
            egui::PointerButton::Primary,
        );
        let open = settle(&ctx, &mut layout, &data);
        assert_eq!(
            menu_entries(&open, "J2"),
            vec!["drop", "open", "rename"],
            "a refused entry is GREYED, not hidden"
        );
        let out = click_at(
            &ctx,
            &mut layout,
            &data,
            open["menuitem:J2:open"].center(),
            egui::PointerButton::Primary,
        );
        assert!(out.actions.is_empty(), "a disabled entry fires nothing");

        // ...and an allowed one fires, once, naming its row. (The click on the
        // greyed entry closed the menu, as a click anywhere in a menu does, so
        // open it again.)
        click_at(
            &ctx,
            &mut layout,
            &data,
            hits["menu:J2"].center(),
            egui::PointerButton::Primary,
        );
        let open = settle(&ctx, &mut layout, &data);
        let out = click_at(
            &ctx,
            &mut layout,
            &data,
            open["menuitem:J2:rename"].center(),
            egui::PointerButton::Primary,
        );
        assert_eq!(
            out.actions,
            vec![RowActionClick {
                row_id: "J2".into(),
                action: "rename".into()
            }]
        );
        assert!(out.edits.is_empty(), "a menu never writes a cell");
        let after = settle(&ctx, &mut layout, &data);
        assert!(
            menu_entries(&after, "J2").is_empty(),
            "choosing an entry closes the menu"
        );
    }

    /// A row that declares no action offers no menu from either trigger — and
    /// its trigger cell is still drawn, so the column stays a column.
    #[test]
    fn a_row_that_declares_nothing_opens_nothing() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        let data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        assert!(hits.contains_key("menu:J2-P1"), "the trigger cell is drawn");

        click_at(
            &ctx,
            &mut layout,
            &data,
            hits["menu:J2-P1"].center(),
            egui::PointerButton::Primary,
        );
        right_click_at(&ctx, &mut layout, &data, hits["cell:J2-P1:note"].center());
        let after = settle(&ctx, &mut layout, &data);
        assert!(
            after.keys().all(|key| !key.starts_with("menuitem:")),
            "no menu from either trigger: {:?}",
            after.keys().collect::<Vec<_>>()
        );
    }

    // ---------------------------------------------------------------- freezing

    /// A layout with `frozen` columns pins them: scrolling the remainder moves
    /// the scrolling headings and leaves the frozen ones exactly where they
    /// were. Without the split (one scroll area over everything) the frozen
    /// heading would travel with the rest.
    #[test]
    fn frozen_columns_hold_still_while_the_rest_scroll() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout {
            frozen: 2,
            ..Default::default()
        };
        // Wide enough that the remainder MUST scroll inside a 700pt frame.
        layout.widths.insert("note".into(), 400.0);
        layout.widths.insert("grade".into(), 400.0);
        let data = rows();
        let (_, before) = frame(&ctx, &mut layout, &data, vec![]);
        assert!(before.contains_key("freeze:divider"), "the boundary is drawn");
        let divider = before["freeze:divider"];
        assert!(before["col:qty"].right() <= divider.left() + 1.0, "qty is pinned");
        assert!(before["col:note"].left() >= divider.left(), "note scrolls");

        // Wheel over the scrolling side.
        let over = before["col:note"].center();
        for _ in 0..8 {
            frame(
                &ctx,
                &mut layout,
                &data,
                vec![
                    egui::Event::PointerMoved(over),
                    egui::Event::MouseWheel {
                        unit: egui::MouseWheelUnit::Point,
                        delta: egui::vec2(-60.0, 0.0),
                        phase: egui::TouchPhase::Move,
                        modifiers: egui::Modifiers::default(),
                    },
                ],
            );
        }
        let (_, after) = frame(&ctx, &mut layout, &data, vec![]);
        assert_eq!(
            after["col:name"], before["col:name"],
            "a frozen heading does not move"
        );
        assert_eq!(after["col:qty"], before["col:qty"], "nor the second one");
        assert_eq!(after["row:J1"], before["row:J1"], "nor the frozen tree cell");
        assert!(
            after["col:note"].left() < before["col:note"].left() - 20.0,
            "and the scrolling side did scroll: {:?} -> {:?}",
            before["col:note"],
            after["col:note"]
        );
    }

    /// Freezing EVERY column reads as freezing none: there would be nothing to
    /// scroll it against, and a column past the right edge would be stranded
    /// with no way to reach it.
    #[test]
    fn freezing_every_column_reads_as_none() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout {
            frozen: 99,
            ..Default::default()
        };
        let (_, hits) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(!hits.contains_key("freeze:divider"), "no boundary is drawn");
        assert!(hits.contains_key("col:act"), "and the last column is still there");
    }

    /// The boundary counts over the arranged order INCLUDING hidden columns, so
    /// hiding a frozen column does not silently pull the next one in.
    #[test]
    fn hiding_a_frozen_column_does_not_promote_the_next_one() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout {
            frozen: 2,
            ..Default::default()
        };
        layout.widths.insert("note".into(), 400.0);
        layout.widths.insert("grade".into(), 400.0);
        let (_, before) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(before["col:note"].left() >= before["freeze:divider"].left());

        layout.hidden.insert("qty".into());
        let (_, after) = frame(&ctx, &mut layout, &rows(), vec![]);
        assert!(
            after["col:note"].left() >= after["freeze:divider"].left(),
            "note stayed on the scrolling side rather than being promoted"
        );
        assert!(
            after["col:name"].right() <= after["freeze:divider"].left() + 1.0,
            "and the surviving frozen column is still frozen"
        );
    }

    /// The horizontal scrollbar FLOATS over the content, and it lands on the
    /// last row — where it silently eats the clicks on the bottom half of that
    /// row's cells. The widget reserves a gutter for it; without one, the last
    /// row's action menu opens from the top edge of its trigger and not from
    /// the middle, which is where anyone actually clicks.
    #[test]
    fn the_horizontal_scrollbar_does_not_eat_the_last_rows_clicks() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout::default();
        // Wide enough that the remainder MUST scroll, so the bar is drawn.
        layout.widths.insert("note".into(), 300.0);
        layout.widths.insert("grade".into(), 300.0);
        let mut data = rows();
        data[1].expanded = false; // ...so the LAST drawn row is one with actions

        // Wheel the trailing action column into view.
        let mut hits = frame(&ctx, &mut layout, &data, vec![]).1;
        for _ in 0..12 {
            hits = frame(
                &ctx,
                &mut layout,
                &data,
                vec![
                    egui::Event::PointerMoved(egui::pos2(350.0, 40.0)),
                    egui::Event::MouseWheel {
                        unit: egui::MouseWheelUnit::Point,
                        delta: egui::vec2(-60.0, 0.0),
                        phase: egui::TouchPhase::Move,
                        modifiers: egui::Modifiers::default(),
                    },
                ],
            )
            .1;
        }
        let trigger = *hits
            .get("menu:J2")
            .expect("the trailing action column scrolled into view");

        click_at(
            &ctx,
            &mut layout,
            &data,
            trigger.center(),
            egui::PointerButton::Primary,
        );
        let hits = settle(&ctx, &mut layout, &data);
        assert!(
            !menu_entries(&hits, "J2").is_empty(),
            "the CENTRE of the last row's trigger opened nothing: {trigger:?}"
        );
    }

    /// The widget is drawn inside a VERTICAL scroll area in the real shell
    /// (`dock.rs`), where the available height is INFINITE. Everything still
    /// lays out, publishes finite rects and opens its menu — the "it works in a
    /// unit test and vanishes in the app" gap.
    #[test]
    fn it_survives_being_nested_in_a_vertical_scroll_area() {
        let ctx = egui::Context::default();
        let cols = columns();
        let spec = spec(&cols);
        let data = rows();
        // Frozen, but narrow enough that every column is on screen — this is
        // about the INFINITE height the scroll area hands down, not scrolling.
        let mut layout = ColumnLayout {
            frozen: 2,
            ..Default::default()
        };

        let mut draw = |events: Vec<egui::Event>| {
            let mut hits = HashMap::new();
            let raw = egui::RawInput {
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::pos2(0.0, 0.0),
                    egui::vec2(700.0, 500.0),
                )),
                events,
                ..Default::default()
            };
            let _ = ctx.run_ui(raw, |ui| {
                egui::ScrollArea::vertical()
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        column_tree(ui, &spec, &mut layout, &data, Some(&mut hits));
                    });
            });
            hits
        };

        let hits = draw(vec![]);
        for (key, rect) in &hits {
            // Finite everywhere: the enclosing scroll area hands the widget an
            // INFINITE available height, and an infinity that reaches a rect is
            // a pane that draws nothing.
            assert!(rect.is_finite(), "{key} has an infinite rect {rect:?}");
            // ...and the things a verifier must be able to CLICK have an area.
            // (An empty read-only cell's label is legitimately zero-wide.)
            if key.starts_with("row:")
                || key.starts_with("col:")
                || key.starts_with("menu")
                || key.starts_with("freeze:")
            {
                assert!(rect.is_positive(), "{key} is unclickable: {rect:?}");
            }
        }
        assert!(hits.contains_key("freeze:divider"), "still frozen in there");
        assert!(hits["row:J1"].top() < 500.0, "and drawn on screen");

        // ...and the menu still opens, from inside the scroll area.
        let trigger = hits["menu:J1"].center();
        draw(vec![
            egui::Event::PointerMoved(trigger),
            egui::Event::PointerButton {
                pos: trigger,
                button: egui::PointerButton::Primary,
                pressed: true,
                modifiers: egui::Modifiers::default(),
            },
        ]);
        draw(vec![egui::Event::PointerButton {
            pos: trigger,
            button: egui::PointerButton::Primary,
            pressed: false,
            modifiers: egui::Modifiers::default(),
        }]);
        draw(vec![]);
        let hits = draw(vec![]);
        assert_eq!(menu_entries(&hits, "J1"), vec!["drop", "open", "rename"]);
    }

    /// A heading dragged ACROSS the boundary changes what is frozen — the
    /// bounds of BOTH panes are merged before the drop is resolved, so the drag
    /// does not fall off the edge of the pane it started in.
    #[test]
    fn a_heading_drags_across_the_freeze_boundary() {
        let ctx = egui::Context::default();
        let mut layout = ColumnLayout {
            order: vec![
                "name".into(),
                "qty".into(),
                "note".into(),
                "grade".into(),
                "del".into(),
                "act".into(),
            ],
            frozen: 2,
            ..Default::default()
        };
        let data = rows();
        let (_, hits) = frame(&ctx, &mut layout, &data, vec![]);
        let from = hits["col:note"].center();
        let onto = hits["col:name"].center();

        frame(
            &ctx,
            &mut layout,
            &data,
            vec![
                egui::Event::PointerMoved(from),
                egui::Event::PointerButton {
                    pos: from,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        for step in 1..=4 {
            let at = egui::pos2(from.x + (onto.x - from.x) * step as f32 / 4.0, from.y);
            frame(&ctx, &mut layout, &data, vec![egui::Event::PointerMoved(at)]);
        }
        let out = frame(
            &ctx,
            &mut layout,
            &data,
            vec![egui::Event::PointerButton {
                pos: onto,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        )
        .0;
        assert!(out.layout_changed, "the drop is a layout change");
        assert_eq!(
            layout.order.first().map(String::as_str),
            Some("note"),
            "the scrolling column took the frozen one's slot: {:?}",
            layout.order
        );
    }
}