iced-cube 0.0.21

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
//! Compact pills for chosen values, such as guests or tags, with an
//! optional x button that removes them.
//!
//! Chips share the [badge](mod@crate::feedback::badge) colours and are
//! [`Variant::Secondary`] by default. Give a chip [`Chip::on_remove`] to
//! draw the x, and [`Chip::id`] to find that x in tests through
//! [`remove_id`].
//!
//! ```no_run
//! use iced::Element;
//! use iced_cube::feedback::chip::chip;
//!
//! #[derive(Debug, Clone)]
//! enum Message {
//!     Remove(usize),
//! }
//!
//! fn guests(names: &[&str]) -> Element<'static, Message> {
//!     iced::widget::row(names.iter().enumerate().map(|(index, name)| {
//!         chip(name.to_string())
//!             .on_remove(Message::Remove(index))
//!             .into()
//!     }))
//!     .spacing(4)
//!     .wrap()
//!     .into()
//! }
//! ```

use std::fmt;

use iced::widget::{self, button, container, row, text};
use iced::{Alignment, Background, Border, Element, Length, Padding, Shadow};

pub use crate::feedback::badge::Variant;
use crate::feedback::badge::{self, colours};
use crate::icon::{Glyph, themed};
use crate::natural::natural;
use crate::theme::{Tokens, fade, radius, text_size};

/// Space between the leading icon or element, the label and the x.
const GAP: f32 = 4.0;
/// Padding around the x glyph inside its round button.
const REMOVE_PADDING: f32 = 1.0;

/// Chip dimensions. [`Size::Sm`] matches a badge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Size {
    Sm,
    #[default]
    Md,
}

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

    /// Height, horizontal padding, text size, icon size and x size.
    pub const fn metrics(self) -> Metrics {
        match self {
            Size::Sm => Metrics {
                height: 20.0,
                padding_x: 10.0,
                text: text_size::XS,
                icon: 12.0,
                remove: 12.0,
            },
            Size::Md => Metrics {
                height: 26.0,
                padding_x: 10.0,
                text: text_size::SM,
                icon: 14.0,
                remove: 14.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,
    pub remove: f32,
}

impl Metrics {
    /// The chip's padding: less on the left beside a leading element, so an
    /// avatar sits in the curve, and less on the right beside the x.
    pub fn padding(self, leading_element: bool, removable: bool) -> Padding {
        Padding {
            top: 0.0,
            bottom: 0.0,
            left: if leading_element { 1.0 } else { self.padding_x },
            right: if removable { 3.0 } else { self.padding_x },
        }
    }
}

/// The widget id of the x button of the chip with [`Chip::id`] `key`.
pub fn remove_id(key: &str) -> widget::Id {
    widget::Id::from(format!("iced-cube-chip-remove-{key}"))
}

enum Leading<'a, Message> {
    None,
    Icon(Glyph),
    Element(Element<'a, Message>),
}

/// A chip builder. Convert it into an [`Element`] to render.
///
/// A chip without [`on_remove`](Chip::on_remove) has no x button.
pub struct Chip<'a, Message> {
    label: text::Fragment<'a>,
    leading: Leading<'a, Message>,
    variant: Variant,
    size: Size,
    key: Option<String>,
    on_remove: Option<Message>,
}

/// Creates a chip with a text label.
pub fn chip<'a, Message>(label: impl text::IntoFragment<'a>) -> Chip<'a, Message> {
    Chip {
        label: label.into_fragment(),
        leading: Leading::None,
        variant: Variant::Secondary,
        size: Size::default(),
        key: None,
        on_remove: None,
    }
}

impl<Message: fmt::Debug> fmt::Debug for Chip<'_, Message> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let leading = match &self.leading {
            Leading::None => "none",
            Leading::Icon(_) => "icon",
            Leading::Element(_) => "element",
        };
        f.debug_struct("Chip")
            .field("label", &self.label)
            .field("leading", &leading)
            .field("variant", &self.variant)
            .field("size", &self.size)
            .field("key", &self.key)
            .field("on_remove", &self.on_remove)
            .finish()
    }
}

