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
//! The assembly BOM panel — the parts list on the shared
//! [`crate::column_tree`] widget.
//!
//! This module is the BOM-shaped half: it turns the engine's component
//! projection into the widget's generic rows, and turns the widget's generic
//! edits back into the two attribute stores. The widget itself knows none of
//! this, which is what lets a second consumer (the wire-harness connection
//! list) reuse it untouched.
//!
//! # Packed and unpacked
//!
//! Two views of the same occurrences.
//!
//! * **Unpacked** — one row per placement. `Quantity` reads 1.
//! * **Packed** — one row per DISTINCT part **whose occurrence data matches**.
//!   Two occurrences roll up only when they agree on EVERY occurrence field;
//!   one differing Reference Designator and they stay two rows. `Quantity` is
//!   the size of the group, read-only in both views because it is derived and
//!   so can never disagree with the model.
//!
//! Editing a packed row applies to every occurrence it rolls up, and that
//! fan-out is ONE undo step, not N — `EngineState::set_occurrence_attribute`
//! takes the whole group and checkpoints once. A part-level edit is inherently
//! the same shape (the value lives on the part, so every occurrence of it sees
//! the change) and is one undo step for the same reason.
//!
//! # Nested sub-assembly rows are READ-ONLY
//!
//! A rigid sub-assembly's internal components appear as child rows, so the BOM
//! reads as the tree it is — but their part and occurrence data lives in the
//! SUB-ASSEMBLY's own document, not this one. That is the rigid-nesting model
//! (the same reason `EngineState::export_bom_csv` reports a sub-assembly as one
//! row at this level), not a limit of the widget: editing them means opening
//! that document. They are drawn weak and take no edit.
//!
//! # The row ACTION MENU
//!
//! The rightmost column's `⋯` opens a menu — and so does a right-click
//! anywhere on the row; both are the widget's ONE menu, declared here as
//! [`RowAction`]s. Its entries are the SHARED component actions
//! ([`crate::panels::component_actions`], the same dispatcher the assembly
//! structure tree's row buttons route through) plus this panel's own
//! "Edit feature" — the `✎` button the menu replaced.
//!
//! Availability is decided PER ROW here, because only this panel knows what
//! refuses what: a fixed component will not Move, an embedded-only part has no
//! source document to Open, and a PACKED row standing for several placements
//! refuses the per-instance actions rather than guessing which placement was
//! meant (and Delete across a group would be N undo steps, not the one this
//! panel promises). Refused entries are greyed with the reason, never hidden.
//!
//! # The write lanes
//!
//! * occurrence field → `set_occurrence_attribute(ids, key, value)`.
//! * part field → `set_part_attribute(part, key, value)`, then the shared
//!   write-through lane ([`crate::panels::parts_library::write_through`]) so
//!   the part's file and the entry's signature keep agreeing. There is no
//!   second write path.

use crate::column_tree::{self, CellEdit, ColumnLayout, ColumnTreeSpec, RowAction, RowNode};
use crate::panels::parts_library;
use crate::panels::component_actions::{
    run_component_action, ComponentAction, ComponentActionRequest,
};
use crate::panels::assembly_components::{self, ChainNode, ComponentRow};
use crate::panels::update_components::UpdateComponents;
use crate::panels::bom_columns::{
    self, ParsedColumns, Scope, FLAGS_KEY, ITEM_KEY, QUANTITY_KEY, VISIBLE_KEY,
};
use crate::store::ModelStore;
use brep_render::engine_state::EngineState;
use eframe::egui;
use serde_json::Value;
use std::collections::{BTreeMap, HashMap, HashSet};

/// The row menu's own entry: roll to the component's feature and open it in
/// the history tree. Not a [`ComponentAction`] — the shared set is the
/// COMPONENT vocabulary (spec §8.5) and the context bar draws a button per
/// member of it, so a document-navigation entry does not belong in there. The
/// assembly structure tree keeps this action locally for the same reason.
const EDIT_FEATURE: &str = "edit-feature";

/// What a BOM frame hands back to the shell.
#[derive(Default)]
pub struct BomOutcome {
    /// A feature id to roll to + expand in the history tree (the row menu's
    /// "Edit feature") — the structure panel's `focus` contract, verbatim, so
    /// the shell routes both the same way.
    pub focus: Option<String>,
    /// A document-level flow the SHELL owns (Edit Part → open the part's own
    /// document tab), handed
    /// back by the shared component-action dispatcher exactly as the selection
    /// context bar hands it back.
    pub component: Option<ComponentActionRequest>,
}

/// One occurrence, flattened out of the engine's projection.
#[derive(Clone)]
struct Occurrence {
    /// The owning ACOMP feature id.
    id: String,
    part_name: String,
    /// This occurrence's own attribute record.
    attributes: Value,
    selected: bool,
    /// Grounded (the ⏚ badge, and what refuses Move).
    fixed: bool,
    /// The library entry no longer matches its store source (the ↻ badge).
    outdated: bool,
    /// Worst constraint status referencing this component, if any.
    status: Option<String>,
    /// Every member solid currently visible.
    visible: bool,
    /// Member scene names, for the visibility toggle.
    solids: Vec<String>,
    /// Read-only nested component rows, from the member name chains. FULL
    /// depth: a sub-assembly inside a sub-assembly renders as such.
    children: Vec<ChainNode>,
}

/// The BOM panel's transient UI state. The data lives in the document; the
/// column arrangement lives in the settings text; this holds only what is true
/// for this session.
pub struct BomPanel {
    hits: HashMap<String, egui::Rect>,
    /// The widget's live column arrangement. Rebuilt from the settings text
    /// whenever that text changes, keeping session-only widths + sort.
    layout: ColumnLayout,
    /// The settings text `layout` was built from — the change detector.
    layout_source: String,
    /// The parsed configuration for `layout_source`.
    parsed: ParsedColumns,
    /// Packed (one row per distinct part + occurrence data) or unpacked (one
    /// row per placement).
    packed: bool,
    /// Rows explicitly collapsed, by row id (absent = open).
    collapsed: HashSet<String>,
}

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

impl BomPanel {
    pub fn new() -> Self {
        Self {
            hits: HashMap::new(),
            layout: ColumnLayout::default(),
            layout_source: String::new(),
            parsed: ParsedColumns::default(),
            // Packed is the BOM a person asks for: a parts list, not a
            // placement list.
            packed: true,
            collapsed: HashSet::new(),
        }
    }

