BREP_app 0.3.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
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
//! Scene panel — the engine-native **Scene tree** ("Scene Manager"), the second
//! sidebar tree in the design reference. Built on the SAME reusable [`tree`] node
//! helper (connector lines + `[+]`/`[-]` collapse boxes) the history panel uses,
//! so the two trees read as one system.
//!
//! # What it draws
//!
//! Above the tree sits a **type-visibility button row** (`Faces` / `Edges` /
//! `Vertices`, plus `Sketches` / `Planes` when the scene has them): each button
//! hides/shows EVERY object of that type SCENE-WIDE in one click — the missing
//! bulk complement to the per-solid group tristate below. The toggle follows the
//! same rule as the group checkbox + selection-filter toggle-all: if EVERY object
//! of that type is currently visible → hide them all; otherwise (some or all
//! hidden) → show them all. There is deliberately no `Solids` button — the Scene
//! ROOT checkbox already toggles every solid.
//!
//! A file-tree of the engine's display scene:
//!   * `[-] Scene <☑>` — the root; its checkbox toggles ALL solids' visibility.
//!   * per solid `[-] <Name> <☑>` — the checkbox toggles that solid's visibility
//!     through the engine ([`EngineState::set_visible`]); expands to
//!   * `[+] Faces <☑>`, `[+] Edges <☑>`, `[+] Vertices <☑>` — each expands to the
//!     individual entities BY KERNEL NAME (vertices by index/position).
//!
//! # Selection sync (both ways)
//!
//! Clicking an entity row drives the engine's name-based SELECTION
//! ([`EngineState::select_by_name`] / [`select_vertex_by_position`]) so it
//! highlights (emphasis) in the viewport; and the engine's CURRENT selection
//! (`state.emphasis`) bolds the matching tree row — the same emphasis the
//! viewport reads, so a viewport pick lights up the tree and vice-versa.
//!
//! # This panel OWNS NO model state
//!
//! The scene + selection live in the engine ([`EngineState`], the single source
//! of truth). The panel holds only transient UI state: which nodes are expanded
//! and the per-frame `hits` map (widget screen rects) the headed verifier reads.
//! Each frame it snapshots the scene into owned rows FIRST, draws from that, and
//! applies at most one deferred engine mutation after the draw loop (so no borrow
//! of `state` is held across a `&mut` call — the history panel's pattern).
//!
//! # Two deliberate reshapes (functional-over-1:1, per the design doc)
//!
//! * The visibility checkbox is drawn in the row's RIGHT slot: the shared tree
//!   widget reserves the left columns for the collapse box + connector + glyph,
//!   and (per the constraints) it is reused verbatim, not modified. Functionally
//!   identical to the reference's left checkbox.
//! * **Per-entity visibility (live):** the engine now hides individual faces /
//!   edges / vertices and whole groups ([`EngineState::set_entity_visible`] /
//!   [`EngineState::set_group_visible`]). So each Faces/Edges/Vertices group
//!   checkbox is a live TRISTATE (all / some / none of that kind shown) and each
//!   entity leaf carries its own live checkbox — the render pass skips a hidden
//!   entity's triangles / segments / point. The whole-solid + whole-scene
//!   checkboxes still compose: a hidden solid draws nothing; re-showing it keeps
//!   any per-entity hides intact.

use crate::panels::toolbar_button;
use crate::panels::tree::{self, TreeRow};
use brep_render::engine_state::EngineState;
use brep_render::visibility::{EntityKind as VisKind, GroupState};
use eframe::egui;
use std::collections::{HashMap, HashSet};

/// One entity leaf's identity — how a click maps to an engine selection call.
#[derive(Clone)]
enum EntityKind {
    /// Face, selected by kernel name (empty = unnamed → not selectable).
    Face(String),
    /// Edge, selected by kernel name (empty = unnamed → not selectable).
    Edge(String),
    /// Vertex, selected by owning-solid + world position (no kernel name).
    Vertex([f64; 3]),
}

/// One row under a Faces/Edges/Vertices group — a display label, its selection
/// identity, whether it is currently in the engine selection, and whether it is
/// currently VISIBLE in the engine (its live per-entity checkbox state).
#[derive(Clone)]
struct Entity {
    label: String,
    kind: EntityKind,
    selected: bool,
    visible: bool,
}

/// One solid's owned snapshot for the frame (decoupled from `state.scene` so the
/// draw loop can issue deferred `&mut state` mutations afterwards).
struct SolidRow {
    name: String,
    visible: bool,
    selected: bool,
    faces: Vec<Entity>,
    edges: Vec<Entity>,
    vertices: Vec<Entity>,
}

