BREP_app 0.4.0

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
//! 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::automation::hit_keys::HitKeyDoc;
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);

        if crate::automation::registry::enabled() {
            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();
            crate::automation::registry::publish("__brepBom", "BOM groups {key, partName, ids, quantity}", &Value::Array(listing).to_string());
            crate::automation::registry::publish("__brepBomHit", "BOM widget rects (BOM:, cell:)", &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.
    pub fn hits_json(&self) -> String {
        crate::automation::hit_rects::hits_json(&self.hits)
    }
}

/// 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 {
    crate::color::rgb_to_hex([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}")
}

// BREP private tests: 3c26b46ba10327e2

/// The hit keys this panel publishes (see `automation::hit_keys`).
pub static HIT_KEYS: &[HitKeyDoc] = &[
    HitKeyDoc { panel: "bom", prefix: "bom:expand-all", meaning: "expand every group", command: None },
    HitKeyDoc { panel: "bom", prefix: "bom:collapse-all", meaning: "collapse every group", command: None },
    HitKeyDoc { panel: "bom", prefix: "bom:packed", meaning: "packed view", command: None },
    HitKeyDoc { panel: "bom", prefix: "bom:unpacked", meaning: "unpacked view", command: None },
    HitKeyDoc { panel: "bom", prefix: "bom:panel:clip", meaning: "the visible region of the pane", command: None },
    HitKeyDoc { panel: "bom", prefix: "BOM:", meaning: "a row action", command: None },
    HitKeyDoc { panel: "bom", prefix: "cell:", meaning: "a table cell (cell:row:column)", command: Some("bom_set_occurrence_attribute") },
    HitKeyDoc { panel: "bom", prefix: "row:", meaning: "a structure-tree row (row:node key)", command: Some("component_select") },
    HitKeyDoc { panel: "bom", prefix: "box:", meaning: "a structure-tree row's expander (box:node key)", command: None },
    HitKeyDoc { panel: "bom", prefix: "col:", meaning: "a table column header (col:field) — click to sort", command: None },
    HitKeyDoc { panel: "bom", prefix: "grip:", meaning: "a column's resize grip (grip:field)", command: None },
    HitKeyDoc { panel: "bom", prefix: "freeze:divider", meaning: "the frozen-column divider", command: None },
];