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