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