iced-cube 0.0.13

Themeable application components for the iced GUI library, with Lucide icons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Single-line text inputs with an optional leading icon.
//!
//! Besides iced's own editing keys (select all, copy, cut, paste, moving by
//! word, Home and End), inputs undo and redo, delete a word with
//! Ctrl+Backspace and Ctrl+Delete, and keep Escape to themselves: see
//! [`Shortcut`] and [`default_keymap`]. Pass a [`Shortcuts`] set to
//! [`Input::shortcuts`] to switch some or all of them off, and a keymap to
//! [`Input::keymap`] to rebind them. Textareas and every component with a
//! search or filter field take the same set.
//!
//! ```no_run
//! use iced_cube::input;
//! use iced_cube::primitives::input::{Shortcut, Shortcuts};
//!
//! #[derive(Debug, Clone)]
//! enum Message { Name(String) }
//!
//! // The app has its own undo, so the field leaves Ctrl+Z and Ctrl+Y alone.
//! let view: iced::Element<'_, Message> = input("Name", "Ada")
//!     .shortcuts(Shortcuts::all().without(Shortcut::Undo).without(Shortcut::Redo))
//!     .on_input(Message::Name)
//!     .into();
//! ```

use std::cell::Cell;
use std::fmt;
use std::rc::Rc;

use iced::widget::text::LineHeight;
use iced::widget::text_input::{Status, Style};
use iced::widget::{Id, container, stack, text_input};
use iced::{Alignment, Background, Border, Color, Element, Length, Padding};

pub use crate::editing::{Shortcut, Shortcuts, default_keymap};

use crate::editing::{self, Editing};
use crate::icon::{Glyph, opacity, themed};
use crate::keys::Keymap;
use crate::theme::{Tokens, fade, mix, radius, space, text_size};

const LINE_HEIGHT: f32 = 1.3;

/// Input dimensions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Size {
    Sm,
    #[default]
    Md,
    Lg,
}

impl Size {
    pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];

    /// Height, horizontal padding, text size and icon size.
    pub const fn metrics(self) -> Metrics {
        match self {
            Size::Sm => Metrics {
                height: 32.0,
                padding_x: 10.0,
                text: text_size::SM,
                icon: 14.0,
            },
            Size::Md => Metrics {
                height: 36.0,
                padding_x: 12.0,
                text: text_size::SM,
                icon: 16.0,
            },
            Size::Lg => Metrics {
                height: 40.0,
                padding_x: 14.0,
                text: text_size::MD,
                icon: 18.0,
            },
        }
    }
}

/// Resolved dimensions for a [`Size`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Metrics {
    pub height: f32,
    pub padding_x: f32,
    pub text: f32,
    pub icon: f32,
}

impl Metrics {
    /// Inner padding that makes the input exactly `height` tall, leaving
    /// room for a leading icon when there is one.
    pub fn padding(self, with_icon: bool) -> Padding {
        let vertical = ((self.height - self.text * LINE_HEIGHT) / 2.0).max(0.0);
        let left = if with_icon {
            self.padding_x + self.icon + space::SM
        } else {
            self.padding_x
        };
        Padding {
            top: vertical,
            bottom: vertical,
            left,
            right: self.padding_x,
        }
    }
}

/// A text input builder. Convert it into an [`Element`] to render.
///
/// An input without an `on_input` message is rendered disabled.
pub struct Input<'a, Message> {
    placeholder: String,
    value: String,
    id: Option<Id>,
    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
    on_submit: Option<Message>,
    icon: Option<Glyph>,
    secure: bool,
    invalid: bool,
    size: Size,
    width: Length,
    shortcuts: Shortcuts,
    keymap: Keymap<Shortcut>,
}

/// Creates a text input showing `value`, with `placeholder` while empty.
pub fn input<'a, Message>(placeholder: &str, value: &str) -> Input<'a, Message> {
    Input {
        placeholder: placeholder.to_owned(),
        value: value.to_owned(),
        id: None,
        on_input: None,
        on_submit: None,
        icon: None,
        secure: false,
        invalid: false,
        size: Size::default(),
        width: Length::Fill,
        shortcuts: Shortcuts::all(),
        keymap: default_keymap(),
    }
}

impl<'a, Message> Input<'a, Message> {
    /// Sets the widget id, used to focus the input or find it in tests.
    pub fn id(mut self, id: impl Into<Id>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Sets the message produced for every edit. Without it the input is disabled.
    pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'a) -> Self {
        self.on_input = Some(Box::new(on_input));
        self
    }

