Skip to main content

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