Skip to main content

brep_app/ui_kit/
input.rs

1//! Text and number inputs: a `bg.input` field with a 1 px border that turns
2//! accent on focus, an error state that keeps the user's text, a search
3//! variant, and numbers with the unit inside the field.
4use super::{paint, Show};
5use crate::theme::{radius, space, Text, Theme, BORDER};
6use eframe::egui::{self, Rect, Stroke, Vec2};
7
8/// What an input drew.
9pub struct InputOutput {
10    /// The text edit's own response (focus, changed, lost_focus).
11    pub response: egui::Response,
12    /// The whole framed field: the rect a hit key publishes.
13    pub rect: Rect,
14    /// The clear × was pressed (search fields).
15    pub cleared: bool,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19enum Lead {
20    None,
21    Search,
22}
23
24/// A single-line text field.
25#[must_use = "an input does nothing until `show` is called"]
26pub struct TextInput<'a> {
27    text: &'a mut String,
28    placeholder: &'a str,
29    error: Option<&'a str>,
30    width: Option<f32>,
31    enabled: bool,
32    lead: Lead,
33    suffix: Option<&'a str>,
34    right_aligned: bool,
35    id: Option<egui::Id>,
36    show: Show,
37}
38
39/// A text field. `text_input(&mut name).placeholder("Name").show(ui)`.
40pub fn text_input(text: &mut String) -> TextInput<'_> {
41    TextInput { text, placeholder: "", error: None, width: None, enabled: true, lead: Lead::None, suffix: None, right_aligned: false, id: None, show: Show::Live }
42}
43
44/// A search field: a leading magnifier, and a clear × when not empty.
45pub fn search_input(text: &mut String) -> TextInput<'_> {
46    let mut input = text_input(text);
47    input.lead = Lead::Search;
48    input.placeholder = "Search";
49    input
50}
51
52impl<'a> TextInput<'a> {
53    pub fn placeholder(mut self, text: &'a str) -> Self {
54        self.placeholder = text;
55        self
56    }
57    /// A `danger` border and the message below in caption size.
58    pub fn error(mut self, message: Option<&'a str>) -> Self {
59        self.error = message;
60        self
61    }
62    pub fn width(mut self, width: f32) -> Self {
63        self.width = Some(width);
64        self
65    }
66    pub fn enabled(mut self, enabled: bool) -> Self {
67        self.enabled = enabled;
68        self
69    }
70    /// Muted text INSIDE the field after the value (a unit).
71    pub fn suffix(mut self, suffix: &'a str) -> Self {
72        self.suffix = Some(suffix);
73        self
74    }
75    pub fn right_aligned(mut self, right: bool) -> Self {
76        self.right_aligned = right;
77        self
78    }
79    pub fn id(mut self, id: egui::Id) -> Self {
80        self.id = Some(id);
81        self
82    }
83    pub fn show_state(mut self, show: Show) -> Self {
84        self.show = show;
85        self
86    }
87
88    pub fn show(mut self, ui: &mut egui::Ui) -> InputOutput {
89        self.enabled = self.enabled && ui.is_enabled();
90        let theme = Theme::of(ui);
91        let c = &theme.colors;
92        let width = self.width.unwrap_or_else(|| ui.spacing().text_edit_width.min(ui.available_width()));
93        let height = theme.control_height();
94        let id = self.id.unwrap_or_else(|| ui.next_auto_id().with("ui-kit-input"));
95        let (rect, hover) = ui.allocate_exact_size(Vec2::new(width, height), egui::Sense::hover());
96        let focused = (self.enabled && ui.memory(|m| m.has_focus(id))) || self.show == Show::Focus;
97        let hovered = self.enabled && (hover.hovered() || self.show == Show::Hover);
98        let focus = ui.ctx().animate_bool_with_time(id.with("focus"), focused, theme.motion_base());
99        let fill = if self.enabled { c.bg_input } else { crate::theme::over(c.bg_panel, c.hover) };
100        let border = if self.error.is_some() {
101            c.danger
102        } else if !self.enabled {
103            c.border_subtle
104        } else {
105            let rest = if hovered { crate::theme::mix(c.border_strong, c.text_secondary, 0.35) } else { c.border_strong };
106            paint::lerp_color(rest, c.accent_ring, focus)
107        };
108        ui.painter().rect(rect, radius::INPUT, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
109        if focused {
110            paint::focus_ring(ui, rect, radius::INPUT, &theme);
111        }
112
113        let pad = space::MD;
114        let mut inner = rect.shrink2(Vec2::new(pad, 0.0));
115        if self.lead == Lead::Search {
116            let slot = Rect::from_min_size(inner.min, Vec2::new(14.0, height));
117            paint::magnifier(ui.painter(), slot.center(), 5.0, Stroke::new(1.4, c.text_secondary));
118            inner.min.x += 14.0 + space::SM;
119        }
120        let mut cleared = false;
121        if self.lead == Lead::Search && !self.text.is_empty() && self.enabled {
122            let slot = Rect::from_center_size(egui::pos2(inner.right() - 7.0, rect.center().y), Vec2::splat(16.0));
123            let clear = ui.interact(slot, id.with("clear"), egui::Sense::click());
124            clear.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Clear"));
125            if clear.hovered() {
126                ui.painter().rect_filled(slot, radius::INPUT, c.hover);
127            }
128            paint::cross(ui.painter(), slot.center(), 3.5, Stroke::new(1.4, c.text_secondary));
129            if clear.clicked() {
130                self.text.clear();
131                cleared = true;
132            }
133            inner.max.x -= 16.0 + space::XS;
134        }
135        if let Some(suffix) = self.suffix {
136            let g = paint::galley(ui, suffix, theme.font(Text::Body));
137            inner.max.x -= g.size().x;
138            ui.painter().galley(egui::pos2(inner.right(), rect.center().y - g.size().y / 2.0), g, if self.enabled { c.text_secondary } else { c.text_disabled });
139            inner.max.x -= space::XS;
140        }
141        let font = theme.font(Text::Body);
142        let row = ui.fonts_mut(|f| f.row_height(&font));
143        let text_rect = Rect::from_center_size(inner.center(), Vec2::new(inner.width(), row));
144        let edit = egui::TextEdit::singleline(self.text)
145            .id(id)
146            .frame(egui::Frame::NONE)
147            .margin(egui::Margin::ZERO)
148            .font(font)
149            .text_color(if self.enabled { c.text_primary } else { c.text_disabled })
150            .hint_text(egui::RichText::new(self.placeholder).color(c.text_disabled))
151            .horizontal_align(if self.right_aligned { egui::Align::RIGHT } else { egui::Align::LEFT })
152            .desired_width(inner.width())
153            .interactive(self.enabled);
154        let response = ui.put(text_rect, edit);
155        if let Some(message) = self.error {
156            ui.label(egui::RichText::new(message).font(theme.font(Text::Caption)).color(c.danger));
157        }
158        InputOutput { response, rect, cleared }
159    }
160}
161
162/// The millimetres in one of a length unit, or `None` for a unit that is not a length.
163fn length_mm(unit: &str) -> Option<f64> {
164    Some(match unit {
165        "mm" => 1.0,
166        "cm" => 10.0,
167        "m" => 1000.0,
168        "um" | "µm" => 0.001,
169        "in" | "\"" => 25.4,
170        "ft" | "'" => 304.8,
171        "mil" | "thou" => 0.0254,
172        _ => return None,
173    })
174}
175
176/// The degrees in one of an angle unit.
177fn angle_deg(unit: &str) -> Option<f64> {
178    Some(match unit {
179        "deg" | "°" => 1.0,
180        "rad" => 180.0 / std::f64::consts::PI,
181        _ => return None,
182    })
183}
184
185/// The factor that turns a value written in `written` into the field's `unit`.
186fn unit_factor(written: &str, unit: &str) -> Result<f64, String> {
187    if written == unit {
188        return Ok(1.0);
189    }
190    if let (Some(a), Some(b)) = (length_mm(written), length_mm(unit)) {
191        return Ok(a / b);
192    }
193    if let (Some(a), Some(b)) = (angle_deg(written), angle_deg(unit)) {
194        return Ok(a / b);
195    }
196    if unit.is_empty() {
197        return Err(format!("this field has no unit; `{written}` cannot be used here"));
198    }
199    Err(format!("`{written}` cannot be converted to {unit}"))
200}
201
202/// Evaluate what a user typed into a number field whose unit is `unit` ("" for
203/// none): `+ - * /`, parentheses, and unit names, which multiply the value
204/// before them into the field's unit, so `1/2 in` in a millimetre field is
205/// 12.7 and `2 in + 5` is 55.8. This is the gallery's stand-in: the form
206/// wiring (rollout step 3) hands the text to the engine's expression evaluator.
207pub fn evaluate(text: &str, unit: &str) -> Result<f64, String> {
208    struct Parser<'a> {
209        chars: std::iter::Peekable<std::str::Chars<'a>>,
210        unit: &'a str,
211    }
212    impl Parser<'_> {
213        fn skip(&mut self) {
214            while self.chars.peek().is_some_and(|c| c.is_whitespace()) {
215                self.chars.next();
216            }
217        }
218        fn expr(&mut self) -> Result<f64, String> {
219            let mut value = self.term()?;
220            loop {
221                self.skip();
222                match self.chars.peek() {
223                    Some('+') => {
224                        self.chars.next();
225                        value += self.term()?;
226                    }
227                    Some('-') => {
228                        self.chars.next();
229                        value -= self.term()?;
230                    }
231                    _ => return Ok(value),
232                }
233            }
234        }
235        fn term(&mut self) -> Result<f64, String> {
236            let mut value = self.factor()?;
237            loop {
238                self.skip();
239                match self.chars.peek().copied() {
240                    Some('*') => {
241                        self.chars.next();
242                        value *= self.factor()?;
243                    }
244                    Some('/') => {
245                        self.chars.next();
246                        let d = self.factor()?;
247                        if d == 0.0 {
248                            return Err("division by zero".into());
249                        }
250                        value /= d;
251                    }
252                    // A unit name multiplies what is before it: `1/2 in`.
253                    Some(ch) if ch.is_alphabetic() || matches!(ch, '"' | '\'' | '°') => {
254                        let mut name = String::new();
255                        while let Some(ch) = self.chars.peek().copied().filter(|ch| ch.is_alphabetic() || matches!(ch, '"' | '\'' | '°')) {
256                            name.push(ch);
257                            self.chars.next();
258                        }
259                        value *= unit_factor(&name, self.unit)?;
260                    }
261                    _ => return Ok(value),
262                }
263            }
264        }
265        fn factor(&mut self) -> Result<f64, String> {
266            self.skip();
267            match self.chars.peek().copied() {
268                Some('-') => {
269                    self.chars.next();
270                    Ok(-self.factor()?)
271                }
272                Some('+') => {
273                    self.chars.next();
274                    self.factor()
275                }
276                Some('(') => {
277                    self.chars.next();
278                    let value = self.expr()?;
279                    self.skip();
280                    match self.chars.next() {
281                        Some(')') => Ok(value),
282                        _ => Err("a `(` is not closed".into()),
283                    }
284                }
285                Some(ch) if ch.is_ascii_digit() || ch == '.' => {
286                    let mut digits = String::new();
287                    while let Some(ch) = self.chars.peek().copied().filter(|ch| ch.is_ascii_digit() || *ch == '.') {
288                        digits.push(ch);
289                        self.chars.next();
290                    }
291                    digits.parse().map_err(|_| format!("`{digits}` is not a number"))
292                }
293                Some(ch) => Err(format!("unexpected `{ch}`")),
294                None => Err("a value is missing".into()),
295            }
296        }
297    }
298    let mut parser = Parser { chars: text.chars().peekable(), unit };
299    let value = parser.expr()?;
300    parser.skip();
301    match parser.chars.peek() {
302        Some(ch) => Err(format!("unexpected `{ch}`")),
303        None if value.is_finite() => Ok(value),
304        None => Err("the value is not finite".into()),
305    }
306}
307
308/// A value as a field shows it: up to six decimals, no trailing zeros.
309pub fn format_number(value: f64) -> String {
310    format_number_to(value, 6)
311}
312
313/// A value with up to `decimals` decimals, no trailing zeros.
314pub fn format_number_to(value: f64, decimals: usize) -> String {
315    let text = format!("{value:.decimals$}");
316    let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { &text };
317    if text == "-0" { "0".into() } else { text.into() }
318}
319
320/// A number field with its unit inside the field.
321#[must_use = "an input does nothing until `show` is called"]
322pub struct NumberInput<'a> {
323    value: &'a mut f64,
324    unit: &'a str,
325    label: Option<&'a str>,
326    width: Option<f32>,
327    speed: f64,
328    enabled: bool,
329    decimals: usize,
330    id: Option<egui::Id>,
331}
332
333/// `number_input(&mut depth).unit("mm").label("Depth").show(ui)`.
334pub fn number_input(value: &mut f64) -> NumberInput<'_> {
335    NumberInput { value, unit: "", label: None, width: None, speed: 0.1, enabled: true, decimals: 6, id: None }
336}
337
338pub struct NumberOutput {
339    pub input: InputOutput,
340    /// The value changed this frame (a commit, or a drag on the label).
341    pub changed: bool,
342    /// What was typed could not be read; the field keeps it and shows this.
343    pub error: Option<String>,
344}
345
346impl<'a> NumberInput<'a> {
347    pub fn unit(mut self, unit: &'a str) -> Self {
348        self.unit = unit;
349        self
350    }
351    /// A label before the field that is also the DRAG HANDLE: dragging it
352    /// sideways changes the value (the field itself is for typing only).
353    pub fn label(mut self, label: &'a str) -> Self {
354        self.label = Some(label);
355        self
356    }
357    pub fn width(mut self, width: f32) -> Self {
358        self.width = Some(width);
359        self
360    }
361    /// Value change per point dragged on the label.
362    pub fn speed(mut self, speed: f64) -> Self {
363        self.speed = speed;
364        self
365    }
366    pub fn enabled(mut self, enabled: bool) -> Self {
367        self.enabled = enabled;
368        self
369    }
370    /// The most decimals the field shows (6 by default); raise it for small
371    /// tolerances, which would otherwise read and commit as 0.
372    pub fn decimals(mut self, decimals: usize) -> Self {
373        self.decimals = decimals;
374        self
375    }
376    pub fn id(mut self, id: egui::Id) -> Self {
377        self.id = Some(id);
378        self
379    }
380
381    pub fn show(mut self, ui: &mut egui::Ui) -> NumberOutput {
382        self.enabled = self.enabled && ui.is_enabled();
383        let theme = Theme::of(ui);
384        let id = self.id.unwrap_or_else(|| ui.next_auto_id().with("ui-kit-number"));
385        let buffer_id = id.with("buffer");
386        let error_id = id.with("error");
387        let mut changed = false;
388        ui.horizontal(|ui| {
389            if let Some(label) = self.label {
390                let g = paint::galley(ui, label, theme.font(Text::Label));
391                let sense = if self.enabled { egui::Sense::drag() } else { egui::Sense::hover() };
392                let (rect, drag) = ui.allocate_exact_size(Vec2::new(g.size().x, theme.control_height()), sense);
393                let ink = if !self.enabled {
394                    theme.colors.text_disabled
395                } else if drag.hovered() || drag.dragged() {
396                    theme.colors.text_primary
397                } else {
398                    theme.colors.text_secondary
399                };
400                ui.painter().galley(egui::pos2(rect.left(), rect.center().y - g.size().y / 2.0), g, ink);
401                if self.enabled {
402                    let drag = drag.on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
403                    if drag.dragged() {
404                        let delta = f64::from(drag.drag_delta().x) * self.speed;
405                        if delta != 0.0 {
406                            *self.value += delta;
407                            changed = true;
408                            ui.data_mut(|d| {
409                                d.remove::<String>(buffer_id);
410                                d.remove::<String>(error_id);
411                            });
412                        }
413                    }
414                }
415            }
416            ui.vertical(|ui| {
417                // The buffer is the user's text while they edit and while it is
418                // in error; otherwise the field shows the value.
419                let stored = ui.data(|d| d.get_temp::<String>(buffer_id));
420                let mut text = stored.clone().unwrap_or_else(|| format_number_to(*self.value, self.decimals));
421                let error = ui.data(|d| d.get_temp::<String>(error_id));
422                let mut input = text_input(&mut text).id(id).right_aligned(true).enabled(self.enabled).error(error.as_deref());
423                if !self.unit.is_empty() {
424                    input = input.suffix(self.unit);
425                }
426                if let Some(width) = self.width {
427                    input = input.width(width);
428                }
429                let out = input.show(ui);
430                let mut error = error;
431                if out.response.changed() || (out.response.has_focus() && stored.is_none()) {
432                    ui.data_mut(|d| d.insert_temp(buffer_id, text.clone()));
433                }
434                if out.response.lost_focus() {
435                    match evaluate(&text, self.unit) {
436                        Ok(value) => {
437                            if value != *self.value {
438                                *self.value = value;
439                                changed = true;
440                            }
441                            error = None;
442                            ui.data_mut(|d| {
443                                d.remove::<String>(buffer_id);
444                                d.remove::<String>(error_id);
445                            });
446                        }
447                        Err(message) => {
448                            ui.data_mut(|d| {
449                                d.insert_temp(buffer_id, text.clone());
450                                d.insert_temp(error_id, message.clone());
451                            });
452                            error = Some(message);
453                        }
454                    }
455                }
456                NumberOutput { input: out, changed, error }
457            })
458            .inner
459        })
460        .inner
461    }
462}
463
464impl InputOutput {
465    /// The text edit's response (focus, changed, lost_focus) with the rect of
466    /// the whole framed field, so a caller that published a hit key from a
467    /// `TextEdit`'s response keeps publishing the field it can click.
468    pub fn framed(self) -> egui::Response {
469        self.response.with_new_rect(self.rect)
470    }
471}