    pub fn on_input_maybe(mut self, on_input: Option<impl Fn(String) -> Message + 'a>) -> Self {
        self.on_input = on_input.map(|f| Box::new(f) as Box<dyn Fn(String) -> Message + 'a>);
        self
    }

    /// Sets the message produced when Enter is pressed.
    pub fn on_submit(mut self, message: Message) -> Self {
        self.on_submit = Some(message);
        self
    }

    pub fn on_submit_maybe(mut self, message: Option<Message>) -> Self {
        self.on_submit = message;
        self
    }

    /// Adds a Lucide icon at the start of the input.
    pub fn icon(mut self, glyph: Glyph) -> Self {
        self.icon = Some(glyph);
        self
    }

    /// Masks the value, for passwords and other secrets.
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    /// Marks the value as invalid, drawing a destructive border.
    pub fn invalid(mut self, invalid: bool) -> Self {
        self.invalid = invalid;
        self
    }

    pub fn size(mut self, size: Size) -> Self {
        self.size = size;
        self
    }

    /// Overrides the width. Inputs fill the available width by default.
    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = width.into();
        self
    }

    /// Sets which [`Shortcut`]s the input handles. All of them by default;
    /// pass [`Shortcuts::none`] to turn them all off. The keys of a shortcut
    /// that is off reach the app, and iced's own editing keys always work.
    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
        self.shortcuts = shortcuts;
        self
    }

    /// Replaces the [`default_keymap`], to bind the shortcuts to other keys.
    pub fn keymap(mut self, keymap: Keymap<Shortcut>) -> Self {
        self.keymap = keymap;
        self
    }

    pub fn is_enabled(&self) -> bool {
        self.on_input.is_some()
    }
}

/// Builds an iced text input from `field` with `on_input` wired up and the
/// editing shortcuts around it.
pub(crate) fn with_shortcuts<'a, Message: Clone + 'a>(
    field: text_input::TextInput<'a, Message>,
    value: &str,
    secure: bool,
    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
    keymap: Keymap<Shortcut>,
    shortcuts: Shortcuts,
) -> Element<'a, Message> {
    let Some(on_input) = on_input else {
        return field.into();
    };
    let on_input: Rc<dyn Fn(String) -> Message + 'a> = Rc::from(on_input);
    let edited = Rc::new(Cell::new(false));
    let field = field.on_input({
        let (on_input, edited) = (Rc::clone(&on_input), Rc::clone(&edited));
        move |value| {
            edited.set(true);
            on_input(value)
        }
    });
    Editing::new(
        field,
        editing::Input::new(value, secure, on_input),
        keymap,
        shortcuts,
        edited,
    )
    .into()
}

impl<Message: fmt::Debug> fmt::Debug for Input<'_, Message> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Input")
            .field("placeholder", &self.placeholder)
            .field("value", &self.value)
            .field("id", &self.id)
            .field("enabled", &self.is_enabled())
            .field("on_submit", &self.on_submit)
            .field("icon", &self.icon)
            .field("secure", &self.secure)
            .field("invalid", &self.invalid)
            .field("size", &self.size)
            .field("width", &self.width)
            .field("shortcuts", &self.shortcuts)
            .field("keymap", &self.keymap)
            .finish()
    }
}

impl<'a, Message: Clone + 'a> From<Input<'a, Message>> for Element<'a, Message> {
    fn from(input: Input<'a, Message>) -> Self {
        let metrics = input.size.metrics();
        let invalid = input.invalid;
        let enabled = input.is_enabled();

        let mut field = text_input(&input.placeholder, &input.value)
            .secure(input.secure)
            .size(metrics.text)
            .line_height(LineHeight::Relative(LINE_HEIGHT))
            .padding(metrics.padding(input.icon.is_some()))
            .width(Length::Fill)
            .on_submit_maybe(input.on_submit.filter(|_| enabled))
            .style(move |theme, status| style(&Tokens::of(theme), status, invalid));
        if let Some(id) = input.id {
            field = field.id(id);
        }
        let field = with_shortcuts(
            field,
            &input.value,
            input.secure,
            input.on_input,
            input.keymap,
            input.shortcuts,
        );

        let Some(glyph) = input.icon else {
            return container(field).width(input.width).into();
        };

        let status = if enabled {
            Status::Active
        } else {
            Status::Disabled
        };
        let icon = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
            style(&Tokens::of(theme), status, invalid).icon
        });
        let icon = container(icon)
            .padding(Padding::ZERO.left(metrics.padding_x))
            .height(Length::Fill)
            .align_y(Alignment::Center);

        stack![field, icon].width(input.width).into()
    }
}

