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
855
856
857
858
859
860
861
862
863
864
865
866
867
//! History panel — the SINGLE integrated **feature tree** (the design reference).
//! Not a tree + a separate dialog: each feature is a tree node, and EXPANDING it
//! reveals its schema fields INLINE beneath it (grouped into Transform / Boolean /
//! Outputs sub-nodes), rendered by the shared form engine. One feature is
//! expanded at a time; expanding rolls the model to that step; features
//! drag-reorder; each has a delete X. Built on the reusable [`tree`] node helper
//! (connector lines + `[+]`/`[-]` collapse boxes) the rest of the sidebar reuses.
//!
//! This panel OWNS NO model state — it calls the ENGINE's history methods
//! (`state.*`) and reads the history + last-run report back to draw. The engine
//! core (`EngineState.history`) is the single source of truth. The panel holds
//! only transient UI state: which feature is expanded, which sub-nodes are
//! collapsed, an in-flight drag, the add-menu toggle, and the per-frame `hits`
//! map (widget screen rects) the headed verifier reads to drive real clicks.

use crate::form;
use crate::palette::{Palette, PaletteItem};
use crate::panels::tree::{self, TreeRow};
use brep_render::engine_state::EngineState;
use brep_render::features;
use brep_render::style::FieldKind;
use eframe::egui;
use serde_json::Value;
use std::collections::{HashMap, HashSet};

/// The red of the per-feature delete affordance (theme-independent — it must read
/// as "destructive" in both light and dark).
const DELETE_RED: egui::Color32 = egui::Color32::from_rgb(0xd8, 0x54, 0x4f);

/// The red of a feature's error message node — a brighter, clearly-legible red for
/// wrapped body text (the delete red is tuned for a small glyph). Matches the
/// hardcoded-chrome-red convention of `DELETE_RED`.
const ERROR_RED: egui::Color32 = egui::Color32::from_rgb(0xff, 0x6b, 0x6b);

/// The error message for feature `id` from the run report's `featureErrors` array,
/// or `None` when that feature ran clean. The kernel records each hard failure as
/// `"<feature id>: <message>"` (see `pipeline::SceneBuildReport`); this matches the
/// `"<id>: "` prefix (the delimiter after the exact id stops a shorter id from
/// matching a longer one) and returns just the message.
fn feature_error_message(report: &serde_json::Value, id: &str) -> Option<String> {
    let prefix = format!("{id}: ");
    report
        .get("featureErrors")?
        .as_array()?
        .iter()
        .filter_map(serde_json::Value::as_str)
        .find(|entry| entry.starts_with(&prefix))
        .map(|entry| entry[prefix.len()..].to_string())
}