    /// Draw the BOM. Snapshots the projection, draws the column tree, then
    /// applies at most one deferred engine mutation — the shared panel
    /// pattern, and the reason the draw can borrow `state` immutably.
    pub fn show(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        store: &dyn ModelStore,
        updates: &UpdateComponents,
    ) -> BomOutcome {
        self.hits.clear();
        // What is actually VISIBLE of this pane. Every other rect below is a
        // raw LAYOUT rect, so a widget scrolled past the pane's edge is still
        // published while being unclickable — a headed verifier has to scroll
        // it into this rect first. (The constraints panel publishes
        // `acon:panel:clip` for exactly the same reason.)
        self.hits.insert("bom:panel:clip".into(), ui.clip_rect());
        let mut outcome = BomOutcome::default();
        state.ensure_assembly_synced();

        self.sync_columns(state);
        let component_rows = assembly_components::snapshot(state, updates);
        let occurrences = occurrences_from(state, &component_rows);
        let groups = group(&occurrences, self.packed, &self.packing_fields());

        // --- header: the packed/unpacked switch ------------------------------
        ui.horizontal(|ui| {
            let packed = ui
                .selectable_label(self.packed, "Packed")
                .on_hover_text("One row per part, rolled up where every occurrence field matches");
            self.hits.insert("bom:packed".into(), packed.rect);
            if packed.clicked() {
                self.packed = true;
            }
            let unpacked = ui
                .selectable_label(!self.packed, "Unpacked")
                .on_hover_text("One row per individual instance");
            self.hits.insert("bom:unpacked".into(), unpacked.rect);
            if unpacked.clicked() {
                self.packed = false;
            }
            let expand = ui
                .button("Expand all")
                .on_hover_text("Expand every row with nested components");
            self.hits.insert("bom:expand-all".into(), expand.rect);
            if expand.clicked() {
                self.collapsed.clear();
            }
            let collapse = ui
                .button("Collapse all")
                .on_hover_text("Collapse every row with nested components");
            self.hits.insert("bom:collapse-all".into(), collapse.rect);
            if collapse.clicked() {
                // Every key the tree can hold: the group rows and, beneath
                // them, every nested chain node — collapse-all has to fold the
                // WHOLE tree, at every depth, with no key drift.
                self.collapsed = collapsible_keys(&groups);
            }
            ui.label(
                egui::RichText::new(format!("{} rows / {} occurrences", groups.len(), occurrences.len()))
                    .weak(),
            );
        });
        ui.add_space(2.0);

        // --- the tree ---------------------------------------------------------
        let rows: Vec<RowNode> = groups
            .iter()
            .map(|group| self.row_for(state, group))
            .collect();
        let specs = bom_columns::column_specs(&self.parsed);
        let mut root_cells: HashMap<String, Value> = HashMap::new();
        root_cells.insert(
            QUANTITY_KEY.to_string(),
            Value::from(occurrences.len() as u64),
        );
        let spec = ColumnTreeSpec {
            id: "bom",
            columns: &specs,
            root_label: Some("Assembly"),
            root_cells: Some(&root_cells),
            empty_hint: Some("(no components — insert one via Add new feature)"),
            hits_prefix: "",
        };
        let out = column_tree::column_tree(
            ui,
            &spec,
            &mut self.layout,
            &rows,
            Some(&mut self.hits),
        );

        // --- act on what the widget reported ---------------------------------
        if out.layout_changed {
            self.persist_layout(state, store);
        }
        if let Some(id) = &out.toggled {
            if !self.collapsed.remove(id) {
                self.collapsed.insert(id.clone());
            }
        }
        if let Some(id) = &out.clicked {
            if let Some(group) = groups.iter().find(|group| group.key == *id) {
                state.select_components(&group.ids);
            }
        }
        // The row menu. Engine-mutating actions run in the SHARED dispatcher
        // (one truth, one undo lane, the same one the structure tree's buttons
        // and the context bar use); the two document-level flows come back as
        // a request for the shell.
        let mut acted = false;
        for click in &out.actions {
            let Some(group) = groups.iter().find(|group| group.key == click.row_id) else {
                continue;
            };
            let Some(first) = group.ids.first() else {
                continue;
            };
            acted = true;
            if click.action == EDIT_FEATURE {
                if let Some(index) = state.history.index_of(first) {
                    state.roll_to(index);
                }
                outcome.focus = Some(first.clone());
            } else if let Some(action) = ComponentAction::from_id(&click.action) {
                outcome.component = run_component_action(state, action, first);
            }
        }
        // At most ONE edit lands per frame (egui gives one widget the focus),
        // and applying it re-runs the history, so take the first and let the
        // next frame carry any other. An action that just deleted the feature
        // this edit names would make the write fail loudly, so the action wins
        // the frame and the edit comes back on the next one.
        if !acted {
            if let Some(edit) = out.edits.first() {
                if edit.column == VISIBLE_KEY {
                    // Scene state, not a stored attribute: write it straight
                    // through to every member solid the row stands for.
                    let visible = edit.value.as_bool().unwrap_or(true);
                    if let Some(group) = groups.iter().find(|g| g.key == edit.row_id) {
                        for solid in &group.solids {
                            state.set_visible(solid, visible);
                        }
                    }
                } else {
                    self.apply_edit(state, store, &groups, edit);
                }
            }
        }

        // The component oracle the headed verifiers read. Published from the
        // shared projection rather than from these rows, so it stays engine
        // truth: `verify_bom_menu` uses it to prove a menu action reached the
        // engine, and proving that against the BOM's own rendering would be
        // checking the panel against itself.
        assembly_components::publish_tree(&component_rows);

        #[cfg(target_arch = "wasm32")]
        {
            let listing: Vec<Value> = groups
                .iter()
                .map(|group| {
                    serde_json::json!({
                        "key": group.key,
                        "partName": group.part_name,
                        "ids": group.ids,
                        "quantity": group.ids.len(),
                    })
                })
                .collect();
            publish("__brepBom", &Value::Array(listing).to_string());
            publish("__brepBomHit", &self.hits_json());
        }

        outcome
    }

    /// Rebuild the column layout when the settings text has changed. Widths
    /// and sort are session state and survive the rebuild — a re-parse must
    /// not resize the table under the user's hands.
    fn sync_columns(&mut self, state: &EngineState) {
        let text = bom_columns::effective_text(&state.settings.bom_columns);
        if text == self.layout_source {
            return;
        }
        self.parsed = bom_columns::parse(&text);
        self.layout = bom_columns::layout_from(&self.parsed, &self.layout);
        self.layout_source = text;
    }

    /// Fold a layout the user changed BY DRAGGING back into the settings text,
    /// so the table and the configuration can never disagree.
    fn persist_layout(&mut self, state: &mut EngineState, store: &dyn ModelStore) {
        let columns = bom_columns::columns_from_layout(&self.parsed, &self.layout);
        let text = bom_columns::serialize(
            &columns,
            &self.parsed.preserved,
            // Dragging a column across the freeze boundary moves the marker,
            // exactly as dragging one across another moves its line.
            bom_columns::frozen_from_layout(&self.layout),
        );
        let mut settings: Value =
            serde_json::from_str(&state.settings_json()).unwrap_or(Value::Null);
        let Some(object) = settings.as_object_mut() else {
            return;
        };
        object.insert("bomColumns".into(), Value::String(text.clone()));
        let json = settings.to_string();
        let _ = state.apply_settings_json(&json);
        let _ = store.write(crate::store::SETTINGS_KEY, &json);
        // Adopt it as our own source so `sync_columns` does not now rebuild
        // (and discard) the very layout the user just dragged.
        self.parsed = bom_columns::parse(&text);
        self.layout_source = text;
    }

    /// The occurrence fields a packed row is keyed by: the VISIBLE
    /// occurrence-scoped columns, in the arrangement's order.
    ///
    /// Visible, not every field: a BOM row stands for what the table SHOWS, so
    /// two placements that differ only in a column nobody is looking at are one
    /// line. Part-scoped columns are identical across every placement of a part
    /// by definition, so they cannot split a row and are not consulted; the
    /// derived quantity is not a field at all.
    fn packing_fields(&self) -> Vec<String> {
        self.parsed
            .columns
            .iter()
            .filter(|column| column.scope == Scope::Occurrence)
            .filter(|column| column.key() != QUANTITY_KEY)
            .filter(|column| !self.layout.hidden.contains(&column.key()))
            .map(|column| column.field.clone())
            .collect()
    }