/// A deferred engine mutation, collected during the draw and applied once after
/// the loop (one per frame — the history panel's pattern).
enum Action {
    SetVisible(String, bool),
    SetAllVisible(bool),
    /// Hide/show one entity: `(solid, kind, index-in-kind-list, visible)`.
    SetEntityVisible(String, VisKind, usize, bool),
    /// Hide/show a whole group: `(solid, kind, visible)`.
    SetGroupVisible(String, VisKind, bool),
    /// Hide/show one group KIND across EVERY solid in the scene: `(kind, visible)`.
    SetAllGroupVisible(VisKind, bool),
    /// Hide/show EVERY committed sketch's overlay: `(visible)`.
    SetAllSketchVisible(bool),
    /// Hide/show EVERY construction datum/plane: `(visible)`.
    SetAllDatumVisible(bool),
    Select(&'static str, String),
    SelectVertex(String, [f64; 3]),
    /// Show/hide a committed sketch's persistent overlay: `(feature-id, visible)`.
    SetSketchVisible(String, bool),
    /// Show/hide a construction datum/plane's plane: `(frame-name, visible)`.
    SetDatumVisible(String, bool),
    /// Select a construction datum/plane by frame NAME (a row click).
    SelectDatum(String),
}

/// The Scene tree panel's transient UI state (the scene + selection live in the
/// engine).
#[derive(Default)]
pub struct ScenePanel {
    /// Per-frame egui widget screen rects, published to JS for the headed
    /// verifier. Rebuilt every frame.
    hits: HashMap<String, egui::Rect>,
    /// The Scene ROOT is collapsed (absent/false = open — it defaults open).
    root_collapsed: bool,
    /// Solids explicitly COLLAPSED, by name (absent = open — solids default open,
    /// matching the reference showing a solid's Faces/Edges/Vertices).
    collapsed_solids: HashSet<String>,
    /// Faces/Edges/Vertices group nodes explicitly EXPANDED, keyed
    /// `"<solid>/<group>"` (absent = collapsed — groups default collapsed `[+]`).
    expanded_groups: HashSet<String>,
    /// The `Planes & Datums` group node is collapsed (absent/false = open — it
    /// defaults open so construction datums are visible in the tree).
    datums_collapsed: bool,
}

impl ScenePanel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Draw the Scene tree. Snapshots the scene + current selection into owned
    /// rows, draws them via the shared [`tree`] node helper, then applies at most
    /// one deferred engine mutation.
    pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
        self.hits.clear();

        // --- snapshot scene + selection (owned) so we can mutate after drawing --
        let sel_solids = state.emphasis.selected_solids.clone();
        let sel_faces = state.emphasis.selected_faces.clone();
        let sel_edges = state.emphasis.selected_edges.clone();
        let sel_vertices = state.emphasis.selected_vertices.clone();
        let solids = snapshot(state, &sel_solids, &sel_faces, &sel_edges, &sel_vertices);
        // Committed sketches (id, visible) — listed under the solids in the tree.
        let sketches = state.committed_sketches();
        // Construction datums/planes (name, visible) + which are selected — listed as
        // the tree's LAST group.
        let sel_datums = state.emphasis.selected_datums.clone();
        let datums = state.construction_datums();

        // Tight, tree-like row spacing so connector verticals read continuously.
        ui.spacing_mut().item_spacing.y = 2.0;

        let mut action: Option<Action> = None;

        // --- TYPE-VISIBILITY button row (scene-wide, ABOVE the tree) -----------
        // One button per display TYPE; each hides/shows EVERY object of that type
        // across the whole scene. Same toggle rule as the per-solid group tristate
        // + the selection-filter toggle-all: all-visible → hide all; otherwise
        // (some or all hidden) → show all. Buttons show a "pressed" (selected) look
        // when all of that type are currently visible. There is no `Solids` button
        // — the Scene root checkbox already toggles every solid.
        ui.horizontal(|ui| {
            let has_solids = !solids.is_empty();

            // Faces / Edges / Vertices — scene-wide across ALL solids. All-visible
            // means every solid reports GroupState::All for that kind.
            let groups: [(VisKind, &str, bool); 3] = [
                (
                    VisKind::Face,
                    "Faces",
                    has_solids
                        && solids
                            .iter()
                            .all(|s| matches!(group_state(&s.faces), GroupState::All)),
                ),
                (
                    VisKind::Edge,
                    "Edges",
                    has_solids
                        && solids
                            .iter()
                            .all(|s| matches!(group_state(&s.edges), GroupState::All)),
                ),
                (
                    VisKind::Vertex,
                    "Vertices",
                    has_solids
                        && solids
                            .iter()
                            .all(|s| matches!(group_state(&s.vertices), GroupState::All)),
                ),
            ];
            for (kind, label, all_visible) in groups {
                let tip = if all_visible {
                    format!("Hide all {}", label.to_lowercase())
                } else {
                    format!("Show all {}", label.to_lowercase())
                };
                // Disabled (greyed + non-interactive) with no solids, matching the
                // Scene root checkbox's `add_enabled(!solids.is_empty(), …)` spirit.
                let resp = ui
                    .add_enabled_ui(has_solids, |ui| {
                        toolbar_button::toggle(ui, all_visible, label, &tip)
                    })
                    .inner;
                self.hits.insert(format!("typevis:{label}"), resp.rect);
                if resp.clicked() {
                    action = Some(Action::SetAllGroupVisible(kind, !all_visible));
                }
            }

            // Sketches — shown only when the scene has committed sketches (mirrors
            // `render_sketches` being conditional). All-visible = every sketch shown.
            if !sketches.is_empty() {
                let all_visible = sketches.iter().all(|(_, v)| *v);
                let tip = if all_visible {
                    "Hide all sketches"
                } else {
                    "Show all sketches"
                };
                let resp = toolbar_button::toggle(ui, all_visible, "Sketches", tip);
                self.hits.insert("typevis:Sketches".into(), resp.rect);
                if resp.clicked() {
                    action = Some(Action::SetAllSketchVisible(!all_visible));
                }
            }

            // Planes & Datums — shown only when the scene has construction datums
            // (mirrors `render_datums` being conditional). Hit key is the literal
            // `typevis:Datums` the verifier drives; the button LABEL reads "Planes".
            if !datums.is_empty() {
                let all_visible = datums.iter().all(|(_, v)| *v);
                let tip = if all_visible {
                    "Hide all planes & datums"
                } else {
                    "Show all planes & datums"
                };
                let resp = toolbar_button::toggle(ui, all_visible, "Planes", tip);
                self.hits.insert("typevis:Datums".into(), resp.rect);
                if resp.clicked() {
                    action = Some(Action::SetAllDatumVisible(!all_visible));
                }
            }
        });

