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