iced-cube 0.0.26

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
//! Square, icon-only buttons with a label and an optional pressed state.
//!
//! Icon buttons share their [`Size`] and colours with
//! [`button`](fn@crate::primitives::button), and every button variant except
//! `Link`. A pressed icon button stays highlighted, which suits toolbar
//! toggles such as bold or italic.

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

use crate::after_touch::after_touch;
use crate::focus::{Ring, focusable};
use crate::icon::{Glyph, opacity, themed};
use crate::overlay::tooltip::{Position, tooltip};
use crate::primitives::button::{self, Colours, Size};
use crate::theme::{Tokens, fade, mix, radius};

/// Visual emphasis of an icon button.
///
/// These are the text button variants without `Link`, which needs text to
/// read as a link and on an icon alone looks just like `Ghost`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Variant {
    Primary,
    Secondary,
    Destructive,
    Outline,
    #[default]
    Ghost,
}

impl Variant {
    pub const ALL: [Variant; 5] = [
        Variant::Primary,
        Variant::Secondary,
        Variant::Destructive,
        Variant::Outline,
        Variant::Ghost,
    ];

    /// The text button variant with the same colours.
    pub const fn button(self) -> button::Variant {
        match self {
            Variant::Primary => button::Variant::Primary,
            Variant::Secondary => button::Variant::Secondary,
            Variant::Destructive => button::Variant::Destructive,
            Variant::Outline => button::Variant::Outline,
            Variant::Ghost => button::Variant::Ghost,
        }
    }
}

impl From<Variant> for button::Variant {
    fn from(variant: Variant) -> Self {
        variant.button()
    }
}

/// An icon button builder. Convert it into an [`Element`] to render.
///
/// An icon button without a message is rendered disabled.
///
/// Like [`button`](fn@crate::primitives::button), an enabled icon button
/// takes keyboard focus from iced's focus operations, rings while focused
/// and is pressed with Enter or Space. Focus also shows its tooltip.
#[derive(Debug)]
pub struct IconButton<'a, Message> {
    glyph: Glyph,
    label: Option<text::Fragment<'a>>,
    tooltip: Option<Position>,
    variant: Variant,
    size: Size,
    kind: Kind,
    id: Option<widget::Id>,
    on_press: Option<Message>,
}

/// What an icon button is for, which decides how it reports itself and
/// whether it is drawn held down.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Kind {
    /// A plain button.
    #[default]
    Plain,
    /// A toggle, on or off.
    Toggle(bool),
    /// Opens a menu or panel, shown or not.
    Trigger(bool),
}

impl Kind {
    fn is_held(self) -> bool {
        matches!(self, Kind::Toggle(true) | Kind::Trigger(true))
    }
}

/// Creates a square ghost button showing `glyph`.
pub fn icon_button<'a, Message>(glyph: Glyph) -> IconButton<'a, Message> {
    IconButton {
        glyph,
        label: None,
        tooltip: Some(Position::default()),
        variant: Variant::Ghost,
        size: Size::Md,
        kind: Kind::Plain,
        id: None,
        on_press: None,
    }
}

impl<'a, Message> IconButton<'a, Message> {
    /// Names the action, such as "Bold". The label shows as a tooltip on
    /// hover unless [`tooltip`](Self::tooltip) turns it off.
    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
        self.label = Some(label.into_fragment());
        self
    }

    /// Where the label's tooltip appears, or `None` to never show it.
    /// Defaults to above the button.
    pub fn tooltip(mut self, position: Option<Position>) -> Self {
        self.tooltip = position;
        self
    }

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

    /// The side length follows the button [`Size`]: `Sm` is 32 pixels,
    /// `Md` is 36 and `Lg` is 40.
    pub fn size(mut self, size: Size) -> Self {
        self.size = size;
        self
    }

    /// Makes the button a toggle, drawn as switched on while `pressed`, for
    /// toggles in a toolbar.
    pub fn pressed(mut self, pressed: bool) -> Self {
        self.kind = Kind::Toggle(pressed);
        self
    }

    /// Makes the button the trigger of a menu or panel, drawn held down
    /// while it is `expanded`.
    pub fn expanded(mut self, expanded: bool) -> Self {
        self.kind = Kind::Trigger(expanded);
        self
    }

    /// Sets a widget id, for clicking the button in tests or focusing it
    /// with iced's `focus` operation.
    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
        self.id = Some(id.into());
        self
    }

    pub fn on_press(mut self, message: Message) -> Self {
        self.on_press = Some(message);
        self
    }

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

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

    /// Whether it is drawn held down: a toggle that is on, or a trigger
    /// whose menu is open.
    pub fn is_pressed(&self) -> bool {
        self.kind.is_held()
    }

    /// Whether it is a toggle, on or off.
    pub fn is_toggle(&self) -> bool {
        matches!(self.kind, Kind::Toggle(_))
    }

    /// The label, if one is set.
    pub fn label_text(&self) -> Option<&str> {
        self.label.as_deref()
    }
}

