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