/// The history panel's transient UI state (the model lives in the engine).
#[derive(Default)]
pub struct HistoryPanel {
    /// The per-frame map of egui widget screen rects, published to JS for the
    /// headed verifier. Rebuilt every frame.
    hits: HashMap<String, egui::Rect>,
    /// The id of the ONE top-level feature currently expanded (exclusive) — its
    /// fields render inline; expanding another collapses this one.
    expanded: Option<String>,
    /// The feature id the panel last AUTO-ARMED a dimension gizmo for (gizmo-on-
    /// expand). Compared to `expanded` each frame: on a CHANGE (expand a different
    /// feature, or collapse) the panel disarms the old gizmo and arms the dimension
    /// gizmo for the newly-expanded feature IF it has dimensions — once per
    /// transition, so the in-viewport sphere/center toggle (transform↔dimension)
    /// isn't clobbered back to dimension each frame.
    gizmo_armed_for: Option<String>,
    /// Sub-nodes (Transform / Boolean / Outputs) explicitly COLLAPSED, keyed
    /// `"<featureId>/<group>"`. Absent = open (sub-nodes default open, matching
    /// the reference), so a fresh feature shows its groups expanded.
    closed_sub: HashSet<String>,
    /// Reference nodes (e.g. `Tool solids`) explicitly EXPANDED, keyed
    /// `"<featureId>/ref/<path>"`. Present = open (references default COLLAPSED —
    /// the row shows the label + `Select`; expanding reveals the chosen refs as
    /// child nodes). Opposite default of `closed_sub` on purpose.
    open_ref: HashSet<String>,
    /// The feature index currently being drag-reordered (None = not dragging).
    drag_src: Option<usize>,
    /// The reusable searchable command palette that `Add new feature` opens,
    /// populated from the kernel feature catalogue. Generic + engine-agnostic —
    /// this panel drives it and acts on the returned type code.
    palette: Palette,
    /// A schema `button` field click staged this frame — `(feature id, button
    /// key)` — applied AFTER the draw loop (so no engine mutation runs mid-render).
    /// E.g. `editSketch` on a SKETCH feature → `enter_sketch_mode`.
    pending_button: Option<(String, String)>,
}

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

    /// Draw the feature tree. While a reference-selection picker is active the
    /// shell HIDES this whole panel (the design doc's "hide the rest of the UI")
    /// and shows the picker in the top-right mode card ([`super::mode_bar`]), so
    /// this method is not called in that mode.
    pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
        self.hits.clear();

        // Publish the armed transform gizmo's origin in VIEWPORT-LOCAL px (the
        // center handle sits there) so the headed verifier can locate + drag it.
        // Map to page px with `window.__brepView`'s origin (viewport rect).
        if let Some((ax, ay)) = state.transform_gizmo_anchor() {
            self.hits.insert(
                "gizmo-anchor".into(),
                egui::Rect::from_min_size(egui::pos2(ax as f32, ay as f32), egui::Vec2::ZERO),
            );
        }

        // Last-run report → per-feature timing + output solid names (parsed once).
        let report: Value = serde_json::from_str(&state.history_report_json()).unwrap_or(Value::Null);

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

        // --- ROOT: `[-] Features` (always open) -------------------------------
        tree::node(
            ui,
            TreeRow {
                guides: &[],
                is_last: true,
                expandable: true,
                expanded: true,
                root: true,
                glyph: None,
                label: "Features",
                selected: false,
                draggable: false,
            },
            |_| {},
        );

        let len = state.history_len();
        if len == 0 {
            let g = tree::child_guides(&[], true);
            tree::node(ui, TreeRow::leaf(&g, true, "(empty — add a feature)"), |_| {});
        }

        // Deferred engine mutations (applied after the draw loop so no borrow of
        // `self`/`state` is held across them).
        let mut roll: Option<usize> = None;
        let mut delete: Option<String> = None;
        let mut drag_move: Option<(usize, usize)> = None;
        let mut feature_rects: Vec<(usize, egui::Rect)> = Vec::with_capacity(len);

        let current = state.history_rollback();
        for i in 0..len {
            let ty = state.feature_type_at(i).unwrap_or_else(|| "?".into());
            let id = state.feature_id_at(i).unwrap_or_else(|| "(no id)".into());
            let is_last_feature = i + 1 == len;
            let expanded = self.expanded.as_deref() == Some(id.as_str());
            let ms = report
                .get("featureTimings")
                .and_then(|m| m.get(&id))
                .and_then(Value::as_f64)
                .unwrap_or(0.0);
            let label = format!("{id}  {}", features::feature_long_name(&ty));

            // --- feature header row: [+/-] id LongName   N ms   [X] -----------
            // No per-type glyph: features will carry their own icons later.
            let mut del_rect = egui::Rect::NOTHING;
            let mut del_clicked = false;
            let resp = tree::node(
                ui,
                TreeRow::branch(&[], is_last_feature, expanded, &label)
                    .selected(i == current)
                    .draggable(true),
                |ui| {
                    // right-to-left: X first (rightmost), then the timing.
                    let del = ui.add(
                        egui::Button::new(egui::RichText::new("").color(DELETE_RED))
                            .stroke(egui::Stroke::new(1.0, DELETE_RED))
                            .small(),
                    );
                    del_rect = del.rect;
                    del_clicked = del.clicked();
                    ui.add_space(6.0);
                    ui.label(egui::RichText::new(format!("{} ms", ms.round() as i64)).weak());
                },
            );
            self.hits.insert(format!("step:{i}"), resp.label.rect);
            self.hits.insert(format!("box:{i}"), resp.box_rect);
            self.hits.insert(format!("del:{i}"), del_rect);
            feature_rects.push((i, resp.row_rect));

            if del_clicked {
                delete = Some(id.clone());
            }
            // Collapse box → toggle + roll to the TIP on collapse ("done editing");
            // label click → expand (exclusive) + roll; drag → reorder.
            if resp.toggled {
                if expanded {
                    self.expanded = None;
                    // Collapsing = finished editing this feature → return the model
                    // to the tip so the WHOLE history runs and every downstream
                    // feature (e.g. a boolean that consumes this one) reappears and
                    // reflects the edit. Without this the view stays rolled at the
                    // just-collapsed feature and the result never updates — half of
                    // the reported "edit the cylinder, close it, nothing changes"
                    // bug (the other half was the stale cache, fixed in the kernel).
                    // The cache makes this cheap: unchanged features replay instantly.
                    roll = Some(len.saturating_sub(1));
                } else {
                    self.expanded = Some(id.clone());
                    roll = Some(i);
                }
            }
            if resp.label.clicked() {
                if !expanded {
                    self.expanded = Some(id.clone());
                }
                roll = Some(i);
            }
            if resp.label.drag_started() {
                self.drag_src = Some(i);
            }

            // --- inline fields when THIS feature is the expanded one -----------
            let fields_follow = self.expanded.as_deref() == Some(id.as_str());
            let error_message = feature_error_message(&report, &id);
            if fields_follow {
                let base = tree::child_guides(&[], is_last_feature);
                self.render_feature_fields(
                    ui, state, i, &id, &ty, &base, &report, error_message.is_some(),
                );
            }
            // --- error node: shown under a FAILING feature, ALWAYS (even collapsed)
            // so a failure is visible while scanning the tree, and gone the moment
            // the feature runs clean. It renders AFTER the inline fields, so the error
            // is the last child — BELOW the parameters — whether the feature is
            // expanded (fields precede it) or collapsed (it is the only child).
            if let Some(message) = error_message {
                let g = tree::child_guides(&[], is_last_feature);
                tree::message_leaf(ui, &g, true, &message, ERROR_RED);
            }
        }

        // --- resolve an in-flight drag ----------------------------------------
        if let Some(src) = self.drag_src {
            let released = ui.input(|i| i.pointer.any_released());
            let ptr = ui.input(|i| i.pointer.interact_pos());
            match (ptr, released) {
                (Some(p), released) => {
                    let target = feature_rects
                        .iter()
                        .min_by(|a, b| {
                            let da = (a.1.center().y - p.y).abs();
                            let db = (b.1.center().y - p.y).abs();
                            da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
                        })
                        .map(|(idx, _)| *idx)
                        .unwrap_or(src);
                    if released {
                        drag_move = Some((src, target));
                        self.drag_src = None;
                    } else if target != src {
                        // Draw an insertion indicator at the target row edge.
                        if let Some((_, rect)) = feature_rects.iter().find(|(idx, _)| *idx == target)
                        {
                            let y = if target >= src { rect.bottom() } else { rect.top() };
                            ui.painter().hline(
                                rect.x_range(),
                                y,
                                egui::Stroke::new(2.0, ui.visuals().selection.bg_fill),
                            );
                        }
                    }
                }
                (None, true) => self.drag_src = None,
                _ => {}
            }
        }

        // --- Add new feature (full-width) → open the searchable palette -------
        ui.add_space(6.0);
        let add = ui.add_sized(
            [ui.available_width(), 26.0],
            egui::Button::new("Add new feature"),
        );
        self.hits.insert("add:menu".into(), add.rect);
        if add.clicked() {
            self.palette
                .open(feature_palette_items(), "Add feature", "Search features…");
        }

        // --- apply deferred engine mutations (one per frame) ------------------
        if let Some((src, to)) = drag_move {
            self.move_feature(state, src, to);
            if let Some(id) = state.feature_id_at(to) {
                self.expanded = Some(id);
            }
        } else if let Some(id) = delete {
            state.delete_feature(&id);
            if self.expanded.as_deref() == Some(id.as_str()) {
                self.expanded = None;
            }
        } else if let Some(i) = roll {
            state.roll_to(i);
        }

        // --- apply a staged schema-button click (after the draw loop) ----------
        if let Some((fid, key)) = self.pending_button.take() {
            self.handle_feature_button(state, &fid, &key);
        }

        // --- the command palette (a ctx-level modal; drawn last) --------------
        // A pick returns the chosen feature TYPE CODE; add that feature to the
        // engine-owned history with schema-derived defaults + a unique id.
        let ctx = ui.ctx().clone();
        if let Some(type_code) = self.palette.show(&ctx) {
            self.add_feature_of_type(state, &type_code);
        }
        // Republish the palette's widget rects (prefixed) so the headed verifier
        // can locate + drive the modal without the app shell knowing about it.
        let palette_hits: Vec<(String, egui::Rect)> = self
            .palette
            .hits()
            .iter()
            .map(|(k, r)| (format!("palette:{k}"), *r))
            .collect();
        self.hits.extend(palette_hits);

        // --- gizmo-on-expand (Phase 1) ---------------------------------------
        // Arm the DIMENSION gizmo for the expanded feature so its draggable arrows
        // appear on expand (the reported bug), and DISARM on collapse so gizmos
        // don't leak. Runs only on an expand/collapse TRANSITION (expanded changed
        // since last frame) so it never thrashes per frame — that lets the
        // in-viewport sphere/center toggle flip a feature to transform mode and STAY
        // there (a per-frame re-arm would snap it back to dimension). Guarded on the
        // feature actually having dimension annotations, so types without a builder
        // stay armless.
        if self.gizmo_armed_for != self.expanded {
            state.disarm_transform();
            if let Some(id) = self.expanded.clone() {
                if state.feature_dimension_annotations_json(&id) != "[]" {
                    // Has dimensions → dimension arrows (sphere-toggle to transform).
                    state.arm_dimension(&id);
                } else if state.feature_has_transform(&id) {
                    // No dimensions but transformable (datum/helix/pattern/port) →
                    // arm the TRANSFORM gizmo directly, so it isn't stranded without
                    // a gizmo now that the ◎ arm button is gone.
                    state.arm_transform(&id);
                }
            }
            self.gizmo_armed_for = self.expanded.clone();
        }
    }

    /// Render one expanded feature's schema fields INLINE as tree children:
    /// direct `Parameters` leaves (scalars — the read-only `id` is already in the
    /// header, so it is skipped), then each other group (`Transform`, `Boolean`…)
    /// as a collapsible sub-node, then a read-only `Outputs` sub-node listing the
    /// feature's output solid name(s). The `References` group is NOT drawn as a
    /// wrapper node — a `reference_selection` field is already a self-titled,
    /// expandable node (label + `Select` + value rows), so each such field renders
    /// as its OWN direct child instead (the redundant "References" nesting is
    /// eliminated — one less level to dig through for every feature that uses a
    /// reference-selection widget). Editing any field commits the whole param
    /// buffer once → the engine re-runs live.
    fn render_feature_fields(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        index: usize,
        id: &str,
        ty: &str,
        base_guides: &[bool],
        report: &Value,
        error_follows: bool,
    ) {
        let mut params: Value =
            serde_json::from_str(&state.feature_params_json(index)).unwrap_or(Value::Null);
        let fields = features::feature_form_fields(ty);

        // Partition: direct `Parameters` leaves vs the other groups, in order.
        let mut param_leaves: Vec<&brep_render::style::FormField> = Vec::new();
        let mut groups: Vec<(String, Vec<&brep_render::style::FormField>)> = Vec::new();
        for f in &fields {
            if f.group == "Parameters" {
                if matches!(f.kind, FieldKind::Text { read_only: true }) {
                    continue; // the id — shown in the header
                }
                param_leaves.push(f);
            } else if let Some(g) = groups.iter_mut().find(|(n, _)| *n == f.group) {
                g.1.push(f);
            } else {
                groups.push((f.group.clone(), vec![f]));
            }
        }

        // Total children = direct leaves + the Outputs sub-node + one node per
        // group, EXCEPT the `References` group, whose fields each render as their
        // own direct child (no wrapper), so it counts once per field. When an error
        // node follows these fields (a failing, expanded feature), count it too so
        // the last real child draws `├` and the feature-column guide continues down
        // to the trailing error node instead of terminating at the Outputs row.
        let total = param_leaves.len()
            + groups
                .iter()
                .map(|(gname, gfields)| if gname == "References" { gfields.len() } else { 1 })
                .sum::<usize>()
            + 1
            + usize::from(error_follows);
        let mut child_idx = 0usize;
        let mut changed = false;

        // (1) direct parameter leaves
        for f in &param_leaves {
            let is_last = child_idx + 1 == total;
            child_idx += 1;
            changed |= self.schema_field(ui, state, f, &mut params, id, base_guides, is_last);
        }

        // (2) group sub-nodes (Transform / Boolean / …)
        for (gname, gfields) in &groups {
            // The `References` group is inlined: each `reference_selection` field
            // is already a self-titled expandable node ([`Self::reference_node`],
            // carrying its own `Select` button + value rows), so it renders as a
            // DIRECT child of the feature — the old "References" wrapper node is
            // gone. `schema_field` routes Reference kinds to `reference_node`, so
            // Select / picking / clearing are untouched; only the nesting changed.
            if gname == "References" {
                for f in gfields {
                    let is_last = child_idx + 1 == total;
                    child_idx += 1;
                    changed |= self.schema_field(ui, state, f, &mut params, id, base_guides, is_last);
                }
                continue;
            }

            let is_last = child_idx + 1 == total;
            child_idx += 1;
            let key = format!("{id}/{gname}");
            let open = !self.closed_sub.contains(&key);

            // Hoist a group's LEADING enum onto the group node row (e.g. Boolean's
            // `operation` renders as `[-] Boolean  [UNION ▾]`) instead of a child
            // row. The Transform group is a plain expandable node now — its gizmo is
            // driven ENTIRELY by expanding the feature (auto-arm dimension) plus the
            // in-viewport orange sphere/center toggle, so it carries no button.
            let hoist_enum: Option<&brep_render::style::FormField> = gfields
                .first()
                .copied()
                .filter(|f| matches!(f.kind, FieldKind::Enum { .. }));

            let mut enum_changed = false;
            let mut enum_rect = egui::Rect::NOTHING;
            let mut enum_probe: HashMap<String, egui::Rect> = HashMap::new();
            let resp = tree::node(
                ui,
                TreeRow::branch(base_guides, is_last, open, gname),
                |ui| {
                    if let Some(f) = hoist_enum {
                        // A hoisted group leader is always an Enum, never a button.
                        let (ch, r) = form::field_input(
                            ui,
                            f,
                            &mut params,
                            Some(&mut enum_probe),
                            None,
                            &mut None,
                        );
                        enum_changed = ch;
                        enum_rect = r;
                    }
                },
            );
            self.hits.insert(format!("sub:{key}"), resp.box_rect);
            if let Some(f) = hoist_enum {
                self.hits.insert(format!("field:{}", f.path.join(".")), enum_rect);
                for (k, r) in enum_probe.drain() {
                    self.hits.insert(format!("field:{k}"), r);
                }
            }
            changed |= enum_changed;
            if resp.toggled || resp.label.clicked() {
                if open {
                    self.closed_sub.insert(key.clone());
                } else {
                    self.closed_sub.remove(&key);
                }
            }
            if !self.closed_sub.contains(&key) {
                let gg = tree::child_guides(base_guides, is_last);
                // Skip the leading enum when it was hoisted onto the group row.
                let start = usize::from(hoist_enum.is_some());
                let child_fields = &gfields[start..];
                let n = child_fields.len();
                for (fi, f) in child_fields.iter().enumerate() {
                    changed |= self.schema_field(ui, state, f, &mut params, id, &gg, fi + 1 == n);
                }
            }
        }

        // (3) read-only Outputs sub-node
        {
            let is_last = child_idx + 1 == total;
            let key = format!("{id}/Outputs");
            let open = !self.closed_sub.contains(&key);
            let resp = tree::node(ui, TreeRow::branch(base_guides, is_last, open, "Outputs"), |_| {});
            self.hits.insert(format!("sub:{key}"), resp.box_rect);
            if resp.toggled || resp.label.clicked() {
                if open {
                    self.closed_sub.insert(key.clone());
                } else {
                    self.closed_sub.remove(&key);
                }
            }
            if !self.closed_sub.contains(&key) {
                let gg = tree::child_guides(base_guides, is_last);
                let names: Vec<String> = report
                    .get("featureOutputs")
                    .and_then(|m| m.get(id))
                    .and_then(Value::as_array)
                    .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
                    .unwrap_or_default();
                if names.is_empty() {
                    tree::node(ui, TreeRow::leaf(&gg, true, "(none)"), |_| {});
                } else {
                    let n = names.len();
                    for (ni, name) in names.iter().enumerate() {
                        tree::node(ui, TreeRow::leaf(&gg, ni + 1 == n, name), |_| {});
                    }
                }
            }
        }

        if changed {
            let _ = state.update_feature_params(id, &params.to_string());
        }
    }

    /// Render one schema field as a tree child. A reference field is its own
    /// EXPANDABLE tree node ([`Self::reference_node`]); every other kind is a
    /// leaf row — `label` (the tree node) + the input widget right-aligned.
    fn schema_field(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        field: &brep_render::style::FormField,
        params: &mut Value,
        feature_id: &str,
        guides: &[bool],
        is_last: bool,
    ) -> bool {
        if matches!(field.kind, FieldKind::Reference { .. }) {
            return self.reference_node(ui, state, field, params, feature_id, guides, is_last);
        }
        let mut probe = HashMap::new();
        let mut changed = false;
        let mut rect = egui::Rect::NOTHING;
        let mut clicked: Option<String> = None;
        tree::node(ui, TreeRow::leaf(guides, is_last, &field.label), |ui| {
            // The tree row's content area is RIGHT-aligned (`right_to_left`), so the
            // input sits at the panel edge with the label on the left. A Vec3 reverses
            // its own components (see `form::field_input`) so they still read x, y, z
            // despite the right-to-left placement. Scope the widget id-stack to THIS
            // (feature, field) so a Scalar's per-location egui-memory edit buffer (+
            // TextEdit focus id) can't collide when two expanded features share a
            // param name (two extrudes → `distance`); `make_persistent_id` folds in
            // the ui id-stack only, so without this the buffers would merge.
            ui.push_id((feature_id, field.key()), |ui| {
                let (ch, r) =
                    form::field_input(ui, field, params, Some(&mut probe), None, &mut clicked);
                changed = ch;
                rect = r;
            });
        });
        self.hits.insert(format!("field:{}", field.path.join(".")), rect);
        for (k, r) in probe {
            self.hits.insert(format!("field:{k}"), r);
        }
        // A button click (e.g. `editSketch`) binds to no param — stage it as a
        // deferred action keyed by (feature id, button key); `show` acts after the
        // draw loop so no engine mutation happens mid-render.
        if let Some(key) = clicked {
            self.pending_button = Some((feature_id.to_string(), key));
        }
        changed
    }

    /// The engine-native reference field as an EXPANDABLE tree node. The node row
    /// is `[+/-] <label>  [▣ Select …]` — the label + the `Select` activation
    /// button (right-aligned via `add_right`); EXPANDING it lists the chosen refs
    /// as one CHILD node each (`• <name> [×]`, removable via its `×`). `Select`
    /// enters the engine's modal picking mode (`begin_ref_select`, which rolls to
    /// the pre-feature before-state and lights up the seed); only this RESTING
    /// rendering changed from the old inline block. References default COLLAPSED.
    fn reference_node(
        &mut self,
        ui: &mut egui::Ui,
        state: &mut EngineState,
        field: &brep_render::style::FormField,
        params: &mut Value,
        feature_id: &str,
        guides: &[bool],
        is_last: bool,
    ) -> bool {
        let (filter, multiple) = match &field.kind {
            FieldKind::Reference { filter, multiple } => (filter.clone(), *multiple),
            _ => return false,
        };
        let path = field.path.clone();
        let pkey = path.join(".");
        let key = format!("{feature_id}/ref/{pkey}");
        let open = self.open_ref.contains(&key);
        let names = form::reference_names(form::value_at(params, &path));

        // --- the reference node row: [+/-] <label>   ▣ Select (…) -------------
        let mut activate = false;
        let mut activate_rect = egui::Rect::NOTHING;
        let resp = tree::node(
            ui,
            TreeRow::branch(guides, is_last, open, &field.label),
            |ui| {
                // A COMPACT `Select` on the node row (the filter/multiplicity is
                // shown by the picker prompt) so it never overlaps the node label.
                let btn = ui.button("▣ Select");
                activate_rect = btn.rect;
                activate = btn.clicked();
            },
        );
        self.hits.insert(format!("sub:{key}"), resp.box_rect);
        self.hits.insert(format!("field:{pkey}#box"), resp.box_rect);
        self.hits.insert(format!("field:{pkey}#activate"), activate_rect);
        if resp.toggled || resp.label.clicked() {
            if open {
                self.open_ref.remove(&key);
            } else {
                self.open_ref.insert(key.clone());
            }
        }
        if activate {
            state.begin_ref_select(
                feature_id,
                path.clone(),
                field.label.clone(),
                filter.clone(),
                multiple,
                names.clone(),
            );
        }

        // --- children: one node per chosen ref (• <name> [×]) -----------------
        let mut changed = false;
        if open {
            let gg = tree::child_guides(guides, is_last);
            if names.is_empty() {
                tree::node(ui, TreeRow::leaf(&gg, true, "(none)"), |_| {});
            } else {
                let n = names.len();
                let mut removed = None;
                for (i, name) in names.iter().enumerate() {
                    let bullet = format!("{name}");
                    let mut x_rect = egui::Rect::NOTHING;
                    let mut x_clicked = false;
                    tree::node(ui, TreeRow::leaf(&gg, i + 1 == n, &bullet), |ui| {
                        let x = ui.add(
                            egui::Button::new(egui::RichText::new("").color(DELETE_RED))
                                .stroke(egui::Stroke::new(1.0, DELETE_RED))
                                .small(),
                        );
                        x_rect = x.rect;
                        x_clicked = x.clicked();
                    });
                    self.hits.insert(format!("field:{pkey}#x{i}"), x_rect);
                    if x_clicked {
                        removed = Some(i);
                    }
                }
                if let Some(i) = removed {
                    let mut kept = names.clone();
                    kept.remove(i);
                    let value = if multiple {
                        Value::Array(kept.into_iter().map(Value::String).collect())
                    } else {
                        Value::String(kept.first().cloned().unwrap_or_default())
                    };
                    form::set_at(params, &path, value);
                    changed = true;
                }
            }
        }
        changed
    }

    /// Move feature `from` to slot `to` via the engine's adjacent-swap reorder
    /// (each swap re-runs the truncated history — small N, and the ONE reorder
    /// primitive the engine exposes).
    fn move_feature(&mut self, state: &mut EngineState, from: usize, to: usize) {
        if from == to {
            return;
        }
        let mut cur = from;
        if to > from {
            while cur < to {
                state.reorder_feature(cur, false);
                cur += 1;
            }
        } else {
            while cur > to {
                state.reorder_feature(cur, true);
                cur -= 1;
            }
        }
    }

    /// Expand (open the inline dialog of) the feature `id` — the ONE top-level
    /// feature shown expanded is exclusive, so this replaces any current one. The
    /// context action bar calls this via the shell after creating a feature from
    /// the selection or opening a selection's owning feature (both of which also
    /// rolled the model to that step), so the target node's dialog is open for
    /// tweaking on the next frame.
    pub fn focus_feature(&mut self, id: String) {
        self.expanded = Some(id);
    }

    /// Act on a schema `button` field click on a feature. `editSketch` on a SKETCH
    /// feature opens the engine-native sketcher on THAT feature (roll-to-before +
    /// plane orient, per S1) and collapses the tree (the sketch-mode bar takes over
    /// the UI); `dumpSketchDiagnostics` logs the feature's sketch + solved
    /// diagnostics for debugging. `enter_sketch_mode` guards the feature is a
    /// sketch, so a stray click on a non-sketch is a harmless no-op.
    fn handle_feature_button(&mut self, state: &mut EngineState, feature_id: &str, key: &str) {
        match key {
            "editSketch" => match state.enter_sketch_mode(feature_id) {
                Ok(_) => self.expanded = None,
                Err(_err) => {
                    #[cfg(not(target_arch = "wasm32"))]
                    eprintln!("Edit Sketch failed for '{feature_id}': {_err}");
                }
            },
            "dumpSketchDiagnostics" => {
                let dump = state.sketch_diagnostics_dump_json(feature_id);
                log_sketch_dump(feature_id, &dump);
            }
            _ => {}
        }
    }

    /// 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, Value> = self
            .hits
            .iter()
            .map(|(k, r)| {
                (
                    k.clone(),
                    serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]),
                )
            })
            .collect();
        Value::Object(map).to_string()
    }

    /// Append a feature of type `type_code` to the engine-owned history: build a
    /// fresh descriptor whose `inputParams` are the schema DEFAULTS
    /// ([`features::feature_default_params`]) with an engine-unique `id` assigned,
    /// hand it to `EngineState::add_feature` (which appends + rolls to it), and
    /// expand the new node. Works for ANY registered feature type — the catalogue
    /// drives both the palette and the defaults.
    fn add_feature_of_type(&mut self, state: &mut EngineState, type_code: &str) {
        let id = state.next_feature_id(&features::feature_short_name(type_code));
        let mut params = features::feature_default_params(type_code);
        if let Value::Object(map) = &mut params {
            map.insert("id".into(), Value::String(id.clone()));
        }
        let feature = serde_json::json!({
            "type": type_code, "inputParams": params, "persistentData": {}
        });
        if state.add_feature(&feature.to_string()).is_ok() {
            self.expanded = Some(id);
        }
    }

}

