Skip to main content

iced_cube/primitives/
input.rs

1//! Single-line text inputs with an optional leading icon.
2//!
3//! Besides iced's own editing keys (select all, copy, cut, paste, moving by
4//! word, Home and End), inputs undo and redo, delete a word with
5//! Ctrl+Backspace and Ctrl+Delete, and keep Escape to themselves: see
6//! [`Shortcut`] and [`default_keymap`]. Pass a [`Shortcuts`] set to
7//! [`Input::shortcuts`] to switch some or all of them off, and a keymap to
8//! [`Input::keymap`] to rebind them. Textareas and every component with a
9//! search or filter field take the same set.
10//!
11//! ```no_run
12//! use iced_cube::input;
13//! use iced_cube::primitives::input::{Shortcut, Shortcuts};
14//!
15//! #[derive(Debug, Clone)]
16//! enum Message { Name(String) }
17//!
18//! // The app has its own undo, so the field leaves Ctrl+Z and Ctrl+Y alone.
19//! let view: iced::Element<'_, Message> = input("Name", "Ada")
20//!     .shortcuts(Shortcuts::all().without(Shortcut::Undo).without(Shortcut::Redo))
21//!     .on_input(Message::Name)
22//!     .into();
23//! ```
24
25use std::cell::Cell;
26use std::fmt;
27use std::rc::Rc;
28
29use iced::widget::text::LineHeight;
30use iced::widget::text_input::{Status, Style};
31use iced::widget::{self, Id, container, stack, text_input};
32use iced::{Alignment, Background, Border, Color, Element, Length, Padding};
33
34pub use crate::editing::{Shortcut, Shortcuts, default_keymap};
35
36use crate::editing::{self, Editing, Limit};
37use crate::icon::{Glyph, opacity, themed};
38use crate::keys::Keymap;
39use crate::theme::{Tokens, fade, mix, radius, space, text_size};
40
41const LINE_HEIGHT: f32 = 1.3;
42
43/// Input dimensions.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
45pub enum Size {
46    Sm,
47    #[default]
48    Md,
49    Lg,
50}
51
52impl Size {
53    pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
54
55    /// Height, horizontal padding, text size and icon size.
56    pub const fn metrics(self) -> Metrics {
57        match self {
58            Size::Sm => Metrics {
59                height: 32.0,
60                padding_x: 10.0,
61                text: text_size::SM,
62                icon: 14.0,
63            },
64            Size::Md => Metrics {
65                height: 36.0,
66                padding_x: 12.0,
67                text: text_size::SM,
68                icon: 16.0,
69            },
70            Size::Lg => Metrics {
71                height: 40.0,
72                padding_x: 14.0,
73                text: text_size::MD,
74                icon: 18.0,
75            },
76        }
77    }
78}
79
80/// Resolved dimensions for a [`Size`].
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct Metrics {
83    pub height: f32,
84    pub padding_x: f32,
85    pub text: f32,
86    pub icon: f32,
87}
88
89impl Metrics {
90    /// Inner padding that makes the input exactly `height` tall, leaving
91    /// room for a leading icon when there is one.
92    pub fn padding(self, with_icon: bool) -> Padding {
93        let vertical = ((self.height - self.text * LINE_HEIGHT) / 2.0).max(0.0);
94        let left = if with_icon {
95            self.padding_x + self.icon + space::SM
96        } else {
97            self.padding_x
98        };
99        Padding {
100            top: vertical,
101            bottom: vertical,
102            left,
103            right: self.padding_x,
104        }
105    }
106}
107
108/// A text input builder. Convert it into an [`Element`] to render.
109///
110/// An input without an `on_input` message is rendered disabled.
111pub struct Input<'a, Message> {
112    placeholder: String,
113    value: String,
114    id: Option<Id>,
115    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
116    on_submit: Option<Message>,
117    icon: Option<Glyph>,
118    secure: bool,
119    invalid: bool,
120    size: Size,
121    width: Length,
122    shortcuts: Shortcuts,
123    keymap: Keymap<Shortcut>,
124    on_clear: Option<Message>,
125    max_length: Option<usize>,
126}
127
128/// Creates a text input showing `value`, with `placeholder` while empty.
129pub fn input<'a, Message>(placeholder: &str, value: &str) -> Input<'a, Message> {
130    Input {
131        placeholder: placeholder.to_owned(),
132        value: value.to_owned(),
133        id: None,
134        on_input: None,
135        on_submit: None,
136        icon: None,
137        secure: false,
138        invalid: false,
139        size: Size::default(),
140        width: Length::Fill,
141        shortcuts: Shortcuts::all(),
142        keymap: default_keymap(),
143        on_clear: None,
144        max_length: None,
145    }
146}
147
148/// The id of the clear button of a [clearable](Input::clearable) input,
149/// to find or press it in tests. Every clearable input shares it.
150pub fn clear_id() -> Id {
151    Id::new("iced-cube-input-clear")
152}
153
154impl<'a, Message> Input<'a, Message> {
155    /// Sets the widget id, used to focus the input or find it in tests.
156    pub fn id(mut self, id: impl Into<Id>) -> Self {
157        self.id = Some(id.into());
158        self
159    }
160
161    /// Sets the message produced for every edit. Without it the input is disabled.
162    pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'a) -> Self {
163        self.on_input = Some(Box::new(on_input));
164        self
165    }
166
167    pub fn on_input_maybe(mut self, on_input: Option<impl Fn(String) -> Message + 'a>) -> Self {
168        self.on_input = on_input.map(|f| Box::new(f) as Box<dyn Fn(String) -> Message + 'a>);
169        self
170    }
171
172    /// Sets the message produced when Enter is pressed.
173    pub fn on_submit(mut self, message: Message) -> Self {
174        self.on_submit = Some(message);
175        self
176    }
177
178    pub fn on_submit_maybe(mut self, message: Option<Message>) -> Self {
179        self.on_submit = message;
180        self
181    }
182
183    /// Adds a Lucide icon at the start of the input.
184    pub fn icon(mut self, glyph: Glyph) -> Self {
185        self.icon = Some(glyph);
186        self
187    }
188
189    /// Masks the value, for passwords and other secrets.
190    pub fn secure(mut self, secure: bool) -> Self {
191        self.secure = secure;
192        self
193    }
194
195    /// Marks the value as invalid, drawing a destructive border.
196    pub fn invalid(mut self, invalid: bool) -> Self {
197        self.invalid = invalid;
198        self
199    }
200
201    pub fn size(mut self, size: Size) -> Self {
202        self.size = size;
203        self
204    }
205
206    /// Overrides the width. Inputs fill the available width by default.
207    pub fn width(mut self, width: impl Into<Length>) -> Self {
208        self.width = width.into();
209        self
210    }
211
212    /// Sets which [`Shortcut`]s the input handles. All of them by default;
213    /// pass [`Shortcuts::none`] to turn them all off. The keys of a shortcut
214    /// that is off reach the app, and iced's own editing keys always work.
215    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
216        self.shortcuts = shortcuts;
217        self
218    }
219
220    /// Replaces the [`default_keymap`], to bind the shortcuts to other keys.
221    pub fn keymap(mut self, keymap: Keymap<Shortcut>) -> Self {
222        self.keymap = keymap;
223        self
224    }
225
226    /// Draws an x button at the end of the field while it holds text and is
227    /// enabled. Pressing it emits `message`; the app empties the value.
228    pub fn clearable(mut self, message: Message) -> Self {
229        self.on_clear = Some(message);
230        self
231    }
232
233    /// Stops edits from growing the value past `max_length` characters.
234    /// Typed text that does not fit is dropped and pasted text is cut short.
235    /// A longer value set by the app is shown as it is and can only shrink.
236    pub fn max_length(mut self, max_length: usize) -> Self {
237        self.max_length = Some(max_length);
238        self
239    }
240
241    pub fn is_enabled(&self) -> bool {
242        self.on_input.is_some()
243    }
244
245    /// Whether the clear button shows: the input is clearable, enabled and
246    /// not empty.
247    pub fn shows_clear(&self) -> bool {
248        self.on_clear.is_some() && self.is_enabled() && !self.value.is_empty()
249    }
250}
251
252/// Builds an iced text input from `field` with `on_input` wired up and the
253/// editing shortcuts around it.
254#[cfg(any(feature = "combobox", feature = "command"))]
255pub(crate) fn with_shortcuts<'a, Message: Clone + 'a>(
256    field: text_input::TextInput<'a, Message>,
257    value: &str,
258    secure: bool,
259    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
260    keymap: Keymap<Shortcut>,
261    shortcuts: Shortcuts,
262) -> Element<'a, Message> {
263    limited(field, value, secure, on_input, keymap, shortcuts, None)
264}
265
266/// Builds the field with its editing shortcuts, keeping the value within
267/// `max_length` characters when it is set.
268fn limited<'a, Message: Clone + 'a>(
269    field: text_input::TextInput<'a, Message>,
270    value: &str,
271    secure: bool,
272    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
273    keymap: Keymap<Shortcut>,
274    shortcuts: Shortcuts,
275    max_length: Option<usize>,
276) -> Element<'a, Message> {
277    let Some(on_input) = on_input else {
278        return field.into();
279    };
280    let on_input: Rc<dyn Fn(String) -> Message + 'a> = Rc::from(on_input);
281    let edited = Rc::new(Cell::new(false));
282    let limit = max_length.map(|max| Rc::new(Limit::new(max, value)));
283    let field = field.on_input({
284        let (on_input, edited, limit) = (Rc::clone(&on_input), Rc::clone(&edited), limit.clone());
285        move |value| {
286            edited.set(true);
287            match &limit {
288                Some(limit) => on_input(limit.apply(value)),
289                None => on_input(value),
290            }
291        }
292    });
293    Editing::new(
294        field,
295        editing::Input::new(value, secure, on_input).limit(limit),
296        keymap,
297        shortcuts,
298        edited,
299    )
300    .into()
301}
302
303impl<Message: fmt::Debug> fmt::Debug for Input<'_, Message> {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.debug_struct("Input")
306            .field("placeholder", &self.placeholder)
307            .field("value", &self.value)
308            .field("id", &self.id)
309            .field("enabled", &self.is_enabled())
310            .field("on_submit", &self.on_submit)
311            .field("icon", &self.icon)
312            .field("secure", &self.secure)
313            .field("invalid", &self.invalid)
314            .field("size", &self.size)
315            .field("width", &self.width)
316            .field("shortcuts", &self.shortcuts)
317            .field("keymap", &self.keymap)
318            .field("on_clear", &self.on_clear)
319            .field("max_length", &self.max_length)
320            .finish()
321    }
322}
323
324impl<'a, Message: Clone + 'a> From<Input<'a, Message>> for Element<'a, Message> {
325    fn from(input: Input<'a, Message>) -> Self {
326        let metrics = input.size.metrics();
327        let invalid = input.invalid;
328        let enabled = input.is_enabled();
329        let clearable = input.on_clear.is_some() && enabled;
330        let clear = input
331            .shows_clear()
332            .then_some(input.on_clear.clone())
333            .flatten();
334
335        let mut padding = metrics.padding(input.icon.is_some());
336        // The room stays while the field is empty, so the text does not
337        // reflow when the button appears.
338        if clearable {
339            padding.right = metrics.padding_x + metrics.icon + space::SM;
340        }
341        let mut field = text_input(&input.placeholder, &input.value)
342            .secure(input.secure)
343            .size(metrics.text)
344            .line_height(LineHeight::Relative(LINE_HEIGHT))
345            .padding(padding)
346            .width(Length::Fill)
347            .on_submit_maybe(input.on_submit.filter(|_| enabled))
348            .style(move |theme, status| style(&Tokens::of(theme), status, invalid));
349        if let Some(id) = input.id {
350            field = field.id(id);
351        }
352        let field = limited(
353            field,
354            &input.value,
355            input.secure,
356            input.on_input,
357            input.keymap,
358            input.shortcuts,
359            input.max_length,
360        );
361
362        // A clearable field keeps the same widget tree whether or not the
363        // button shows, so it stays focused as the first character is typed.
364        if input.icon.is_none() && !clearable {
365            return container(field).width(input.width).into();
366        }
367
368        let status = if enabled {
369            Status::Active
370        } else {
371            Status::Disabled
372        };
373        let icon = input.icon.map(|glyph| {
374            let icon = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
375                style(&Tokens::of(theme), status, invalid).icon
376            });
377            container(icon)
378                .padding(Padding::ZERO.left(metrics.padding_x))
379                .height(Length::Fill)
380                .align_y(Alignment::Center)
381        });
382        let clear = clear.map(|message| clear_button(metrics, message));
383
384        stack![field]
385            .push(icon)
386            .push(clear)
387            .width(input.width)
388            .into()
389    }
390}
391
392/// Padding around the clear button's icon.
393const CLEAR_PADDING: f32 = 2.0;
394
395/// The x button at the end of a clearable input, lined up with the text
396/// padding.
397fn clear_button<'a, Message: Clone + 'a>(
398    metrics: Metrics,
399    message: Message,
400) -> Element<'a, Message> {
401    let icon = themed(crate::lucide!(X), metrics.icon, 1.0, |theme| {
402        Tokens::of(theme).muted_foreground
403    });
404    let button = widget::button(icon)
405        .padding(CLEAR_PADDING)
406        .on_press(message)
407        .style(|theme, status| clear_style(&Tokens::of(theme), status));
408    container(container(button).id(clear_id()))
409        .padding(Padding::ZERO.right(metrics.padding_x - CLEAR_PADDING))
410        .width(Length::Fill)
411        .height(Length::Fill)
412        .align_x(Alignment::End)
413        .align_y(Alignment::Center)
414        .into()
415}
416
417/// The clear button: bare at rest, on the accent surface under the pointer.
418pub fn clear_style(tokens: &Tokens, status: widget::button::Status) -> widget::button::Style {
419    use widget::button::Status as Button;
420    let background = matches!(status, Button::Hovered | Button::Pressed)
421        .then_some(Background::Color(tokens.accent));
422    widget::button::Style {
423        background,
424        text_color: tokens.muted_foreground,
425        border: Border {
426            radius: radius::SM.into(),
427            ..Border::default()
428        },
429        ..widget::button::Style::default()
430    }
431}
432
433/// The iced text input style for a status, optionally marked invalid.
434pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
435    let border = match (invalid, status) {
436        (true, _) => tokens.destructive,
437        (false, Status::Focused { .. }) => mix(tokens.border, tokens.foreground, 0.6),
438        (false, Status::Hovered) => mix(tokens.border, tokens.foreground, 0.25),
439        (false, Status::Active | Status::Disabled) => tokens.border,
440    };
441
442    // Transparent so the field takes the colour of whatever surface it sits
443    // on, such as a dialog or popover.
444    let active = Style {
445        background: Background::Color(Color::TRANSPARENT),
446        border: Border {
447            color: border,
448            width: 1.0,
449            radius: radius::MD.into(),
450        },
451        icon: tokens.muted_foreground,
452        placeholder: tokens.muted_foreground,
453        value: tokens.foreground,
454        selection: fade(tokens.primary, 0.25),
455    };
456
457    if status != Status::Disabled {
458        return active;
459    }
460    Style {
461        background: Background::Color(tokens.disabled_field()),
462        border: Border {
463            color: fade(border, 0.5),
464            ..active.border
465        },
466        icon: fade(active.icon, 0.5),
467        placeholder: fade(active.placeholder, 0.5),
468        value: fade(active.value, 0.5),
469        selection: Color::TRANSPARENT,
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use crate::theme::{dark, light};
477
478    const STATES: [Status; 5] = [
479        Status::Active,
480        Status::Hovered,
481        Status::Focused { is_hovered: false },
482        Status::Focused { is_hovered: true },
483        Status::Disabled,
484    ];
485
486    fn border(style: Style) -> Color {
487        style.border.color
488    }
489
490    #[test]
491    fn default_builder_is_medium_fill_and_disabled() {
492        let i: Input<'_, ()> = input("Email", "");
493        assert_eq!(i.size, Size::Md);
494        assert_eq!(i.width, Length::Fill);
495        assert!(!i.secure && !i.invalid);
496        assert!(i.icon.is_none() && i.id.is_none());
497        assert!(!i.is_enabled());
498        assert_eq!(i.shortcuts, Shortcuts::all());
499        assert_eq!(i.keymap, default_keymap());
500        assert!(i.on_clear.is_none() && i.max_length.is_none());
501        assert!(!i.shows_clear());
502    }
503
504    #[test]
505    fn the_clear_button_shows_only_for_an_enabled_field_with_text() {
506        let shows = |value: &str, enabled: bool| {
507            input::<String>("", value)
508                .clearable(String::new())
509                .on_input_maybe(enabled.then_some(|s| s))
510                .shows_clear()
511        };
512        assert!(shows("text", true));
513        assert!(!shows("", true));
514        assert!(!shows("text", false));
515        assert!(!input::<String>("", "text").on_input(|s| s).shows_clear());
516    }
517
518    #[test]
519    fn max_length_is_kept() {
520        let i: Input<'_, ()> = input("", "").max_length(8);
521        assert_eq!(i.max_length, Some(8));
522    }
523
524    #[test]
525    fn the_clear_button_highlights_under_the_pointer() {
526        use widget::button::Status as Button;
527        for theme in [light(), dark()] {
528            let tokens = Tokens::of(&theme);
529            assert_eq!(clear_style(&tokens, Button::Active).background, None);
530            for status in [Button::Hovered, Button::Pressed] {
531                assert_eq!(
532                    clear_style(&tokens, status).background,
533                    Some(Background::Color(tokens.accent))
534                );
535            }
536            assert_eq!(
537                clear_style(&tokens, Button::Active).text_color,
538                tokens.muted_foreground
539            );
540        }
541    }
542
543    #[test]
544    fn shortcuts_and_keymap_can_be_changed() {
545        let i: Input<'_, ()> = input("", "")
546            .shortcuts(Shortcuts::none())
547            .keymap(Keymap::new());
548        assert_eq!(i.shortcuts, Shortcuts::none());
549        assert!(i.keymap.is_empty());
550    }
551
552    #[test]
553    fn on_input_enables_and_on_input_maybe_none_disables() {
554        assert!(input::<String>("", "").on_input(|s| s).is_enabled());
555        let none: Option<fn(String) -> String> = None;
556        assert!(
557            !input::<String>("", "")
558                .on_input(|s| s)
559                .on_input_maybe(none)
560                .is_enabled()
561        );
562    }
563
564    #[test]
565    fn builder_keeps_placeholder_and_value() {
566        let i: Input<'_, ()> = input("Search", "iced").secure(true).invalid(true);
567        assert_eq!(i.placeholder, "Search");
568        assert_eq!(i.value, "iced");
569        assert!(i.secure && i.invalid);
570    }
571
572    #[test]
573    fn sizes_grow_monotonically() {
574        let heights = Size::ALL.map(|s| s.metrics().height);
575        assert!(heights.windows(2).all(|w| w[0] < w[1]));
576    }
577
578    #[test]
579    fn padding_produces_the_target_height() {
580        for size in Size::ALL {
581            let m = size.metrics();
582            let p = m.padding(false);
583            let height = m.text * LINE_HEIGHT + p.top + p.bottom;
584            assert!((height - m.height).abs() < 1e-3, "{size:?}");
585        }
586    }
587
588    #[test]
589    fn icon_reserves_space_on_the_left_only() {
590        let m = Size::Md.metrics();
591        let plain = m.padding(false);
592        let with_icon = m.padding(true);
593        assert!(with_icon.left > plain.left + m.icon);
594        assert_eq!(with_icon.right, plain.right);
595        assert_eq!(with_icon.top, plain.top);
596    }
597
598    #[test]
599    fn hover_and_focus_strengthen_the_border() {
600        for theme in [light(), dark()] {
601            let tokens = Tokens::of(&theme);
602            let active = border(style(&tokens, Status::Active, false));
603            let hovered = border(style(&tokens, Status::Hovered, false));
604            let focused = border(style(&tokens, Status::Focused { is_hovered: false }, false));
605            assert_ne!(active, hovered);
606            assert_ne!(hovered, focused);
607            assert_eq!(
608                focused,
609                border(style(&tokens, Status::Focused { is_hovered: true }, false))
610            );
611        }
612    }
613
614    #[test]
615    fn invalid_uses_destructive_border_in_every_enabled_status() {
616        for theme in [light(), dark()] {
617            let tokens = Tokens::of(&theme);
618            for status in STATES {
619                let style = style(&tokens, status, true);
620                let expected = if status == Status::Disabled {
621                    fade(tokens.destructive, 0.5)
622                } else {
623                    tokens.destructive
624                };
625                assert_eq!(style.border.color, expected, "{status:?}");
626            }
627        }
628    }
629
630    #[test]
631    fn disabled_halves_text_alpha_and_mutes_background() {
632        for theme in [light(), dark()] {
633            let tokens = Tokens::of(&theme);
634            let active = style(&tokens, Status::Active, false);
635            let disabled = style(&tokens, Status::Disabled, false);
636            assert!((disabled.value.a - active.value.a * 0.5).abs() < 1e-6);
637            assert!((disabled.placeholder.a - active.placeholder.a * 0.5).abs() < 1e-6);
638            assert_ne!(disabled.background, active.background);
639            assert_eq!(
640                disabled.background,
641                Background::Color(tokens.disabled_field())
642            );
643        }
644    }
645
646    #[test]
647    fn enabled_fields_take_the_colour_of_their_surface() {
648        for theme in [light(), dark()] {
649            let tokens = Tokens::of(&theme);
650            for status in STATES.into_iter().filter(|s| *s != Status::Disabled) {
651                for invalid in [false, true] {
652                    let style = style(&tokens, status, invalid);
653                    assert_eq!(style.background, Background::Color(Color::TRANSPARENT));
654                }
655            }
656        }
657    }
658
659    #[test]
660    fn every_status_has_a_visible_border_and_readable_value() {
661        for theme in [light(), dark()] {
662            let tokens = Tokens::of(&theme);
663            for status in STATES {
664                for invalid in [false, true] {
665                    let style = style(&tokens, status, invalid);
666                    assert_eq!(style.border.width, 1.0);
667                    assert!(style.border.color.a > 0.0);
668                    assert_ne!(style.value, tokens.background);
669                }
670            }
671        }
672    }
673}