impl<'a, Message> Chip<'a, Message> {
    /// Defaults to [`Variant::Secondary`].
    pub fn variant(mut self, variant: Variant) -> Self {
        self.variant = variant;
        self
    }

    /// Defaults to [`Size::Md`].
    pub fn size(mut self, size: Size) -> Self {
        self.size = size;
        self
    }

    /// Adds an icon before the label. Replaces any leading element.
    pub fn icon(mut self, glyph: Glyph) -> Self {
        self.leading = Leading::Icon(glyph);
        self
    }

    /// Adds an element before the label, such as a small avatar, laid out at
    /// its own size against the chip's left edge. Replaces any icon.
    pub fn leading(mut self, element: impl Into<Element<'a, Message>>) -> Self {
        self.leading = Leading::Element(element.into());
        self
    }

    /// A key, unique on screen, that gives the x button the widget id
    /// [`remove_id`]`(key)`, to find or click it in tests.
    pub fn id(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Draws an x button after the label that sends `message` when pressed.
    pub fn on_remove(mut self, message: Message) -> Self {
        self.on_remove = Some(message);
        self
    }

    /// Like [`on_remove`](Self::on_remove); `None` leaves the x out.
    pub fn on_remove_maybe(mut self, message: Option<Message>) -> Self {
        self.on_remove = message;
        self
    }

    pub fn is_removable(&self) -> bool {
        self.on_remove.is_some()
    }
}

impl<'a, Message: Clone + 'a> From<Chip<'a, Message>> for Element<'a, Message> {
    fn from(chip: Chip<'a, Message>) -> Self {
        let Chip {
            label,
            leading,
            variant,
            size,
            key,
            on_remove,
        } = chip;
        let metrics = size.metrics();
        #[cfg(feature = "icedwright")]
        let name = label.clone();
        let foreground = move |theme: &iced::Theme| colours(&Tokens::of(theme), variant).foreground;

        let leading_element = matches!(leading, Leading::Element(_));
        let mut content = row![].spacing(GAP).align_y(Alignment::Center);
        match leading {
            Leading::None => {}
            Leading::Icon(glyph) => {
                content = content.push(themed(glyph, metrics.icon, 1.0, foreground));
            }
            Leading::Element(element) => content = content.push(element),
        }
        content = content.push(
            text(label)
                .size(metrics.text)
                .wrapping(text::Wrapping::None),
        );

        let removable = on_remove.is_some();
        if let Some(message) = on_remove {
            let remove = button(themed(crate::lucide!(X), metrics.remove, 1.0, foreground))
                .padding(REMOVE_PADDING)
                .on_press(message)
                .style(move |theme, status| remove_style(&Tokens::of(theme), variant, status));
            let mut remove = container(remove);
            if let Some(key) = &key {
                remove = remove.id(remove_id(key));
            }
            #[cfg(feature = "icedwright")]
            let remove = icedwright_probe::semantic(remove)
                .role(icedwright_probe::role::Button)
                .name(format!("Remove {name}"))
                .component("iced_cube::chip");
            content = content.push(remove);
        }

        let element = natural(
            container(content)
                .height(Length::Fixed(metrics.height))
                .align_y(Alignment::Center)
                .padding(metrics.padding(leading_element, removable))
                .style(move |theme| style(&Tokens::of(theme), variant)),
        );
        #[cfg(feature = "icedwright")]
        let element = icedwright_probe::semantic(element)
            .role(icedwright_probe::role::Group)
            .name(name)
            .component("iced_cube::chip")
            .into();
        element
    }
}

/// The chip's container style: the badge style of the same variant.
pub fn style(tokens: &Tokens, variant: Variant) -> container::Style {
    badge::style(tokens, variant)
}

/// The x button style: clear until hovered or pressed, then a faint circle
/// of the chip's foreground colour.
pub fn remove_style(tokens: &Tokens, variant: Variant, status: button::Status) -> button::Style {
    let foreground = colours(tokens, variant).foreground;
    let background = match status {
        button::Status::Hovered => Some(fade(foreground, 0.15)),
        button::Status::Pressed => Some(fade(foreground, 0.25)),
        button::Status::Active | button::Status::Disabled => None,
    };
    button::Style {
        background: background.map(Background::Color),
        text_color: foreground,
        border: Border {
            radius: radius::FULL.into(),
            ..Border::default()
        },
        shadow: Shadow::default(),
        snap: true,
    }
}

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