/// Build one [`PaletteItem`] per registered feature from the kernel catalogue:
/// `id` = the feature TYPE CODE (e.g. `P.CU`), `label` = its long name (e.g.
/// `Primitive Cube`), `keywords` = the type code + short name (aliases the user
/// might type). The palette sorts them alphabetically by label on open.
fn feature_palette_items() -> Vec<PaletteItem> {
    let catalogue = features::feature_catalogue();
    let mut items = Vec::new();
    if let Some(list) = catalogue.get("features").and_then(Value::as_array) {
        for feature in list {
            let ty = feature.get("type").and_then(Value::as_str).unwrap_or("");
            if ty.is_empty() {
                continue;
            }
            let long = feature.get("longName").and_then(Value::as_str).unwrap_or(ty);
            let short = feature.get("shortName").and_then(Value::as_str).unwrap_or(ty);
            let mut keywords = vec![ty.to_string()];
            if short != ty {
                keywords.push(short.to_string());
            }
            items.push(PaletteItem::new(ty, long, keywords));
        }
    }
    items
}

/// Surface a `dumpSketchDiagnostics` payload for debugging: on the browser build it
/// is mirrored to `window.__brepSketchDump` (verifier-visible, like the other
/// `publish_to_js` mirrors); natively it prints to stderr. Intentionally lean — the
/// button is a debug affordance, not a shipped download flow.
fn log_sketch_dump(feature_id: &str, dump: &str) {
    #[cfg(target_arch = "wasm32")]
    {
        let _ = feature_id;
        if let Some(win) = web_sys::window() {
            let _ = js_sys::Reflect::set(
                &win,
                &wasm_bindgen::JsValue::from_str("__brepSketchDump"),
                &wasm_bindgen::JsValue::from_str(dump),
            );
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        eprintln!("sketch diagnostics [{feature_id}]: {dump}");
    }
}

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

    #[test]
    fn error_message_matches_by_exact_id_prefix() {
        let report = serde_json::json!({
            "featureErrors": [
                "Box: makeBoxSolid: sizes must be positive",
                "R6: boolean UNION failed: invalid topology"
            ]
        });
        // The `"<id>: "` prefix is stripped, the (colon-bearing) message is kept.
        assert_eq!(
            feature_error_message(&report, "Box").as_deref(),
            Some("makeBoxSolid: sizes must be positive")
        );
        assert_eq!(
            feature_error_message(&report, "R6").as_deref(),
            Some("boolean UNION failed: invalid topology")
        );
        // A feature that ran clean has no entry.
        assert_eq!(feature_error_message(&report, "Pin"), None);
    }

    #[test]
    fn shorter_id_does_not_match_a_longer_ids_error() {
        // "R6" must NOT pick up "R60"'s error — the ": " delimiter guards the prefix.
        let report = serde_json::json!({ "featureErrors": ["R60: boom"] });
        assert_eq!(feature_error_message(&report, "R6"), None);
        assert_eq!(feature_error_message(&report, "R60").as_deref(), Some("boom"));
    }

    #[test]
    fn missing_or_empty_errors_yield_none() {
        assert_eq!(feature_error_message(&serde_json::json!({}), "Box"), None);
        assert_eq!(
            feature_error_message(&serde_json::json!({ "featureErrors": [] }), "Box"),
            None
        );
    }
}