1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
//! History panel — a feature **tree** that switches to a full-panel **form**.
//!
//! The panel has exactly two modes ([`PanelMode`]):
//!
//! * **Tree** — one row per feature: `[+/-] id LongName N ms [✎] [✕]`. The
//! collapse box is a PURE ROLL control (roll the model to that step, nothing
//! opens); the `✎` edit button and a plain LABEL CLICK both open that
//! feature's form (and roll to it); rows drag-reorder; `✕` deletes. Built on
//! the reusable [`tree`] node helper (connector lines + `[+]`/`[-]` boxes) the
//! rest of the sidebar reuses.
//! * **Form** — the whole panel is replaced by ONE feature's dialog, drawn by
//! the shared [`crate::form_view`], with a single `Return to tree` button at
//! the bottom. There is no OK/Cancel and no buffer: editing is LIVE and UNDO
//! is the revert mechanism (`History::set_feature_params` checkpoints and
//! coalesces per feature).
//!
//! Both entry points roll the model to the feature, exactly as expanding did;
//! returning to the tree rolls to the TIP so downstream features rebuild and the
//! edit becomes visible.
//!
//! 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: the mode, an in-flight drag, the add-menu toggle,
//! the run-spinner clock, and the per-frame `hits` map (widget screen rects) the
//! headed verifier reads to drive real clicks.
//!
//! The tree also shows HOW FAR the model is built: the rolled-to feature is the
//! last one EXECUTED, so a rollback BAR is drawn under its block, every feature
//! below that bar — not yet executed — is dimmed, and its `[+]`/`[-]` box reads
//! `[-]` down to the rolled-to step and `[+]` below it.
use crate::form_view::{form_view, FormViewSpec};
use crate::palette::{Palette, PaletteItem};
use crate::panels::tree::{self, TreeRow};
use brep_render::engine_state::EngineState;
use brep_render::features;
use eframe::egui;
use serde_json::Value;
use std::collections::HashMap;
/// 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 height of the ROLLBACK BAR row — the horizontal rule painted after the
/// rolled-to feature ("the model is executed up to HERE"). Tall enough to read as
/// a break between the executed block above and the dimmed, not-yet-executed rows
/// below.
const ROLLBACK_BAR_H: f32 = 8.0;
/// How long a run must be in flight before the tree header's spinner appears, in
/// seconds. A single param edit lands in a frame or two, and a spinner that blinks
/// for one frame reads as a glitch — only a run the user actually WAITS on spins.
const RUN_SPINNER_DELAY: f64 = 0.2;
/// 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())
}
/// What the panel is showing: the feature TREE, or ONE feature's FORM filling
/// the whole panel. Exclusive by construction — there is no "expanded feature"
/// inside the tree any more, so there is nothing to reconcile between them.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub enum PanelMode {
/// The feature tree (the resting state).
#[default]
Tree,
/// `feature_id`'s dialog, replacing the whole panel. Falls back to
/// [`PanelMode::Tree`] the moment that id stops resolving (undo, delete,
/// document load) — see the validity guard at the top of
/// [`HistoryPanel::show`].
Form { feature_id: String },
}
impl PanelMode {
/// The open form's feature id, or `None` in tree mode.
fn feature_id(&self) -> Option<&str> {
match self {
PanelMode::Tree => None,
PanelMode::Form { feature_id } => Some(feature_id.as_str()),
}
}
}
/// 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>,
/// Tree, or one feature's full-panel form.
mode: PanelMode,
/// The feature id the panel last AUTO-ARMED a dimension gizmo for (gizmo-on-
/// open). Compared to the OPEN FORM's feature id each frame: on a CHANGE
/// (open a different feature's form, or return to the tree) the panel
/// disarms the old gizmo and arms the dimension gizmo for the newly-opened
/// 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>,
/// 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,
palette_display_loaded: bool,
/// 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)>,
/// The egui clock time (`Input::time`, seconds) at which the CURRENT in-flight
/// run was FIRST seen pending, or `None` when nothing is running. Drives the
/// header spinner's anti-flicker delay ([`RUN_SPINNER_DELAY`]); egui's own
/// clock, not `Instant` (which panics on wasm32).
run_started: Option<f64>,
/// Set when the palette picked the ACOMP type: the insert flow must NOT
/// open a bare feature dialog — the shell polls this
/// ([`Self::take_insert_component_request`]) and opens the COMPONENT
/// SELECTOR (the file dialog's insert mode) instead.
pending_insert_component: bool,
}
impl HistoryPanel {
/// Load once per panel (including document switches), save only user changes.
pub fn sync_palette_display(&mut self, store: &dyn crate::store::ModelStore) {
use crate::store::FEATURE_PALETTE_DISPLAY_KEY;
if !self.palette_display_loaded {
self.palette.display = store.read(FEATURE_PALETTE_DISPLAY_KEY)
.and_then(|json| serde_json::from_str(&json).ok()).unwrap_or_default();
self.palette_display_loaded = true;
}
if self.palette.take_display_change() {
if let Ok(json) = serde_json::to_string(&self.palette.display) {
let _ = store.write(FEATURE_PALETTE_DISPLAY_KEY, &json);
}
}
}
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();
// The panel's VISIBLE region (the enclosing dock pane's scroll viewport).
// Every other rect below is a raw LAYOUT rect: a long feature list — or a
// long form — runs past the pane's bottom, where egui clips it and it
// stops being clickable even though the rect is still published. The
// headed verifier intersects against this to
// know when it must scroll a row into view first — without it a script
// clicks dead space outside the panel and silently no-ops.
self.hits.insert("panel:clip".into(), ui.clip_rect());
// --- validity guard: a form whose SUBJECT is gone falls back, silently.
// One check covers every hazard — undo that removed the feature, a delete
// from another surface, a document load that changed the ids wholesale.
// With no Cancel there is no dirty state to protect, so there is nothing
// to ask the user about (params edits are already committed and undoable).
if let Some(id) = self.mode.feature_id() {
if feature_index_of(state, id).is_none() {
self.mode = PanelMode::Tree;
}
}
// 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;
// --- run-indicator bookkeeping (both modes) ---------------------------
// Tracked in EVERY mode so a run that starts in the form and finishes
// while the tree is up can't strand a stale start time (which would flash
// the spinner on the next tree frame).
let now = ui.input(|i| i.time);
match (state.run_pending(), self.run_started) {
(true, None) => self.run_started = Some(now),
(false, Some(_)) => self.run_started = None,
_ => {}
}
// --- THE MODE SWITCH: the tree, or ONE feature's form -----------------
match self.mode.clone() {
PanelMode::Tree => self.show_tree(ui, state, &report),
PanelMode::Form { feature_id } => self.show_form(ui, state, &report, &feature_id),
}
// --- 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);
}
// --- gizmo-on-open (Phase 1) ------------------------------------------
// Arm the DIMENSION gizmo for the feature whose FORM is open so its
// draggable arrows appear on open (the reported bug), and DISARM on
// return to the tree so gizmos don't leak. Runs only on an open/close
// TRANSITION (the open feature 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 or a schema-declared Transform group.
let open_feature = self.mode.feature_id().map(str::to_string);
if self.gizmo_armed_for != open_feature {
state.disarm_transform();
if let Some(id) = open_feature.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 (Transform/datum/helix/…) →
// 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 = open_feature;
}
}
/// Draw ONE feature's dialog filling the whole panel, through the SHARED
/// [`form_view`]. The panel supplies the schema + the live params and acts on
/// the intents that come back — it is the engine side of a form view that
/// holds no engine itself. Editing is LIVE (every change commits and
/// re-runs); the single bottom button returns to the tree and rolls to the
/// TIP, so downstream features rebuild and the edit becomes visible — the
/// same reason collapsing an inline dialog used to roll to the tip.
fn show_form(
&mut self,
ui: &mut egui::Ui,
state: &mut EngineState,
report: &Value,
id: &str,
) {
// The guard in `show` already proved the id resolves.
let Some(index) = feature_index_of(state, id) else {
return;
};
let ty = state.feature_type_at(index).unwrap_or_else(|| "?".into());
// NO glyph: an egui window title is plain text and cannot hold a widget,
// so it is the one place an icon cannot be drawn as artwork — and with
// no icon font there is nothing else to draw a private-use character
// with. The id and name identify the form; the tree row behind it shows
// the icon.
let title = format!("{id} {}", features::feature_plain_name(&ty));
let fields = features::feature_form_fields(&ty);
let mut params: Value =
serde_json::from_str(&state.feature_params_json(index)).unwrap_or(Value::Null);
// The feature's error shows HERE, as a banner above the fields — and the
// tree row keeps its own error leaf, so a failure is still visible while
// scanning the tree.
let error = feature_error_message(report, id);
let outputs: 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();
let trailing = [("Outputs", outputs)];
let spec = FormViewSpec {
title: &title,
subtitle: None,
fields: &fields,
banner: error.as_deref().map(|m| (m, ERROR_RED)),
trailing: Some(&trailing),
exit_label: "Return to tree",
// A feature LIVES in the rolled history, so leaving its form rolls to
// the tip (Q2). Declared here, acted on below via `out.roll_to_tip`.
rollback: true,
// History shows ONE form at a time, so its field keys stay exactly
// the tree's — `field:sizeX`, `field:boolean.operation` — and every
// verifier field flow keeps working unchanged.
hits_prefix: "",
};
let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
// WHICH feature the form is showing, as a presence-only zero-size rect
// beside the header's real rect (`form:feature`) — the same convention
// `run:spinner` uses for "this is showing right now".
let anchor = self
.hits
.get("form:feature")
.map(|r| r.min)
.unwrap_or(egui::Pos2::ZERO);
self.hits.insert(
format!("form:feature:{id}"),
egui::Rect::from_min_size(anchor, egui::Vec2::ZERO),
);
if out.changed {
let _ = state.update_feature_params(id, ¶ms.to_string());
}
// 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 so no engine mutation happens mid-render.
if let Some(key) = out.button_clicked {
self.pending_button = Some((id.to_string(), key));
}
if let Some(activate) = out.ref_activate {
state.begin_ref_select(
id,
activate.path,
activate.label,
activate.filter,
activate.multiple,
activate.seed,
);
}
if out.exit_clicked {
self.mode = PanelMode::Tree;
}
if out.roll_to_tip {
// Finished editing → 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-edited 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.
//
// The ROLL half is gated by `spec.rollback` (the form view's one-place
// decision), not by an `if self is the history panel` here — a consumer
// with no rollback simply never receives this intent.
state.roll_to(state.history_len().saturating_sub(1));
}
}
/// Draw the feature TREE — one row per feature, the rollback bar, and the
/// add-feature palette.
fn show_tree(&mut self, ui: &mut egui::Ui, state: &mut EngineState, report: &Value) {
// --- run indicator (INTERIM) ------------------------------------------
// A history run is ATOMIC from the app's side — the runner (browser worker /
// native thread) computes the WHOLE history and replies once, so the engine
// can only say "something is running" ([`EngineState::run_pending`]), never
// WHICH feature is executing. So the spinner rides the tree HEADER, not a
// feature row: it is honest about what is actually known. (A true
// per-feature spinner needs a progress channel out of the kernel's execute
// loop — planned, not built.) The shell already repaints every frame while a
// run is pending, so the spinner animates; under the synchronous Inline
// runner `run_pending()` is never true, so nothing ever spins there.
let now = ui.input(|i| i.time);
let spinning = self
.run_started
.is_some_and(|started| now - started >= RUN_SPINNER_DELAY);
// What the runner says it is executing (posted before each feature it
// runs), and the feature a cancelled run was stuck on until the next
// rebuild.
let progress = state.run_progress().cloned();
let cancelled = state.cancelled_run().map(str::to_string);
// --- ROOT: `[-] Features` (always open) -------------------------------
let mut spinner_rect = egui::Rect::NOTHING;
let mut cancel_rect = egui::Rect::NOTHING;
let mut cancel_clicked = false;
tree::node(
ui,
TreeRow {
guides: &[],
is_last: true,
expandable: true,
expanded: true,
root: true,
glyph: None,
label: "Features",
selected: false,
draggable: false,
},
|ui| {
// The row's right-hand slot lays out RIGHT TO LEFT, so the
// first widget sits at the pane's edge: the button goes first,
// where a narrow pane can never push it under the row label.
if spinning {
let cancel = ui.small_button("Cancel").on_hover_text(
"Stop the run. The model keeps the last completed result; \
edit or delete the slow feature to rebuild.",
);
cancel_rect = cancel.rect;
cancel_clicked = cancel.clicked();
spinner_rect = ui.add(egui::Spinner::new().size(12.0)).rect;
if let Some(progress) = &progress {
ui.weak(format!(
"{} · {}/{}",
progress.feature_id,
progress.index + 1,
progress.total
));
}
} else if let Some(cancelled) = &cancelled {
let note = if cancelled.is_empty() {
"run cancelled — the next edit rebuilds".to_string()
} else {
format!("run cancelled at {cancelled} — edit or delete it to rebuild")
};
ui.colored_label(ERROR_RED, note);
}
},
);
// Published only while it SHOWS, so the verifier reads presence, not a rect.
if spinning {
self.hits.insert("run:spinner".into(), spinner_rect);
self.hits.insert("run:cancel".into(), cancel_rect);
}
if cancel_clicked {
state.cancel_run();
}
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;
// The feature whose FORM to open — `(index, id)`. Applied after the draw
// loop, with the roll, so the mode flip and the roll are one step.
let mut open_form: Option<(usize, String)> = 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 ms = report
.get("featureTimings")
.and_then(|m| m.get(&id))
.and_then(Value::as_f64)
.unwrap_or(0.0);
// The feature's glyph goes in the tree's OWN glyph column rather
// than inline in the label, so the icons line up down the tree and
// a catalogued COLOUR icon is drawn as its artwork instead of as a
// one-colour font character (see `tree::node`). `feature_plain_name`
// is `feature_long_name` without the glyph it would prepend.
let glyph = features::feature_icon(&ty).map(String::from);
let label = format!("{id} {}", features::feature_plain_name(&ty));
// Features AFTER the rollback point have NOT been executed: dim the
// WHOLE row — header, timing, edit + delete buttons and the connector
// lines — with egui's own disabled dimming, the app's existing
// "not active" language (see `panels::toolbar_button`). Dimmed, NOT
// disabled: a click on one still rolls the model FORWARD to it.
let pending = i > current;
ui.scope(|ui| {
if pending {
ui.set_opacity(ui.visuals().disabled_alpha());
}
// --- feature header row: [+/-] {glyph} id LongName N ms [✎] [X] --
// The per-type glyph sits in the tree's own glyph column, so it
// is drawn as real COLOUR artwork from the icon catalog rather
// than as a one-colour font character, and the icons line up in
// a column down the tree. See `tree::node`.
//
// The `[+]`/`[-]` box is the BUILT-UP-TO marker: `[-]` down to the
// rolled-to feature, `[+]` on the not-yet-executed ones below it —
// the same boundary the rollback bar and the dimming draw. Clicking
// one MOVES that boundary (a pure roll); nothing expands, because a
// feature's fields no longer live in the tree.
let mut del_rect = egui::Rect::NOTHING;
let mut del_clicked = false;
let mut edit_rect = egui::Rect::NOTHING;
let mut edit_clicked = false;
let resp = tree::node(
ui,
TreeRow::branch(&[], is_last_feature, !pending, &label)
.glyph(glyph.as_deref())
.selected(i == current)
.draggable(true),
|ui| {
// right-to-left: X first (rightmost), then the edit pencil,
// then the timing. Both buttons are `small()` so a third
// control costs the label as little width as possible.
let del = ui.add(
crate::icon_text::icon_button_colored(ui, "✕", Some(DELETE_RED))
.stroke(egui::Stroke::new(1.0, DELETE_RED))
.small(),
);
del_rect = del.rect;
del_clicked = del.clicked();
ui.add_space(4.0);
let edit = ui
.add(crate::icon_text::icon_button(ui, "✎").small())
.on_hover_text("Edit this feature");
edit_rect = edit.rect;
edit_clicked = edit.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);
self.hits.insert(format!("edit:{i}"), edit_rect);
feature_rects.push((i, resp.row_rect));
if del_clicked {
delete = Some(id.clone());
}
// Collapse box → a PURE ROLL to that step (no dialog), so the model
// can be rolled around without opening anything. Edit button OR a
// plain label click → open that feature's form AND roll to it (one
// gesture, two affordances: the button is the discoverable one, the
// label click is the one the hand already does). Drag to ANOTHER row
// → reorder. A drag that ends back on its OWN row is a click that
// egui timed out of the click window — the drag-resolution block
// below routes it here-equivalently (open + roll).
if resp.toggled {
roll = Some(i);
}
if edit_clicked || resp.label.clicked() {
open_form = Some((i, id.clone()));
}
if resp.label.drag_started() {
self.drag_src = Some(i);
}
// --- error node: shown under a FAILING feature, ALWAYS, so a
// failure is visible while SCANNING the tree (the form's banner
// shows the same message to whoever opens the feature), and gone
// the moment the feature runs clean.
if let Some(message) = feature_error_message(report, &id) {
let g = tree::child_guides(&[], is_last_feature);
tree::message_leaf(ui, &g, true, &message, ERROR_RED);
}
});
// --- the EXECUTED-UP-TO boundary --------------------------------
// The rolled-to feature IS executed (a run builds `features[0..=rollback]`
// — see `brep_render::history`; the request's `stopAtId` stops AFTER that
// feature), so the bar goes BELOW its whole block: everything above the
// bar is live, everything below it is dimmed and not yet built. Drawn
// OUTSIDE the dim scope (and at the tip too, where it simply reports that
// the model is built to the end).
if i == current {
let bar = rollback_bar(ui);
self.hits.insert("rollback:bar".into(), bar);
}
}
// --- 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 {
if target == src {
// NOT a reorder — a press that STARTED and ENDED on the
// same row. egui reclassifies a press as a DRAG once it
// outlives `max_click_duration` (0.8 s) or drifts past
// `max_click_dist` (6 pt), so an ordinary human click on
// a label — which routinely lingers or wobbles a few
// pixels — fires `drag_started` and NEVER `clicked`.
// Routing that through the reorder arm below opened the
// feature's dialog but silently dropped the roll (the
// reported "clicking a feature's label doesn't move the
// model" bug), because `drag_move` shadows `roll` in the
// apply chain. A same-slot release IS the label click:
// open that feature's form and roll, exactly like
// `resp.label.clicked()` does. egui never fires both a
// click and a drag for one press, so this can't
// double-roll.
match state.feature_id_at(src) {
Some(id) => open_form = Some((src, id)),
// No id to open a form for — still roll, which is
// the half of the gesture that must never be lost.
None => roll = Some(src),
}
} else {
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() {
// The active workbench TRIMS the creation palette (a UI filter only —
// the history/execution surface is untouched).
let items = feature_palette_items(&state.settings.workbench);
self.palette.open(items, "Add feature", "Search features…");
}
// --- apply deferred engine mutations (one per frame) ------------------
// A reorder does NOT open the moved feature's form: a drag is a
// restructuring gesture, and replacing the whole panel with a dialog
// after one would hide the tree the user was just arranging.
if let Some((src, to)) = drag_move {
self.move_feature(state, src, to);
} else if let Some(id) = delete {
// A deleted feature can't be the open form's subject (the form has no
// delete affordance), and if another surface deletes it the validity
// guard in `show` falls back to the tree next frame.
state.delete_feature(&id);
} else if let Some((i, id)) = open_form {
// Opening ROLLS to that feature, exactly as expanding it used to:
// the dialog and the model it describes must agree.
self.mode = PanelMode::Form { feature_id: id };
state.roll_to(i);
} else if let Some(i) = roll {
state.roll_to(i);
}
// --- 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);
}
/// 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;
}
}
}
/// Open the feature `id`'s FORM — the panel shows one form at a time, so
/// this replaces whatever was open. 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 feature's dialog is up for tweaking on the next frame. If the id
/// does not resolve, the validity guard in [`Self::show`] drops straight back
/// to the tree.
pub fn focus_feature(&mut self, id: String) {
self.mode = PanelMode::Form { feature_id: 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) and returns the panel to the tree (the sketch-mode bar takes
/// over the UI). `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.mode = PanelMode::Tree,
Err(_err) => {
#[cfg(not(target_arch = "wasm32"))]
eprintln!("Edit Sketch failed for '{feature_id}': {_err}");
}
},
_ => {}
}
}
/// 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()
}
/// Whether the palette requested a COMPONENT INSERT this frame (the ACOMP
/// palette entry routes to the component selector, never a bare feature
/// dialog). Consumed by the shell, which opens the file dialog's insert
/// mode.
pub fn take_insert_component_request(&mut self) -> bool {
std::mem::take(&mut self.pending_insert_component)
}
/// 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
/// open the new feature's FORM. Works for ANY registered feature type — the
/// catalogue drives both the palette and the defaults.
///
/// EXCEPTION — `ACOMP` (assembly component): inserting an instance needs a
/// parts-library payload first, so the palette pick surfaces an
/// insert-component REQUEST to the shell (which opens the component
/// selector) instead of appending an empty feature that could only fail.
pub(crate) fn add_feature_of_type(&mut self, state: &mut EngineState, type_code: &str) {
if type_code == "ACOMP" {
self.pending_insert_component = true;
return;
}
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.mode = PanelMode::Form { feature_id: id };
}
}
}
/// The history index of feature `id`, by linear scan over the engine's history.
/// `EngineState` exposes `feature_id_at` but no public `index_of`, and the panel
/// needs one for the form's per-frame validity guard (does the open form's
/// subject still exist?). Small N, once per frame.
fn feature_index_of(state: &EngineState, id: &str) -> Option<usize> {
(0..state.history_len()).find(|i| state.feature_id_at(*i).as_deref() == Some(id))
}
/// Paint the ROLLBACK BAR: a full-width horizontal rule marking the step the model
/// is EXECUTED UP TO. It reuses the drag-reorder insertion indicator's look (a 2 px
/// line in the theme's selection accent — see the drag branch of
/// [`HistoryPanel::show`]) because it says the same thing: "the boundary is HERE".
/// Returns its row rect, which the panel publishes for the headed verifier.
fn rollback_bar(ui: &mut egui::Ui) -> egui::Rect {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width(), ROLLBACK_BAR_H),
egui::Sense::hover(),
);
ui.painter().hline(
rect.x_range(),
rect.center().y,
egui::Stroke::new(2.0, ui.visuals().selection.bg_fill),
);
rect
}
/// 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.
///
/// `workbench` is the active workbench id: only entries that workbench INCLUDES
/// (each workbench classifies off the feature TYPE CODE) are offered. This is a
/// pure UI filter over CREATION — it does not touch the existing history, so a
/// document with sheet-metal features still shows and edits them in Modeling; only
/// the "Add new feature" list is trimmed.
fn feature_palette_items(workbench: &str) -> 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;
}
if !crate::workbench::includes_feature(workbench, ty) {
continue;
}
// `feature_long_name` prepends the glyph; the palette sorts/searches
// on a glyph-stripped key so it stays alphabetical.
let long = features::feature_long_name(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
}
#[cfg(test)]
mod tests {
use super::{feature_error_message, feature_palette_items, HistoryPanel};
use brep_render::engine_state::EngineState;
use eframe::egui;
use std::collections::HashMap;
#[test]
fn palette_display_defaults_and_restores_across_document_panels() {
use crate::palette::PaletteDisplay;
use crate::store::{MemModelStore, ModelStore, FEATURE_PALETTE_DISPLAY_KEY};
let store = MemModelStore::new();
let mut panel = HistoryPanel::new();
panel.sync_palette_display(&store);
assert_eq!(panel.palette.display, PaletteDisplay::LargeIcons);
assert_eq!(store.read(FEATURE_PALETTE_DISPLAY_KEY), None);
store.write(FEATURE_PALETTE_DISPLAY_KEY, "\"compact_multi\"").unwrap();
let mut next_document_panel = HistoryPanel::new();
next_document_panel.sync_palette_display(&store);
assert_eq!(next_document_panel.palette.display, PaletteDisplay::CompactMulti);
store.write(FEATURE_PALETTE_DISPLAY_KEY, "unknown future value").unwrap();
let mut fallback_panel = HistoryPanel::new();
fallback_panel.sync_palette_display(&store);
assert_eq!(fallback_panel.palette.display, PaletteDisplay::LargeIcons);
}
/// Codes offered by the "Add feature" palette for a given workbench.
fn palette_codes(workbench: &str) -> Vec<String> {
feature_palette_items(workbench)
.iter()
.map(|item| item.id.clone())
.collect()
}
#[test]
fn palette_filters_by_active_workbench() {
let all = palette_codes("all");
let modeling = palette_codes("modeling");
let sheet = palette_codes("sheetMetal");
// Modeling: excludes sheet metal, includes a modeling code + the shared
// building blocks S / D / P.
assert!(!modeling.contains(&"SM.TAB".to_string()), "modeling hides SM.TAB: {modeling:?}");
assert!(!modeling.iter().any(|c| c.starts_with("SM.")), "modeling hides all SM.*: {modeling:?}");
for want in ["E", "S", "D", "P"] {
assert!(modeling.contains(&want.to_string()), "modeling includes {want}: {modeling:?}");
}
// Sheet Metal: includes SM.* + the common building blocks, excludes a pure
// modeling code (E).
assert!(sheet.contains(&"SM.TAB".to_string()), "sheet metal includes SM.TAB: {sheet:?}");
for want in ["S", "D", "P"] {
assert!(sheet.contains(&want.to_string()), "sheet metal includes common {want}: {sheet:?}");
}
assert!(!sheet.contains(&"E".to_string()), "sheet metal hides Extrude: {sheet:?}");
// All: the superset — includes everything both others do.
for want in ["SM.TAB", "E", "S", "D", "P"] {
assert!(all.contains(&want.to_string()), "All includes {want}: {all:?}");
}
// An unknown workbench id falls back to Modeling's filtering.
assert_eq!(palette_codes("bogus"), modeling);
}
/// THE INVARIANT: the workbench is a UI filter over CREATION only. It must NOT
/// reduce the history / execution surface — a document that ALREADY contains a
/// sheet-metal feature keeps it in the engine's feature list under Modeling,
/// even though Modeling's creation palette hides SM.* (asserted above).
#[test]
fn workbench_does_not_reduce_history_or_execution() {
use brep_render::engine_state::EngineState;
let mut state = EngineState::new();
state.settings.workbench = "modeling".to_string();
// Append an SM.* feature to the document (default params + a unique id).
let mut params = brep_render::features::feature_default_params("SM.TAB");
if let serde_json::Value::Object(map) = &mut params {
map.insert("id".into(), serde_json::Value::String("SM.TAB1".into()));
}
let feature = serde_json::json!({
"type": "SM.TAB", "inputParams": params, "persistentData": {}
});
state.add_feature(&feature.to_string()).expect("append SM.TAB");
// The feature is in the engine's history regardless of the Modeling
// workbench (whether or not it builds successfully).
assert_eq!(
state.feature_type_at(0).as_deref(),
Some("SM.TAB"),
"SM.TAB stays in history under the Modeling workbench"
);
assert_eq!(state.feature_id_at(0).as_deref(), Some("SM.TAB1"));
assert!(
state.history_listing_json().contains("SM.TAB"),
"the history listing retains SM.TAB under Modeling"
);
// And the Modeling creation palette still hides SM.TAB — filtered UI,
// intact history, in one assertion pair.
assert!(!palette_codes(&state.settings.workbench).contains(&"SM.TAB".to_string()));
}
/// An engine holding `n` cheap cube features, appended through the real
/// add-feature path (so the history, ids and run report are the genuine ones).
/// `add_feature` rolls to the feature it appends, so the tip is `n - 1`.
fn cube_history(n: usize) -> EngineState {
let mut state = EngineState::new();
for _ in 0..n {
let id = state.next_feature_id("Cube");
let mut params = brep_render::features::feature_default_params("P.CU");
if let serde_json::Value::Object(map) = &mut params {
map.insert("id".into(), serde_json::Value::String(id));
}
let feature = serde_json::json!({
"type": "P.CU", "inputParams": params, "persistentData": {}
});
state.add_feature(&feature.to_string()).expect("append P.CU");
}
state
}
/// Draw the REAL panel for one frame on a CONTROLLED clock (`time`, egui
/// seconds) and return the widget rects it published — the same `hits` map the
/// headed verifier reads, so these assert on the shipped signal.
fn panel_hits(
panel: &mut HistoryPanel,
ctx: &egui::Context,
state: &mut EngineState,
time: f64,
) -> HashMap<String, egui::Rect> {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(320.0, 700.0),
)),
time: Some(time),
..Default::default()
};
let _ = ctx.run_ui(raw, |ui| panel.show(ui, state));
panel.hits.clone()
}
/// THE BOUNDARY: a run builds `features[0..=rollback]`, so the rolled-to
/// feature IS executed and the "executed up to here" bar belongs BELOW its row
/// — above the first not-yet-executed one. Asserted at every rollback point,
/// including the tip (where the bar simply trails the last feature).
#[test]
fn rollback_bar_sits_below_the_rolled_to_feature() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
for rolled in 0..3 {
state.roll_to(rolled);
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.0);
let bar = hits["rollback:bar"];
let row = hits[&format!("step:{rolled}")];
assert!(
bar.center().y > row.center().y,
"rolled to {rolled}: that feature IS executed, so the bar is below it"
);
if let Some(next) = hits.get(&format!("step:{}", rolled + 1)) {
assert!(
bar.center().y < next.center().y,
"rolled to {rolled}: the bar is above the first pending feature"
);
}
}
}
/// A dimmed row is DIMMED, not disabled: clicking a not-yet-executed feature
/// must still roll the model FORWARD to it (the click path runs inside the
/// opacity scope, so this guards that the scope changed painting only).
#[test]
fn clicking_a_not_yet_executed_row_rolls_forward_to_it() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
// Learn the rects, then press + release on the LAST (dimmed) feature's label.
let target = panel_hits(&mut panel, &ctx, &mut state, 0.0)["step:2"].center();
for (time, pressed) in [(0.1, true), (0.2, false)] {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(320.0, 700.0),
)),
time: Some(time),
events: vec![
egui::Event::PointerMoved(target),
egui::Event::PointerButton {
pos: target,
button: egui::PointerButton::Primary,
pressed,
modifiers: egui::Modifiers::default(),
},
],
..Default::default()
};
let _ = ctx.run_ui(raw, |ui| panel.show(ui, &mut state));
}
assert_eq!(state.history_rollback(), 2, "the click rolled the model forward");
// The label click also OPENED that feature's form (Q9), so the tree — and
// its rollback bar — are off screen until we return. Returning rolls to the
// TIP, which for this 3-cube history IS feature 2, so the bar must have
// followed the roll to the same boundary.
assert!(
click_key(&mut panel, &ctx, &mut state, "form:return", 0.3),
"the form's return button is published"
);
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.6);
assert_eq!(state.history_rollback(), 2, "returning rolled to the tip");
assert!(hits["rollback:bar"].center().y > hits["step:2"].center().y);
}
/// Feed one raw egui frame at `time`, with the pointer at `pos` and an
/// optional press/release, into the REAL panel. `pressed = None` is a frame
/// with no button event — the button simply stays in whatever state it was.
fn pointer_frame(
panel: &mut HistoryPanel,
ctx: &egui::Context,
state: &mut EngineState,
time: f64,
pos: egui::Pos2,
pressed: Option<bool>,
) {
let mut events = vec![egui::Event::PointerMoved(pos)];
if let Some(pressed) = pressed {
events.push(egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: egui::Modifiers::default(),
});
}
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::pos2(0.0, 0.0),
egui::vec2(320.0, 700.0),
)),
time: Some(time),
events,
..Default::default()
};
let _ = ctx.run_ui(raw, |ui| panel.show(ui, state));
}
/// CRISP-click the centre of the published rect `key` (press + release two
/// frames apart, well inside egui's 0.8 s click window). Returns false when
/// the key is not published this frame.
fn click_key(
panel: &mut HistoryPanel,
ctx: &egui::Context,
state: &mut EngineState,
key: &str,
time: f64,
) -> bool {
let Some(rect) = panel_hits(panel, ctx, state, time).get(key).copied() else {
return false;
};
let c = rect.center();
pointer_frame(panel, ctx, state, time + 0.02, c, Some(true));
pointer_frame(panel, ctx, state, time + 0.05, c, Some(false));
true
}
/// THE REGRESSION (the reported "clicking a feature's label doesn't roll the
/// model" bug): a press on a feature's label that egui classifies as a DRAG
/// rather than a crisp click — held past `max_click_duration` (0.8 s), or
/// drifted past `max_click_dist` (6 pt) — but RELEASED ON ITS OWN ROW is not
/// a reorder. It must open that feature's form AND roll the model, exactly
/// like a quick click. The panel used to route it through the drag-reorder arm,
/// which opened the dialog (so the click clearly registered) but silently
/// dropped the roll, because `drag_move` shadows `roll` in the apply chain.
/// A human's click routinely lingers past 0.8 s or drifts a few pixels — the
/// synthetic clicks in the other tests never do, which is why this only ever
/// showed up when driving the app by hand / in the browser.
#[test]
fn slow_label_press_on_its_own_row_still_rolls() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
let target = panel_hits(&mut panel, &ctx, &mut state, 0.0)["step:2"].center();
// Press, hold past egui's 0.8 s click window (so `drag_started` fires on
// the label), then release on the SAME row.
for (time, pressed) in [(0.1, Some(true)), (1.0, None), (1.5, None), (1.6, Some(false))] {
pointer_frame(&mut panel, &ctx, &mut state, time, target, pressed);
}
assert_eq!(
state.history_rollback(),
2,
"a slow press released on its own row rolls like a click"
);
// …and it opened that feature's FORM, like a click does. (Adapted from the
// old `sub:{id}/Outputs` assertion: the dialog is no longer a set of
// inline tree sub-nodes, so the equivalent signal is the form's own
// "which feature am I showing" marker. The ROLL assertion above — the
// regression this test exists for — is untouched.)
let hits = panel_hits(&mut panel, &ctx, &mut state, 2.0);
let id = state.feature_id_at(2).expect("feature 2 id");
assert!(
hits.contains_key(&format!("form:feature:{id}")),
"the slow press also opened feature 2's form"
);
}
/// The same press, but DRIFTED sideways past egui's 6 pt click distance while
/// staying on its own row — the other way a human click becomes a "drag".
/// Still a click: open + roll.
#[test]
fn drifted_label_press_on_its_own_row_still_rolls() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
let target = panel_hits(&mut panel, &ctx, &mut state, 0.0)["step:2"].center();
pointer_frame(&mut panel, &ctx, &mut state, 0.1, target, Some(true));
for k in 1..=5 {
let drift = egui::pos2(target.x + k as f32 * 2.0, target.y);
pointer_frame(&mut panel, &ctx, &mut state, 0.1 + k as f64 * 0.02, drift, None);
}
let end = egui::pos2(target.x + 10.0, target.y);
pointer_frame(&mut panel, &ctx, &mut state, 0.3, end, Some(false));
assert_eq!(
state.history_rollback(),
2,
"a press that drifted within its own row rolls like a click"
);
}
/// The other half of the invariant: a press that ends on a DIFFERENT row is
/// still a REORDER, not a click — the fix must not disarm drag-to-reorder.
#[test]
fn dragging_a_label_onto_another_row_still_reorders() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
let ids: Vec<String> = (0..3).map(|i| state.feature_id_at(i).unwrap()).collect();
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.0);
let from = hits["step:0"].center();
let to = hits["step:2"].center();
pointer_frame(&mut panel, &ctx, &mut state, 0.1, from, Some(true));
for k in 1..=6 {
let t = k as f32 / 6.0;
let p = egui::pos2(from.x, from.y + (to.y - from.y) * t);
pointer_frame(&mut panel, &ctx, &mut state, 0.1 + k as f64 * 0.05, p, None);
}
pointer_frame(&mut panel, &ctx, &mut state, 0.5, to, Some(false));
assert_eq!(
state.feature_id_at(2).as_deref(),
Some(ids[0].as_str()),
"the dragged feature moved to the drop row"
);
}
// --- the tree ⇄ form mode switch ------------------------------------------
/// Whether the panel is currently showing feature `id`'s form, read off the
/// SHIPPED signal (the published hit map) rather than the private field, so
/// these tests assert exactly what a verifier script can see.
fn form_open_for(hits: &HashMap<String, egui::Rect>, id: &str) -> bool {
hits.contains_key(&format!("form:feature:{id}"))
}
/// THE ENTRY POINT the design depends on: the per-row `✎` button opens that
/// feature's form (replacing the whole panel) AND rolls the model to it, so
/// the dialog and the model it describes agree (Q1).
#[test]
fn edit_button_opens_the_form_and_rolls_to_it() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
let id = state.feature_id_at(2).expect("feature 2 id");
assert!(
click_key(&mut panel, &ctx, &mut state, "edit:2", 0.0),
"every feature row publishes an edit button"
);
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.3);
assert!(form_open_for(&hits, &id), "the edit button opened feature 2's form");
assert_eq!(state.history_rollback(), 2, "opening rolled the model to it");
// R2: the form replaces the WHOLE panel — no tree rows survive behind it.
assert!(!hits.contains_key("step:0"), "the tree is gone in form mode");
assert!(!hits.contains_key("add:menu"), "so is the add button");
assert!(hits.contains_key("form:return"), "and the ONE exit button is there");
}
/// Q9: a plain label click does what the edit button does — enter the form
/// for that feature (and roll). The button is the discoverable affordance,
/// not the only way in; the two must not disagree.
#[test]
fn a_plain_label_click_opens_the_same_form_the_edit_button_does() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
let id = state.feature_id_at(1).expect("feature 1 id");
assert!(click_key(&mut panel, &ctx, &mut state, "step:1", 0.0));
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.3);
assert!(form_open_for(&hits, &id), "the label click opened feature 1's form");
assert_eq!(state.history_rollback(), 1, "and rolled to it");
}
/// THE COLLAPSE BOX is now a PURE ROLL control: it moves the executed-up-to
/// boundary and opens NOTHING, so the model can be rolled around without a
/// dialog taking over the panel. (It is also idempotent — clicking the box of
/// the already-rolled-to feature must not bounce the model to the tip the way
/// collapsing an inline dialog used to.)
#[test]
fn the_collapse_box_rolls_without_opening_a_form() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
assert!(click_key(&mut panel, &ctx, &mut state, "box:2", 0.0));
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.3);
assert_eq!(state.history_rollback(), 2, "the box rolled the model");
assert!(hits.contains_key("step:0"), "…and stayed in the tree");
assert!(
!hits.keys().any(|k| k.starts_with("form:")),
"the box opened no form: {:?}",
hits.keys().filter(|k| k.starts_with("form:")).collect::<Vec<_>>()
);
// Clicking the box of the rolled-to feature is a no-op roll, not a jump.
assert!(click_key(&mut panel, &ctx, &mut state, "box:2", 0.4));
assert_eq!(state.history_rollback(), 2, "re-clicking the same box holds");
}
/// Q2: the ONE bottom button returns to the tree AND rolls to the TIP, so
/// every downstream feature rebuilds and the edit becomes visible — the
/// reason collapsing an inline dialog used to roll to the tip.
#[test]
fn return_button_restores_the_tree_and_rolls_to_the_tip() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
state.roll_to(0);
assert!(click_key(&mut panel, &ctx, &mut state, "edit:0", 0.0));
assert_eq!(state.history_rollback(), 0);
assert!(click_key(&mut panel, &ctx, &mut state, "form:return", 0.3));
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.6);
assert_eq!(state.history_rollback(), 2, "returning rolled to the tip");
for key in ["step:0", "step:1", "step:2", "add:menu"] {
assert!(hits.contains_key(key), "the tree is back ({key})");
}
assert!(!hits.keys().any(|k| k.starts_with("form:")), "and the form is gone");
}
/// THE VALIDITY GUARD: a form whose subject is deleted from another surface
/// falls back to the tree silently — no stale dialog, no "are you sure"
/// (there is no uncommitted state to protect; edits commit live and undo).
#[test]
fn form_falls_back_to_tree_when_the_feature_is_deleted() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
let id = state.feature_id_at(1).expect("feature 1 id");
assert!(click_key(&mut panel, &ctx, &mut state, "edit:1", 0.0));
assert!(form_open_for(&panel_hits(&mut panel, &ctx, &mut state, 0.3), &id));
state.delete_feature(&id);
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.4);
assert!(!form_open_for(&hits, &id), "the deleted feature's form closed");
assert!(hits.contains_key("step:0"), "…back to the tree");
}
/// The same guard, reached the other way: UNDO removes the open feature.
#[test]
fn form_falls_back_to_tree_after_undo_removes_the_feature() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
let id = state.feature_id_at(2).expect("feature 2 id");
assert!(click_key(&mut panel, &ctx, &mut state, "edit:2", 0.0));
assert!(form_open_for(&panel_hits(&mut panel, &ctx, &mut state, 0.3), &id));
let _ = state.undo();
assert_eq!(state.history_len(), 2, "undo really removed the third cube");
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.4);
assert!(!form_open_for(&hits, &id), "the undone feature's form closed");
assert!(hits.contains_key("step:0"), "…back to the tree");
}
/// A press that STARTS on the edit button is consumed by the button, so it
/// never reaches the row label's drag sense: dragging off it must not
/// reorder the history. (The row is `draggable(true)`, so this is the one
/// interaction a third control could plausibly break.)
#[test]
fn pressing_the_edit_button_does_not_start_a_reorder_drag() {
let ctx = egui::Context::default();
let mut state = cube_history(3);
let mut panel = HistoryPanel::new();
let ids: Vec<String> = (0..3).map(|i| state.feature_id_at(i).unwrap()).collect();
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.0);
let from = hits["edit:0"].center();
let to = hits["step:2"].center();
pointer_frame(&mut panel, &ctx, &mut state, 0.1, from, Some(true));
for k in 1..=6 {
let t = k as f32 / 6.0;
let p = egui::pos2(from.x, from.y + (to.y - from.y) * t);
pointer_frame(&mut panel, &ctx, &mut state, 0.1 + k as f64 * 0.05, p, None);
}
pointer_frame(&mut panel, &ctx, &mut state, 0.5, to, Some(false));
let after: Vec<String> = (0..3).map(|i| state.feature_id_at(i).unwrap()).collect();
assert_eq!(after, ids, "a press on the edit button never reorders the history");
}
#[test]
fn opening_transform_feature_arms_shared_gizmo_and_returning_disarms() {
let ctx = egui::Context::default();
let mut state = cube_history(1);
let source = state.feature_id_at(0).unwrap();
let mut params = brep_render::features::feature_default_params("XFORM");
params["id"] = serde_json::json!("Move");
params["solids"] = serde_json::json!([source]);
state.add_feature(&serde_json::json!({"type": "XFORM", "inputParams": params}).to_string()).unwrap();
let mut panel = HistoryPanel::new();
assert!(click_key(&mut panel, &ctx, &mut state, "edit:1", 0.0));
assert!(state.transform_armed_for("Move"));
assert!(state.transform_gizmo_anchor().is_some());
panel_hits(&mut panel, &ctx, &mut state, 0.3);
assert!(state.transform_armed_for("Move"));
assert!(click_key(&mut panel, &ctx, &mut state, "form:return", 0.5));
assert!(!state.transform_armed());
}
/// THE GIZMO RE-KEY (silently breakable, hence this test): the auto-arm is
/// keyed off the OPEN FORM's feature id and fires only on a TRANSITION. So
/// opening a form arms the dimension gizmo ONCE — and a later in-viewport
/// sphere toggle to the transform gizmo must NOT be snapped back to dimension
/// on the next frame — and returning to the tree disarms.
#[test]
fn opening_a_form_arms_the_dimension_gizmo_once_and_returning_disarms() {
let ctx = egui::Context::default();
let mut state = cube_history(2);
let mut panel = HistoryPanel::new();
let id = state.feature_id_at(1).expect("feature 1 id");
assert_ne!(
state.feature_dimension_annotations_json(&id),
"[]",
"precondition: a cube HAS dimension annotations to arm"
);
assert!(click_key(&mut panel, &ctx, &mut state, "edit:1", 0.0));
assert_eq!(
state.dimension_armed_feature(),
id,
"opening the form armed the dimension gizmo for that feature"
);
// The in-viewport orange sphere flips dimension -> transform. The panel
// must leave it there: a per-frame re-arm would clobber the toggle.
state.arm_transform(&id);
assert_eq!(state.dimension_armed_feature(), "", "the toggle took effect");
panel_hits(&mut panel, &ctx, &mut state, 0.3);
panel_hits(&mut panel, &ctx, &mut state, 0.4);
assert_eq!(
state.dimension_armed_feature(),
"",
"no transition, no re-arm — the sphere toggle survives"
);
assert!(click_key(&mut panel, &ctx, &mut state, "form:return", 0.5));
assert_eq!(state.dimension_armed_feature(), "");
assert!(
state.transform_gizmo_anchor().is_none(),
"returning to the tree disarmed both gizmos"
);
}
/// THE VERIFIER CONTRACT: the form publishes the SAME `field:` keys the
/// inline tree did — `verify_history.mjs` drives `field:sizeX` and
/// `field:boolean.operation` by name, so re-keying them would break it
/// silently. Only the way IN changed.
#[test]
fn the_form_publishes_the_same_field_keys_the_inline_tree_did() {
let ctx = egui::Context::default();
let mut state = cube_history(1);
let mut panel = HistoryPanel::new();
assert!(click_key(&mut panel, &ctx, &mut state, "edit:0", 0.0));
let hits = panel_hits(&mut panel, &ctx, &mut state, 0.3);
for key in ["field:sizeX", "field:sizeY", "field:sizeZ"] {
assert!(hits.contains_key(key), "{key} survives the move into the form");
}
assert!(
hits.contains_key("form:section:Transform"),
"the Transform group is a form SECTION now: {:?}",
hits.keys().filter(|k| k.starts_with("form:")).collect::<Vec<_>>()
);
assert!(
!hits.keys().any(|k| k.starts_with("sub:")),
"…and no inline-tree sub-node keys remain"
);
}
/// A runner that ACCEPTS a run and never replies, so `run_pending()` stays true
/// for as many frames as the test wants. The real background runners (native
/// thread / browser worker) finish whenever they finish — not something a
/// timing assertion can stand on.
struct StuckRunner;
impl brep_render::runner::HistoryRunner for StuckRunner {
fn submit_run(&mut self, _request: brep_render::brep_kernel::HistoryRequest, _gen: u64) {}
fn poll_run(&mut self) -> Option<brep_render::runner::RunReply> {
None
}
fn submit_query(&mut self, _query: brep_render::runner::MeasureQuery) {}
fn poll_query(&mut self) -> Option<brep_render::runner::MeasureReply> {
None
}
fn submit_mesh_import(&mut self, _request: brep_render::runner::MeshImportRequest) {}
fn poll_mesh_import(&mut self) -> Option<brep_render::runner::MeshImportReply> {
None
}
fn submit_step_probe(&mut self, _request: brep_render::runner::StepProbeRequest) {}
fn poll_step_probe(&mut self) -> Option<brep_render::runner::StepProbeReply> {
None
}
fn reset(&mut self) {}
}
/// The INTERIM run indicator: the header spinner appears only once a run has
/// been in flight longer than `RUN_SPINNER_DELAY` (a run that lands in a frame
/// or two must not blink), and never when nothing is running.
#[test]
fn header_spinner_waits_out_a_short_run() {
let ctx = egui::Context::default();
let mut state = cube_history(2);
let mut panel = HistoryPanel::new();
// Nothing in flight (the synchronous Inline runner) → no spinner, ever.
assert!(!panel_hits(&mut panel, &ctx, &mut state, 0.0).contains_key("run:spinner"));
// A run that never lands: still silent below the delay, spinning above it.
state.set_runner(Box::new(StuckRunner));
state.roll_to(0);
assert!(state.run_pending(), "the stuck runner keeps the run in flight");
assert!(
!panel_hits(&mut panel, &ctx, &mut state, 1.0).contains_key("run:spinner"),
"the frame a run starts on must not flash the spinner"
);
assert!(
!panel_hits(&mut panel, &ctx, &mut state, 1.1).contains_key("run:spinner"),
"a run shorter than the delay never spins"
);
let hits = panel_hits(&mut panel, &ctx, &mut state, 1.5);
assert!(hits.contains_key("run:spinner"), "a run the user actually waits on spins");
assert!(
hits.contains_key("run:cancel"),
"…and offers Cancel beside the spinner, on the same delay"
);
}
#[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
);
}
}