    const STATUSES: [button::Status; 4] = [
        button::Status::Active,
        button::Status::Hovered,
        button::Status::Pressed,
        button::Status::Disabled,
    ];

    #[test]
    fn default_builder_is_a_secondary_medium_chip_without_x() {
        let c: Chip<'_, ()> = chip("Ada");
        assert_eq!(c.variant, Variant::Secondary);
        assert_eq!(c.size, Size::Md);
        assert!(matches!(c.leading, Leading::None));
        assert!(c.key.is_none());
        assert!(!c.is_removable());
    }

    #[test]
    fn builder_keeps_its_options() {
        let c = chip("Ada")
            .variant(Variant::Outline)
            .size(Size::Sm)
            .icon(crate::lucide!(User))
            .id("ada")
            .on_remove(1);
        assert_eq!(c.variant, Variant::Outline);
        assert_eq!(c.size, Size::Sm);
        assert!(matches!(c.leading, Leading::Icon(glyph) if glyph.name() == "user"));
        assert_eq!(c.key.as_deref(), Some("ada"));
        assert_eq!(c.on_remove, Some(1));
        assert!(!c.on_remove_maybe(None).is_removable());
    }

    #[test]
    fn leading_element_replaces_the_icon_and_back() {
        let c: Chip<'_, ()> = chip("Ada").icon(crate::lucide!(User)).leading(text("A"));
        assert!(matches!(c.leading, Leading::Element(_)));
        let c = c.icon(crate::lucide!(User));
        assert!(matches!(c.leading, Leading::Icon(_)));
    }

    #[test]
    fn small_chips_match_badges_and_sizes_grow() {
        let sm = Size::Sm.metrics();
        let md = Size::Md.metrics();
        assert_eq!(sm.text, text_size::XS);
        assert_eq!(sm.icon, 12.0);
        assert!(md.height > sm.height);
        assert!(md.text > sm.text);
        for size in Size::ALL {
            let metrics = size.metrics();
            assert!(
                metrics.remove + 2.0 * REMOVE_PADDING < metrics.height,
                "{size:?}"
            );
        }
    }

    #[test]
    fn padding_tightens_beside_an_element_and_the_x() {
        let metrics = Size::Md.metrics();
        let plain = metrics.padding(false, false);
        assert_eq!((plain.left, plain.right), (10.0, 10.0));
        let both = metrics.padding(true, true);
        assert!(both.left < plain.left && both.right < plain.right);
    }

    #[test]
    fn chips_use_the_badge_style_of_their_variant() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in Variant::ALL {
                assert_eq!(style(&tokens, variant), badge::style(&tokens, variant));
                assert_eq!(style(&tokens, variant).border.radius, radius::FULL.into());
            }
        }
    }

    #[test]
    fn the_x_is_clear_until_hovered_or_pressed() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in Variant::ALL {
                let foreground = colours(&tokens, variant).foreground;
                for status in STATUSES {
                    let style = remove_style(&tokens, variant, status);
                    assert_eq!(style.text_color, foreground, "{variant:?} {status:?}");
                    let filled =
                        matches!(status, button::Status::Hovered | button::Status::Pressed);
                    assert_eq!(style.background.is_some(), filled, "{variant:?} {status:?}");
                }
                let hovered = remove_style(&tokens, variant, button::Status::Hovered);
                let pressed = remove_style(&tokens, variant, button::Status::Pressed);
                assert_ne!(hovered.background, pressed.background, "{variant:?}");
            }
        }
    }

    #[test]
    fn remove_ids_differ_by_key() {
        assert_eq!(remove_id("ada"), remove_id("ada"));
        assert_ne!(remove_id("ada"), remove_id("bob"));
    }
}