Skip to main content

iced_cube/primitives/
checkbox.rs

1//! Checkboxes with checked, unchecked and indeterminate states.
2//!
3//! An enabled checkbox takes keyboard focus from iced's focus operations,
4//! such as a dialog's Tab order. While focused its box rings and Space or
5//! Enter toggles it.
6
7use iced::keyboard::key::Named;
8use iced::widget::{self, button::Status, container, mouse_area, row, space, text};
9use iced::{Alignment, Background, Border, Color, Element, Length, Shadow, Theme, mouse};
10
11use crate::focus::{Ring, focusable};
12use crate::icon::{Glyph, opacity, themed};
13use crate::keys::{self, Chord, Keymap};
14use crate::theme::{Tokens, fade, mix, radius, space as spacing, text_size};
15
16/// Side length of the check box in logical pixels.
17pub const BOX_SIZE: f32 = 16.0;
18
19const ICON_SIZE: f32 = 14.0;
20
21/// The value a checkbox shows.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
23pub enum CheckState {
24    #[default]
25    Unchecked,
26    Checked,
27    /// Partly checked, such as a "select all" box over a mixed selection.
28    Indeterminate,
29}
30
31impl CheckState {
32    pub const ALL: [CheckState; 3] = [
33        CheckState::Unchecked,
34        CheckState::Checked,
35        CheckState::Indeterminate,
36    ];
37
38    /// The state after a click. Indeterminate boxes become checked.
39    pub const fn toggled(self) -> Self {
40        match self {
41            CheckState::Checked => CheckState::Unchecked,
42            CheckState::Unchecked | CheckState::Indeterminate => CheckState::Checked,
43        }
44    }
45
46    pub const fn is_checked(self) -> bool {
47        matches!(self, CheckState::Checked)
48    }
49
50    /// Whether the box is drawn filled, which is true when checked or indeterminate.
51    pub const fn is_filled(self) -> bool {
52        !matches!(self, CheckState::Unchecked)
53    }
54
55    fn glyph(self) -> Option<Glyph> {
56        match self {
57            CheckState::Unchecked => None,
58            CheckState::Checked => Some(crate::lucide!(Check)),
59            CheckState::Indeterminate => Some(crate::lucide!(Minus)),
60        }
61    }
62}
63
64impl From<bool> for CheckState {
65    fn from(checked: bool) -> Self {
66        if checked {
67            CheckState::Checked
68        } else {
69            CheckState::Unchecked
70        }
71    }
72}
73
74/// A checkbox builder. Convert it into an [`Element`] to render.
75///
76/// A checkbox without a message is rendered disabled.
77#[derive(Debug)]
78pub struct Checkbox<'a, Message> {
79    state: CheckState,
80    label: Option<text::Fragment<'a>>,
81    on_toggle: Option<Message>,
82}
83
84/// Creates a checkbox showing `state`. Accepts a `bool` or a [`CheckState`].
85pub fn checkbox<'a, Message>(state: impl Into<CheckState>) -> Checkbox<'a, Message> {
86    Checkbox {
87        state: state.into(),
88        label: None,
89        on_toggle: None,
90    }
91}
92
93impl<'a, Message> Checkbox<'a, Message> {
94    pub fn label(mut self, label: impl text::IntoFragment<'a>) -> Self {
95        self.label = Some(label.into_fragment());
96        self
97    }
98
99    /// Sets the message for a click. It receives the new checked value, so an
100    /// indeterminate box reports `true`.
101    pub fn on_toggle(mut self, on_toggle: impl FnOnce(bool) -> Message) -> Self {
102        self.on_toggle = Some(on_toggle(self.state.toggled().is_checked()));
103        self
104    }
105
106    /// Like [`Checkbox::on_toggle`], but `None` disables the checkbox.
107    pub fn on_toggle_maybe(mut self, on_toggle: Option<impl FnOnce(bool) -> Message>) -> Self {
108        let next = self.state.toggled().is_checked();
109        self.on_toggle = on_toggle.map(|f| f(next));
110        self
111    }
112
113    pub fn state(&self) -> CheckState {
114        self.state
115    }
116
117    pub fn is_enabled(&self) -> bool {
118        self.on_toggle.is_some()
119    }
120}
121
122impl<'a, Message: Clone + 'a> From<Checkbox<'a, Message>> for Element<'a, Message> {
123    fn from(checkbox: Checkbox<'a, Message>) -> Self {
124        let state = checkbox.state;
125        let enabled = checkbox.on_toggle.is_some();
126        let resting = if enabled {
127            Status::Active
128        } else {
129            Status::Disabled
130        };
131
132        let mark: Element<'a, Message> = match state.glyph() {
133            Some(glyph) => themed(glyph, ICON_SIZE, opacity(enabled), move |theme| {
134                colours(&Tokens::of(theme), state, resting).icon
135            })
136            .into(),
137            None => space().into(),
138        };
139
140        let indicator = widget::button(container(mark).center(Length::Fill))
141            .width(BOX_SIZE)
142            .height(BOX_SIZE)
143            .padding(0)
144            .on_press_maybe(checkbox.on_toggle.clone())
145            .style(move |theme, status| style(&Tokens::of(theme), state, status));
146        let on_activate = checkbox
147            .on_toggle
148            .clone()
149            .map(|message| Box::new(move || message.clone()) as Box<dyn Fn() -> Message + 'a>);
150        let indicator = focusable(indicator, on_activate, Ring::around(radius::SM));
151
152        let indicator: Element<'a, Message> = indicator.into();
153        let Some(label) = checkbox.label else {
154            return indicator;
155        };
156
157        let label = text(label)
158            .size(text_size::SM)
159            .style(move |theme: &Theme| text::Style {
160                color: Some(colours(&Tokens::of(theme), state, resting).label),
161            });
162        let label = match checkbox.on_toggle {
163            Some(message) => mouse_area(label)
164                .on_press(message)
165                .interaction(mouse::Interaction::Pointer),
166            None => mouse_area(label),
167        };
168
169        row![indicator, label]
170            .spacing(spacing::SM)
171            .align_y(Alignment::Center)
172            .into()
173    }
174}
175
176/// Colours of a checkbox in a given state and interaction status.
177#[derive(Debug, Clone, Copy, PartialEq)]
178pub struct Colours {
179    pub background: Color,
180    pub border: Color,
181    pub icon: Color,
182    pub label: Color,
183}
184
185/// Resolves the colours of a checkbox for a value and interaction status.
186pub fn colours(tokens: &Tokens, state: CheckState, status: Status) -> Colours {
187    let hover = matches!(status, Status::Hovered | Status::Pressed);
188    let pressed = status == Status::Pressed;
189
190    let colours = if state.is_filled() {
191        let target = if tokens.is_dark {
192            Color::BLACK
193        } else {
194            Color::WHITE
195        };
196        let amount = match (hover, pressed) {
197            (_, true) => 0.2,
198            (true, false) => 0.1,
199            _ => 0.0,
200        };
201        let fill = mix(tokens.primary, target, amount);
202        Colours {
203            background: fill,
204            border: Color::TRANSPARENT,
205            icon: tokens.primary_foreground,
206            label: tokens.foreground,
207        }
208    } else {
209        Colours {
210            background: if pressed {
211                tokens.accent
212            } else {
213                Color::TRANSPARENT
214            },
215            border: mix(
216                tokens.border,
217                tokens.foreground,
218                if hover { 0.6 } else { 0.3 },
219            ),
220            icon: tokens.primary_foreground,
221            label: tokens.foreground,
222        }
223    };
224
225    if status != Status::Disabled {
226        return colours;
227    }
228    Colours {
229        background: fade(colours.background, 0.5),
230        border: fade(colours.border, 0.5),
231        icon: fade(colours.icon, 0.5),
232        label: fade(colours.label, 0.5),
233    }
234}
235
236/// The iced button style used for the check box itself.
237pub fn style(tokens: &Tokens, state: CheckState, status: Status) -> widget::button::Style {
238    let colours = colours(tokens, state, status);
239    widget::button::Style {
240        background: Some(Background::Color(colours.background)),
241        text_color: colours.icon,
242        border: Border {
243            color: colours.border,
244            width: 1.0,
245            radius: radius::SM.into(),
246        },
247        shadow: Shadow::default(),
248        snap: true,
249    }
250}
251
252/// What a checkbox keyboard shortcut does. Useful when the app tracks
253/// which checkbox is current.
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
255pub enum Action {
256    Toggle,
257}
258
259impl Action {
260    /// The checked value to send through the checkbox's `on_toggle`
261    /// message, matching a click.
262    pub fn apply(self, state: CheckState) -> bool {
263        match self {
264            Action::Toggle => state.toggled().is_checked(),
265        }
266    }
267}
268
269impl keys::Action for Action {
270    const ALL: &'static [Self] = &[Action::Toggle];
271
272    fn defaults() -> Keymap<Self> {
273        default_keymap()
274    }
275
276    fn name(self) -> &'static str {
277        "Toggle"
278    }
279
280    fn description(self) -> &'static str {
281        "Checks or unchecks the current checkbox. An indeterminate box becomes checked."
282    }
283}
284
285/// The default checkbox shortcuts:
286///
287/// | Keys | Action |
288/// | --- | --- |
289/// | `Space` | [`Action::Toggle`] |
290pub fn default_keymap() -> Keymap<Action> {
291    Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use crate::theme::{dark, light};
298
299    #[test]
300    fn toggle_matches_a_click() {
301        assert!(Action::Toggle.apply(CheckState::Unchecked));
302        assert!(!Action::Toggle.apply(CheckState::Checked));
303        assert!(Action::Toggle.apply(CheckState::Indeterminate));
304    }
305
306    #[test]
307    fn default_keymap_and_overrides() {
308        let keymap = default_keymap();
309        assert_eq!(
310            keymap.resolve(
311                &iced::keyboard::Key::Named(Named::Space),
312                Default::default()
313            ),
314            Some(Action::Toggle)
315        );
316        let custom = keymap
317            .clear()
318            .bind("Enter".parse().unwrap(), Action::Toggle);
319        assert_eq!(custom.len(), 1);
320        assert_eq!(
321            custom.resolve(
322                &iced::keyboard::Key::Named(Named::Enter),
323                Default::default()
324            ),
325            Some(Action::Toggle)
326        );
327    }
328
329    const STATES: [Status; 4] = [
330        Status::Active,
331        Status::Hovered,
332        Status::Pressed,
333        Status::Disabled,
334    ];
335
336    #[test]
337    fn default_builder_is_unchecked_unlabelled_and_disabled() {
338        let c: Checkbox<'_, ()> = checkbox(false);
339        assert_eq!(c.state(), CheckState::Unchecked);
340        assert!(c.label.is_none());
341        assert!(!c.is_enabled());
342    }
343
344    #[test]
345    fn bool_converts_to_two_states() {
346        assert_eq!(CheckState::from(true), CheckState::Checked);
347        assert_eq!(CheckState::from(false), CheckState::Unchecked);
348    }
349
350    #[test]
351    fn toggling_cycles_between_checked_and_unchecked() {
352        assert_eq!(CheckState::Unchecked.toggled(), CheckState::Checked);
353        assert_eq!(CheckState::Checked.toggled(), CheckState::Unchecked);
354        assert_eq!(CheckState::Indeterminate.toggled(), CheckState::Checked);
355    }
356
357    #[test]
358    fn on_toggle_receives_the_next_value() {
359        assert_eq!(checkbox(false).on_toggle(|v| v).on_toggle, Some(true));
360        assert_eq!(checkbox(true).on_toggle(|v| v).on_toggle, Some(false));
361        let mixed = checkbox(CheckState::Indeterminate).on_toggle(|v| v);
362        assert_eq!(mixed.on_toggle, Some(true));
363    }
364
365    #[test]
366    fn on_toggle_maybe_none_disables() {
367        let c = checkbox(true).on_toggle_maybe(None::<fn(bool) -> bool>);
368        assert!(!c.is_enabled());
369    }
370
371    #[test]
372    fn only_filled_states_draw_a_mark() {
373        assert!(CheckState::Unchecked.glyph().is_none());
374        assert_eq!(CheckState::Checked.glyph().map(Glyph::name), Some("check"));
375        assert_eq!(
376            CheckState::Indeterminate.glyph().map(Glyph::name),
377            Some("minus")
378        );
379    }
380
381    #[test]
382    fn filled_states_use_primary_and_unchecked_is_transparent() {
383        for theme in [light(), dark()] {
384            let tokens = Tokens::of(&theme);
385            let checked = colours(&tokens, CheckState::Checked, Status::Active);
386            let mixed = colours(&tokens, CheckState::Indeterminate, Status::Active);
387            let unchecked = colours(&tokens, CheckState::Unchecked, Status::Active);
388            assert_eq!(checked.background, tokens.primary);
389            assert_eq!(checked, mixed);
390            assert_eq!(unchecked.background, Color::TRANSPARENT);
391        }
392    }
393
394    #[test]
395    fn hover_and_press_change_the_box_in_every_state() {
396        for theme in [light(), dark()] {
397            let tokens = Tokens::of(&theme);
398            for state in CheckState::ALL {
399                let active = colours(&tokens, state, Status::Active);
400                let hovered = colours(&tokens, state, Status::Hovered);
401                let pressed = colours(&tokens, state, Status::Pressed);
402                assert_ne!(active, hovered, "{state:?}");
403                assert_ne!(hovered, pressed, "{state:?}");
404            }
405        }
406    }
407
408    #[test]
409    fn disabled_halves_alpha_everywhere() {
410        for theme in [light(), dark()] {
411            let tokens = Tokens::of(&theme);
412            for state in CheckState::ALL {
413                let active = colours(&tokens, state, Status::Active);
414                let disabled = colours(&tokens, state, Status::Disabled);
415                assert!((disabled.border.a - active.border.a * 0.5).abs() < 1e-6);
416                assert!((disabled.label.a - active.label.a * 0.5).abs() < 1e-6);
417                assert!((disabled.icon.a - active.icon.a * 0.5).abs() < 1e-6);
418            }
419        }
420    }
421
422    #[test]
423    fn every_style_has_a_rounded_one_pixel_border() {
424        for theme in [light(), dark()] {
425            let tokens = Tokens::of(&theme);
426            for state in CheckState::ALL {
427                for status in STATES {
428                    let style = style(&tokens, state, status);
429                    assert_eq!(style.border.width, 1.0);
430                    assert!(style.background.is_some());
431                }
432            }
433        }
434    }
435}