brep_app/form.rs
1//! The generic, schema-driven egui form engine — ONE per-field renderer for BOTH
2//! the display-settings dialog AND the schema-driven feature dialogs (the user's
3//! principle: the structure of a thing drives the UI; you don't rewrite UI code
4//! per field, and you don't write two dialog engines).
5//!
6//! [`field_input`] emits ONLY the input widget(s) for one [`FormField`] — no
7//! leading label, no forced row layout — so the CALLER owns the placement. Both
8//! side trees drive it DIRECTLY: the history feature tree (`panels::history`) and
9//! the settings tree (`panels::settings`) each render a field as a `tree` LEAF
10//! whose node label is the field label and whose right-aligned content is this
11//! input. The widget per [`FieldKind`]:
12//! * `Color` → `color_edit_button_srgb`
13//! * `Bool` → checkbox
14//! * `Enum` → combo box
15//! * `Number`/`Range` → slider (bounded settings)
16//! * `Scalar` → an EXPRESSION-CAPABLE single-line field (unbounded feature
17//! numbers): the user types a plain number OR a variable name / inline
18//! equation (`width * 2`) that the kernel evaluates against the history's
19//! `expressions` sheet; while focused, the mouse wheel steps a pure number.
20//! * `BoundedScalar` → the same field, bounding numeric literals only when
21//! an edit commits; the plugin runtime remains the authoritative validator.
22//! * `Text` → single-line edit (disabled for a read-only `id`)
23//! * `Vec3` → three drag values (transform position/rotation/scale)
24//! * `Button` → an action button; a click is surfaced to the caller by the
25//! field key (via the `clicked` out-param) — e.g. `editSketch` opens the
26//! engine-native sketcher.
27//! * `Reference` → a full-width activation button with the current selection
28//! listed BENEATH it, one line per entity, each with an `✕` to remove it.
29//! The `✕` is pinned to the line's RIGHT edge and the name truncates into
30//! what is left (hover for the whole one) — an entity name is as long as the
31//! modelling history made it, and a line laid out name-first would push its
32//! own remove button off the panel.
33//! Pressing the button is surfaced to the caller by the field key (the same
34//! `clicked` out-param a `Button` uses) — opening the pick needs the
35//! engine, and this file deliberately has none. HOVERING a line reports the
36//! entity NAME on it the same way ([`FieldActions::hovered_entity`]), so the
37//! caller can light that entity in the 3D scene. While a pick RUNS in a
38//! field ([`ActivePick`], passed through [`field_input_with`]) that field
39//! draws FOCUSED — an accent ring, the engine's running picks as its list,
40//! its button reading `Done` — and reports [`FieldActions::pick_done`] and
41//! [`FieldActions::pick_remove`] instead of an edit: the dialog's selection
42//! box, the way other CAD applications keep it in focus while you click in
43//! the view.
44//!
45//! # Width, and who decides it
46//!
47//! An input fills the width it is given in a TOP-DOWN layout (the label-above
48//! form view: [`crate::form_view`]) and stays COMPACT in a RIGHT-TO-LEFT row
49//! (the tree/settings idiom, where the label is the tree node and the input sits
50//! at the panel edge). `ui.layout().prefer_right_to_left()` is the one
51//! discriminator — the same one `Vec3` has always used to order its components —
52//! so neither caller passes a layout flag and neither can drift from the other.
53//!
54//! A field binds to a `path` (a chain of JSON object keys), so it can read/write
55//! a NESTED value (`["transform","position"]`, `["boolean","operation"]`), not
56//! just a top-level key. On any change it writes back into `current` (the JSON
57//! document being edited — settings JSON, or a feature's `inputParams`) and
58//! returns `true`; the caller re-applies / re-runs. There is deliberately NO
59//! per-field code, so this file is reusable verbatim by a later `brep-ui` crate.
60
61pub(crate) use brep_render::brep_kernel::reference_names;
62use crate::color::rgb_to_hex;
63use brep_render::style::{parse_css_hex, FieldKind, FormField};
64use eframe::egui;
65use serde_json::Value;
66use std::collections::HashMap;
67
68/// The red of a reference line's remove `✕` — the destructive red the history
69/// tree's delete affordance uses (theme-independent on purpose: it must read as
70/// "removes something" in both light and dark).
71const REMOVE_RED: egui::Color32 = egui::Color32::from_rgb(0xd8, 0x54, 0x4f);
72
73/// The width an input should take: whatever the caller has left in a TOP-DOWN
74/// form (label above, full-width field), or `compact` in a RIGHT-TO-LEFT tree
75/// row, where the input shares the row with its label.
76fn input_width(ui: &egui::Ui, compact: f32) -> f32 {
77 if ui.layout().prefer_right_to_left() {
78 compact
79 } else {
80 ui.available_width()
81 }
82}
83
84/// What the user did to a field that only the CALLER can act on — both of these
85/// need an engine (entering the reference picker; lighting an entity in the 3D
86/// scene), and this file deliberately has none.
87///
88/// ONE struct rather than two `&mut Option<String>` out-params: they carry
89/// different things (a field KEY vs an entity NAME) but the same type, so
90/// adjacent out-params would swap silently at a call site.
91#[derive(Debug, Default, Clone, PartialEq)]
92pub struct FieldActions {
93 /// A [`FieldKind::Button`] was pressed, or a `Reference`'s `Select` was — the
94 /// field KEY, because acting on either needs the engine.
95 pub clicked: Option<String>,
96 /// The pointer is over a reference LINE: the entity NAME that line lists, for
97 /// the caller to hover-highlight in the 3D scene.
98 pub hovered_entity: Option<String>,
99 /// The FOCUSED reference field's button (`Done`) was pressed: the running
100 /// pick is to be committed. Never set together with `clicked`.
101 pub pick_done: bool,
102 /// An `✕` on the FOCUSED reference field's list: drop the i-th RUNNING pick.
103 /// That list is the engine's, not `current`'s, so this is an intent for the
104 /// consumer rather than an edit reported through `changed`.
105 pub pick_remove: Option<usize>,
106}
107
108/// The reference field a pick is RUNNING in, as the form draws it: the
109/// field whose `path` this names is the FOCUSED one — it lists `names` (the
110/// engine's running picks, not the stored value), its button reads `Done`
111/// and ends the pick, and its `✕`s report [`FieldActions::pick_remove`]. The
112/// other reference fields draw as usual, and pressing one of them is still
113/// [`FieldActions::clicked`]: the consumer finishes this pick and opens that
114/// one, the way a CAD dialog moves its focus from one selection box to the
115/// next.
116#[derive(Debug, Clone, Copy, PartialEq)]
117pub struct ActivePick<'a> {
118 /// The focused field's JSON path.
119 pub path: &'a [String],
120 /// The running picks.
121 pub names: &'a [String],
122}
123
124/// Emit ONLY the input widget(s) for one field — NO leading label, NO forced row
125/// layout (the caller supplies both: the form view puts the label ABOVE and gives
126/// the input the full width; the settings tree puts the label in the tree node
127/// and this input in the row's right-aligned content). Writes any change back
128/// into `current` at the field's `path`, returns
129/// `(changed, interactive_widget_rect)`.
130///
131/// `probe`, when present, additionally receives each OPEN enum item's rect (keyed
132/// `"<path>#<variant>"`) and a reference field's activation, per-line and
133/// per-line-remove rects (`"<path>#activate"`, `"<path>#line<index>"`,
134/// `"<path>#x<index>"`) for the headed verifier.
135///
136/// `actions` is the out-param for what is NOT a value: a `Button` press, a
137/// `Reference`'s `Select` press, and the entity a hovered reference line names.
138pub fn field_input(
139 ui: &mut egui::Ui,
140 field: &FormField,
141 current: &mut Value,
142 probe: Option<&mut HashMap<String, egui::Rect>>,
143 actions: &mut FieldActions,
144) -> (bool, egui::Rect) {
145 field_input_with(ui, field, current, probe, actions, None)
146}
147
148pub use brep_ecad_egui::widgets::enum_dropdown;
149
150/// The form's single-line text box (a [`FieldKind::Text`] field's), for a
151/// panel field that must see its whole response — one that commits on focus
152/// loss rather than on every keystroke.
153pub fn text_input(ui: &mut egui::Ui, text: &mut String, width: f32) -> egui::Response {
154 ui.add(
155 egui::TextEdit::singleline(text)
156 .margin(crate::viewport::touch::text_edit_margin(ui))
157 .desired_width(width)
158 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)),
159 )
160}
161
162/// The width a form input takes in the current layout: see `input_width`.
163pub fn text_input_width(ui: &egui::Ui) -> f32 {
164 input_width(ui, ui.spacing().text_edit_width)
165}
166
167/// [`field_input`] for a form that may have a reference pick RUNNING:
168/// `picking` names the focused field (see [`ActivePick`]). Every other field
169/// draws exactly as [`field_input`] draws it.
170pub fn field_input_with(
171 ui: &mut egui::Ui,
172 field: &FormField,
173 current: &mut Value,
174 mut probe: Option<&mut HashMap<String, egui::Rect>>,
175 actions: &mut FieldActions,
176 picking: Option<ActivePick<'_>>,
177) -> (bool, egui::Rect) {
178 let path = &field.path;
179 match &field.kind {
180 FieldKind::Color => {
181 let mut rgb = read_rgb(value_at(current, path));
182 let r = ui.color_edit_button_srgb(&mut rgb);
183 if r.changed() {
184 set_at(current, path, Value::String(rgb_to_hex(rgb)));
185 }
186 (r.changed(), r.rect)
187 }
188 FieldKind::Bool => {
189 let mut b = value_at(current, path).and_then(Value::as_bool).unwrap_or(false);
190 let r = ui.checkbox(&mut b, "");
191 if r.changed() {
192 set_at(current, path, Value::Bool(b));
193 }
194 (r.changed(), r.rect)
195 }
196 FieldKind::Enum { variants, labels } => {
197 let orig = value_at(current, path)
198 .and_then(Value::as_str)
199 .unwrap_or("")
200 .to_string();
201 let mut sel = orig.clone();
202 // The value is also the hit key's suffix (`…#transform`); the label
203 // is only what the box shows.
204 let choices: Vec<(String, &str, &str)> = variants
205 .iter()
206 .enumerate()
207 .map(|(i, v)| (v.to_string(), v.as_str(), labels.get(i).map_or(v.as_str(), String::as_str)))
208 .collect();
209 let width = (!ui.layout().prefer_right_to_left()).then(|| ui.available_width());
210 let (changed, response) = enum_dropdown(ui, &path.join("."), &choices, &mut sel, width, probe.as_deref_mut());
211 if changed {
212 set_at(current, path, Value::String(sel));
213 }
214 (changed, response.rect)
215 }
216 FieldKind::Number { min, max, step } | FieldKind::Range { min, max, step } => {
217 let mut v = value_at(current, path).and_then(Value::as_f64).unwrap_or(*min);
218 let r = ui.add(egui::Slider::new(&mut v, *min..=*max).step_by(*step));
219 if r.changed() {
220 set_at(current, path, serde_json::json!(v));
221 }
222 (r.changed(), r.rect)
223 }
224 FieldKind::Scalar { step } | FieldKind::BoundedScalar { step, .. } => {
225 // An EXPRESSION-CAPABLE numeric field — see [`scalar_widget`], which
226 // owns the whole behaviour so a `Vec3` component gets exactly the same
227 // field.
228 let (committed, rect) = scalar_widget(
229 ui,
230 ("scalar-edit", path.join(".")),
231 value_at(current, path),
232 *step,
233 input_width(ui, 72.0),
234 );
235 let changed = committed.is_some();
236 if let Some(mut value) = committed {
237 if let (FieldKind::BoundedScalar { min, max, .. }, Some(number)) = (&field.kind, value.as_f64()) {
238 let bounded = number.clamp(*min, *max);
239 if bounded != number {
240 value = serde_json::json!(bounded);
241 }
242 }
243 set_at(current, path, value);
244 }
245 (changed, rect)
246 }
247 FieldKind::Text { read_only } => {
248 let mut s = value_at(current, path)
249 .and_then(Value::as_str)
250 .unwrap_or("")
251 .to_string();
252 let width = input_width(ui, ui.spacing().text_edit_width);
253 if *read_only {
254 let r = ui.add_enabled(
255 false,
256 egui::TextEdit::singleline(&mut s).margin(crate::viewport::touch::text_edit_margin(ui)).desired_width(width)
257 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO)),
258 );
259 (false, r.rect)
260 } else {
261 let r = text_input(ui, &mut s, width);
262 if r.changed() {
263 set_at(current, path, Value::String(s));
264 }
265 (r.changed(), r.rect)
266 }
267 }
268 FieldKind::Vec3 { step } => {
269 // THREE expression-capable scalar fields, not three number-only drag
270 // values: a transform component is a numeric param like any other, so
271 // `position: ["W/2", 0, 0]` must be typeable and must SURVIVE. The
272 // number-only widget showed a stored expression as `0` and wrote all
273 // three slots back as numbers on any edit, silently destroying the
274 // other two — [`vec3_with_slot`] rewrites ONLY the edited index and
275 // keeps its siblings' JSON verbatim.
276 let stored = value_at(current, path).cloned();
277 let mut edited: Option<(usize, Value)> = None;
278 let mut rect = egui::Rect::NOTHING;
279 let mut component = |ui: &mut egui::Ui, index: usize, width: f32| {
280 let (committed, r) = scalar_widget(
281 ui,
282 ("vec3-edit", path.join("."), index),
283 vec3_slot(stored.as_ref(), index),
284 *step,
285 width,
286 );
287 if let Some(value) = committed {
288 edited = Some((index, value));
289 }
290 rect = rect.union(r);
291 };
292 if ui.layout().prefer_right_to_left() {
293 // In a RIGHT-TO-LEFT row (the right-aligned tree / settings content)
294 // egui lays widgets from the right, which would show the components
295 // as z,y,x. Add them in reverse so they still READ x, y, z.
296 for index in [2usize, 1, 0] {
297 component(ui, index, 56.0);
298 }
299 } else {
300 // Label-above form: ONE row of three EQUAL-width fields under the
301 // single label, reading x, y, z. `ui.horizontal` is this arm's own —
302 // the caller's layout is vertical, so without it the three
303 // components would stack.
304 let gap = ui.spacing().item_spacing.x;
305 let each = ((ui.available_width() - 2.0 * gap) / 3.0).max(24.0);
306 ui.horizontal(|ui| {
307 for index in 0..3 {
308 component(ui, index, each);
309 }
310 });
311 }
312 match edited {
313 Some((index, value)) => {
314 set_at(current, path, vec3_with_slot(stored.as_ref(), index, value));
315 (true, rect)
316 }
317 None => (false, rect),
318 }
319 }
320 FieldKind::Button { label } => {
321 // An action button binds to no value; a click is surfaced via `clicked`
322 // (set to the field key) so the host — the history tree, which holds
323 // `&mut EngineState` — can act on it (e.g. `editSketch` → sketch mode).
324 //
325 // FULL WIDTH, like the reference field's `Select` below: an action
326 // button is the primary thing to do in its section (Edit Sketch IS the
327 // sketch form), and a content-width button floating at the left of a
328 // full-width form reads as a minor control rather than the main one.
329 //
330 // A vec3 field's PICK button (`pivot#pick`) is the one button a
331 // pick can run in: while it does, the button is drawn focused and
332 // says what to click, and pressing it again ends the pick (Done,
333 // with nothing picked: the field keeps its value).
334 let focused = picking.is_some_and(|pick| pick.path == path.as_slice());
335 let caption = if focused { "Picking: click a vertex, edge or face (press to stop)" } else { label.as_str() };
336 let r = ui.add_sized(
337 [ui.available_width(), ui.spacing().interact_size.y],
338 egui::Button::new(caption).selected(focused),
339 );
340 if r.clicked() {
341 if focused {
342 actions.pick_done = true;
343 } else {
344 actions.clicked = Some(field.key().to_string());
345 }
346 }
347 (false, r.rect)
348 }
349 FieldKind::Reference { filter, multiple } => {
350 // R4 — the reference widget: a full-width activation button with the
351 // chosen entities listed BENEATH it, one per line, each with an `✕`
352 // to remove it. Nothing expands: the selection is what the user needs
353 // to see, so it is never hidden behind a `[+]`.
354 //
355 // Pressing `Select` reports the field key through `clicked` (exactly
356 // as a `Button` does) — opening the pick is the ENGINE's job and the
357 // caller owns which flavour of pick to open. Removing a line, by
358 // contrast, is a pure edit of `current`, so it happens here and
359 // reports `changed` like any other field.
360 //
361 // The FOCUSED field — the one a pick is running in — lists the
362 // engine's running picks instead of the stored value, and its
363 // button ends the pick rather than starting one. This is how the
364 // dialog keeps its selection box in focus while the user clicks in
365 // the view, instead of handing the picks to a separate mode.
366 let focused = picking.filter(|pick| pick.path == path.as_slice());
367 let names = match focused {
368 Some(pick) => pick.names.to_vec(),
369 None => reference_names(value_at(current, path)),
370 };
371 let pkey = path.join(".");
372 let mut removed: Option<usize> = None;
373 let mut activate_rect = egui::Rect::NOTHING;
374 // CHIP SELECTION in a list field:
375 // click a line to select it, Ctrl/Cmd+click toggles one, Shift+
376 // click selects the RANGE from the last clicked line; "Remove
377 // selected" drops them all. Kept by NAME in egui
378 // memory, so a list that changed under it simply forgets the gone.
379 let chips_id = egui::Id::new(("brep-ref-chips", pkey.clone()));
380 let mut chips: RefChips = ui.data(|d| d.get_temp(chips_id)).unwrap_or_default();
381 chips.selected.retain(|n| names.contains(n));
382 // A focused field removes one running pick per frame (the engine
383 // takes them by index), highest first so the rest stay valid.
384 chips.pending.retain(|n| names.contains(n));
385 if let Some(i) = chips.pending.iter().filter_map(|n| names.iter().position(|m| m == n)).max() {
386 chips.pending.retain(|n| *n != names[i]);
387 removed = Some(i);
388 ui.ctx().request_repaint();
389 }
390 let mut remove_selected = false;
391 ui.vertical(|ui| {
392 let width = ui.available_width();
393 let hint = if focused.is_some() {
394 // A list keeps taking picks until the user says so; a
395 // single field closes on its one pick (the consumer
396 // finishes it), and Done before that keeps what it has.
397 "▣ Done".to_string()
398 } else {
399 format!(
400 "▣ Select {}{}",
401 filter.join("/"),
402 if *multiple { " …" } else { "" }
403 )
404 };
405 let select = crate::icon_text::icon_button(ui, &hint).selected(focused.is_some());
406 let button = ui.add_sized(
407 [width, ui.spacing().interact_size.y],
408 select,
409 );
410 activate_rect = button.rect;
411 if button.clicked() {
412 if focused.is_some() {
413 actions.pick_done = true;
414 } else {
415 actions.clicked = Some(field.key().to_string());
416 }
417 }
418 if let Some(map) = probe.as_deref_mut() {
419 map.insert(format!("{pkey}#activate"), button.rect);
420 }
421 if focused.is_some() {
422 // The focus ring: the whole field reads as the one the
423 // view's clicks go to, not just its button.
424 let accent = ui.visuals().selection.stroke.color;
425 ui.painter().rect_stroke(
426 button.rect.expand(2.0),
427 3.0,
428 egui::Stroke::new(1.5, accent),
429 egui::StrokeKind::Outside,
430 );
431 let what = if *multiple { "Click in the view to add; Escape restores" } else { "Click in the view to pick; Escape restores" };
432 ui.label(egui::RichText::new(what).weak().small());
433 }
434 if names.is_empty() {
435 ui.label(egui::RichText::new(if focused.is_some() { "(nothing picked yet)" } else { "(none)" }).weak());
436 return;
437 }
438 for (i, name) in names.iter().enumerate() {
439 // The ✕ is allocated FIRST, from the RIGHT edge, and the name
440 // takes what is left over — the same order the form view's
441 // title row uses, for the same reason. An entity name is as
442 // long as the modelling history made it (a fillet on a blend
443 // edge reaches 76 characters), so name-then-button lets the
444 // name push the button clean off the panel: measured 212 pt
445 // past the edge of a 320 pt panel, where an ancestor clip
446 // then eats the click as well as the pixels.
447 ui.horizontal(|ui| {
448 ui.with_layout(
449 egui::Layout::right_to_left(egui::Align::Center),
450 |ui| {
451 let remove = crate::icon_text::icon_button_colored(
452 ui,
453 "✕",
454 Some(REMOVE_RED),
455 )
456 .stroke(egui::Stroke::new(1.0, REMOVE_RED))
457 .small();
458 let x = ui.add(remove);
459 if let Some(map) = probe.as_deref_mut() {
460 map.insert(format!("{pkey}#x{i}"), x.rect);
461 }
462 if x.clicked() {
463 removed = Some(i);
464 }
465 // Back to reading order for the name, inside
466 // whatever width the button left behind. It
467 // TRUNCATES there rather than wrapping: these
468 // names differ in their tails (`[0]` vs `[1]`,
469 // `NZ` vs `NY`), and a `Label` that elides shows
470 // the WHOLE text on hover by itself
471 // (`show_tooltip_when_elided`, on by default),
472 // so the tail is a hover away and adding an
473 // `on_hover_text` here would only stack a second
474 // tooltip on egui's.
475 ui.with_layout(
476 egui::Layout::left_to_right(egui::Align::Center),
477 |ui| {
478 let selected = *multiple && chips.selected.contains(name);
479 let mut text = egui::RichText::new(format!("• {name}"));
480 if selected {
481 text = text
482 .background_color(ui.visuals().selection.bg_fill)
483 .color(ui.visuals().selection.stroke.color);
484 }
485 let line = ui.add(
486 egui::Label::new(text)
487 .truncate()
488 .sense(egui::Sense::click()),
489 );
490 if *multiple && line.clicked() {
491 chips.click(&names, name, crate::select_mods::RowClick::in_ctx(ui.ctx()));
492 }
493 // Hovering the line reports the entity it
494 // names, so the caller can light it in the
495 // 3D scene exactly as mousing over it there
496 // would — a reference list is a list of
497 // things in the model, and reading which
498 // `…|BOUNDARY[1]` is which off the name
499 // alone is what the highlight replaces.
500 if line.hovered() {
501 actions.hovered_entity = Some(name.clone());
502 }
503 if let Some(map) = probe.as_deref_mut() {
504 map.insert(
505 format!("{pkey}#line{i}"),
506 line.rect,
507 );
508 }
509 },
510 );
511 },
512 );
513 });
514 }
515 if *multiple && !chips.selected.is_empty() {
516 let label = format!("✕ Remove selected ({})", chips.selected.len());
517 let resp = ui.add(egui::Button::new(egui::RichText::new(label).color(REMOVE_RED)).small());
518 if let Some(map) = probe.as_deref_mut() {
519 map.insert(format!("{pkey}#xsel"), resp.rect);
520 }
521 remove_selected = resp.clicked();
522 }
523 });
524 if remove_selected {
525 if focused.is_some() {
526 chips.pending = std::mem::take(&mut chips.selected);
527 if let Some(i) = chips.pending.iter().filter_map(|n| names.iter().position(|m| m == n)).max() {
528 chips.pending.retain(|n| *n != names[i]);
529 removed = Some(i);
530 ui.ctx().request_repaint();
531 }
532 } else {
533 let gone = std::mem::take(&mut chips.selected);
534 ui.data_mut(|d| d.insert_temp(chips_id, chips));
535 let kept: Vec<String> = names.into_iter().filter(|n| !gone.contains(n)).collect();
536 set_at(current, path, Value::Array(kept.into_iter().map(Value::String).collect()));
537 return (true, activate_rect);
538 }
539 }
540 ui.data_mut(|d| d.insert_temp(chips_id, chips.clone()));
541 if let Some(i) = removed {
542 if focused.is_some() {
543 // The running list is the engine's: an intent, not an edit.
544 actions.pick_remove = Some(i);
545 return (false, activate_rect);
546 }
547 let mut kept = names;
548 kept.remove(i);
549 let value = if *multiple {
550 Value::Array(kept.into_iter().map(Value::String).collect())
551 } else {
552 Value::String(kept.first().cloned().unwrap_or_default())
553 };
554 set_at(current, path, value);
555 return (true, activate_rect);
556 }
557 (false, activate_rect)
558 }
559 }
560}
561
562/// A list reference field's chip selection (see the field drawer).
563#[derive(Clone, Default, Debug)]
564struct RefChips {
565 selected: Vec<String>,
566 anchor: Option<String>,
567 /// Running picks still to remove, one per frame.
568 pending: Vec<String>,
569}
570
571impl RefChips {
572 fn click(&mut self, names: &[String], name: &String, click: crate::select_mods::RowClick) {
573 use crate::select_mods::RowClick;
574 let range = self.anchor.as_ref().and_then(|a| crate::select_mods::range(names, a, name)).map(<[String]>::to_vec);
575 match (click, range) {
576 (RowClick::Range, Some(range)) => self.selected = range,
577 (RowClick::AddRange, Some(range)) => {
578 for n in range {
579 if !self.selected.contains(&n) {
580 self.selected.push(n);
581 }
582 }
583 }
584 (RowClick::Toggle | RowClick::AddRange, _) => {
585 if let Some(at) = self.selected.iter().position(|n| n == name) {
586 self.selected.remove(at);
587 } else {
588 self.selected.push(name.clone());
589 }
590 }
591 (RowClick::Replace | RowClick::Range, _) => {
592 // A plain click on the only selected line clears it.
593 if self.selected.len() == 1 && self.selected[0] == *name {
594 self.selected.clear();
595 } else {
596 self.selected = vec![name.clone()];
597 }
598 }
599 }
600 if click.sets_anchor() || self.anchor.as_ref().is_none_or(|a| !names.contains(a)) {
601 self.anchor = Some(name.clone());
602 }
603 }
604}
605
606// --- nested JSON read / write ------------------------------------------------
607
608/// Resolve `path` (object keys) to a value inside `root`, if present.
609pub(crate) fn value_at<'a>(root: &'a Value, path: &[String]) -> Option<&'a Value> {
610 let mut cur = root;
611 for seg in path {
612 cur = cur.get(seg.as_str())?;
613 }
614 Some(cur)
615}
616
617/// Write `new_val` into `root` at `path`, auto-vivifying intermediate objects
618/// (so a feature whose `inputParams` omits `transform` still accepts an edit).
619pub(crate) fn set_at(root: &mut Value, path: &[String], new_val: Value) {
620 if path.is_empty() {
621 *root = new_val;
622 return;
623 }
624 if !root.is_object() {
625 *root = Value::Object(serde_json::Map::new());
626 }
627 let mut cur = root;
628 for seg in &path[..path.len() - 1] {
629 let obj = cur.as_object_mut().expect("object by construction");
630 cur = obj
631 .entry(seg.clone())
632 .or_insert_with(|| Value::Object(serde_json::Map::new()));
633 if !cur.is_object() {
634 *cur = Value::Object(serde_json::Map::new());
635 }
636 }
637 cur.as_object_mut()
638 .expect("object by construction")
639 .insert(path[path.len() - 1].clone(), new_val);
640}
641
642// --- Scalar (expression-capable feature number) helpers ----------------------
643
644/// The ONE expression-capable numeric field: a [`FieldKind::Scalar`], and each
645/// component of a [`FieldKind::Vec3`].
646///
647/// It shows a stored NUMBER as text and a stored EXPRESSION (`width * 2`)
648/// VERBATIM — never clobbering a string param to `0` the way a number-only
649/// `DragValue` does — and lets the user type either. A transient edit buffer
650/// lives in egui memory (keyed by `id_source`) and is committed on focus-loss
651/// (Enter / click-away), mirroring `panels::expressions`, so a half-typed
652/// expression (`width *`) never re-runs the history mid-keystroke. While the
653/// field is focused, the mouse wheel STEPS a pure number by `step` (recovering
654/// the old drag-value stepping); a scroll notch is a complete, valid edit, so it
655/// commits immediately.
656///
657/// Returns the value to STORE when the edit committed (the caller owns where it
658/// goes — a whole param for `Scalar`, one slot of the array for `Vec3`) and the
659/// widget rect.
660fn scalar_widget(
661 ui: &mut egui::Ui,
662 id_source: impl std::hash::Hash + std::fmt::Debug,
663 stored: Option<&Value>,
664 step: f64,
665 width: f32,
666) -> (Option<Value>, egui::Rect) {
667 let buf_id = ui.make_persistent_id(id_source);
668 let stored_text = scalar_display(stored);
669 // Seed from the live buffer while editing; otherwise from the stored value
670 // (an undo / gizmo edit may have changed it out from under us).
671 let mut buf = ui
672 .data_mut(|d| d.get_temp::<String>(buf_id))
673 .unwrap_or_else(|| stored_text.clone());
674
675 let r = ui.add(
676 egui::TextEdit::singleline(&mut buf).margin(crate::viewport::touch::text_edit_margin(ui))
677 .id(buf_id)
678 .desired_width(width)
679 .min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO))
680 .vertical_align(if crate::viewport::touch::enabled(ui.ctx()) { egui::Align::Center } else { egui::Align::TOP }),
681 );
682
683 let mut committed = None;
684 if r.gained_focus() {
685 // Start each edit from the current stored value.
686 buf = stored_text.clone();
687 if crate::viewport::touch::enabled(ui.ctx()) {
688 if let Some(mut edit) = egui::TextEdit::load_state(ui.ctx(), r.id) {
689 edit.cursor.set_char_range(Some(egui::text::CCursorRange::two(
690 egui::text::CCursor::new(0), egui::text::CCursor::new(buf.chars().count()),
691 )));
692 edit.store(ui.ctx(), r.id);
693 }
694 }
695 }
696 // Scroll-to-step a PURE number by `step` (wheel up = +step) while the field
697 // is focused AND the pointer is over it ("scroll over the field to step
698 // it"). A non-numeric expression is un-steppable (`scroll_step_scalar` →
699 // `None`) and left untouched — typing still works. Step ONLY when the cursor
700 // is actually over this field, so a focused field doesn't swallow panel
701 // scrolling while the user scrolls elsewhere to navigate (that would
702 // silently edit the value). Two independent "pointer is over me" signals for
703 // robustness — a real wheel carries the cursor position on native/desktop;
704 // only synthetic (headless-test) wheels lack it.
705 let pointer_over_field = r.hovered()
706 || ui
707 .input(|i| i.pointer.latest_pos())
708 .is_some_and(|pos| r.rect.contains(pos));
709 if r.has_focus() && pointer_over_field {
710 let notches = wheel_notches(ui);
711 // EAT the wheel so the enclosing side-panel `ScrollArea` can't ALSO
712 // scroll the panel — the field owns the scroll while the cursor is over
713 // it. Do this EVERY frame the cursor is here, not only on the notch
714 // frame: egui SMOOTHS a wheel notch across several frames, and only the
715 // first carries a `MouseWheel` event, so zeroing just that frame let the
716 // smoothed TAIL leak into the panel (visible on the desktop build; the
717 // web scroll wasn't smoothed so it looked fine). On non-scroll frames
718 // these are harmless no-ops. The ScrollArea reads the smoothed delta in
719 // its epilogue (after this content), so zeroing here blocks it; we also
720 // drop the wheel events.
721 ui.input_mut(|i| {
722 i.smooth_scroll_delta = egui::Vec2::ZERO;
723 i.events
724 .retain(|e| !matches!(e, egui::Event::MouseWheel { .. }));
725 });
726 if notches != 0.0 {
727 if let Some(stepped) = scroll_step_scalar(&buf, notches, step) {
728 buf = stepped;
729 committed = Some(scalar_store(&buf));
730 }
731 }
732 }
733 if r.lost_focus() {
734 // Commit on Enter / click-away. Skip an EMPTY buffer (a `String("")` is a
735 // guaranteed kernel eval error) and a NO-OP (compare by the DISPLAYED
736 // text so a whole-float `20.0` vs a typed `20` — same display — doesn't
737 // re-run the history for nothing).
738 let trimmed = buf.trim();
739 if !trimmed.is_empty() && trimmed != stored_text {
740 committed = Some(scalar_store(&buf));
741 }
742 ui.data_mut(|d| d.remove::<String>(buf_id));
743 } else if r.has_focus() {
744 // Keep the in-progress buffer (incl. any scroll step) across frames.
745 ui.data_mut(|d| d.insert_temp(buf_id, buf.clone()));
746 } else {
747 // Unfocused and not committing: drop any transient buffer so the next
748 // edit reseeds from the (possibly externally changed) value.
749 ui.data_mut(|d| d.remove::<String>(buf_id));
750 }
751 (committed, r.rect)
752}
753
754/// One slot of a stored vec3 (`[x, y, z]`), or `None` when the param is absent /
755/// not an array / short. A slot is read VERBATIM — a number stays a number and an
756/// expression string stays that string, so `scalar_display` shows it as authored.
757fn vec3_slot(stored: Option<&Value>, index: usize) -> Option<&Value> {
758 stored?.as_array()?.get(index).filter(|v| !v.is_null())
759}
760
761/// The vec3 to STORE after one component was edited: a full three-element array
762/// with `index` replaced and the OTHER TWO slots carried over verbatim. Carrying
763/// them is the point — writing all three back from three coerced `f64`s is what
764/// silently turned a sibling `"W/2"` into `0`. A missing sibling materializes as
765/// `0`, which is what the number-only widget already displayed for it.
766fn vec3_with_slot(stored: Option<&Value>, index: usize, value: Value) -> Value {
767 let mut out: Vec<Value> = (0..3)
768 .map(|i| vec3_slot(stored, i).cloned().unwrap_or(Value::from(0.0)))
769 .collect();
770 out[index] = value;
771 Value::Array(out)
772}
773
774/// The text to SHOW for a [`FieldKind::Scalar`] field: a stored NUMBER as its
775/// shortest decimal string (`20`, not `20.0`; `20.5` as `20.5` — no precision
776/// loss), a stored EXPRESSION string VERBATIM (`width * 2`, never clobbered to
777/// `0`), and a missing / other value as empty.
778fn scalar_display(value: Option<&Value>) -> String {
779 match value {
780 Some(Value::String(s)) => s.clone(),
781 // Rust's `f64` Display is the shortest round-tripping form and omits a
782 // trailing `.0`, so an integer OR whole-float number both show as `20`.
783 Some(Value::Number(n)) => n.as_f64().map(|f| f.to_string()).unwrap_or_default(),
784 _ => String::new(),
785 }
786}
787
788/// Turn committed field text into the stored param [`Value`]: a PURE numeric
789/// literal becomes a JSON `Number` (clean serialization + the kernel's fast
790/// `as_f64` path), anything else becomes a `Value::String` the kernel evaluates
791/// against the history `expressions` sheet (`ctx.number` at
792/// `feature_pipeline/mod.rs`: a `String` param is `env.eval`'d). Numeric-ness is
793/// decided by a strict JSON number parse, so `10.` / `1e` and other half-typed
794/// forms stay strings rather than round-tripping through a reformat.
795fn scalar_store(text: &str) -> Value {
796 let trimmed = text.trim();
797 match serde_json::from_str::<Value>(trimmed) {
798 Ok(v @ Value::Number(_)) => v,
799 _ => Value::String(trimmed.to_string()),
800 }
801}
802
803/// Apply `notches` mouse-wheel steps of size `step` to a Scalar field's text.
804/// Only a PURE numeric literal steps (wheel up = `+step`); a non-numeric
805/// expression (`width * 2`) is un-steppable and yields `None` (a no-op — the
806/// caller leaves the text alone so typing keeps working).
807fn scroll_step_scalar(text: &str, notches: f64, step: f64) -> Option<String> {
808 let base: f64 = text.trim().parse().ok()?;
809 Some(format_scalar_number(base + notches * step, step))
810}
811
812/// Format a stepped number to the STEP's decimal precision so repeated steps do
813/// not accumulate binary-float noise (`0.1` steps stay `10.1`, `10.2`, … not
814/// `10.299999`). Trailing zeros / dot are trimmed (`10.50 → 10.5`, `9.0 → 9`).
815fn format_scalar_number(v: f64, step: f64) -> String {
816 let decimals = step_decimals(step);
817 let mut s = format!("{:.*}", decimals, v);
818 if s.contains('.') {
819 while s.ends_with('0') {
820 s.pop();
821 }
822 if s.ends_with('.') {
823 s.pop();
824 }
825 }
826 s
827}
828
829/// Decimal places implied by `step` (`0.5 → 1`, `0.1 → 1`, `0.01 → 2`, `1 → 0`),
830/// capped so a pathological step can't ask for absurd precision.
831fn step_decimals(step: f64) -> usize {
832 let step = step.abs();
833 if step == 0.0 || !step.is_finite() {
834 return 3;
835 }
836 let mut d = 0usize;
837 let mut s = step;
838 while (s - s.round()).abs() > 1e-9 && d < 6 {
839 s *= 10.0;
840 d += 1;
841 }
842 d
843}
844
845/// Whole mouse-wheel notches scrolled this frame (wheel up = `+`), rounded to an
846/// integer notch count. Read from the raw `MouseWheel` events (not
847/// `smooth_scroll_delta`) so one physical notch is one discrete step. Browser
848/// backends report a conventional wheel detent as roughly 100 pixels (Chromium)
849/// or 3 lines (Firefox), whereas native winit reports it as 40 points or 1 line;
850/// keep those platform scales separate so the web field doesn't jump by 2–3
851/// schema steps for the same wheel movement. The caller gates this on the field
852/// being focused.
853fn wheel_notches(ui: &egui::Ui) -> f64 {
854 let raw: f32 = ui.input(|i| {
855 i.events
856 .iter()
857 .filter_map(|event| match event {
858 egui::Event::MouseWheel { unit, delta, .. } => Some(wheel_delta_to_notches(
859 *unit,
860 delta.y,
861 cfg!(target_arch = "wasm32"),
862 )),
863 _ => None,
864 })
865 .sum()
866 });
867 (raw as f64).round()
868}
869
870fn wheel_delta_to_notches(unit: egui::MouseWheelUnit, delta_y: f32, web: bool) -> f32 {
871 let (lines_per_notch, points_per_notch) = if web { (3.0, 100.0) } else { (1.0, 40.0) };
872 match unit {
873 egui::MouseWheelUnit::Line => delta_y / lines_per_notch,
874 egui::MouseWheelUnit::Point => delta_y / points_per_notch,
875 egui::MouseWheelUnit::Page => delta_y * 20.0,
876 }
877}
878
879/// Read a `#rrggbb` value as `[u8; 3]` for `color_edit_button_srgb`.
880fn read_rgb(value: Option<&Value>) -> [u8; 3] {
881 let hex = value.and_then(Value::as_str).unwrap_or("#000000");
882 let rgb = parse_css_hex(hex).unwrap_or([0.0, 0.0, 0.0]);
883 [
884 (rgb[0] * 255.0).round() as u8,
885 (rgb[1] * 255.0).round() as u8,
886 (rgb[2] * 255.0).round() as u8,
887 ]
888}
889