Skip to main content

elegance/
input.rs

1//! Styled single-line text input.
2//!
3//! Wraps [`egui::TextEdit`] with:
4//!
5//! * The slate input background
6//! * A crisp 1-px border that turns sky-coloured on focus
7//! * An optional "dirty" indicator (a 3-px sky-coloured bar down the left
8//!   edge) to signal unsaved changes
9//! * An optional label and optional hint text
10//! * Success / error flash animations triggered via
11//!   [`ResponseFlashExt`](crate::ResponseFlashExt)
12
13use egui::{
14    CornerRadius, FontSelection, Response, Stroke, TextEdit, Ui, Vec2, Widget, WidgetInfo,
15    WidgetText, WidgetType,
16};
17
18use crate::{flash, theme::Theme};
19
20/// A styled single-line text input.
21///
22/// ```no_run
23/// # use elegance::TextInput;
24/// # egui::__run_test_ui(|ui| {
25/// let mut email = String::new();
26/// ui.add(TextInput::new(&mut email).label("Email").hint("you@example.com"));
27/// # });
28/// ```
29///
30/// # Ids, focus, and flash state
31///
32/// Flash animations, focus, and cursor state are keyed off the widget's
33/// egui id. Without [`id_salt`](Self::id_salt), the id is derived from
34/// egui's auto-id counter, which is layout-dependent — if a sibling
35/// appears or disappears above this input between frames, the id shifts
36/// and any in-flight flash, focus, or cursor state is lost. Any input
37/// you flash via [`ResponseFlashExt`](crate::ResponseFlashExt) should pin
38/// its id with [`id_salt`](Self::id_salt).
39#[must_use = "Add with `ui.add(...)`."]
40pub struct TextInput<'a> {
41    text: &'a mut String,
42    label: Option<WidgetText>,
43    hint: Option<&'a str>,
44    dirty: bool,
45    password: bool,
46    desired_width: Option<f32>,
47    id_salt: Option<egui::Id>,
48}
49
50impl<'a> std::fmt::Debug for TextInput<'a> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("TextInput")
53            .field("dirty", &self.dirty)
54            .field("password", &self.password)
55            .field("desired_width", &self.desired_width)
56            .finish()
57    }
58}
59
60impl<'a> TextInput<'a> {
61    /// Create a text input bound to `text`.
62    pub fn new(text: &'a mut String) -> Self {
63        Self {
64            text,
65            label: None,
66            hint: None,
67            dirty: false,
68            password: false,
69            desired_width: None,
70            id_salt: None,
71        }
72    }
73
74    /// Show a label above the input.
75    pub fn label(mut self, text: impl Into<WidgetText>) -> Self {
76        self.label = Some(text.into());
77        self
78    }
79
80    /// Show placeholder-style hint text when the field is empty.
81    pub fn hint(mut self, text: &'a str) -> Self {
82        self.hint = Some(text);
83        self
84    }
85
86    /// Mark the input as having unsaved changes. Shows a sky-coloured
87    /// accent bar down the left side.
88    pub fn dirty(mut self, dirty: bool) -> Self {
89        self.dirty = dirty;
90        self
91    }
92
93    /// Mask the text as a password field.
94    pub fn password(mut self, password: bool) -> Self {
95        self.password = password;
96        self
97    }
98
99    /// Desired width (points) for the editor portion of the widget.
100    pub fn desired_width(mut self, width: f32) -> Self {
101        self.desired_width = Some(width);
102        self
103    }
104
105    /// Supply a stable id salt. Useful when two inputs share the same label.
106    pub fn id_salt(mut self, id: impl std::hash::Hash) -> Self {
107        self.id_salt = Some(egui::Id::new(id));
108        self
109    }
110}
111
112impl<'a> Widget for TextInput<'a> {
113    fn ui(self, ui: &mut Ui) -> Response {
114        let theme = Theme::current(ui.ctx());
115        let p = &theme.palette;
116        let t = &theme.typography;
117
118        ui.vertical(|ui| {
119            if let Some(label) = &self.label {
120                ui.add_space(2.0);
121                let rich = egui::RichText::new(label.text())
122                    .color(p.text_muted)
123                    .size(t.label);
124                ui.add(egui::Label::new(rich).wrap_mode(egui::TextWrapMode::Extend));
125                ui.add_space(2.0);
126            }
127
128            // Pin a stable id_salt so the TextEdit id is predictable —
129            // we need it to look up flash state before painting.
130            //
131            // `TextEdit::id_salt` internally wraps its input in
132            // `Id::new(...)` before calling `make_persistent_id`, so we
133            // mirror that step here to get the *same* widget id.
134            let id_salt = self.id_salt.unwrap_or_else(|| ui.next_auto_id());
135            let widget_id = ui.make_persistent_id(egui::Id::new(id_salt));
136
137            let flash = flash::active_flash(ui.ctx(), widget_id);
138            let bg_fill = flash::background_fill(&theme, p.input_bg, flash);
139
140            let desired_width = self.desired_width.unwrap_or_else(|| ui.available_width());
141            let margin = Vec2::new(theme.control_padding_x * 0.5, theme.control_padding_y);
142
143            // Swap visuals so the TextEdit picks up our look, then restore.
144            let response = crate::theme::with_themed_visuals(ui, |ui| {
145                let v = ui.visuals_mut();
146                crate::theme::themed_input_visuals(v, &theme, bg_fill);
147                v.extreme_bg_color = bg_fill;
148                v.selection.bg_fill = crate::theme::with_alpha(p.sky, 90);
149                v.selection.stroke = Stroke::new(1.0, p.sky);
150
151                let mut edit = TextEdit::singleline(self.text)
152                    .id_salt(id_salt)
153                    .font(FontSelection::FontId(egui::FontId::proportional(t.body)))
154                    .text_color(p.text)
155                    .margin(margin)
156                    .desired_width(desired_width);
157                if let Some(hint) = self.hint {
158                    edit = edit.hint_text(egui::RichText::new(hint).color(p.text_faint));
159                }
160                if self.password {
161                    edit = edit.password(true);
162                }
163
164                ui.add(edit)
165            });
166
167            if self.dirty && ui.is_rect_visible(response.rect) {
168                // Hug the inside of the border with a fixed geometry that does
169                // *not* change across hover/focus. The bar is a status
170                // indicator, not an interactive element — jittering it with the
171                // cursor reads as a bug. All input states use a 1 pt stroke
172                // (only the colour changes on focus), so inset = 1.0 matches
173                // the inner edge of the border in every state, and the bar's
174                // 5 pt inner corner radius matches the border's inner arc.
175                let stroke_w = 1.0;
176                let bar_w = 3.0;
177                let r = (theme.control_radius - stroke_w).max(0.0) as u8;
178                let bar = egui::Rect::from_min_max(
179                    egui::pos2(
180                        response.rect.min.x + stroke_w,
181                        response.rect.min.y + stroke_w,
182                    ),
183                    egui::pos2(
184                        response.rect.min.x + stroke_w + bar_w,
185                        response.rect.max.y - stroke_w,
186                    ),
187                );
188                let corner = CornerRadius {
189                    nw: r,
190                    sw: r,
191                    ne: 0,
192                    se: 0,
193                };
194                ui.painter().rect_filled(bar, corner, p.sky);
195            }
196
197            // Expose the field label via accesskit so screen readers announce
198            // the field purpose. TextEdit sets its own widget_info (with the
199            // current text value as the label); replacing it with ours makes
200            // the field queryable by its semantic label instead.
201            if let Some(label) = &self.label {
202                let label = label.text().to_string();
203                response.widget_info(|| WidgetInfo::labeled(WidgetType::TextEdit, true, &label));
204            }
205
206            response
207        })
208        .inner
209    }
210}