    /// Build one widget row for a group: the tree cell, every configured
    /// column's value, and the read-only nested component rows beneath.
    fn row_for(&self, state: &EngineState, group: &Group) -> RowNode {
        let mut cells: HashMap<String, Value> = HashMap::new();
        let label = if self.packed {
            group.part_name.clone()
        } else {
            format!("{} ({})", group.part_name, group.key)
        };
        cells.insert(ITEM_KEY.to_string(), Value::String(label));
        cells.insert(VISIBLE_KEY.to_string(), Value::Bool(group.visible));
        cells.insert(FLAGS_KEY.to_string(), Value::Array(badges(group)));
        // Quantity is DERIVED — the size of the roll-up — and never stored.
        cells.insert(
            QUANTITY_KEY.to_string(),
            Value::from(group.ids.len() as u64),
        );

        let part_attributes = state.part_attributes(&group.part_name);
        for column in &self.parsed.columns {
            let key = column.key();
            if key == QUANTITY_KEY {
                continue;
            }
            let source = match column.scope {
                Scope::Part => &part_attributes,
                Scope::Occurrence => &group.attributes,
            };
            if let Some(value) = source.get(&column.field) {
                cells.insert(key, value.clone());
            }
        }

        RowNode {
            id: group.key.clone(),
            cells,
            editable: true,
            selected: group.selected,
            expanded: !self.collapsed.contains(&group.key),
            actions: actions_for(state, group),
            // Nested components belong to the sub-assembly's own document, so
            // they show but never take an edit (rigid nesting). Rendered to
            // FULL depth: a sub-assembly inside a sub-assembly is a real thing
            // in the model and the list has to be able to show it.
            children: chain_rows(&group.key, &group.children),
        }
    }

    /// Route ONE cell edit to its store. The column's scope decides which:
    /// occurrence fields fan out across the group's ACOMPs in one undo step,
    /// part fields go to the part document and then through the shared
    /// write-through.
    fn apply_edit(
        &self,
        state: &mut EngineState,
        store: &dyn ModelStore,
        groups: &[Group],
        edit: &CellEdit,
    ) {
        let Some(group) = groups.iter().find(|group| group.key == edit.row_id) else {
            return; // a nested sub-assembly row — read-only, nothing to write
        };
        let Some(column) = self
            .parsed
            .columns
            .iter()
            .find(|column| column.key() == edit.column)
        else {
            return;
        };
        match column.scope {
            Scope::Occurrence => {
                // The fan-out: EVERY occurrence the packed row rolls up, as
                // ONE undo step.
                if let Err(error) =
                    state.set_occurrence_attribute(&group.ids, &column.field, edit.value.clone())
                {
                    state.push_notice(format!("BOM: {error}"));
                }
            }
            Scope::Part => {
                // The part's `(sourceKey, signature-as-inserted)` must be read
                // BEFORE the edit re-stamps the signature — that pair is what
                // the write-through compares the file against.
                let target = state.part_source(&group.part_name).and_then(|(key, sig)| {
                    (!key.is_empty()).then_some((key, sig))
                });
                if let Err(error) =
                    state.set_part_attribute(&group.part_name, &column.field, edit.value.clone())
                {
                    state.push_notice(format!("BOM: {error}"));
                    return;
                }
                // The part document that just changed is saved back to the file
                // it came from, through the shared write-through lane, so the
                // entry's signature and the file agree.
                if let Some(document) = state.part_document_json(&group.part_name) {
                    parts_library::write_through(
                        state,
                        store,
                        &group.part_name,
                        target.as_ref(),
                        &document,
                    );
                }
            }
        }
    }

    /// The published widget hit-rects for the headed verifier.
    #[cfg(target_arch = "wasm32")]
    pub fn hits_json(&self) -> String {
        let map: serde_json::Map<String, Value> = self
            .hits
            .iter()
            .map(|(key, rect)| {
                (
                    key.clone(),
                    serde_json::json!([rect.min.x, rect.min.y, rect.width(), rect.height()]),
                )
            })
            .collect();
        Value::Object(map).to_string()
    }
}

/// The row menu for one group: "Edit feature" (this panel's own) then the
/// SHARED component actions in bar order, each refused-with-a-reason where this
/// row cannot honour it.
///
/// The per-INSTANCE actions (Move, Fix/Unfix, Delete) are refused on a PACKED
/// row that rolls up more than one placement: acting on "the first" of four is
/// a trap, and fanning Delete or Fix out across the group would be N undo steps
/// where every other BOM edit is one. The part-level flows (Edit in place, Open
/// Part) mean the same thing for every placement, so they stay live; and
/// "Edit feature" only rolls the history, which is what the ✎ button it
/// replaced always did.
fn actions_for(state: &EngineState, group: &Group) -> Vec<RowAction> {
    let Some(first) = group.ids.first() else {
        return Vec::new();
    };
    let fixed = state
        .component_info(first)
        .map(|info| info.fixed)
        .unwrap_or(false);
    let rolled_up = group.ids.len() > 1;
    let unpack = |verb: &str| {
        format!(
            "{} placements on this row — switch to Unpacked to {verb} one",
            group.ids.len()
        )
    };
    // An embedded-only part (no `sourceKey`) has no document to open.
    let embedded = !state
        .part_source(&group.part_name)
        .is_some_and(|(key, _)| !key.is_empty());

    let mut actions = vec![RowAction::new(EDIT_FEATURE, "\u{270E} Edit feature")
        .tooltip("Roll to this component's feature and open it in the history")];
    for action in ComponentAction::ALL {
        let entry = RowAction::new(action.id(), action.label(fixed)).tooltip(action.tooltip());
        let entry = match action {
            ComponentAction::Move if fixed => {
                entry.disabled("This component is fixed — unfix it before moving it")
            }
            ComponentAction::Move if rolled_up => entry.disabled(unpack("move")),
            ComponentAction::ToggleFixed if rolled_up => entry.disabled(unpack("fix or unfix")),
            ComponentAction::Delete if rolled_up => entry.disabled(unpack("delete")),
            ComponentAction::OpenPart if embedded => {
                entry.disabled("This part is embedded in the assembly — it has no source document")
            }
            _ => entry,
        };
        actions.push(match action {
            // The destructive tail, fenced off from the rest.
            ComponentAction::Delete => entry.separator_above().destructive(),
            _ => entry,
        });
    }
    actions
}

/// Every key the tree can place in `collapsed`: each group row that has nested
/// components, and every nested chain node beneath it that has children of its
/// own. Collapse-all writes exactly this set.
fn collapsible_keys(groups: &[Group]) -> HashSet<String> {
    /// Does this node own a nested COMPONENT anywhere below it? Bodies do not
    /// count — they are not drawn, so a node holding only bodies has nothing to
    /// collapse and must not claim a key.
    fn owns_component(nodes: &[ChainNode]) -> bool {
        nodes
            .iter()
            .any(|node| assembly_components::is_acomp_segment(&node.label))
    }
    fn walk(parent: &str, nodes: &[ChainNode], out: &mut HashSet<String>) {
        for node in nodes
            .iter()
            .filter(|node| assembly_components::is_acomp_segment(&node.label))
        {
            let id = format!("{parent}:{}", node.label);
            if owns_component(&node.children) {
                out.insert(id.clone());
            }
            walk(&id, &node.children, out);
        }
    }
    let mut out = HashSet::new();
    for group in groups {
        if owns_component(&group.children) {
            out.insert(group.key.clone());
        }
        walk(&group.key, &group.children, &mut out);
    }
    out
}

/// The row's status glyphs: grounded, outdated, and the worst constraint
/// status referencing it. Colour carries the meaning for the last two, which is
/// why these are badges rather than text.
fn badges(group: &Group) -> Vec<Value> {
    let mut out = Vec::new();
    if group.fixed {
        out.push(serde_json::json!({
            "glyph": assembly_components::FIXED_GLYPH,
            "tooltip": "Grounded — unfix it before moving it",
        }));
    }
    if group.outdated {
        out.push(serde_json::json!({
            "glyph": assembly_components::OUTDATED_GLYPH,
            "color": color_hex(assembly_components::OUTDATED_AMBER),
            "tooltip": "The source part has changed since this was inserted",
        }));
    }
    if let Some(status) = &group.status {
        out.push(serde_json::json!({
            "glyph": "\u{25CF}",
            "color": brep_render::assembly_status::status_color_hex(status),
            "tooltip": format!("Constraint status: {status}"),
        }));
    }
    out
}