        // --- ROOT: `[-] Scene  ☑` (visibility toggles every solid) ------------
        let root_open = !self.root_collapsed;
        let all_visible = !solids.is_empty() && solids.iter().all(|s| s.visible);
        let mut root_vis = all_visible;
        let mut root_vis_rect = egui::Rect::NOTHING;
        let mut root_vis_clicked = false;
        let root_resp = tree::node(
            ui,
            TreeRow {
                guides: &[],
                is_last: true,
                expandable: true,
                expanded: root_open,
                root: true,
                glyph: None,
                label: "Scene",
                selected: false,
                draggable: false,
            },
            |ui| {
                let cb = ui.add_enabled(!solids.is_empty(), egui::Checkbox::new(&mut root_vis, ""));
                root_vis_rect = cb.rect;
                root_vis_clicked = cb.clicked();
            },
        );
        self.hits.insert("box:__scene".into(), root_resp.box_rect);
        self.hits.insert("vis:__scene".into(), root_vis_rect);
        if root_vis_clicked {
            action = Some(Action::SetAllVisible(root_vis));
        }
        if root_resp.toggled || root_resp.label.clicked() {
            self.root_collapsed = !self.root_collapsed;
        }

        if solids.is_empty() && sketches.is_empty() && datums.is_empty() {
            let g = tree::child_guides(&[], true);
            tree::node(ui, TreeRow::leaf(&g, true, "(scene is empty)"), |_| {});
        }

        if root_open {
            // Top-level children under the root, in order: solids, then each committed
            // sketch as its OWN top-level row (no group wrapper — a committed sketch is
            // a scene solid, listed like the solids), then the `Planes & Datums` group
            // (the last child), so nothing "below" is marked last while a later child
            // still follows.
            let has_sketches = !sketches.is_empty();
            let has_datums = !datums.is_empty();
            let n = solids.len();
            for (si, solid) in solids.iter().enumerate() {
                let is_last = !has_sketches && !has_datums && si + 1 == n;
                self.render_solid(ui, solid, is_last, &mut action);
            }
            let m = sketches.len();
            for (i, (id, visible)) in sketches.iter().enumerate() {
                let is_last = !has_datums && i + 1 == m;
                let selected = sel_solids.contains(id);
                self.render_sketch_row(ui, id, *visible, selected, is_last, &mut action);
            }
            if has_datums {
                self.render_datums(ui, &datums, &sel_datums, &mut action);
            }
        }

        // --- apply the one deferred engine mutation ---------------------------
        match action {
            Some(Action::SetVisible(name, v)) => {
                state.set_visible(&name, v);
            }
            Some(Action::SetAllVisible(v)) => {
                for s in &solids {
                    state.set_visible(&s.name, v);
                }
            }
            Some(Action::SetEntityVisible(name, kind, index, v)) => {
                state.set_entity_visible(&name, kind, index, v);
            }
            Some(Action::SetGroupVisible(name, kind, v)) => {
                state.set_group_visible(&name, kind, v);
            }
            Some(Action::SetAllGroupVisible(kind, v)) => {
                for s in &solids {
                    state.set_group_visible(&s.name, kind, v);
                }
            }
            Some(Action::SetAllSketchVisible(v)) => {
                for (id, _) in &sketches {
                    state.set_sketch_visible(id, v);
                }
            }
            Some(Action::SetAllDatumVisible(v)) => {
                for (name, _) in &datums {
                    state.set_datum_visible(name, v);
                }
            }
            Some(Action::Select(kind, name)) => {
                state.select_by_name(kind, &name);
            }
            Some(Action::SelectVertex(solid, pos)) => {
                state.select_vertex_by_position(&solid, pos);
            }
            Some(Action::SetSketchVisible(id, v)) => {
                state.set_sketch_visible(&id, v);
            }
            Some(Action::SetDatumVisible(name, v)) => {
                state.set_datum_visible(&name, v);
            }
            Some(Action::SelectDatum(name)) => {
                state.select_datum(&name);
            }
            None => {}
        }

