Skip to main content

egui_pop_core/
input.rs

1//! The decorated input: one component around a text, number, path or
2//! search field, with what desktop and web toolkits put around a field.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - a **placeholder** shown while the field is empty (`field.tone.muted.text`);
8//! - **leading and trailing slots**: an icon, a prefix or a suffix text,
9//!   a unit;
10//! - a **clear ✕**, shown while there is a value and the field can be
11//!   edited, reachable by Tab (Enter or Space presses it); clearing is
12//!   one change, so one undo step when the field is bound to a store
13//!   (and one in the field's own Ctrl+Z history);
14//! - a **reset** arrow while the [field state](crate::field) offers
15//!   "reset to default";
16//! - **attached buttons** joined to the field's end (Browse, a picker),
17//!   each a button of its own, or a **split button**: its action and a
18//!   chevron opening a menu;
19//! - a **dropdown chevron** opening a list of choices for the value;
20//! - the **field state** drawn as every field draws it (an edge, a marker
21//!   icon per state, the disabled reason as a tooltip), given to
22//!   assistive technologies and reported to agents ([`crate::field`]).
23//!
24//! Two text fields go beyond one visible line of plain text:
25//!
26//! - a **masked** field ([`Input::masked`]: a password, a token, an API
27//!   key) draws every character as a bullet, cannot be copied or cut
28//!   from, and gives assistive technologies its name and the
29//!   password-input role, never its value (the value and the text runs
30//!   they read are bullets too); agents get its kind (`masked`), never
31//!   its value;
32//! - a **multi-line** field ([`Input::multiline`]) shows
33//!   [`rows`](Input::rows) lines when it is short (2 by default), grows
34//!   with its text up to [`max_rows`](Input::max_rows) lines (8 by
35//!   default), then scrolls. Enter starts a new line and Ctrl+Enter
36//!   (Cmd+Enter on macOS) submits ([`InputOutput::submitted`], the field
37//!   keeps the focus); with [`submit_on_enter`](Input::submit_on_enter),
38//!   Enter submits and Shift+Enter starts a new line, as in a chat box.
39//!   Ctrl+Enter is a key binding's when the keymap binds it (the
40//!   dispatcher leaves only Escape and Enter without Ctrl or Alt to a
41//!   text field). Tab still moves the focus; the slots, the buttons and
42//!   the markers stay on the first line.
43//!
44//! The field itself is egui's `TextEdit`, so it follows the focus rules
45//! of every text input: while it has the focus, Escape and Enter are its
46//! own (Escape leaves the field, Enter commits it), and no key binding
47//! fires on them. A number field commits the value typed (a number or
48//! an expression, as a slider's typed entry reads it) when it loses the
49//! focus, except to Escape, which drops what was typed.
50//!
51//! Every part that takes the focus joins the Tab order of the
52//! [`crate::tab`] scope it is drawn in, as one group: the field, then its
53//! buttons. A disabled input is skipped; a read-only one is not.
54//!
55//! ```
56//! use egui_pop_core::icon::Icon;
57//! use egui_pop_core::input::{Attached, Input};
58//! use egui_pop_model::field::FieldState;
59//!
60//! fn row(ui: &mut egui::Ui, query: &mut String, folder: &mut String, iso: &mut f64) {
61//!     Input::search(query, "Search").placeholder("Search photos").show(ui);
62//!     let out = Input::path(folder, "Folder")
63//!         .button(Attached::text("Browse…", "Browse for a folder"))
64//!         .state(FieldState::new().required())
65//!         .show(ui);
66//!     if out.button == Some(0) { /* open a file dialog */ }
67//!     Input::number(iso, "ISO").unit("ISO").choices(["100", "400", "1600"]).show(ui);
68//! }
69//!
70//! fn account(ui: &mut egui::Ui, token: &mut String, notes: &mut String) {
71//!     Input::masked(token, "API token").show(ui);
72//!     let out = Input::multiline(notes, "Notes").rows(3).max_rows(6).show(ui);
73//!     if out.submitted { /* Ctrl+Enter: send the notes */ }
74//! }
75//! ```
76
77use egui::{
78    Align2, Color32, CornerRadius, FontId, Id, Rect, Response, Role, Sense, Stroke, StrokeKind,
79    TextStyle, Ui, Vec2, WidgetInfo, pos2, vec2,
80};
81use egui_pop_model::field::FieldState;
82
83use crate::field;
84use crate::icon::{Icon, IconRef};
85use crate::kit::{Kit, State, Tone};
86use crate::state;
87use crate::strings::{self, FIELD_RESET, INPUT_CHOICES, INPUT_CLEAR, INPUT_MORE};
88use crate::tab::{self, TabStop};
89use crate::theme::Tokens;
90use crate::widgets;
91
92/// What is typed in a number field while it has the focus, per field.
93const BUFFER: state::Slot<String> = state::Slot::new("core.input.buffer");
94
95/// What a field edits.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum Kind {
98    Text,
99    /// A number, typed or as an expression; committed on leaving.
100    Number,
101    /// A file or folder path.
102    Path,
103    /// A search query: a magnifier before it, clearable.
104    Search,
105}
106
107impl Kind {
108    pub fn name(self) -> &'static str {
109        match self {
110            Kind::Text => "text",
111            Kind::Number => "number",
112            Kind::Path => "path",
113            Kind::Search => "search",
114        }
115    }
116}
117
118/// Something drawn inside the field, before or after the value.
119#[derive(Clone, Debug, PartialEq)]
120pub enum Slot {
121    Icon(Icon),
122    /// A prefix, a suffix or a unit.
123    Text(String),
124}
125
126/// A button joined to the field's end.
127#[derive(Clone, Debug, PartialEq)]
128pub struct Attached {
129    icon: Option<Icon>,
130    text: Option<String>,
131    label: String,
132    menu: Vec<String>,
133}
134
135impl Attached {
136    /// An icon button, named `label` for assistive technologies; the
137    /// icon by value or by name (`"folder"`, `"phosphor:export"`; an
138    /// unknown name is reported and drawn as the placeholder).
139    pub fn icon(icon: impl Into<IconRef>, label: &str) -> Self {
140        Self {
141            icon: Some(icon.into().or_placeholder("input button")),
142            text: None,
143            label: label.into(),
144            menu: Vec::new(),
145        }
146    }
147
148    /// A text button (`Browse…`), named `label`.
149    pub fn text(text: &str, label: &str) -> Self {
150        Self {
151            icon: None,
152            text: Some(text.into()),
153            label: label.into(),
154            menu: Vec::new(),
155        }
156    }
157
158    /// Makes it a split button: its action, and a chevron opening a menu
159    /// of these items.
160    pub fn menu<S: Into<String>>(mut self, items: impl IntoIterator<Item = S>) -> Self {
161        self.menu = items.into_iter().map(Into::into).collect();
162        self
163    }
164}
165
166enum Value<'a> {
167    Text(&'a mut String),
168    Number(&'a mut f64),
169}
170
171/// A decorated input (see [the module](self)).
172#[must_use]
173pub struct Input<'a> {
174    value: Value<'a>,
175    kind: Kind,
176    label: String,
177    placeholder: Option<String>,
178    leading: Vec<Slot>,
179    trailing: Vec<Slot>,
180    clearable: bool,
181    buttons: Vec<Attached>,
182    choices: Vec<String>,
183    state: FieldState,
184    stop: TabStop,
185    width: Option<f32>,
186    cell: Option<Vec2>,
187    salt: Option<Id>,
188    default: Option<String>,
189    precision: Option<usize>,
190    masked: bool,
191    lines: Option<Lines>,
192}
193
194/// A multi-line field's rows and its Enter key.
195#[derive(Clone, Copy, Debug)]
196struct Lines {
197    rows: usize,
198    max_rows: usize,
199    submit_on_enter: bool,
200}
201
202impl std::fmt::Debug for Input<'_> {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        f.debug_struct("Input")
205            .field("kind", &self.kind)
206            .field("label", &self.label)
207            .field("masked", &self.masked)
208            .field("multiline", &self.lines.is_some())
209            .field("state", &self.state)
210            .finish_non_exhaustive()
211    }
212}
213
214/// What an input did in a frame.
215#[derive(Debug)]
216pub struct InputOutput {
217    /// The field's response (the text), with the state's tooltips.
218    pub response: Response,
219    /// The value changed (typed, cleared, chosen, reset, committed).
220    pub changed: bool,
221    /// The clear ✕ was pressed.
222    pub cleared: bool,
223    /// The reset arrow was pressed.
224    pub reset: bool,
225    /// Enter was pressed in the field (in a multi-line field,
226    /// Ctrl+Enter, or Enter with [`Input::submit_on_enter`]).
227    pub submitted: bool,
228    /// An attached button (its action, for a split button), by index.
229    pub button: Option<usize>,
230    /// A split button's menu item: the button's index and the item's.
231    pub menu: Option<(usize, usize)>,
232    /// A choice from the dropdown, by index (the value is set to it).
233    pub choice: Option<usize>,
234}
235
236impl<'a> Input<'a> {
237    fn with(value: Value<'a>, kind: Kind, label: &str) -> Self {
238        Self {
239            value,
240            kind,
241            label: label.into(),
242            placeholder: None,
243            leading: Vec::new(),
244            trailing: Vec::new(),
245            clearable: matches!(kind, Kind::Search),
246            buttons: Vec::new(),
247            choices: Vec::new(),
248            state: FieldState::default(),
249            stop: TabStop::new(),
250            width: None,
251            cell: None,
252            salt: None,
253            default: None,
254            precision: None,
255            masked: false,
256            lines: None,
257        }
258    }
259
260    /// A text field named `label` (for assistive technologies and
261    /// agents; the label itself is drawn by the form around it).
262    ///
263    /// Need (input): a single-line text field.
264    /// Need (input): a text field with a placeholder.
265    pub fn text(value: &'a mut String, label: &str) -> Self {
266        Self::with(Value::Text(value), Kind::Text, label)
267    }
268
269    /// A masked text field (a password, a token, a key): every character
270    /// a bullet, nothing to copy, and its value never given to assistive
271    /// technologies or agents, only its name.
272    ///
273    /// Need (input): a password field.
274    /// Need (input): a masked field for a secret (token, API key).
275    pub fn masked(value: &'a mut String, label: &str) -> Self {
276        let mut input = Self::with(Value::Text(value), Kind::Text, label);
277        input.masked = true;
278        input
279    }
280
281    /// A multi-line text field: [`rows`](Self::rows) lines tall, growing
282    /// with its text up to [`max_rows`](Self::max_rows), then scrolling;
283    /// Enter starts a new line, Ctrl+Enter submits (see
284    /// [`submit_on_enter`](Self::submit_on_enter)).
285    ///
286    /// Need (input): a multi-line text field (a description, notes).
287    /// Need (input): a text area that grows with its text.
288    pub fn multiline(value: &'a mut String, label: &str) -> Self {
289        let mut input = Self::with(Value::Text(value), Kind::Text, label);
290        input.lines = Some(Lines {
291            rows: 2,
292            max_rows: 8,
293            submit_on_enter: false,
294        });
295        input
296    }
297
298    /// A multi-line field's height when its text is short, in lines (at
299    /// least one; 2 by default). Raises [`max_rows`](Self::max_rows) to
300    /// it if needed. Nothing on a single-line field.
301    pub fn rows(mut self, rows: usize) -> Self {
302        if let Some(l) = &mut self.lines {
303            l.rows = rows.max(1);
304            l.max_rows = l.max_rows.max(l.rows);
305        }
306        self
307    }
308
309    /// The most lines a multi-line field grows to before it scrolls (8 by
310    /// default; never under [`rows`](Self::rows)). Nothing on a
311    /// single-line field.
312    pub fn max_rows(mut self, max_rows: usize) -> Self {
313        if let Some(l) = &mut self.lines {
314            l.max_rows = max_rows.max(l.rows);
315        }
316        self
317    }
318
319    /// In a multi-line field, Enter submits and Shift+Enter starts a new
320    /// line (a chat box); by default Enter starts a new line and
321    /// Ctrl+Enter submits. Nothing on a single-line field.
322    pub fn submit_on_enter(mut self, on: bool) -> Self {
323        if let Some(l) = &mut self.lines {
324            l.submit_on_enter = on;
325        }
326        self
327    }
328
329    /// A search field: a magnifier before the query, clearable.
330    ///
331    /// Need (input): a search field.
332    /// Need (input): a filter box.
333    pub fn search(value: &'a mut String, label: &str) -> Self {
334        Self::with(Value::Text(value), Kind::Search, label).leading_icon(Icon::Search)
335    }
336
337    /// A path field.
338    ///
339    /// Need (input): a file or folder path field.
340    pub fn path(value: &'a mut String, label: &str) -> Self {
341        Self::with(Value::Text(value), Kind::Path, label)
342    }
343
344    /// A number field: a number or an expression (`x * 2`, `1,5`),
345    /// committed when it loses the focus.
346    ///
347    /// Need (input): a number field with a unit.
348    pub fn number(value: &'a mut f64, label: &str) -> Self {
349        Self::with(Value::Number(value), Kind::Number, label)
350    }
351
352    /// The hint shown while the field is empty.
353    pub fn placeholder(mut self, text: &str) -> Self {
354        self.placeholder = Some(text.into());
355        self
356    }
357
358    /// An icon before the value, by value or by name (an unknown name is
359    /// reported and drawn as the placeholder).
360    pub fn leading_icon(mut self, icon: impl Into<IconRef>) -> Self {
361        self.leading
362            .push(Slot::Icon(icon.into().or_placeholder("input icon")));
363        self
364    }
365
366    /// A text before the value (`https://`, `#`).
367    pub fn prefix(mut self, text: &str) -> Self {
368        self.leading.push(Slot::Text(text.into()));
369        self
370    }
371
372    /// A text after the value (`.jpg`).
373    pub fn suffix(mut self, text: &str) -> Self {
374        self.trailing.push(Slot::Text(text.into()));
375        self
376    }
377
378    /// A unit after the value (`px`, `EV`).
379    pub fn unit(self, unit: &str) -> Self {
380        self.suffix(unit)
381    }
382
383    /// An icon after the value, by value or by name.
384    pub fn trailing_icon(mut self, icon: impl Into<IconRef>) -> Self {
385        self.trailing
386            .push(Slot::Icon(icon.into().or_placeholder("input icon")));
387        self
388    }
389
390    /// Shows the clear ✕ while there is a value (on by default for a
391    /// search field). A number field has none: its reset is the default.
392    pub fn clearable(mut self, on: bool) -> Self {
393        self.clearable = on;
394        self
395    }
396
397    /// A button joined to the field's end; its click is
398    /// [`InputOutput::button`].
399    pub fn button(mut self, button: Attached) -> Self {
400        self.buttons.push(button);
401        self
402    }
403
404    /// A dropdown chevron offering these values.
405    pub fn choices<S: Into<String>>(mut self, items: impl IntoIterator<Item = S>) -> Self {
406        self.choices = items.into_iter().map(Into::into).collect();
407        self
408    }
409
410    /// The field's state: modified, required, invalid, disabled (with a
411    /// reason), read-only, pending.
412    pub fn state(mut self, state: FieldState) -> Self {
413        self.state = state;
414        self
415    }
416
417    /// Its place in the Tab order of the scope it is drawn in.
418    pub fn tab(mut self, stop: TabStop) -> Self {
419        self.stop = stop;
420        self
421    }
422
423    /// Its width, attached buttons included (the available width by
424    /// default).
425    pub fn width(mut self, width: f32) -> Self {
426        self.width = Some(width);
427        self
428    }
429
430    /// A compact cell: exactly `size` (attached buttons included), for
431    /// a slot of a dense layout (a HUD part, a table cell, a property
432    /// row), its padding the small step (`space.xs`) instead of
433    /// `space.s`, and none of the room an input otherwise keeps for its
434    /// text (four rows' height). Everything else is the input's: the
435    /// placeholder, the slots, the state, the keys and the name.
436    pub fn cell(mut self, size: Vec2) -> Self {
437        self.cell = Some(size);
438        self
439    }
440
441    /// Distinguishes inputs with the same label in one place.
442    pub fn id_salt(mut self, salt: impl std::hash::Hash + std::fmt::Debug) -> Self {
443        self.salt = Some(Id::unique(salt));
444        self
445    }
446
447    /// The value "reset to default" puts back, as text (for a number,
448    /// its text: `"0"`).
449    pub fn default_value(mut self, value: &str) -> Self {
450        self.default = Some(value.into());
451        self
452    }
453
454    /// A number field's decimals when it is not being typed in.
455    pub fn precision(mut self, decimals: usize) -> Self {
456        self.precision = Some(decimals);
457        self
458    }
459
460    /// Draws the input; says what it did.
461    pub fn show(self, ui: &mut Ui) -> InputOutput {
462        let base = match self.salt {
463            Some(s) => ui.make_persistent_id(("egui_pop_input", s)),
464            None => ui.make_persistent_id(("egui_pop_input", &self.label)),
465        };
466        let disabled = self.state.is_disabled();
467        ui.scope(|ui| {
468            if disabled {
469                ui.disable();
470            }
471            self.draw(ui, base)
472        })
473        .inner
474    }
475
476    fn draw(self, ui: &mut Ui, base: Id) -> InputOutput {
477        let Input {
478            mut value,
479            kind,
480            label,
481            placeholder,
482            leading,
483            trailing,
484            clearable,
485            buttons,
486            choices,
487            state,
488            stop,
489            width,
490            cell,
491            salt: _,
492            default,
493            precision,
494            masked,
495            lines,
496        } = self;
497        let ctx = ui.ctx().clone();
498        let t = Tokens::of(&ctx);
499        let kit = Kit::of(&ctx);
500        let fk = &kit.field;
501        let h = cell.map_or(ui.spacing().interact_size.y, |c| c.y.max(1.0));
502        if cell.is_some() {
503            // The text field inside is no taller than the cell (egui's
504            // text edit is at least a row high); `draw` runs in a scope.
505            ui.spacing_mut().interact_size.y = h;
506        }
507        let pad = if cell.is_some() {
508            t.space.xs
509        } else {
510            t.space.s
511        };
512        let gap = t.space.xs;
513        let side = t.size.icon_inline.min(h - 2.0);
514        let font = TextStyle::Body.resolve(ui.style());
515        let measure = ui.painter().clone();
516        let text_w = |s: &str| {
517            measure
518                .layout_no_wrap(s.to_string(), font.clone(), Color32::WHITE)
519                .size()
520                .x
521        };
522        let button_font = TextStyle::Button.resolve(ui.style());
523        let button_w = |s: &str| {
524            measure
525                .layout_no_wrap(s.to_string(), button_font.clone(), Color32::WHITE)
526                .size()
527                .x
528        };
529        let editable = state.is_editable();
530        let group = stop
531            .group_name()
532            .map_or_else(|| format!("{base:?}"), str::to_string);
533        let mut part_stop = TabStop::new().group(group);
534        if let Some(i) = stop.explicit_index() {
535            part_stop = part_stop.index(i);
536        }
537
538        // The row: the field, then the attached buttons.
539        let widths: Vec<(f32, f32)> = buttons
540            .iter()
541            .map(|b| {
542                let main = match &b.text {
543                    Some(s) => button_w(s) + 2.0 * pad,
544                    None => h,
545                };
546                let chevron = if b.menu.is_empty() { 0.0 } else { h * 0.8 };
547                (main, chevron)
548            })
549            .collect();
550        let attached: f32 = widths.iter().map(|(a, b)| a + b).sum();
551        let total = match cell {
552            Some(c) => c.x.max(attached + h),
553            None => width
554                .unwrap_or_else(|| ui.available_width())
555                .max(attached + h * 4.0),
556        };
557        let text_id = base.with("text");
558
559        // Its text as shown.
560        let typing = ui.memory(|m| m.has_focus(text_id));
561        let buffer_id = BUFFER.keyed(base);
562        let mut buffer = match &value {
563            Value::Text(s) => (*s).clone(),
564            Value::Number(v) => match buffer_id.get(&ctx) {
565                Some(b) if typing => b,
566                _ => format_number(&ctx, **v, precision),
567            },
568        };
569        let has_value = !buffer.is_empty();
570        let mut changed = false;
571        let mut cleared = false;
572        let mut reset_pressed = false;
573        let mut clicked = None;
574        let mut menu = None;
575        let mut choice = None;
576
577        // What the field keeps beside its text, on its first line.
578        let slot_w = |s: &Slot| match s {
579            Slot::Icon(_) => side + gap,
580            Slot::Text(x) => text_w(x) + gap,
581        };
582        let has_chevron = !choices.is_empty() && editable;
583        let show_clear = clearable && kind != Kind::Number && editable && has_value;
584        let markers_w = field::markers_width(&state, side * 0.8, gap / 2.0);
585        let parts = [has_chevron, state.is_resettable(), show_clear]
586            .iter()
587            .filter(|on| **on)
588            .count() as f32;
589        let right_used = gap
590            + parts * h * 0.8
591            + trailing.iter().map(slot_w).sum::<f32>()
592            + if markers_w > 0.0 {
593                markers_w + gap
594            } else {
595                0.0
596            };
597        let left_used = field::edge_width(&t) + pad + leading.iter().map(slot_w).sum::<f32>();
598
599        // A multi-line field: as many lines as its text, between its rows
600        // and its most rows; the first line where a single-line text sits.
601        let row_h = ui.text_style_height(&TextStyle::Body);
602        let inset = ((h - row_h) / 2.0).max(0.0);
603        let (field_h, shown_rows) = match lines {
604            None => (h, 1),
605            Some(l) => {
606                let wrap = (total - attached - right_used - left_used).max(h);
607                let n = measure
608                    .layout(buffer.clone(), font.clone(), Color32::WHITE, wrap)
609                    .rows
610                    .len()
611                    .max(1);
612                let shown = n.clamp(l.rows, l.max_rows);
613                (h.max(shown as f32 * row_h + 2.0 * inset), shown)
614            }
615        };
616        let (_, row) = ui.allocate_space(vec2(total, field_h));
617        let field = Rect::from_min_max(row.min, pos2(row.right() - attached, row.bottom()));
618        let line = Rect::from_min_max(field.min, pos2(field.right(), field.top() + h));
619
620        // From the right end of the field: the chevron, the reset, the
621        // clear ✕, the trailing slots, the state's markers.
622        let mut right = line.right() - gap;
623        let mut take = |w: f32| {
624            let r = Rect::from_min_max(pos2(right - w, line.top()), pos2(right, line.bottom()));
625            right -= w;
626            r
627        };
628        let chevron_rect = has_chevron.then(|| take(h * 0.8));
629        let reset_rect = state.is_resettable().then(|| take(h * 0.8));
630        let clear_rect = show_clear.then(|| take(h * 0.8));
631        let mut trailing_rects = Vec::new();
632        for s in trailing.iter().rev() {
633            trailing_rects.push((take(slot_w(s)), s));
634        }
635        let markers_rect = (markers_w > 0.0).then(|| take(markers_w + gap));
636        let mut left = line.left() + field::edge_width(&t) + pad;
637        let mut leading_rects = Vec::new();
638        for s in &leading {
639            let w = slot_w(s);
640            leading_rects.push((
641                Rect::from_min_max(pos2(left, line.top()), pos2(left + w, line.bottom())),
642                s,
643            ));
644            left += w;
645        }
646        let text_rect = if lines.is_some() {
647            Rect::from_min_max(
648                pos2(left, field.top() + inset),
649                pos2(right.max(left + h), field.bottom() - inset),
650            )
651        } else {
652            Rect::from_min_max(
653                pos2(left, field.top()),
654                pos2(right.max(left + h), field.bottom()),
655            )
656        };
657
658        // The frame, then the text (drawn before the buttons inside the
659        // field: egui's own Tab order is the order of drawing).
660        if ui.is_rect_visible(field) {
661            let radius = CornerRadius::same(t.radius.widget.round().clamp(0.0, 255.0) as u8);
662            let fill = if state.read_only {
663                fk.style_toned(Tone::Muted, State::REST).fill
664            } else {
665                fk.style(State::REST).fill
666            };
667            ui.painter().rect_filled(field, radius, fill);
668        }
669        let look = Look {
670            id: text_id,
671            width: text_rect.width(),
672            color: fk.style(State::REST).text,
673            number: kind == Kind::Number,
674            masked,
675            lines: lines.map(|l| (l, shown_rows)),
676        };
677        let response = if editable {
678            let mut text = look.apply(if lines.is_some() {
679                egui::TextEdit::multiline(&mut buffer)
680            } else {
681                egui::TextEdit::singleline(&mut buffer)
682            });
683            if let Some(p) = &placeholder {
684                text = text.hint_text(
685                    egui::RichText::new(p).color(fk.style_toned(Tone::Muted, State::REST).text),
686                );
687            }
688            put_text(ui, text_rect, base, lines.is_some(), text)
689        } else {
690            // Read-only: selectable and copyable (unless masked), never
691            // changed.
692            let shown_text = buffer.clone();
693            let mut shown: &str = shown_text.as_str();
694            let text = look.apply(if lines.is_some() {
695                egui::TextEdit::multiline(&mut shown)
696            } else {
697                egui::TextEdit::singleline(&mut shown)
698            });
699            put_text(ui, text_rect, base, lines.is_some(), text)
700        };
701        tab::stop(ui, &response, part_stop.clone().skip(!state.is_focusable()));
702
703        // The buttons inside the field: what they change shows from the
704        // next frame.
705        let clear = clear_rect.map(|r| {
706            let label = strings::tr_args(&ctx, &INPUT_CLEAR, &[("label", label.as_str())]);
707            part(
708                ui,
709                r,
710                base.with("clear"),
711                PartLook::Icon(Icon::Close),
712                &label,
713            )
714        });
715        if let Some(c) = &clear {
716            tab::stop(ui, c, part_stop.clone());
717            if c.clicked() {
718                buffer.clear();
719                cleared = true;
720                ui.memory_mut(|m| m.request_focus(text_id));
721                ui.ctx().request_repaint();
722            }
723        }
724        let reset = reset_rect.map(|r| {
725            let label = strings::tr_args(&ctx, &FIELD_RESET, &[("label", label.as_str())]);
726            part(
727                ui,
728                r,
729                base.with("reset"),
730                PartLook::Icon(Icon::Reset),
731                &label,
732            )
733        });
734        if let Some(r) = &reset {
735            tab::stop(ui, r, part_stop.clone());
736            if r.clicked() {
737                reset_pressed = true;
738                if let Some(d) = &default {
739                    buffer = d.clone();
740                }
741            }
742        }
743        let chevron = chevron_rect.map(|r| {
744            let label = strings::tr_args(&ctx, &INPUT_CHOICES, &[("label", label.as_str())]);
745            part(
746                ui,
747                r,
748                base.with("chevron"),
749                PartLook::Icon(Icon::ChevronDown),
750                &label,
751            )
752        });
753        if let Some(c) = &chevron {
754            tab::stop(ui, c, part_stop.clone());
755            let popup = egui::Popup::menu(c).id(base.with("choices"));
756            let popup_id = popup.get_id();
757            let open = egui::Popup::is_id_open(&ctx, popup_id);
758            ctx.accesskit_node_builder(c.id, |n| {
759                n.set_has_popup(egui::accesskit::HasPopup::Listbox);
760                n.set_expanded(open);
761            });
762            popup.show(|ui| {
763                for (i, item) in choices.iter().enumerate() {
764                    if widgets::selectable_label(ui, *item == buffer, item).clicked() {
765                        choice = Some(i);
766                    }
767                }
768            });
769            if let Some(i) = choice {
770                buffer = choices[i].clone();
771            }
772        }
773
774        let submitted = match lines {
775            None => response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)),
776            // A multi-line field keeps the focus: its submit key is read
777            // as it is pressed (the text edit left it in the events).
778            Some(l) => {
779                response.has_focus()
780                    && ui.input(|i| {
781                        i.events.iter().any(|e| match e {
782                            egui::Event::Key {
783                                key: egui::Key::Enter,
784                                pressed: true,
785                                modifiers,
786                                ..
787                            } => {
788                                if l.submit_on_enter {
789                                    !modifiers.shift
790                                } else {
791                                    modifiers.command
792                                }
793                            }
794                            _ => false,
795                        })
796                    })
797            }
798        };
799
800        // The value written back.
801        match &mut value {
802            Value::Text(s) => {
803                if **s != buffer {
804                    **s = buffer.clone();
805                    changed = true;
806                }
807            }
808            Value::Number(v) => {
809                let commit = choice.is_some() || reset_pressed || !response.has_focus();
810                if response.has_focus() {
811                    buffer_id.set(&ctx, buffer.clone());
812                }
813                if commit {
814                    buffer_id.remove(&ctx);
815                    // Escape leaves the field with nothing: what was
816                    // typed is dropped, the value stays.
817                    let escaped =
818                        typing && !response.has_focus() && crate::focus::escape_left(&ctx, text_id);
819                    let typed_now = (typing || response.lost_focus()) && !escaped;
820                    if (typed_now || choice.is_some() || reset_pressed)
821                        && let Some(n) = crate::slider::parse_typed(&buffer)
822                        && n != **v
823                        && n.is_finite()
824                    {
825                        **v = n;
826                        changed = true;
827                    }
828                }
829            }
830        }
831
832        // Around the text: the slots, the markers, the border, the edge.
833        if ui.is_rect_visible(field) {
834            let painter = ui.painter();
835            let muted = if ui.is_enabled() {
836                t.text.muted
837            } else {
838                t.text.muted.gamma_multiply(0.6)
839            };
840            for (r, s) in leading_rects.iter().chain(trailing_rects.iter()) {
841                paint_slot(ui, *r, s, side, &font, muted);
842            }
843            if let Some(r) = markers_rect {
844                field::paint_markers(
845                    ui,
846                    pos2(r.left() + gap, r.center().y),
847                    side * 0.8,
848                    gap / 2.0,
849                    &state,
850                );
851            }
852            let radius = CornerRadius::same(t.radius.widget.round().clamp(0.0, 255.0) as u8);
853            let focused = response.has_focus()
854                || [&clear, &reset, &chevron]
855                    .iter()
856                    .any(|r| r.as_ref().is_some_and(Response::has_focus));
857            // The field's outline shows the focus of the field and its parts.
858            for r in [
859                Some(&response),
860                clear.as_ref(),
861                reset.as_ref(),
862                chevron.as_ref(),
863            ]
864            .into_iter()
865            .flatten()
866            {
867                crate::focus::own_ring(&r.ctx, r.id);
868            }
869            let stroke = if focused {
870                Stroke::new(2.0, t.focus_ring)
871            } else if response.hovered() && ui.is_enabled() {
872                Stroke::new(1.0, fk.style(State::HOVER).border_color)
873            } else {
874                Stroke::new(1.0, fk.style(State::REST).border_color)
875            };
876            painter.rect_stroke(field, radius, stroke, StrokeKind::Inside);
877            field::paint_edge(ui, field, &state);
878        }
879
880        // The attached buttons.
881        let mut x = field.right();
882        for (i, (b, (main_w, chevron_w))) in buttons.iter().zip(&widths).enumerate() {
883            let r = Rect::from_min_max(pos2(x, row.top()), pos2(x + main_w, row.bottom()));
884            x += main_w;
885            let look = match (&b.text, b.icon) {
886                (Some(s), _) => PartLook::Text(s),
887                (None, Some(icon)) => PartLook::Icon(icon),
888                (None, None) => PartLook::Text(&b.label),
889            };
890            let resp = attached_part(ui, r, base.with(("button", i)), look, &b.label);
891            tab::stop(ui, &resp, part_stop.clone());
892            if resp.clicked() {
893                clicked = Some(i);
894            }
895            if b.menu.is_empty() {
896                continue;
897            }
898            let r = Rect::from_min_max(pos2(x, row.top()), pos2(x + chevron_w, row.bottom()));
899            x += chevron_w;
900            let more = strings::tr_args(&ctx, &INPUT_MORE, &[("label", b.label.as_str())]);
901            let resp = attached_part(
902                ui,
903                r,
904                base.with(("menu", i)),
905                PartLook::Icon(Icon::ChevronDown),
906                &more,
907            );
908            tab::stop(ui, &resp, part_stop.clone());
909            if let Some(item) = split_menu(ui, &resp, base.with(("menu-popup", i)), &b.menu) {
910                menu = Some((i, item));
911            }
912        }
913
914        // The state: named, announced, reported.
915        let shown_label = label.clone();
916        let hint = placeholder.clone();
917        ctx.accesskit_node_builder(response.id, |n| {
918            n.set_label(shown_label);
919            // The placeholder, whatever egui makes of a styled hint.
920            if let Some(p) = hint {
921                n.set_placeholder(p);
922            }
923        });
924        field::access(&ctx, response.id, &state);
925        // What agents read: its kind, never a masked field's value.
926        let kind_name = if masked {
927            "masked"
928        } else if lines.is_some() {
929            "multiline"
930        } else {
931            kind.name()
932        };
933        field::record(&ctx, response.id, &label, kind_name, &state);
934        crate::a11y::input(&ctx, response.id, &label);
935        // Its icons, by name, for agents.
936        for slot in leading.iter().chain(trailing.iter()) {
937            if let Slot::Icon(i) = slot {
938                crate::icon::registry::record(&ctx, "input", &label, i.name());
939            }
940        }
941        for b in &buttons {
942            if let Some(i) = b.icon {
943                crate::icon::registry::record(&ctx, "input button", &b.label, i.name());
944            }
945        }
946        let mut response = field::hover(ui, &response, &state);
947        if changed {
948            response.mark_changed();
949        }
950        InputOutput {
951            response,
952            changed,
953            cleared,
954            reset: reset_pressed,
955            submitted,
956            button: clicked,
957            menu,
958            choice,
959        }
960    }
961}
962
963/// How the field's text is drawn: no frame of its own (the input draws
964/// it), a single line centred in the row (a number to the right), a
965/// multi-line text from the top.
966struct Look {
967    id: Id,
968    width: f32,
969    color: Color32,
970    number: bool,
971    masked: bool,
972    /// A multi-line field: its rows and the lines shown.
973    lines: Option<(Lines, usize)>,
974}
975
976impl Look {
977    fn apply<'t>(&self, text: egui::TextEdit<'t>) -> egui::TextEdit<'t> {
978        let align = match (self.lines, self.number) {
979            (Some(_), _) => Align2::LEFT_TOP,
980            (None, true) => Align2::RIGHT_CENTER,
981            (None, false) => Align2::LEFT_CENTER,
982        };
983        let mut text = text
984            .id(self.id)
985            .frame(egui::Frame::NONE)
986            .margin(egui::Margin::ZERO)
987            .align(align)
988            .desired_width(self.width)
989            .text_color(self.color)
990            .password(self.masked);
991        if let Some((l, shown)) = self.lines {
992            // Enter starts a new line unless it submits; then Shift+Enter
993            // does.
994            let newline = if l.submit_on_enter {
995                egui::Modifiers::SHIFT
996            } else {
997                egui::Modifiers::NONE
998            };
999            text = text
1000                .desired_rows(shown)
1001                .return_key(egui::KeyboardShortcut::new(newline, egui::Key::Enter));
1002        }
1003        text
1004    }
1005}
1006
1007/// Puts the field's text in its place: a single line as it is, a
1008/// multi-line text in a scroll area as tall as the lines shown.
1009fn put_text(
1010    ui: &mut Ui,
1011    rect: Rect,
1012    base: Id,
1013    multiline: bool,
1014    text: egui::TextEdit<'_>,
1015) -> Response {
1016    if !multiline {
1017        return ui.put(rect, text);
1018    }
1019    // From the top-left of its place, whatever the layout around (a
1020    // grid's cell centres its content), in a child that takes no room of
1021    // its own: the field's row is allocated already.
1022    let builder = egui::UiBuilder::new()
1023        .id_salt(base.with("area"))
1024        .max_rect(rect)
1025        .layout(egui::Layout::top_down(egui::Align::Min));
1026    let mut child = ui.new_child(builder);
1027    child.set_clip_rect(rect.intersect(ui.clip_rect()));
1028    egui::ScrollArea::vertical()
1029        .id_salt(base.with("scroll"))
1030        .max_height(rect.height())
1031        .auto_shrink([false, true])
1032        .show(&mut child, |ui| ui.add(text))
1033        .inner
1034}
1035
1036fn format_number(ctx: &egui::Context, v: f64, precision: Option<usize>) -> String {
1037    match precision {
1038        Some(p) => strings::number(ctx, v, p),
1039        None => format!("{v}"),
1040    }
1041}
1042
1043fn paint_slot(ui: &Ui, rect: Rect, slot: &Slot, side: f32, font: &FontId, color: Color32) {
1044    match slot {
1045        Slot::Icon(i) => {
1046            let r = Rect::from_center_size(
1047                pos2(rect.left() + side / 2.0, rect.center().y),
1048                vec2(side, side),
1049            );
1050            i.paint(ui.painter(), r, color);
1051        }
1052        Slot::Text(s) => {
1053            ui.painter().text(
1054                pos2(rect.left(), rect.center().y),
1055                Align2::LEFT_CENTER,
1056                s,
1057                font.clone(),
1058                color,
1059            );
1060        }
1061    }
1062}
1063
1064#[derive(Clone, Copy)]
1065enum PartLook<'s> {
1066    Icon(Icon),
1067    Text(&'s str),
1068}
1069
1070/// A small button inside the field (✕, reset, chevron): focusable,
1071/// named, pressed by a click, Enter or Space.
1072fn part(ui: &mut Ui, rect: Rect, id: Id, look: PartLook<'_>, label: &str) -> Response {
1073    let r = ui.interact(rect, id, Sense::click());
1074    let enabled = ui.is_enabled();
1075    r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, label));
1076    if ui.is_rect_visible(rect) {
1077        let t = Tokens::of(ui.ctx());
1078        let side = t.size.icon_inline.min(rect.height() - 4.0) * 0.8;
1079        let sq = Rect::from_center_size(rect.center(), vec2(side, side) + vec2(4.0, 4.0));
1080        let radius = CornerRadius::same(t.radius.widget.round().clamp(0.0, 255.0) as u8);
1081        if r.hovered() || r.has_focus() {
1082            ui.painter().rect_filled(sq, radius, t.surface.hover);
1083        }
1084        if r.has_focus() {
1085            crate::focus::own_ring(ui.ctx(), r.id);
1086        }
1087        if crate::focus::shows_ring(&r) {
1088            ui.painter().rect_stroke(
1089                sq,
1090                radius,
1091                Stroke::new(1.5, t.focus_ring),
1092                StrokeKind::Inside,
1093            );
1094        }
1095        let color = if !enabled {
1096            t.text.muted
1097        } else if r.hovered() {
1098            t.text.strong
1099        } else {
1100            t.text.default
1101        };
1102        if let PartLook::Icon(i) = look {
1103            i.paint(
1104                ui.painter(),
1105                Rect::from_center_size(rect.center(), vec2(side, side)),
1106                color,
1107            );
1108        }
1109    }
1110    r.on_hover_text(label)
1111}
1112
1113/// A button joined to the field: the button tokens, its own border.
1114fn attached_part(ui: &mut Ui, rect: Rect, id: Id, look: PartLook<'_>, label: &str) -> Response {
1115    let r = ui.interact(rect, id, Sense::click());
1116    let enabled = ui.is_enabled();
1117    r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, label));
1118    if ui.is_rect_visible(rect) {
1119        let t = Tokens::of(ui.ctx());
1120        let kit = Kit::of(ui.ctx());
1121        let b = |state| kit.button.style(state);
1122        let fill = if r.is_pointer_button_down_on() {
1123            b(State::ACTIVE).fill
1124        } else if r.hovered() {
1125            b(State::HOVER).fill
1126        } else {
1127            b(State::REST).fill
1128        };
1129        let radius = CornerRadius::same(b(State::REST).radius.round().clamp(0.0, 255.0) as u8);
1130        ui.painter().rect_filled(rect, radius, fill);
1131        if r.has_focus() {
1132            crate::focus::own_ring(ui.ctx(), r.id);
1133        }
1134        let stroke = if crate::focus::shows_ring(&r) {
1135            Stroke::new(2.0, t.focus_ring)
1136        } else {
1137            Stroke::new(1.0, kit.field.style(State::REST).border_color)
1138        };
1139        ui.painter()
1140            .rect_stroke(rect, radius, stroke, StrokeKind::Inside);
1141        let color = if enabled {
1142            b(State::REST).text
1143        } else {
1144            t.text.muted
1145        };
1146        match look {
1147            PartLook::Icon(i) => {
1148                let side = t.size.icon_inline.min(rect.height() - 4.0);
1149                i.paint(
1150                    ui.painter(),
1151                    Rect::from_center_size(rect.center(), vec2(side, side)),
1152                    color,
1153                );
1154            }
1155            PartLook::Text(s) => {
1156                ui.painter().text(
1157                    rect.center(),
1158                    Align2::CENTER_CENTER,
1159                    s,
1160                    TextStyle::Button.resolve(ui.style()),
1161                    color,
1162                );
1163            }
1164        }
1165    }
1166    if matches!(look, PartLook::Icon(_)) {
1167        r.on_hover_text(label)
1168    } else {
1169        r
1170    }
1171}
1172
1173/// A split button's menu under its chevron: the item chosen.
1174fn split_menu(ui: &Ui, chevron: &Response, id: Id, items: &[String]) -> Option<usize> {
1175    let popup = egui::Popup::menu(chevron).id(id);
1176    let open = egui::Popup::is_id_open(ui.ctx(), id);
1177    ui.ctx().accesskit_node_builder(chevron.id, |n| {
1178        n.set_has_popup(egui::accesskit::HasPopup::Menu);
1179        n.set_expanded(open);
1180    });
1181    let mut chosen = None;
1182    popup.show(|ui| {
1183        for (i, item) in items.iter().enumerate() {
1184            if ui.button(item).clicked() {
1185                chosen = Some(i);
1186            }
1187        }
1188    });
1189    chosen
1190}
1191
1192/// What a split button did.
1193#[derive(Debug)]
1194pub struct SplitOutput {
1195    /// The action's response.
1196    pub response: Response,
1197    /// The action was pressed.
1198    pub clicked: bool,
1199    /// A menu item, by index.
1200    pub chosen: Option<usize>,
1201}
1202
1203/// A split button on its own: an action (`text`) and a chevron opening
1204/// a menu of `items`. Both parts take the focus and join the Tab order.
1205///
1206/// Need (action): a button with a menu of alternatives (split button).
1207pub fn split_button(ui: &mut Ui, text: &str, items: &[&str]) -> SplitOutput {
1208    let t = Tokens::of(ui.ctx());
1209    let h = ui.spacing().interact_size.y;
1210    let font = TextStyle::Button.resolve(ui.style());
1211    let w = ui
1212        .painter()
1213        .layout_no_wrap(text.to_string(), font, Color32::WHITE)
1214        .size()
1215        .x
1216        + 2.0 * t.space.s;
1217    let (id, row) = ui.allocate_space(vec2(w + h * 0.8, h));
1218    let main = Rect::from_min_max(row.min, pos2(row.left() + w, row.bottom()));
1219    let chev = Rect::from_min_max(pos2(main.right(), row.top()), row.max);
1220    let group = format!("{id:?}");
1221    let response = attached_part(ui, main, id.with("action"), PartLook::Text(text), text);
1222    tab::stop(ui, &response, TabStop::new().group(group.clone()));
1223    let more = strings::tr_args(ui.ctx(), &INPUT_MORE, &[("label", text)]);
1224    let c = attached_part(
1225        ui,
1226        chev,
1227        id.with("chevron"),
1228        PartLook::Icon(Icon::ChevronDown),
1229        &more,
1230    );
1231    tab::stop(ui, &c, TabStop::new().group(group));
1232    let items: Vec<String> = items.iter().map(|s| s.to_string()).collect();
1233    let chosen = split_menu(ui, &c, id.with("menu"), &items);
1234    SplitOutput {
1235        clicked: response.clicked(),
1236        response,
1237        chosen,
1238    }
1239}