/// `Color32` → the `#rrggbb` the widget's badge cell parses. (Constraint
/// statuses have their own [`brep_render::assembly_status::status_color_hex`];
/// this is for the badge colours the app owns.)
fn color_hex(color: egui::Color32) -> String {
    format!("#{:02x}{:02x}{:02x}", color.r(), color.g(), color.b())
}

/// Nested COMPONENT rows for one group, to full depth. Read-only throughout:
/// these belong to the sub-assembly's own document, so they carry no cells the
/// BOM may edit and offer no actions in THIS document.
///
/// Only `ACOMP<n>` nodes appear. A BOM lists PARTS and the sub-assemblies a
/// part contains — the bodies inside a part are that part's internals and live
/// on the Scene tree, not here. Filtering recursively also means a part whose
/// chain holds nothing but bodies ends up with no children at all, so the
/// widget draws no collapse box on a row with nothing behind it.
fn chain_rows(parent: &str, nodes: &[ChainNode]) -> Vec<RowNode> {
    nodes
        .iter()
        .filter(|node| assembly_components::is_acomp_segment(&node.label))
        .map(|node| {
            let id = format!("{parent}:{}", node.label);
            let mut cells = HashMap::new();
            cells.insert(ITEM_KEY.to_string(), Value::String(node.label.clone()));
            RowNode {
                children: chain_rows(&id, &node.children),
                id,
                cells,
                editable: false,
                selected: false,
                expanded: false,
                actions: Vec::new(),
            }
        })
        .collect()
}

/// Is `candidate` a worse constraint status than `current`? Uses the ONE status
/// map's severity ordering, so a rolled-up row shows the worst of what it
/// stands for rather than whichever placement happened to be first.
fn worse_status(current: Option<&str>, candidate: Option<&str>) -> bool {
    let Some(candidate) = candidate else {
        return false;
    };
    match current {
        None => true,
        Some(current) => {
            brep_render::assembly_status::status_severity(candidate)
                > brep_render::assembly_status::status_severity(current)
        }
    }
}

/// One BOM row's occurrences: the whole group in the packed view, exactly one
/// in the unpacked view.
struct Group {
    /// The row id. In the packed view this is a synthetic group key; in the
    /// unpacked view it is the ACOMP id itself.
    key: String,
    part_name: String,
    /// Every ACOMP this row stands for — what a packed edit fans out across.
    ids: Vec<String>,
    /// The occurrence attributes shared by the whole group (identical by
    /// construction — that is what made them one group).
    attributes: Value,
    selected: bool,
    /// Rolled up across the group: grounded only when EVERY placement is.
    fixed: bool,
    outdated: bool,
    /// Worst status across the group's placements.
    status: Option<String>,
    /// Visible only when EVERY member solid of every placement is.
    visible: bool,
    /// Every member solid the row stands for — what the toggle writes to.
    solids: Vec<String>,
    children: Vec<ChainNode>,
}

/// Flatten the engine's component projection into occurrences.
///
/// The per-component truth (fixed, outdated, constraint-status rollup,
/// visibility, the nested chain) comes from the SHARED projection in
/// [`assembly_components`] — the same rows the headed verifiers read as
/// `__brepAssemblyTree`. The BOM adds only what is its own: the attribute
/// records it edits.
fn occurrences_from(state: &mut EngineState, rows: &[ComponentRow]) -> Vec<Occurrence> {
    rows.iter()
        .map(|row| Occurrence {
            attributes: state.occurrence_attributes(&row.id),
            selected: row.selected,
            fixed: row.fixed,
            outdated: row.outdated,
            status: row.rollup_status.clone(),
            visible: row.visible,
            solids: row.solids.clone(),
            children: row.children.clone(),
            part_name: row.part_name.clone(),
            id: row.id.clone(),
        })
        .collect()
}

/// Group occurrences into BOM rows.
///
/// PACKED rolls up by `(part name, EVERY occurrence field)` — the owner's rule:
/// occurrences that differ in ANY occurrence field stay separate rows, because
/// a rolled-up row would have to show one of two different values and an edit
/// to it would silently overwrite the other. UNPACKED is one row each.
///
/// Group order follows first appearance, which is the engine's deterministic
/// id order, so the table is stable frame to frame before any sort.
fn group(occurrences: &[Occurrence], packed: bool, fields: &[String]) -> Vec<Group> {
    if !packed {
        return occurrences
            .iter()
            .map(|occurrence| Group {
                key: occurrence.id.clone(),
                part_name: occurrence.part_name.clone(),
                ids: vec![occurrence.id.clone()],
                attributes: occurrence.attributes.clone(),
                selected: occurrence.selected,
                fixed: occurrence.fixed,
                outdated: occurrence.outdated,
                status: occurrence.status.clone(),
                visible: occurrence.visible,
                solids: occurrence.solids.clone(),
                children: occurrence.children.clone(),
            })
            .collect();
    }
    let mut order: Vec<String> = Vec::new();
    let mut groups: HashMap<String, Group> = HashMap::new();
    for occurrence in occurrences {
        let key = format!(
            "{}\u{1}{}",
            occurrence.part_name,
            canonical_over(&occurrence.attributes, fields)
        );
        match groups.get_mut(&key) {
            Some(group) => {
                group.ids.push(occurrence.id.clone());
                group.selected |= occurrence.selected;
                // A rolled-up row states what is true of EVERY placement it
                // stands for: grounded only if all are, visible only if all
                // are. Anything else would let one row claim a state a
                // placement behind it does not have.
                group.fixed &= occurrence.fixed;
                group.visible &= occurrence.visible;
                group.outdated |= occurrence.outdated;
                group.solids.extend(occurrence.solids.iter().cloned());
                if worse_status(group.status.as_deref(), occurrence.status.as_deref()) {
                    group.status = occurrence.status.clone();
                }
                for child in &occurrence.children {
                    if !group.children.iter().any(|kept| kept == child) {
                        group.children.push(child.clone());
                    }
                }
            }
            None => {
                order.push(key.clone());
                groups.insert(
                    key,
                    Group {
                        key: String::new(), // filled below, from the group order
                        part_name: occurrence.part_name.clone(),
                        ids: vec![occurrence.id.clone()],
                        attributes: occurrence.attributes.clone(),
                        selected: occurrence.selected,
                        fixed: occurrence.fixed,
                        outdated: occurrence.outdated,
                        status: occurrence.status.clone(),
                        visible: occurrence.visible,
                        solids: occurrence.solids.clone(),
                        children: occurrence.children.clone(),
                    },
                );
            }
        }
    }
    order
        .into_iter()
        .filter_map(|key| groups.remove(&key))
        .map(|mut group| {
            // The row id must be STABLE across frames (it keys collapse state
            // and every out-value) but must not be a raw attribute dump. The
            // first ACOMP of the group is both — deterministic, because the
            // projection is in id order.
            group.key = format!(
                "pack:{}",
                group.ids.first().cloned().unwrap_or_default()
            );
            group
        })
        .collect()
}

/// The packing key's value half: the named fields, in the given order, with a
/// missing field spelled explicitly. Order comes from the column arrangement
/// rather than the record, so two placements whose attributes were WRITTEN in a
/// different order still key the same. (serde_json runs with `preserve_order`
/// in this workspace, so a naive `to_string` of the record would not.)
fn canonical_over(attributes: &Value, fields: &[String]) -> String {
    fields
        .iter()
        .map(|field| {
            let value = attributes
                .get(field)
                .map(Value::to_string)
                .unwrap_or_default();
            format!("{field}={value}")
        })
        .collect::<Vec<_>>()
        .join("\u{2}")
}

