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