impl<'a, Message: Clone + 'a> From<IconButton<'a, Message>> for Element<'a, Message> {
    fn from(icon_button: IconButton<'a, Message>) -> Self {
        let IconButton {
            glyph,
            label,
            tooltip: position,
            variant,
            size,
            kind,
            id,
            on_press,
        } = icon_button;
        let pressed = kind.is_held();
        let metrics = size.metrics();
        let enabled = on_press.is_some();
        let resting = if enabled {
            Status::Active
        } else {
            Status::Disabled
        };

        let glyph = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
            colours(&Tokens::of(theme), variant, pressed, resting).foreground
        });

        let on_activate = on_press
            .clone()
            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
        let button = widget::button(glyph)
            .width(Length::Fixed(metrics.height))
            .height(Length::Fixed(metrics.height))
            .padding(Padding::from((metrics.height - metrics.icon) / 2.0))
            .on_press_maybe(on_press)
            .style(move |theme, status| style(&Tokens::of(theme), variant, pressed, status));
        let mut button = focusable(after_touch(button), on_activate, Ring::around(radius::MD));
        button.id = id.clone();

        let mut element: Element<'a, Message> = match id {
            Some(id) => container(button).id(id).into(),
            None => button.into(),
        };
        #[cfg(feature = "icedwright")]
        {
            element = annotate(element, label.clone(), kind, enabled, position.is_some());
        }
        if let (Some(label), Some(position)) = (label, position) {
            element = tooltip(element, label).position(position).into();
        }
        element
    }
}

/// A plain icon button is a `Button`, a toggle is a `ToggleButton` with its
/// pressed state and a trigger is a `Button` with its expanded state. The
/// label names it and is its tooltip when one shows.
#[cfg(feature = "icedwright")]
fn annotate<'a, Message: 'a>(
    element: Element<'a, Message>,
    label: Option<text::Fragment<'a>>,
    kind: Kind,
    enabled: bool,
    tooltip: bool,
) -> Element<'a, Message> {
    use icedwright_probe::role::RoleKind;
    use icedwright_probe::{Semantic, role, semantic};

    fn finish<'a, Message: 'a, R: RoleKind>(
        mut annotated: Semantic<'a, Message, iced::Theme, iced::Renderer, R>,
        label: Option<text::Fragment<'a>>,
        enabled: bool,
        tooltip: bool,
    ) -> Element<'a, Message> {
        annotated = annotated
            .component("iced_cube::icon_button")
            .disabled(!enabled);
        if let Some(label) = label {
            if tooltip {
                annotated = annotated.tooltip(label.clone());
            }
            annotated = annotated.name(label);
        }
        annotated.into()
    }

    match kind {
        Kind::Plain => finish(
            semantic(element).role(role::Button),
            label,
            enabled,
            tooltip,
        ),
        Kind::Toggle(pressed) => finish(
            semantic(element).role(role::ToggleButton).pressed(pressed),
            label,
            enabled,
            tooltip,
        ),
        Kind::Trigger(expanded) => finish(
            semantic(element).role(role::Button).expanded(expanded),
            label,
            enabled,
            tooltip,
        ),
    }
}

/// Colours of an icon button, switched on or off, in a state.
///
/// A pressed button looks held down at rest and darkens a little more on
/// hover, so it reads as on in every state.
pub fn colours(tokens: &Tokens, variant: Variant, pressed: bool, status: Status) -> Colours {
    let variant = variant.button();
    if !pressed {
        return button::colours(tokens, variant, status);
    }

    let held = button::colours(tokens, variant, Status::Pressed);
    match status {
        Status::Active => held,
        Status::Hovered | Status::Pressed => Colours {
            background: held
                .background
                .map(|background| mix(background, tokens.foreground, 0.08)),
            ..held
        },
        Status::Disabled => Colours {
            background: held.background.map(|c| fade(c, 0.5)),
            foreground: fade(held.foreground, 0.5),
            border: held.border.map(|c| fade(c, 0.5)),
        },
    }
}