        // --- verifier hooks (wasm only): scene listing + widget hit-rects ------
        // Published from the panel (not the shared shell) so the headed verifier
        // can assert the tree contents / visibility and drive real clicks, without
        // touching `app.rs`'s shared publish block.
        #[cfg(target_arch = "wasm32")]
        {
            publish("__brepScene", &state.scene_entities_json());
            publish("__brepSketches", &state.sketch_entities_json());
            publish("__brepDatums", &state.datum_entities_json());
            publish("__brepSceneVis", &state.scene_visibility_json());
            publish("__brepSceneHit", &self.hits_json());
        }
    }

    /// One committed sketch as a TOP-LEVEL leaf row (no group wrapper): a
    /// visibility checkbox wired to
    /// [`EngineState::set_sketch_visible`](brep_render::engine_state::EngineState::set_sketch_visible)
    /// and a label that SELECTS the sketch's sheet solid on click (a committed
    /// sketch is a scene solid, dim-cyan / `is_sketch`-styled in the viewport, kept
    /// OUT of the plain-solid rows by the [`snapshot`] filter so it lists exactly
    /// once). Rendered under the solids, before the `Planes & Datums` group;
    /// `is_last` is set only when it is the final top-level child.
    fn render_sketch_row(
        &mut self,
        ui: &mut egui::Ui,
        id: &str,
        visible: bool,
        selected: bool,
        is_last: bool,
        action: &mut Option<Action>,
    ) {
        let mut vis = visible;
        let mut vis_rect = egui::Rect::NOTHING;
        let mut vis_clicked = false;
        let resp = tree::node(
            ui,
            TreeRow::leaf(&[], is_last, id).selected(selected),
            |ui| {
                let cb = ui.add(egui::Checkbox::new(&mut vis, ""));
                vis_rect = cb.rect;
                vis_clicked = cb.clicked();
            },
        );
        self.hits.insert(format!("vis:sketch/{id}"), vis_rect);
        self.hits.insert(format!("sel:sketch/{id}"), resp.label.rect);
        if vis_clicked {
            *action = Some(Action::SetSketchVisible(id.to_string(), vis));
        } else if resp.label.clicked() {
            // A committed sketch is a scene solid — select it like any solid.
            *action = Some(Action::Select("solid", id.to_string()));
        }
    }

    /// The `Planes & Datums` group node + (when open) one row per construction
    /// datum/plane frame, each with a visibility checkbox wired to
    /// [`EngineState::set_datum_visible`](brep_render::engine_state::EngineState::set_datum_visible)
    /// and a label that selects the datum
    /// ([`EngineState::select_datum`](brep_render::engine_state::EngineState::select_datum))
    /// on click. Rendered as the Scene root's LAST child (only when there is at
    /// least one construction datum).
    fn render_datums(
        &mut self,
        ui: &mut egui::Ui,
        datums: &[(String, bool)],
        sel_datums: &HashSet<String>,
        action: &mut Option<Action>,
    ) {
        let open = !self.datums_collapsed;
        let resp = tree::node(
            ui,
            TreeRow::branch(&[], true, open, "Planes & Datums"),
            |ui| {
                ui.add_space(6.0);
                ui.label(egui::RichText::new(format!("{}", datums.len())).weak());
            },
        );
        self.hits.insert("box:__datums".into(), resp.box_rect);
        if resp.toggled || resp.label.clicked() {
            self.datums_collapsed = !self.datums_collapsed;
        }
        if !open {
            return;
        }

        let base = tree::child_guides(&[], true);
        let m = datums.len();
        for (i, (name, visible)) in datums.iter().enumerate() {
            let last = i + 1 == m;
            let selected = sel_datums.contains(name);
            let mut vis = *visible;
            let mut vis_rect = egui::Rect::NOTHING;
            let mut vis_clicked = false;
            let resp = tree::node(
                ui,
                TreeRow::leaf(&base, last, name).selected(selected),
                |ui| {
                    let cb = ui.add(egui::Checkbox::new(&mut vis, ""));
                    vis_rect = cb.rect;
                    vis_clicked = cb.clicked();
                },
            );
            self.hits.insert(format!("vis:datum/{name}"), vis_rect);
            self.hits.insert(format!("sel:datum/{name}"), resp.label.rect);
            if vis_clicked {
                *action = Some(Action::SetDatumVisible(name.clone(), vis));
            } else if resp.label.clicked() {
                *action = Some(Action::SelectDatum(name.clone()));
            }
        }
    }

    /// One solid node + (when open) its Faces / Edges / Vertices groups.
    fn render_solid(
        &mut self,
        ui: &mut egui::Ui,
        solid: &SolidRow,
        is_last: bool,
        action: &mut Option<Action>,
    ) {
        let name = &solid.name;
        let open = !self.collapsed_solids.contains(name);

        let mut vis = solid.visible;
        let mut vis_rect = egui::Rect::NOTHING;
        let mut vis_clicked = false;
        let resp = tree::node(
            ui,
            TreeRow::branch(&[], is_last, open, name).selected(solid.selected),
            |ui| {
                let cb = ui.add(egui::Checkbox::new(&mut vis, ""));
                vis_rect = cb.rect;
                vis_clicked = cb.clicked();
            },
        );
        self.hits.insert(format!("box:{name}"), resp.box_rect);
        self.hits.insert(format!("vis:{name}"), vis_rect);
        self.hits.insert(format!("sel:{name}"), resp.label.rect);

        if vis_clicked {
            *action = Some(Action::SetVisible(name.clone(), vis));
        }
        if resp.toggled {
            if open {
                self.collapsed_solids.insert(name.clone());
            } else {
                self.collapsed_solids.remove(name);
            }
        }
        if resp.label.clicked() {
            *action = Some(Action::Select("solid", name.clone()));
        }

        if open {
            let base = tree::child_guides(&[], is_last);
            self.render_group(ui, name, &base, false, "Faces", VisKind::Face, &solid.faces, action);
            self.render_group(ui, name, &base, false, "Edges", VisKind::Edge, &solid.edges, action);
            self.render_group(ui, name, &base, true, "Vertices", VisKind::Vertex, &solid.vertices, action);
        }
    }

    /// One Faces/Edges/Vertices group node + (when open) its entity leaves. The
    /// group checkbox is a live TRISTATE that hides/shows every entity of `kind`;
    /// each leaf carries its own live checkbox that hides just that entity.
    #[allow(clippy::too_many_arguments)]
    fn render_group(
        &mut self,
        ui: &mut egui::Ui,
        solid_name: &str,
        base: &[bool],
        is_last: bool,
        group: &str,
        kind: VisKind,
        entities: &[Entity],
        action: &mut Option<Action>,
    ) {
        let key = format!("{solid_name}/{group}");
        let open = self.expanded_groups.contains(&key);

        // Tristate over the group's entities (empty group reads All → checked).
        let state = group_state(entities);
        let mut checked = matches!(state, GroupState::All);
        let indeterminate = matches!(state, GroupState::Partial);
        let mut vis_rect = egui::Rect::NOTHING;
        let mut vis_clicked = false;
        let resp = tree::node(
            ui,
            TreeRow::branch(base, is_last, open, group),
            |ui| {
                // right-to-left: the tristate group checkbox (rightmost), then count.
                let cb = ui.add(
                    egui::Checkbox::new(&mut checked, "").indeterminate(indeterminate),
                );
                vis_rect = cb.rect;
                vis_clicked = cb.clicked();
                ui.add_space(6.0);
                ui.label(egui::RichText::new(format!("{}", entities.len())).weak());
            },
        );
        self.hits.insert(format!("box:{key}"), resp.box_rect);
        self.hits.insert(format!("vis:{key}"), vis_rect);
        if vis_clicked {
            // Standard tristate: All → hide all; None/Partial → show all.
            let want_visible = !matches!(state, GroupState::All);
            *action = Some(Action::SetGroupVisible(solid_name.to_string(), kind, want_visible));
        }
        if resp.toggled || resp.label.clicked() {
            if open {
                self.expanded_groups.remove(&key);
            } else {
                self.expanded_groups.insert(key.clone());
            }
        }

        if !open {
            return;
        }
        let gg = tree::child_guides(base, is_last);
        if entities.is_empty() {
            tree::node(ui, TreeRow::leaf(&gg, true, "(none)"), |_| {});
            return;
        }
        let m = entities.len();
        for (ei, e) in entities.iter().enumerate() {
            let last = ei + 1 == m;
            let mut vis = e.visible;
            let mut ev_rect = egui::Rect::NOTHING;
            let mut ev_clicked = false;
            let resp = tree::node(
                ui,
                TreeRow::leaf(&gg, last, &e.label).selected(e.selected),
                |ui| {
                    let cb = ui.add(egui::Checkbox::new(&mut vis, ""));
                    ev_rect = cb.rect;
                    ev_clicked = cb.clicked();
                },
            );
            self.hits.insert(format!("sel:{key}/{ei}"), resp.label.rect);
            self.hits.insert(format!("vis:{key}/{ei}"), ev_rect);
            if ev_clicked {
                *action = Some(Action::SetEntityVisible(solid_name.to_string(), kind, ei, vis));
            } else if resp.label.clicked() {
                *action = Some(match &e.kind {
                    EntityKind::Face(n) => Action::Select("face", n.clone()),
                    EntityKind::Edge(n) => Action::Select("edge", n.clone()),
                    EntityKind::Vertex(p) => Action::SelectVertex(solid_name.to_string(), *p),
                });
            }
        }
    }

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

