BREP_app 0.1.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
//! 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
//!
//! 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::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),
    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 `Sketches` group node is collapsed (absent/false = open — it defaults
    /// open so committed sketches are visible in the tree).
    sketches_collapsed: bool,
    /// 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;

        // --- 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 {
            // Group order under the root: solids, then `Sketches`, then
            // `Planes & Datums` (the last child), so nothing "below" is last while a
            // later group 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);
            }
            if has_sketches {
                self.render_sketches(ui, &sketches, &sel_solids, !has_datums, &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::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());
        }
    }

    /// The `Sketches` group node + (when open) one row per committed sketch, each
    /// with 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). Rendered under the solids (before the
    /// `Planes & Datums` group); `is_last` is set only when no datum group follows.
    fn render_sketches(
        &mut self,
        ui: &mut egui::Ui,
        sketches: &[(String, bool)],
        sel_solids: &HashSet<String>,
        is_last: bool,
        action: &mut Option<Action>,
    ) {
        let open = !self.sketches_collapsed;
        let resp = tree::node(
            ui,
            TreeRow::branch(&[], is_last, open, "Sketches"),
            |ui| {
                ui.add_space(6.0);
                ui.label(egui::RichText::new(format!("{}", sketches.len())).weak());
            },
        );
        self.hits.insert("box:__sketches".into(), resp.box_rect);
        if resp.toggled || resp.label.clicked() {
            self.sketches_collapsed = !self.sketches_collapsed;
        }
        if !open {
            return;
        }

        let base = tree::child_guides(&[], is_last);
        let m = sketches.len();
        for (i, (id, visible)) in sketches.iter().enumerate() {
            let last = i + 1 == m;
            let selected = sel_solids.contains(id);
            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, 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.clone(), vis));
            } else if resp.label.clicked() {
                // A committed sketch is a scene solid — select it like any solid.
                *action = Some(Action::Select("solid", id.clone()));
            }
        }
    }

    /// 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()
        .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"
        );
    }
}