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::{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};
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}
125
126/// Creates a text input showing `value`, with `placeholder` while empty.
127pub fn input<'a, Message>(placeholder: &str, value: &str) -> Input<'a, Message> {
128    Input {
129        placeholder: placeholder.to_owned(),
130        value: value.to_owned(),
131        id: None,
132        on_input: None,
133        on_submit: None,
134        icon: None,
135        secure: false,
136        invalid: false,
137        size: Size::default(),
138        width: Length::Fill,
139        shortcuts: Shortcuts::all(),
140        keymap: default_keymap(),
141    }
142}
143
144impl<'a, Message> Input<'a, Message> {
145    /// Sets the widget id, used to focus the input or find it in tests.
146    pub fn id(mut self, id: impl Into<Id>) -> Self {
147        self.id = Some(id.into());
148        self
149    }
150
151    /// Sets the message produced for every edit. Without it the input is disabled.
152    pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'a) -> Self {
153        self.on_input = Some(Box::new(on_input));
154        self
155    }
156
157    pub fn on_input_maybe(mut self, on_input: Option<impl Fn(String) -> Message + 'a>) -> Self {
158        self.on_input = on_input.map(|f| Box::new(f) as Box<dyn Fn(String) -> Message + 'a>);
159        self
160    }
161
162    /// Sets the message produced when Enter is pressed.
163    pub fn on_submit(mut self, message: Message) -> Self {
164        self.on_submit = Some(message);
165        self
166    }
167
168    pub fn on_submit_maybe(mut self, message: Option<Message>) -> Self {
169        self.on_submit = message;
170        self
171    }
172
173    /// Adds a Lucide icon at the start of the input.
174    pub fn icon(mut self, glyph: Glyph) -> Self {
175        self.icon = Some(glyph);
176        self
177    }
178
179    /// Masks the value, for passwords and other secrets.
180    pub fn secure(mut self, secure: bool) -> Self {
181        self.secure = secure;
182        self
183    }
184
185    /// Marks the value as invalid, drawing a destructive border.
186    pub fn invalid(mut self, invalid: bool) -> Self {
187        self.invalid = invalid;
188        self
189    }
190
191    pub fn size(mut self, size: Size) -> Self {
192        self.size = size;
193        self
194    }
195
196    /// Overrides the width. Inputs fill the available width by default.
197    pub fn width(mut self, width: impl Into<Length>) -> Self {
198        self.width = width.into();
199        self
200    }
201
202    /// Sets which [`Shortcut`]s the input handles. All of them by default;
203    /// pass [`Shortcuts::none`] to turn them all off. The keys of a shortcut
204    /// that is off reach the app, and iced's own editing keys always work.
205    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
206        self.shortcuts = shortcuts;
207        self
208    }
209
210    /// Replaces the [`default_keymap`], to bind the shortcuts to other keys.
211    pub fn keymap(mut self, keymap: Keymap<Shortcut>) -> Self {
212        self.keymap = keymap;
213        self
214    }
215
216    pub fn is_enabled(&self) -> bool {
217        self.on_input.is_some()
218    }
219}
220
221/// Builds an iced text input from `field` with `on_input` wired up and the
222/// editing shortcuts around it.
223pub(crate) fn with_shortcuts<'a, Message: Clone + 'a>(
224    field: text_input::TextInput<'a, Message>,
225    value: &str,
226    secure: bool,
227    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
228    keymap: Keymap<Shortcut>,
229    shortcuts: Shortcuts,
230) -> Element<'a, Message> {
231    let Some(on_input) = on_input else {
232        return field.into();
233    };
234    let on_input: Rc<dyn Fn(String) -> Message + 'a> = Rc::from(on_input);
235    let edited = Rc::new(Cell::new(false));
236    let field = field.on_input({
237        let (on_input, edited) = (Rc::clone(&on_input), Rc::clone(&edited));
238        move |value| {
239            edited.set(true);
240            on_input(value)
241        }
242    });
243    Editing::new(
244        field,
245        editing::Input::new(value, secure, on_input),
246        keymap,
247        shortcuts,
248        edited,
249    )
250    .into()
251}
252
253impl<Message: fmt::Debug> fmt::Debug for Input<'_, Message> {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.debug_struct("Input")
256            .field("placeholder", &self.placeholder)
257            .field("value", &self.value)
258            .field("id", &self.id)
259            .field("enabled", &self.is_enabled())
260            .field("on_submit", &self.on_submit)
261            .field("icon", &self.icon)
262            .field("secure", &self.secure)
263            .field("invalid", &self.invalid)
264            .field("size", &self.size)
265            .field("width", &self.width)
266            .field("shortcuts", &self.shortcuts)
267            .field("keymap", &self.keymap)
268            .finish()
269    }
270}
271
272impl<'a, Message: Clone + 'a> From<Input<'a, Message>> for Element<'a, Message> {
273    fn from(input: Input<'a, Message>) -> Self {
274        let metrics = input.size.metrics();
275        let invalid = input.invalid;
276        let enabled = input.is_enabled();
277
278        let mut field = text_input(&input.placeholder, &input.value)
279            .secure(input.secure)
280            .size(metrics.text)
281            .line_height(LineHeight::Relative(LINE_HEIGHT))
282            .padding(metrics.padding(input.icon.is_some()))
283            .width(Length::Fill)
284            .on_submit_maybe(input.on_submit.filter(|_| enabled))
285            .style(move |theme, status| style(&Tokens::of(theme), status, invalid));
286        if let Some(id) = input.id {
287            field = field.id(id);
288        }
289        let field = with_shortcuts(
290            field,
291            &input.value,
292            input.secure,
293            input.on_input,
294            input.keymap,
295            input.shortcuts,
296        );
297
298        let Some(glyph) = input.icon else {
299            return container(field).width(input.width).into();
300        };
301
302        let status = if enabled {
303            Status::Active
304        } else {
305            Status::Disabled
306        };
307        let icon = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
308            style(&Tokens::of(theme), status, invalid).icon
309        });
310        let icon = container(icon)
311            .padding(Padding::ZERO.left(metrics.padding_x))
312            .height(Length::Fill)
313            .align_y(Alignment::Center);
314
315        stack![field, icon].width(input.width).into()
316    }
317}
318
319/// The iced text input style for a status, optionally marked invalid.
320pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
321    let border = match (invalid, status) {
322        (true, _) => tokens.destructive,
323        (false, Status::Focused { .. }) => mix(tokens.border, tokens.foreground, 0.6),
324        (false, Status::Hovered) => mix(tokens.border, tokens.foreground, 0.25),
325        (false, Status::Active | Status::Disabled) => tokens.border,
326    };
327
328    // Transparent so the field takes the colour of whatever surface it sits
329    // on, such as a dialog or popover.
330    let active = Style {
331        background: Background::Color(Color::TRANSPARENT),
332        border: Border {
333            color: border,
334            width: 1.0,
335            radius: radius::MD.into(),
336        },
337        icon: tokens.muted_foreground,
338        placeholder: tokens.muted_foreground,
339        value: tokens.foreground,
340        selection: fade(tokens.primary, 0.25),
341    };
342
343    if status != Status::Disabled {
344        return active;
345    }
346    Style {
347        background: Background::Color(tokens.disabled_field()),
348        border: Border {
349            color: fade(border, 0.5),
350            ..active.border
351        },
352        icon: fade(active.icon, 0.5),
353        placeholder: fade(active.placeholder, 0.5),
354        value: fade(active.value, 0.5),
355        selection: Color::TRANSPARENT,
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use crate::theme::{dark, light};
363
364    const STATES: [Status; 5] = [
365        Status::Active,
366        Status::Hovered,
367        Status::Focused { is_hovered: false },
368        Status::Focused { is_hovered: true },
369        Status::Disabled,
370    ];
371
372    fn border(style: Style) -> Color {
373        style.border.color
374    }
375
376    #[test]
377    fn default_builder_is_medium_fill_and_disabled() {
378        let i: Input<'_, ()> = input("Email", "");
379        assert_eq!(i.size, Size::Md);
380        assert_eq!(i.width, Length::Fill);
381        assert!(!i.secure && !i.invalid);
382        assert!(i.icon.is_none() && i.id.is_none());
383        assert!(!i.is_enabled());
384        assert_eq!(i.shortcuts, Shortcuts::all());
385        assert_eq!(i.keymap, default_keymap());
386    }
387
388    #[test]
389    fn shortcuts_and_keymap_can_be_changed() {
390        let i: Input<'_, ()> = input("", "")
391            .shortcuts(Shortcuts::none())
392            .keymap(Keymap::new());
393        assert_eq!(i.shortcuts, Shortcuts::none());
394        assert!(i.keymap.is_empty());
395    }
396
397    #[test]
398    fn on_input_enables_and_on_input_maybe_none_disables() {
399        assert!(input::<String>("", "").on_input(|s| s).is_enabled());
400        let none: Option<fn(String) -> String> = None;
401        assert!(
402            !input::<String>("", "")
403                .on_input(|s| s)
404                .on_input_maybe(none)
405                .is_enabled()
406        );
407    }
408
409    #[test]
410    fn builder_keeps_placeholder_and_value() {
411        let i: Input<'_, ()> = input("Search", "iced").secure(true).invalid(true);
412        assert_eq!(i.placeholder, "Search");
413        assert_eq!(i.value, "iced");
414        assert!(i.secure && i.invalid);
415    }
416
417    #[test]
418    fn sizes_grow_monotonically() {
419        let heights = Size::ALL.map(|s| s.metrics().height);
420        assert!(heights.windows(2).all(|w| w[0] < w[1]));
421    }
422
423    #[test]
424    fn padding_produces_the_target_height() {
425        for size in Size::ALL {
426            let m = size.metrics();
427            let p = m.padding(false);
428            let height = m.text * LINE_HEIGHT + p.top + p.bottom;
429            assert!((height - m.height).abs() < 1e-3, "{size:?}");
430        }
431    }
432
433    #[test]
434    fn icon_reserves_space_on_the_left_only() {
435        let m = Size::Md.metrics();
436        let plain = m.padding(false);
437        let with_icon = m.padding(true);
438        assert!(with_icon.left > plain.left + m.icon);
439        assert_eq!(with_icon.right, plain.right);
440        assert_eq!(with_icon.top, plain.top);
441    }
442
443    #[test]
444    fn hover_and_focus_strengthen_the_border() {
445        for theme in [light(), dark()] {
446            let tokens = Tokens::of(&theme);
447            let active = border(style(&tokens, Status::Active, false));
448            let hovered = border(style(&tokens, Status::Hovered, false));
449            let focused = border(style(&tokens, Status::Focused { is_hovered: false }, false));
450            assert_ne!(active, hovered);
451            assert_ne!(hovered, focused);
452            assert_eq!(
453                focused,
454                border(style(&tokens, Status::Focused { is_hovered: true }, false))
455            );
456        }
457    }
458
459    #[test]
460    fn invalid_uses_destructive_border_in_every_enabled_status() {
461        for theme in [light(), dark()] {
462            let tokens = Tokens::of(&theme);
463            for status in STATES {
464                let style = style(&tokens, status, true);
465                let expected = if status == Status::Disabled {
466                    fade(tokens.destructive, 0.5)
467                } else {
468                    tokens.destructive
469                };
470                assert_eq!(style.border.color, expected, "{status:?}");
471            }
472        }
473    }
474
475    #[test]
476    fn disabled_halves_text_alpha_and_mutes_background() {
477        for theme in [light(), dark()] {
478            let tokens = Tokens::of(&theme);
479            let active = style(&tokens, Status::Active, false);
480            let disabled = style(&tokens, Status::Disabled, false);
481            assert!((disabled.value.a - active.value.a * 0.5).abs() < 1e-6);
482            assert!((disabled.placeholder.a - active.placeholder.a * 0.5).abs() < 1e-6);
483            assert_ne!(disabled.background, active.background);
484            assert_eq!(
485                disabled.background,
486                Background::Color(tokens.disabled_field())
487            );
488        }
489    }
490
491    #[test]
492    fn enabled_fields_take_the_colour_of_their_surface() {
493        for theme in [light(), dark()] {
494            let tokens = Tokens::of(&theme);
495            for status in STATES.into_iter().filter(|s| *s != Status::Disabled) {
496                for invalid in [false, true] {
497                    let style = style(&tokens, status, invalid);
498                    assert_eq!(style.background, Background::Color(Color::TRANSPARENT));
499                }
500            }
501        }
502    }
503
504    #[test]
505    fn every_status_has_a_visible_border_and_readable_value() {
506        for theme in [light(), dark()] {
507            let tokens = Tokens::of(&theme);
508            for status in STATES {
509                for invalid in [false, true] {
510                    let style = style(&tokens, status, invalid);
511                    assert_eq!(style.border.width, 1.0);
512                    assert!(style.border.color.a > 0.0);
513                    assert_ne!(style.value, tokens.background);
514                }
515            }
516        }
517    }
518}