/// The iced text input style for a status, optionally marked invalid.
pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
    let border = match (invalid, status) {
        (true, _) => tokens.destructive,
        (false, Status::Focused { .. }) => mix(tokens.border, tokens.foreground, 0.6),
        (false, Status::Hovered) => mix(tokens.border, tokens.foreground, 0.25),
        (false, Status::Active | Status::Disabled) => tokens.border,
    };

    // Transparent so the field takes the colour of whatever surface it sits
    // on, such as a dialog or popover.
    let active = Style {
        background: Background::Color(Color::TRANSPARENT),
        border: Border {
            color: border,
            width: 1.0,
            radius: radius::MD.into(),
        },
        icon: tokens.muted_foreground,
        placeholder: tokens.muted_foreground,
        value: tokens.foreground,
        selection: fade(tokens.primary, 0.25),
    };

    if status != Status::Disabled {
        return active;
    }
    Style {
        background: Background::Color(tokens.disabled_field()),
        border: Border {
            color: fade(border, 0.5),
            ..active.border
        },
        icon: fade(active.icon, 0.5),
        placeholder: fade(active.placeholder, 0.5),
        value: fade(active.value, 0.5),
        selection: Color::TRANSPARENT,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{dark, light};

    const STATES: [Status; 5] = [
        Status::Active,
        Status::Hovered,
        Status::Focused { is_hovered: false },
        Status::Focused { is_hovered: true },
        Status::Disabled,
    ];

    fn border(style: Style) -> Color {
        style.border.color
    }

    #[test]
    fn default_builder_is_medium_fill_and_disabled() {
        let i: Input<'_, ()> = input("Email", "");
        assert_eq!(i.size, Size::Md);
        assert_eq!(i.width, Length::Fill);
        assert!(!i.secure && !i.invalid);
        assert!(i.icon.is_none() && i.id.is_none());
        assert!(!i.is_enabled());
        assert_eq!(i.shortcuts, Shortcuts::all());
        assert_eq!(i.keymap, default_keymap());
    }

    #[test]
    fn shortcuts_and_keymap_can_be_changed() {
        let i: Input<'_, ()> = input("", "")
            .shortcuts(Shortcuts::none())
            .keymap(Keymap::new());
        assert_eq!(i.shortcuts, Shortcuts::none());
        assert!(i.keymap.is_empty());
    }

    #[test]
    fn on_input_enables_and_on_input_maybe_none_disables() {
        assert!(input::<String>("", "").on_input(|s| s).is_enabled());
        let none: Option<fn(String) -> String> = None;
        assert!(
            !input::<String>("", "")
                .on_input(|s| s)
                .on_input_maybe(none)
                .is_enabled()
        );
    }

    #[test]
    fn builder_keeps_placeholder_and_value() {
        let i: Input<'_, ()> = input("Search", "iced").secure(true).invalid(true);
        assert_eq!(i.placeholder, "Search");
        assert_eq!(i.value, "iced");
        assert!(i.secure && i.invalid);
    }

    #[test]
    fn sizes_grow_monotonically() {
        let heights = Size::ALL.map(|s| s.metrics().height);
        assert!(heights.windows(2).all(|w| w[0] < w[1]));
    }

    #[test]
    fn padding_produces_the_target_height() {
        for size in Size::ALL {
            let m = size.metrics();
            let p = m.padding(false);
            let height = m.text * LINE_HEIGHT + p.top + p.bottom;
            assert!((height - m.height).abs() < 1e-3, "{size:?}");
        }
    }

    #[test]
    fn icon_reserves_space_on_the_left_only() {
        let m = Size::Md.metrics();
        let plain = m.padding(false);
        let with_icon = m.padding(true);
        assert!(with_icon.left > plain.left + m.icon);
        assert_eq!(with_icon.right, plain.right);
        assert_eq!(with_icon.top, plain.top);
    }

    #[test]
    fn hover_and_focus_strengthen_the_border() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let active = border(style(&tokens, Status::Active, false));
            let hovered = border(style(&tokens, Status::Hovered, false));
            let focused = border(style(&tokens, Status::Focused { is_hovered: false }, false));
            assert_ne!(active, hovered);
            assert_ne!(hovered, focused);
            assert_eq!(
                focused,
                border(style(&tokens, Status::Focused { is_hovered: true }, false))
            );
        }
    }

    #[test]
    fn invalid_uses_destructive_border_in_every_enabled_status() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for status in STATES {
                let style = style(&tokens, status, true);
                let expected = if status == Status::Disabled {
                    fade(tokens.destructive, 0.5)
                } else {
                    tokens.destructive
                };
                assert_eq!(style.border.color, expected, "{status:?}");
            }
        }
    }

    #[test]
    fn disabled_halves_text_alpha_and_mutes_background() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let active = style(&tokens, Status::Active, false);
            let disabled = style(&tokens, Status::Disabled, false);
            assert!((disabled.value.a - active.value.a * 0.5).abs() < 1e-6);
            assert!((disabled.placeholder.a - active.placeholder.a * 0.5).abs() < 1e-6);
            assert_ne!(disabled.background, active.background);
            assert_eq!(
                disabled.background,
                Background::Color(tokens.disabled_field())
            );
        }
    }

    #[test]
    fn enabled_fields_take_the_colour_of_their_surface() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for status in STATES.into_iter().filter(|s| *s != Status::Disabled) {
                for invalid in [false, true] {
                    let style = style(&tokens, status, invalid);
                    assert_eq!(style.background, Background::Color(Color::TRANSPARENT));
                }
            }
        }
    }

    #[test]
    fn every_status_has_a_visible_border_and_readable_value() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for status in STATES {
                for invalid in [false, true] {
                    let style = style(&tokens, status, invalid);
                    assert_eq!(style.border.width, 1.0);
                    assert!(style.border.color.a > 0.0);
                    assert_ne!(style.value, tokens.background);
                }
            }
        }
    }
}