/// The tristate for a group of entity rows, computed from their live per-entity
/// `visible` flags (the same the engine would report). An empty group reads
/// [`GroupState::All`] — nothing to hide, so the checkbox shows checked.
fn group_state(entities: &[Entity]) -> GroupState {
    if entities.is_empty() {
        return GroupState::All;
    }
    let visible = entities.iter().filter(|e| e.visible).count();
    if visible == entities.len() {
        GroupState::All
    } else if visible == 0 {
        GroupState::None
    } else {
        GroupState::Partial
    }
}

/// Snapshot `state.scene` into owned rows, precomputing each entity's `selected`
/// flag against the current engine selection (cloned in by the caller) and its
/// live per-entity `visible` flag. Face / edge labels fall back to `Face i` /
/// `Edge i` when the kernel left them unnamed; unnamed entities are then not
/// name-selectable (the click is a no-op) but still hideable (by index).
fn snapshot(
    state: &EngineState,
    sel_solids: &HashSet<String>,
    sel_faces: &HashSet<String>,
    sel_edges: &HashSet<String>,
    sel_vertices: &[brep_render::style::VertexRef],
) -> Vec<SolidRow> {
    // Vertex positions are set exactly from the same source; a tiny tolerance
    // guards float round-trips.
    const TOL: f64 = 1e-6;
    state
        .scene
        .solids()
        .iter()
        // Committed-sketch SHEETS are scene solids too, but they list as their OWN
        // top-level sketch rows (`render_sketch_row`, checkbox wired to
        // `set_sketch_visible`) — never as plain solid rows, so they are dropped here
        // and never counted by the root / type-visibility toggles.
        .filter(|s| !s.is_sketch)
        .map(|s| {
            let faces = s
                .faces
                .iter()
                .enumerate()
                .map(|(i, f)| Entity {
                    label: if f.name.is_empty() {
                        format!("Face {i}")
                    } else {
                        f.name.clone()
                    },
                    selected: !f.name.is_empty() && sel_faces.contains(&f.name),
                    visible: s.visibility.is_face_visible(i),
                    kind: EntityKind::Face(f.name.clone()),
                })
                .collect();
            let edges = s
                .edges
                .iter()
                .enumerate()
                .map(|(i, e)| Entity {
                    label: if e.name.is_empty() {
                        format!("Edge {i}")
                    } else {
                        e.name.clone()
                    },
                    selected: !e.name.is_empty() && sel_edges.contains(&e.name),
                    visible: s.visibility.is_edge_visible(i),
                    kind: EntityKind::Edge(e.name.clone()),
                })
                .collect();
            let vertices = s
                .vertices
                .iter()
                .enumerate()
                .map(|(i, v)| Entity {
                    label: format!("Vertex {i}"),
                    selected: sel_vertices.iter().any(|r| {
                        r.solid == s.name
                            && (r.position[0] - v.position[0]).abs() <= TOL
                            && (r.position[1] - v.position[1]).abs() <= TOL
                            && (r.position[2] - v.position[2]).abs() <= TOL
                    }),
                    visible: s.visibility.is_vertex_visible(i),
                    kind: EntityKind::Vertex(v.position),
                })
                .collect();
            SolidRow {
                name: s.name.clone(),
                visible: s.visible,
                selected: sel_solids.contains(&s.name),
                faces,
                edges,
                vertices,
            }
        })
        .collect()
}