/// Mirror a JSON string to `window.<name>` (wasm/verification only).
#[cfg(target_arch = "wasm32")]
fn publish(name: &str, json: &str) {
    if let Some(win) = web_sys::window() {
        let _ = js_sys::Reflect::set(
            &win,
            &wasm_bindgen::JsValue::from_str(name),
            &wasm_bindgen::JsValue::from_str(json),
        );
    }
}

// Native-only (as the update-components + assembly-edit suites are): the
// fixtures ride the test-only in-memory `ModelStore`, which wasm does not
// compile.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    /// The packing fields a test groups by — normally the columns it actually
    /// sets, since packing keys on the VISIBLE occurrence columns.
    fn by(fields: &[&str]) -> Vec<String> {
        fields.iter().map(|field| field.to_string()).collect()
    }

    /// The old one-argument snapshot the tests were written against: the
    /// shared projection with nothing outdated. Keeps every existing test
    /// honest about what it is actually asserting.
    fn snapshot(state: &mut EngineState) -> Vec<Occurrence> {
        let rows = assembly_components::snapshot(state, &UpdateComponents::new());
        occurrences_from(state, &rows)
    }
    use crate::panels::update_components::tests::part_document;
    use crate::store::MemModelStore;
    use brep_render::engine_state::ComponentInsert;

    /// Two instances of `widget` + one `gadget`, all embedded-only unless the
    /// test says otherwise.
    fn assembly() -> EngineState {
        brep_render::brep_kernel::clear_history_cache();
        let mut state = EngineState::new();
        state
            .insert_component(ComponentInsert::New {
                name: "widget",
                source_key: "",
                source_signature: "sig-w",
                document_json: &part_document(4.0),
            })
            .expect("widget inserts");
        state
            .insert_component(ComponentInsert::Existing { part_name: "widget" })
            .expect("second widget");
        state
            .insert_component(ComponentInsert::New {
                name: "gadget",
                source_key: "",
                source_signature: "sig-g",
                document_json: &part_document(7.0),
            })
            .expect("gadget inserts");
        state
    }

    fn panel_with(columns: &str) -> (BomPanel, EngineState) {
        let mut state = assembly();
        state
            .apply_settings_json(&serde_json::json!({ "bomColumns": columns }).to_string())
            .expect("columns apply");
        // Adopt the configuration up front, so a test that calls `row_for`
        // directly (without a draw) still has its columns.
        let mut panel = BomPanel::new();
        panel.sync_columns(&state);
        (panel, state)
    }

    /// Draw one frame.
    fn frame(
        ctx: &egui::Context,
        panel: &mut BomPanel,
        state: &mut EngineState,
        store: &dyn ModelStore,
        events: Vec<egui::Event>,
    ) -> BomOutcome {
        let raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(900.0, 600.0),
            )),
            events,
            ..Default::default()
        };
        let mut outcome = BomOutcome::default();
        let _ = ctx.run_ui(raw, |ui| {
            outcome = panel.show(ui, state, store, &UpdateComponents::new());
        });
        outcome
    }

    /// Draw two idle frames: an egui popup's FIRST frame is a sizing pass whose
    /// widgets are not yet interactable (it asks for a repaint, which a real app
    /// serves immediately and a test has to draw by hand).
    fn settle(
        ctx: &egui::Context,
        panel: &mut BomPanel,
        state: &mut EngineState,
        store: &dyn ModelStore,
    ) {
        frame(ctx, panel, state, store, vec![]);
        frame(ctx, panel, state, store, vec![]);
    }

    fn right_click_at(
        ctx: &egui::Context,
        panel: &mut BomPanel,
        state: &mut EngineState,
        store: &dyn ModelStore,
        pos: egui::Pos2,
    ) -> BomOutcome {
        press_release(ctx, panel, state, store, pos, egui::PointerButton::Secondary)
    }

    fn click_at(
        ctx: &egui::Context,
        panel: &mut BomPanel,
        state: &mut EngineState,
        store: &dyn ModelStore,
        pos: egui::Pos2,
    ) -> BomOutcome {
        press_release(ctx, panel, state, store, pos, egui::PointerButton::Primary)
    }

    fn press_release(
        ctx: &egui::Context,
        panel: &mut BomPanel,
        state: &mut EngineState,
        store: &dyn ModelStore,
        pos: egui::Pos2,
        button: egui::PointerButton,
    ) -> BomOutcome {
        frame(
            ctx,
            panel,
            state,
            store,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        frame(
            ctx,
            panel,
            state,
            store,
            vec![egui::Event::PointerButton {
                pos,
                button,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        )
    }

    /// PACKED rolls the two identical `widget` occurrences into one row with
    /// QTY 2; UNPACKED shows all three placements at QTY 1 each.
    #[test]
    fn packed_rolls_up_identical_occurrences_and_unpacked_does_not() {
        let mut state = assembly();
        let occurrences = snapshot(&mut state);
        assert_eq!(occurrences.len(), 3);

        let packed = group(&occurrences, true, &by(&[]));
        assert_eq!(packed.len(), 2, "widget x2 rolled up, gadget alone");
        assert_eq!(packed[0].part_name, "widget");
        assert_eq!(packed[0].ids, vec!["ACOMP1", "ACOMP2"]);
        assert_eq!(packed[1].ids, vec!["ACOMP3"]);

        let unpacked = group(&occurrences, false, &by(&[]));
        assert_eq!(unpacked.len(), 3, "one row per placement");
        assert!(unpacked.iter().all(|group| group.ids.len() == 1));
        assert_eq!(unpacked[0].key, "ACOMP1", "the row IS the occurrence");
    }

    /// The roll-up rule: occurrences that differ in a VISIBLE occurrence
    /// column stay SEPARATE rows — that row would have to show one of two
    /// different values, and an edit to it would silently overwrite the other.
    /// A field NOT on screen cannot split anything: the row stands for what
    /// the table shows.
    #[test]
    fn a_differing_visible_field_splits_the_packed_row_and_a_hidden_one_does_not() {
        let mut state = assembly();
        state
            .set_occurrence_attribute(
                &["ACOMP2".to_string()],
                "Reference_Designator",
                Value::String("R2".into()),
            )
            .unwrap();
        // Reference_Designator ON SCREEN: the widgets no longer match.
        let shown = by(&["Reference_Designator"]);
        let packed = group(&snapshot(&mut state), true, &shown);
        assert_eq!(packed.len(), 3, "the two widgets no longer match");
        assert_eq!(packed[0].ids, vec!["ACOMP1"]);
        assert_eq!(packed[1].ids, vec!["ACOMP2"]);

        // The SAME documents, with that column hidden: one row again. Nothing
        // about the data changed — only what the table is showing.
        let packed = group(&snapshot(&mut state), true, &by(&["Notes"]));
        assert_eq!(packed.len(), 2, "a hidden difference does not split a row");
        assert_eq!(packed[0].ids, vec!["ACOMP1", "ACOMP2"]);

        // Give ACOMP1 the SAME value and they roll back up — the rule is
        // about content, not about having ever been edited.
        state
            .set_occurrence_attribute(
                &["ACOMP1".to_string()],
                "Reference_Designator",
                Value::String("R2".into()),
            )
            .unwrap();
        let packed = group(&snapshot(&mut state), true, &shown);
        assert_eq!(packed.len(), 2, "identical again");
        assert_eq!(packed[0].ids, vec!["ACOMP1", "ACOMP2"]);
    }

    /// The packing key compares CONTENT, not serialization: two records with
    /// the same fields written in a different ORDER still roll up. (serde_json
    /// runs with `preserve_order` in this workspace, so a naive `to_string`
    /// key would not.)
    #[test]
    fn the_packing_key_ignores_attribute_write_order() {
        let mut state = assembly();
        let one = vec!["ACOMP1".to_string()];
        let two = vec!["ACOMP2".to_string()];
        state.set_occurrence_attribute(&one, "Notes", Value::String("a".into())).unwrap();
        state.set_occurrence_attribute(&one, "Find_Number", Value::String("1".into())).unwrap();
        // ...the other one written in the OPPOSITE order.
        state.set_occurrence_attribute(&two, "Find_Number", Value::String("1".into())).unwrap();
        state.set_occurrence_attribute(&two, "Notes", Value::String("a".into())).unwrap();

        let packed = group(&snapshot(&mut state), true, &by(&["Notes", "Find_Number"]));
        assert_eq!(packed.len(), 2, "still widget x2 + gadget");
        assert_eq!(
            packed[0].ids,
            vec!["ACOMP1", "ACOMP2"],
            "same content, different write order, one row"
        );
    }

    /// Editing a PACKED row's occurrence cell applies to every occurrence it
    /// rolls up — and takes ONE undo to reverse, not two.
    #[test]
    fn a_packed_edit_fans_out_and_undoes_in_one_step() {
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let (mut panel, mut state) = panel_with("*occurrence.Notes\n");
        frame(&ctx, &mut panel, &mut state, &store, vec![]);

        let cell = *panel
            .hits
            .get("cell:pack:ACOMP1:occurrence.Notes")
            .expect("the packed widget row's Notes cell");
        click_at(&ctx, &mut panel, &mut state, &store, cell.center());
        frame(&ctx, &mut panel, &mut state, &store, vec![egui::Event::Text("chk".into())]);
        frame(
            &ctx,
            &mut panel,
            &mut state,
            &store,
            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(),
                },
            ],
        );

        assert_eq!(state.occurrence_attributes("ACOMP1")["Notes"], "chk");
        assert_eq!(
            state.occurrence_attributes("ACOMP2")["Notes"], "chk",
            "the edit fanned out to the whole packed row"
        );
        assert_eq!(
            state.occurrence_attributes("ACOMP3"),
            serde_json::json!({}),
            "and only to that row"
        );

        state.undo();
        assert_eq!(
            state.occurrence_attributes("ACOMP1"),
            serde_json::json!({}),
            "ONE undo takes the whole fan-out back"
        );
        assert_eq!(state.occurrence_attributes("ACOMP2"), serde_json::json!({}));
    }

    /// A PART cell edit writes the part document (so every occurrence of the
    /// part shows it, in either view) and rides the shared write-through lane,
    /// so the part's file is updated too.
    #[test]
    fn a_part_edit_writes_the_part_document_and_writes_through_to_its_file() {
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let document = part_document(4.0);
        store.write("widget", &document).unwrap();

        brep_render::brep_kernel::clear_history_cache();
        let mut state = EngineState::new();
        state
            .insert_component(ComponentInsert::New {
                name: "widget",
                source_key: "widget",
                source_signature: &parts_library::document_signature(&document),
                document_json: &document,
            })
            .unwrap();
        state
            .insert_component(ComponentInsert::Existing { part_name: "widget" })
            .unwrap();
        state
            .apply_settings_json(r##"{"bomColumns": "*part.Material\n"}"##)
            .unwrap();
        let mut panel = BomPanel::new();
        frame(&ctx, &mut panel, &mut state, &store, vec![]);

        let cell = *panel
            .hits
            .get("cell:pack:ACOMP1:part.Material")
            .expect("the Material cell");
        click_at(&ctx, &mut panel, &mut state, &store, cell.center());
        frame(&ctx, &mut panel, &mut state, &store, vec![egui::Event::Text("6061".into())]);
        frame(
            &ctx,
            &mut panel,
            &mut state,
            &store,
            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(),
                },
            ],
        );

        assert_eq!(state.part_attributes("widget")["Material"], "6061");
        // Write-through: the file the part came from now carries it too, and
        // its signature matches the entry's — so Update Components does not
        // badge the component outdated against a file it is newer than.
        let stored = store.read("widget").expect("the part file");
        let stored_document: Value = serde_json::from_str(&stored).unwrap();
        assert_eq!(stored_document["partAttributes"]["Material"], "6061");
        let (_, signature) = state.part_source("widget").unwrap();
        assert_eq!(
            signature,
            parts_library::document_signature(&stored),
            "the entry's signature and the file describe the same content"
        );
    }

    /// The `occurrence.Quantity` column is DERIVED and read-only: packed shows
    /// the roll-up size, unpacked shows 1, and neither is ever stored.
    #[test]
    fn quantity_is_derived_read_only_and_never_stored() {
        let (panel, mut state) = panel_with("*occurrence.Quantity\n");
        let groups = group(&snapshot(&mut state), true, &by(&[]));
        let row = panel.row_for(&state, &groups[0]);
        assert_eq!(row.cells[QUANTITY_KEY], serde_json::json!(2));

        let mut unpacked = BomPanel::new();
        unpacked.packed = false;
        unpacked.parsed = panel.parsed.clone();
        let groups = group(&snapshot(&mut state), false, &by(&[]));
        let row = unpacked.row_for(&state, &groups[0]);
        assert_eq!(row.cells[QUANTITY_KEY], serde_json::json!(1));

        // Never stored: the occurrence record stays empty.
        assert_eq!(state.occurrence_attributes("ACOMP1"), serde_json::json!({}));
        assert_eq!(
            panel.parsed.columns[0].kind(),
            crate::column_tree::CellKind::ReadOnly
        );
    }

    /// The settings text drives which columns the table shows, and in what
    /// order — including a user-added custom field.
    #[test]
    fn the_settings_text_drives_the_columns() {
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let (mut panel, mut state) =
            panel_with("*occurrence.Notes\n*part.Part_Number\npart.Mass\n*occurrence.Torque\n");
        frame(&ctx, &mut panel, &mut state, &store, vec![]);

        assert!(panel.hits.contains_key("col:occurrence.Notes"));
        assert!(panel.hits.contains_key("col:part.Part_Number"));
        assert!(panel.hits.contains_key("col:occurrence.Torque"), "custom field");
        assert!(
            !panel.hits.contains_key("col:part.Mass"),
            "unstarred = hidden"
        );
        assert!(
            panel.hits["col:occurrence.Notes"].left() < panel.hits["col:part.Part_Number"].left(),
            "the text's order is the table's order"
        );
        // Re-applying the SAME text does not rebuild the layout under the user.
        panel.layout.widths.insert("occurrence.Notes".into(), 300.0);
        frame(&ctx, &mut panel, &mut state, &store, vec![]);
        assert_eq!(panel.layout.widths["occurrence.Notes"], 300.0);
    }

    /// Hiding a column by dragging writes BACK to the settings text, so the
    /// table and the configuration can never disagree.
    #[test]
    fn a_layout_change_persists_into_the_settings_text() {
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let (mut panel, mut state) = panel_with("*occurrence.Notes\n*part.Part_Number\n");
        frame(&ctx, &mut panel, &mut state, &store, vec![]);

        panel.layout.hidden.insert("part.Part_Number".into());
        panel.persist_layout(&mut state, &store);
        assert_eq!(
            state.settings.bom_columns, "*occurrence.Notes\npart.Part_Number\n",
            "the star came off the hidden column"
        );
        // ...and a redraw keeps it hidden rather than re-reading the old text.
        frame(&ctx, &mut panel, &mut state, &store, vec![]);
        assert!(!panel.hits.contains_key("col:part.Part_Number"));
    }

    /// The actions cell opens the MENU, and choosing "Edit feature" reports the
    /// row's feature for the shell to focus — the ✎ button's old job, now one
    /// entry of a list.
    #[test]
    fn the_actions_cell_opens_the_menu_and_edit_feature_focuses_the_row() {
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let (mut panel, mut state) = panel_with("*occurrence.Notes\n");
        frame(&ctx, &mut panel, &mut state, &store, vec![]);
        let trigger = *panel
            .hits
            .get("menu:pack:ACOMP3")
            .expect("the gadget row's menu trigger");

        click_at(&ctx, &mut panel, &mut state, &store, trigger.center());
        settle(&ctx, &mut panel, &mut state, &store);
        let entry = *panel
            .hits
            .get("menuitem:pack:ACOMP3:edit-feature")
            .expect("Edit feature is on the menu");
        let outcome = click_at(&ctx, &mut panel, &mut state, &store, entry.center());
        assert_eq!(outcome.focus.as_deref(), Some("ACOMP3"));
    }

    /// A RIGHT-CLICK anywhere on the row opens the same menu — here over the
    /// Notes text cell, the case a `context_menu` on the row band would lose to
    /// the text editor — and one of the SHARED component actions run from it
    /// reaches the engine through the shared dispatcher.
    #[test]
    fn a_right_click_on_a_row_runs_a_shared_component_action() {
        let ctx = egui::Context::default();
        let store = MemModelStore::new();
        let (mut panel, mut state) = panel_with("*occurrence.Notes\n");
        frame(&ctx, &mut panel, &mut state, &store, vec![]);
        let cell = *panel
            .hits
            .get("cell:pack:ACOMP3:occurrence.Notes")
            .expect("the gadget row's Notes cell");

        right_click_at(&ctx, &mut panel, &mut state, &store, cell.center());
        settle(&ctx, &mut panel, &mut state, &store);
        let entry = *panel
            .hits
            .get("menuitem:pack:ACOMP3:move")
            .expect("Move is on the menu opened by right-click");
        click_at(&ctx, &mut panel, &mut state, &store, entry.center());

        assert!(state.component_move_armed(), "the gizmo armed");
        assert_eq!(state.component_move_armed_feature(), "ACOMP3");
        assert_eq!(
            state.occurrence_attributes("ACOMP3"),
            serde_json::json!({}),
            "and the right-click wrote nothing into the cell it landed on"
        );
    }

    /// The menu is the SHARED component action set plus this panel's own
    /// "Edit feature", and availability is decided per row: a fixed component
    /// refuses Move, an embedded-only part refuses Open Part, and a PACKED row
    /// standing for several placements refuses the per-instance actions rather
    /// than guessing which placement was meant.
    #[test]
    fn the_menu_is_the_shared_action_set_refused_per_row() {
        let (_, mut state) = panel_with("*occurrence.Notes\n");
        let groups = group(&snapshot(&mut state), true, &by(&[]));

        let ids = |actions: &[RowAction]| -> Vec<String> {
            actions.iter().map(|action| action.id.clone()).collect()
        };
        let refused = |actions: &[RowAction]| -> Vec<String> {
            actions
                .iter()
                .filter(|action| !action.enabled)
                .map(|action| action.id.clone())
                .collect()
        };

        // The packed widget row: two placements, and ACOMP1 is the grounded
        // first component.
        let packed = groups.iter().find(|g| g.ids.len() == 2).expect("two widgets");
        let actions = actions_for(&state, packed);
        assert_eq!(
            ids(&actions),
            vec![
                EDIT_FEATURE,
                "move",
                "open-part",
                "toggle-fixed",
                "delete"
            ],
            "Edit feature, then ComponentAction::ALL in bar order"
        );
        assert_eq!(
            refused(&actions),
            vec!["move", "open-part", "toggle-fixed", "delete"],
            "per-instance actions on a rolled-up row, and the embedded part"
        );
        assert!(
            actions.iter().all(|action| !action.tooltip.is_empty()),
            "every entry says what it does — a refused one says why not"
        );
        assert!(
            actions.last().is_some_and(|action| action.destructive
                && action.separator_above
                && action.id == "delete"),
            "Delete is the destructive tail, fenced off"
        );

        // The lone gadget: one placement, free, still embedded-only.
        let single = groups.iter().find(|g| g.ids == ["ACOMP3"]).expect("the gadget");
        assert_eq!(
            refused(&actions_for(&state, single)),
            vec!["open-part"],
            "only the embedded-part refusal survives on an unpacked row"
        );

        // A nested sub-assembly row owns no feature HERE, so it offers nothing.
        let panel = BomPanel::new();
        let row = panel.row_for(&state, single);
        assert!(!row.actions.is_empty(), "the component row offers its menu");
    }

    /// The nested components of a rigid sub-assembly are child ROWS (so the
    /// BOM reads as the tree it is) but take no edit — their data lives in the
    /// sub-assembly's own document.
    #[test]
    fn nested_sub_assembly_rows_are_children_and_read_only() {
        let (panel, mut state) = panel_with("*occurrence.Notes\n");
        let mut groups = group(&snapshot(&mut state), true, &by(&[]));
        groups[0].children = vec![ChainNode {
            label: "ACOMP9".into(),
            children: vec![ChainNode { label: "ACOMP3".into(), children: vec![] }],
        }];
        let row = panel.row_for(&state, &groups[0]);
        assert_eq!(row.children.len(), 1);
        assert!(
            !row.children[0].editable,
            "a nested row belongs to another document"
        );
        assert!(row.editable, "the top-level row is still editable");
        // FULL DEPTH: the nested row's own child renders too. The Structure
        // panel this replaced showed every level, and a BOM that stopped at one
        // would have quietly dropped sub-sub-assemblies from the model's only
        // component list.
        assert_eq!(row.children[0].children.len(), 1, "depth 2 renders");
        assert_eq!(
            row.children[0].children[0].cells.get(ITEM_KEY),
            Some(&Value::String("ACOMP3".into()))
        );
    }

    /// The VISIBILITY toggle (ported from the Structure panel it replaced):
    /// unchecking a row hides every member solid it stands for, and leaves
    /// every other instance alone.
    #[test]
    fn visibility_toggle_hides_every_member_solid_of_the_row() {
        let ctx = egui::Context::default();
        let (mut panel, mut state) = panel_with("*occurrence.Notes\n");
        let store = MemModelStore::new();
        panel.packed = false;
        settle(&ctx, &mut panel, &mut state, &store);
        let cell = *panel
            .hits
            .get(&format!("cell:ACOMP1:{VISIBLE_KEY}"))
            .expect("a visibility cell for the first row");
        click_at(&ctx, &mut panel, &mut state, &store, cell.center());
        assert!(
            !state.scene.solid("ACOMP1:Part").unwrap().visible,
            "the row's member is hidden"
        );
        assert!(
            state.scene.solid("ACOMP2:Part").unwrap().visible,
            "the other instance is untouched"
        );
    }

    /// The BADGES cell carries grounded / outdated / constraint status. The
    /// first instance of a batch is grounded by the insert rule, so ⏚ is the
    /// one badge a bare two-instance document shows.
    #[test]
    fn badges_report_the_grounded_instance() {
        let (_panel, mut state) = panel_with("*occurrence.Notes\n");
        let groups = group(&snapshot(&mut state), false, &by(&[]));
        let grounded = groups.iter().find(|g| g.fixed).expect("one is grounded");
        let glyphs: Vec<String> = badges(grounded)
            .iter()
            .filter_map(|badge| badge.get("glyph").and_then(Value::as_str))
            .map(str::to_string)
            .collect();
        assert!(
            glyphs.contains(&assembly_components::FIXED_GLYPH.to_string()),
            "the grounded row shows ⏚, got {glyphs:?}"
        );
        let free = groups.iter().find(|g| !g.fixed).expect("one is free");
        assert!(badges(free).is_empty(), "a plain instance carries no badge");
    }

    /// PACKED ROLL-UP of the new state: a rolled-up row may only claim what is
    /// true of EVERY placement behind it. Two instances, one grounded, roll up
    /// to NOT grounded — the opposite would let the row show a ⏚ that only
    /// half its placements have.
    #[test]
    fn a_packed_row_is_grounded_only_when_every_placement_is() {
        let (_panel, mut state) = panel_with("*occurrence.Notes\n");
        // The fixture is two `widget` placements plus one `gadget`; the
        // insert rule grounds the FIRST component only.
        let unpacked = group(&snapshot(&mut state), false, &by(&[]));
        assert_eq!(unpacked.len(), 3);
        assert_eq!(
            unpacked.iter().filter(|g| g.fixed).count(),
            1,
            "exactly one instance is grounded"
        );
        let packed = group(&snapshot(&mut state), true, &by(&[]));
        let widget = packed
            .iter()
            .find(|g| g.part_name == "widget")
            .expect("the two widgets roll up");
        assert_eq!(widget.ids.len(), 2, "same part, same fields — one row");
        assert!(!widget.fixed, "not grounded, because not ALL of it is");
        assert!(widget.visible, "all are visible, so the row is");
        assert_eq!(
            widget.solids.len(),
            2,
            "the toggle writes to every member of every placement"
        );
    }

    /// VIEWPORT -> BOM sync: picking a component's solid in the 3D view marks
    /// its BOM row selected, in both views. The row is what the user has to
    /// find, so a packed row stands selected when ANY placement it rolls up is.
    #[test]
    fn a_viewport_pick_marks_the_component_row_selected() {
        let (panel, mut state) = panel_with("*occurrence.Notes\n");
        // Nothing picked: no row claims selection.
        assert!(group(&snapshot(&mut state), false, &by(&[]))
            .iter()
            .all(|group| !group.selected));

        // Pick the SECOND widget's solid, exactly as a viewport click does.
        state.select_components(&["ACOMP2".to_string()]);
        let unpacked = group(&snapshot(&mut state), false, &by(&[]));
        let picked: Vec<&str> = unpacked
            .iter()
            .filter(|group| group.selected)
            .map(|group| group.key.as_str())
            .collect();
        assert_eq!(picked, vec!["ACOMP2"], "that row, and only that row");
        assert!(
            panel.row_for(&state, unpacked.iter().find(|g| g.selected).unwrap()).selected,
            "and the widget row carries it, so the band is drawn"
        );

        // PACKED: the row standing for both widgets is selected, because one of
        // the placements behind it is the one the user picked.
        let packed = group(&snapshot(&mut state), true, &by(&[]));
        let widget = packed.iter().find(|g| g.part_name == "widget").unwrap();
        assert_eq!(widget.ids, vec!["ACOMP1", "ACOMP2"]);
        assert!(widget.selected, "any placement selected selects the row");
        assert!(
            !packed.iter().find(|g| g.part_name == "gadget").unwrap().selected,
            "and an unrelated part's row is left alone"
        );
    }

    /// `packing_fields` reads the LIVE arrangement, not the configuration
    /// text: hiding a column through the header checklist re-packs the table on
    /// the next frame, and part-scoped columns never enter the key (they are
    /// identical across every placement of a part, so they cannot split a row).
    #[test]
    fn packing_fields_follow_the_visible_occurrence_columns() {
        let (mut panel, _state) =
            panel_with("*occurrence.Reference_Designator\n*part.Mass\n*occurrence.Notes\n");
        assert_eq!(
            panel.packing_fields(),
            vec!["Reference_Designator".to_string(), "Notes".to_string()],
            "occurrence columns only, in the arrangement's order"
        );

        panel
            .layout
            .hidden
            .insert("occurrence.Reference_Designator".into());
        assert_eq!(
            panel.packing_fields(),
            vec!["Notes".to_string()],
            "hiding a column drops it from the key"
        );

        // Every occurrence column hidden: placements of one part are one row.
        panel.layout.hidden.insert("occurrence.Notes".into());
        assert!(panel.packing_fields().is_empty());
    }

    /// A BOM lists PARTS, not the bodies inside them. A plain part's chain is
    /// all body leaves, so its row has no children and no collapse box — the
    /// bodies belong to the Scene tree.
    #[test]
    fn body_leaves_are_not_rows_and_a_plain_part_has_no_children() {
        let (panel, mut state) = panel_with("*occurrence.Notes\n");
        let mut groups = group(&snapshot(&mut state), false, &by(&[]));
        // A part holding two bodies and ONE nested sub-assembly, which itself
        // holds a body and a deeper component.
        groups[0].children = vec![
            ChainNode { label: "Body".into(), children: vec![] },
            ChainNode { label: "Rim".into(), children: vec![] },
            ChainNode {
                label: "ACOMP9".into(),
                children: vec![
                    ChainNode { label: "Cap".into(), children: vec![] },
                    ChainNode { label: "ACOMP3".into(), children: vec![] },
                ],
            },
        ];
        let row = panel.row_for(&state, &groups[0]);
        let labels: Vec<&Value> = row
            .children
            .iter()
            .filter_map(|child| child.cells.get(ITEM_KEY))
            .collect();
        assert_eq!(
            labels,
            vec![&Value::String("ACOMP9".into())],
            "the bodies are not rows — only the nested component is"
        );
        assert_eq!(
            row.children[0]
                .children
                .iter()
                .filter_map(|c| c.cells.get(ITEM_KEY))
                .collect::<Vec<_>>(),
            vec![&Value::String("ACOMP3".into())],
            "and the same rule applies at depth"
        );

        // A part with nothing but bodies has no children at all, so the widget
        // draws no collapse box on it.
        groups[0].children = vec![ChainNode { label: "Body".into(), children: vec![] }];
        assert!(panel.row_for(&state, &groups[0]).children.is_empty());
        assert!(
            collapsible_keys(&groups).is_empty(),
            "and it claims no collapse key"
        );
    }

    /// Collapse-all folds EVERY depth, not just the top level.
    #[test]
    fn collapse_all_collects_keys_at_every_depth() {
        let groups = vec![Group {
            key: "G".into(),
            part_name: "sub".into(),
            ids: vec!["ACOMP1".into()],
            attributes: Value::Null,
            selected: false,
            fixed: false,
            outdated: false,
            status: None,
            visible: true,
            solids: vec![],
            children: vec![ChainNode {
                label: "ACOMP9".into(),
                children: vec![ChainNode {
                    label: "ACOMP3".into(),
                    children: vec![
                        ChainNode { label: "ACOMP7".into(), children: vec![] },
                        ChainNode { label: "Body".into(), children: vec![] },
                    ],
                }],
            }],
        }];
        let keys = collapsible_keys(&groups);
        assert!(keys.contains("G"), "the group row");
        assert!(keys.contains("G:ACOMP9"), "the nested component");
        assert!(keys.contains("G:ACOMP9:ACOMP3"), "and the one inside THAT");
        assert!(
            !keys.contains("G:ACOMP9:ACOMP3:ACOMP7"),
            "a component holding no further COMPONENT has nothing to collapse"
        );
        assert!(
            !keys.contains("G:ACOMP9:ACOMP3:Body"),
            "and a body is never a row at all"
        );
    }
}