/// The iced button style of an icon button, switched on or off, in a state.
pub fn style(
    tokens: &Tokens,
    variant: Variant,
    pressed: bool,
    status: Status,
) -> widget::button::Style {
    let colours = colours(tokens, variant, pressed, status);
    widget::button::Style {
        background: colours.background.map(Background::Color),
        text_color: colours.foreground,
        border: Border {
            color: colours.border.unwrap_or(iced::Color::TRANSPARENT),
            width: if colours.border.is_some() { 1.0 } else { 0.0 },
            radius: radius::MD.into(),
        },
        shadow: Shadow::default(),
        snap: true,
    }
}

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

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

    #[test]
    fn defaults_to_a_medium_ghost_button_that_is_off_and_disabled() {
        let b: IconButton<'_, ()> = icon_button(crate::lucide!(Plus));
        assert_eq!(b.variant, Variant::Ghost);
        assert_eq!(b.size, Size::Md);
        assert!(!b.is_pressed());
        assert!(!b.is_enabled());
        assert!(b.label_text().is_none());
        assert_eq!(b.tooltip, Some(Position::Top));
    }

    #[test]
    fn builder_sets_every_option() {
        let b = icon_button::<u8>(crate::lucide!(Bold))
            .label("Bold")
            .tooltip(None)
            .variant(Variant::Outline)
            .size(Size::Sm)
            .pressed(true)
            .on_press(1);
        assert_eq!(b.label_text(), Some("Bold"));
        assert!(b.tooltip.is_none());
        assert_eq!(b.variant, Variant::Outline);
        assert_eq!(b.size, Size::Sm);
        assert!(b.is_pressed());
        assert!(b.is_enabled());
        assert!(!b.on_press_maybe(None).is_enabled());
    }

    #[test]
    fn a_toggle_stays_a_toggle_when_off_and_a_trigger_is_held_while_open() {
        let plain = icon_button::<u8>(crate::lucide!(Bold));
        assert!(!plain.is_toggle() && !plain.is_pressed());
        let off = icon_button::<u8>(crate::lucide!(Bold)).pressed(false);
        assert!(off.is_toggle() && !off.is_pressed());
        let closed = icon_button::<u8>(crate::lucide!(Ellipsis)).expanded(false);
        assert!(!closed.is_toggle() && !closed.is_pressed());
        let open = icon_button::<u8>(crate::lucide!(Ellipsis)).expanded(true);
        assert!(!open.is_toggle() && open.is_pressed());
    }

    #[test]
    fn unpressed_matches_the_button_colours() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in Variant::ALL {
                for status in STATES {
                    assert_eq!(
                        colours(&tokens, variant, false, status),
                        button::colours(&tokens, variant.into(), status),
                        "{variant:?} {status:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn variants_map_to_every_button_variant_but_link() {
        let mapped = Variant::ALL.map(Variant::button);
        assert!(!mapped.contains(&button::Variant::Link));
        for variant in button::Variant::ALL {
            assert_eq!(
                mapped.contains(&variant),
                variant != button::Variant::Link,
                "{variant:?}"
            );
        }
    }

    #[test]
    fn pressed_ghost_and_outline_use_the_accent_at_rest() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in [Variant::Ghost, Variant::Outline] {
                let on = colours(&tokens, variant, true, Status::Active);
                assert_eq!(on.background, Some(tokens.accent), "{variant:?}");
                assert_ne!(
                    on.background,
                    colours(&tokens, variant, false, Status::Active).background
                );
            }
        }
    }

    #[test]
    fn pressed_differs_from_unpressed_at_rest_for_filled_variants() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in [
                Variant::Primary,
                Variant::Secondary,
                Variant::Destructive,
                Variant::Outline,
                Variant::Ghost,
            ] {
                assert_ne!(
                    colours(&tokens, variant, true, Status::Active).background,
                    colours(&tokens, variant, false, Status::Active).background,
                    "{variant:?}"
                );
            }
        }
    }

    #[test]
    fn hovering_a_pressed_button_darkens_it() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in [Variant::Ghost, Variant::Outline, Variant::Primary] {
                let rest = colours(&tokens, variant, true, Status::Active);
                for status in [Status::Hovered, Status::Pressed] {
                    let active = colours(&tokens, variant, true, status);
                    assert_ne!(active.background, rest.background, "{variant:?} {status:?}");
                    assert_eq!(active.foreground, rest.foreground);
                }
            }
        }
    }

    #[test]
    fn disabled_pressed_keeps_the_on_look_at_half_alpha() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            for variant in Variant::ALL {
                let on = colours(&tokens, variant, true, Status::Active);
                let disabled = colours(&tokens, variant, true, Status::Disabled);
                assert!((disabled.foreground.a - on.foreground.a * 0.5).abs() < 1e-6);
                assert_eq!(
                    disabled.background.map(|c| c.a),
                    on.background.map(|c| c.a * 0.5)
                );
            }
        }
    }

    #[test]
    fn only_outline_has_a_border_in_every_state() {
        let tokens = Tokens::of(&light());
        for variant in Variant::ALL {
            for pressed in [false, true] {
                for status in STATES {
                    let style = style(&tokens, variant, pressed, status);
                    assert_eq!(style.border.width > 0.0, variant == Variant::Outline);
                    assert_eq!(style.border.radius, radius::MD.into());
                }
            }
        }
    }
}