/// Mirror an engine 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),
        );
    }
}

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

    /// A one-primitive cube history, name-parameterized — mirrors the fixture the
    /// engine-layer visibility tests use so the solid lands as `name` with 6 faces
    /// / 12 edges / 8 vertices.
    fn cube_history(name: &str) -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": name,
                    "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    /// Run ONE egui frame of the Scene panel headlessly (no window / GPU), feeding
    /// `events` as this frame's input. Layout is deterministic, so widget rects are
    /// stable frame-to-frame and the `hits` map can be read back to drive a real
    /// pointer click at a checkbox's screen rect.
    fn run_frame(
        ctx: &egui::Context,
        panel: &mut ScenePanel,
        state: &mut EngineState,
        events: Vec<egui::Event>,
        scroll: bool,
    ) {
        let raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(800.0, 600.0),
            )),
            events,
            ..Default::default()
        };
        let _ = ctx.run_ui(raw, |ui| {
            // `scroll` wraps the tree in the app's `ScrollArea::vertical()` so the
            // click-routing is exercised under the real sidebar geometry (tree.rs
            // warns right-slot content underlapping the scrollbar can be eaten as a
            // scroll drag), not just on a bare root Ui.
            if scroll {
                egui::ScrollArea::vertical().show(ui, |ui| panel.show(ui, state));
            } else {
                panel.show(ui, state);
            }
        });
    }

    /// Left-click at `pos` split across a press frame and a release frame (egui
    /// fires `clicked()` on release), re-running the panel each frame so the
    /// deferred visibility mutation is applied.
    fn click_at(
        ctx: &egui::Context,
        panel: &mut ScenePanel,
        state: &mut EngineState,
        pos: egui::Pos2,
        scroll: bool,
    ) {
        run_frame(
            ctx,
            panel,
            state,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
            scroll,
        );
        run_frame(
            ctx,
            panel,
            state,
            vec![egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
            scroll,
        );
    }

    /// End-to-end through the real egui widget dispatch: clicking a group's
    /// tristate checkbox in the Scene tree must hide EVERY entity of that kind on
    /// the solid (the deferred `SetGroupVisible` action reaching
    /// `EngineState::set_group_visible`). Faces is the reported-broken case; Edges
    /// is the working control — both are driven so a face-specific regression shows
    /// up as an asymmetry, not a harness artifact.
    fn drive_group_checkbox(kind: VisKind, hit_key: &str, scroll: bool) {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        state.set_history_json(&cube_history("Box")).unwrap();
        let mut panel = ScenePanel::new();

        // Frame 1: lay the tree out (no input) so `hits` holds the checkbox rects.
        run_frame(&ctx, &mut panel, &mut state, vec![], scroll);
        assert_eq!(
            state.group_visibility("Box", kind),
            Some(GroupState::All),
            "precondition: every {kind:?} starts visible"
        );
        let rect = *panel.hits.get(hit_key).unwrap_or_else(|| {
            panic!(
                "missing hit rect {hit_key}; have {:?}",
                panel.hits.keys().collect::<Vec<_>>()
            )
        });

        // Click the group checkbox → all of that kind hidden.
        click_at(&ctx, &mut panel, &mut state, rect.center(), scroll);
        assert_eq!(
            state.group_visibility("Box", kind),
            Some(GroupState::None),
            "clicking the {kind:?} group checkbox must hide the whole group"
        );

        // Click again → all shown (the tristate re-shows a fully-hidden group).
        run_frame(&ctx, &mut panel, &mut state, vec![], scroll);
        let rect = *panel.hits.get(hit_key).expect("checkbox rect after hide");
        click_at(&ctx, &mut panel, &mut state, rect.center(), scroll);
        assert_eq!(
            state.group_visibility("Box", kind),
            Some(GroupState::All),
            "re-clicking the {kind:?} group checkbox must re-show the whole group"
        );
    }

    #[test]
    fn scene_tree_faces_group_checkbox_hides_and_shows_through_egui() {
        drive_group_checkbox(VisKind::Face, "vis:Box/Faces", false);
    }

    #[test]
    fn scene_tree_edges_group_checkbox_hides_and_shows_through_egui() {
        drive_group_checkbox(VisKind::Edge, "vis:Box/Edges", false);
    }

    /// Same as the faces group test, but with the tree wrapped in the app's
    /// `ScrollArea::vertical()` — proves the checkbox click routes correctly under
    /// the real sidebar geometry (not eaten as a scroll drag).
    #[test]
    fn scene_tree_faces_group_checkbox_works_inside_scroll_area() {
        drive_group_checkbox(VisKind::Face, "vis:Box/Faces", true);
    }

    /// An INDIVIDUAL face leaf checkbox (group expanded first) hides just that one
    /// face — the deferred `SetEntityVisible` action reaching
    /// `EngineState::set_entity_visible`. The other reported-broken case alongside
    /// the group toggle.
    #[test]
    fn scene_tree_individual_face_checkbox_hides_one_face_through_egui() {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        state.set_history_json(&cube_history("Box")).unwrap();
        let mut panel = ScenePanel::new();

        // Frame 1: layout → the Faces group's collapse box rect is published.
        run_frame(&ctx, &mut panel, &mut state, vec![], false);
        let box_rect = *panel.hits.get("box:Box/Faces").expect("faces group collapse box");

        // Expand the Faces group (a panel-local toggle) so its leaves render.
        click_at(&ctx, &mut panel, &mut state, box_rect.center(), false);
        run_frame(&ctx, &mut panel, &mut state, vec![], false);
        assert_eq!(
            state.entity_visible("Box", VisKind::Face, 0),
            Some(true),
            "face 0 starts visible"
        );
        let leaf = *panel.hits.get("vis:Box/Faces/0").unwrap_or_else(|| {
            panic!(
                "missing face-0 leaf checkbox; have {:?}",
                panel.hits.keys().collect::<Vec<_>>()
            )
        });

        // Click face 0's checkbox → only face 0 hidden.
        click_at(&ctx, &mut panel, &mut state, leaf.center(), false);
        assert_eq!(
            state.entity_visible("Box", VisKind::Face, 0),
            Some(false),
            "clicking face 0's checkbox must hide exactly face 0"
        );
        assert_eq!(
            state.entity_visible("Box", VisKind::Face, 1),
            Some(true),
            "sibling face 1 stays visible"
        );
        assert_eq!(
            state.group_visibility("Box", VisKind::Face),
            Some(GroupState::Partial),
            "one hidden face → group reads Partial"
        );
    }

    /// A TWO-solid history (two independent cubes) so a scene-wide type button can
    /// be proven to touch EVERY solid, not just one. The cubes are offset in X so
    /// they stay separate solids named `Box1` / `Box2` (each 6 faces / 12 edges /
    /// 8 vertices).
    fn two_cube_history() -> String {
        let cube = |name: &str, x: f64| {
            serde_json::json!({
                "type": "P.CU",
                "inputParams": {
                    "id": name,
                    "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
                    "transform": {
                        "position": [x, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            })
        };
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [cube("Box1", 0.0), cube("Box2", 20.0)]
        })
        .to_string()
    }

    /// End-to-end through real egui widget dispatch: clicking a scene-wide
    /// type-visibility button (above the tree) must hide EVERY solid's group of
    /// that kind (the deferred `SetAllGroupVisible` action looping the scene), then
    /// re-clicking must re-show them all — the same all→hide / otherwise→show rule
    /// the per-solid group tristate uses. Driven across TWO solids so a per-solid
    /// (not scene-wide) regression would surface as `Box2` staying visible.
    fn drive_type_button(kind: VisKind, hit_key: &str) {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        state.set_history_json(&two_cube_history()).unwrap();
        let mut panel = ScenePanel::new();

        // Frame 1: lay the row out so `hits` holds the button rect.
        run_frame(&ctx, &mut panel, &mut state, vec![], false);
        for name in ["Box1", "Box2"] {
            assert_eq!(
                state.group_visibility(name, kind),
                Some(GroupState::All),
                "precondition: every {kind:?} on {name} starts visible"
            );
        }
        let rect = *panel.hits.get(hit_key).unwrap_or_else(|| {
            panic!(
                "missing hit rect {hit_key}; have {:?}",
                panel.hits.keys().collect::<Vec<_>>()
            )
        });

        // Click the type button → that kind hidden on EVERY solid.
        click_at(&ctx, &mut panel, &mut state, rect.center(), false);
        for name in ["Box1", "Box2"] {
            assert_eq!(
                state.group_visibility(name, kind),
                Some(GroupState::None),
                "the scene-wide {kind:?} button must hide {name}'s whole group"
            );
        }

        // Click again → shown everywhere (the button re-shows a fully-hidden type).
        run_frame(&ctx, &mut panel, &mut state, vec![], false);
        let rect = *panel.hits.get(hit_key).expect("button rect after hide");
        click_at(&ctx, &mut panel, &mut state, rect.center(), false);
        for name in ["Box1", "Box2"] {
            assert_eq!(
                state.group_visibility(name, kind),
                Some(GroupState::All),
                "re-clicking the scene-wide {kind:?} button must re-show {name}'s group"
            );
        }
    }

    #[test]
    fn scene_type_faces_button_hides_and_shows_all_solids_through_egui() {
        drive_type_button(VisKind::Face, "typevis:Faces");
    }

    #[test]
    fn scene_type_edges_button_hides_and_shows_all_solids_through_egui() {
        drive_type_button(VisKind::Edge, "typevis:Edges");
    }

    /// The Vertices type button, exercised the same way — the third scene-wide
    /// group kind, to guard against a kind-specific wiring slip.
    #[test]
    fn scene_type_vertices_button_hides_and_shows_all_solids_through_egui() {
        drive_type_button(VisKind::Vertex, "typevis:Vertices");
    }

    /// A cube (real solid) followed by a committed closed-rectangle sketch on the XY
    /// plane. The sketch has no consumer, so it survives as a top-level
    /// committed-sketch row alongside the cube.
    fn cube_and_sketch_history() -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [
                {
                    "type": "P.CU",
                    "inputParams": {
                        "id": "Box",
                        "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
                        "transform": {
                            "position": [0.0, 0.0, 0.0],
                            "rotationEuler": [0.0, 0.0, 0.0],
                            "scale": [1.0, 1.0, 1.0]
                        },
                        "boolean": { "targets": [], "operation": "NONE" }
                    },
                    "persistentData": {}
                },
                {
                    "type": "S",
                    "inputParams": { "id": "Sk" },
                    "persistentData": {
                        "basis": { "origin": [0, 0, 0], "x": [1, 0, 0], "y": [0, 1, 0], "z": [0, 0, 1] },
                        "sketch": {
                            "points": [
                                { "id": 0, "x": 0.0,  "y": 0.0 },
                                { "id": 1, "x": 10.0, "y": 0.0 },
                                { "id": 2, "x": 10.0, "y": 6.0 },
                                { "id": 3, "x": 0.0,  "y": 6.0 }
                            ],
                            "geometries": [
                                { "id": 10, "type": "line", "points": [0, 1] },
                                { "id": 11, "type": "line", "points": [1, 2] },
                                { "id": 12, "type": "line", "points": [2, 3] },
                                { "id": 13, "type": "line", "points": [3, 0] }
                            ],
                            "constraints": []
                        }
                    }
                }
            ]
        })
        .to_string()
    }

    /// A committed sketch lists as a TOP-LEVEL row with its OWN sketch-specific
    /// widgets (`sel:sketch/Sk` + `vis:sketch/Sk`, the latter wired to
    /// `set_sketch_visible`), NOT wrapped in a `Sketches` group node
    /// (`box:__sketches` is gone) and NOT double-listed as a plain solid branch
    /// (`box:Sk` / `vis:Sk` absent — the `snapshot` `is_sketch` filter). The real
    /// cube still lists as its own solid branch (`box:Box`).
    #[test]
    fn committed_sketch_is_a_top_level_row_not_a_group() {
        let ctx = egui::Context::default();
        let mut state = EngineState::new();
        state.set_history_json(&cube_and_sketch_history()).unwrap();
        let mut panel = ScenePanel::new();

        // One layout frame publishes the tree's widget hit-rects.
        run_frame(&ctx, &mut panel, &mut state, vec![], false);
        let keys = || panel.hits.keys().cloned().collect::<Vec<_>>();

        // The sketch is a top-level committed-sketch row with sketch-specific hits.
        assert!(
            panel.hits.contains_key("sel:sketch/Sk"),
            "sketch select row present: {:?}",
            keys()
        );
        assert!(
            panel.hits.contains_key("vis:sketch/Sk"),
            "sketch visibility checkbox present: {:?}",
            keys()
        );
        // No `Sketches` group wrapper node.
        assert!(
            !panel.hits.contains_key("box:__sketches"),
            "no Sketches group node: {:?}",
            keys()
        );
        // Not double-listed as a plain solid row (the snapshot filters is_sketch).
        assert!(
            !panel.hits.contains_key("box:Sk"),
            "sketch is not a plain solid branch: {:?}",
            keys()
        );
        assert!(
            !panel.hits.contains_key("vis:Sk"),
            "sketch is not a plain solid checkbox: {:?}",
            keys()
        );
        // The real solid still lists as its own solid branch.
        assert!(
            panel.hits.contains_key("box:Box"),
            "cube solid branch present: {:?}",
            keys()
        );
    }
}