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