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        // The box carries the annotation, so the focus it reports is the
154        // checkbox's. The label is its name.
155        #[cfg(feature = "icedwright")]
156        let indicator = annotate(indicator, checkbox.label.clone(), state, enabled);
157        let Some(label) = checkbox.label else {
158            return indicator;
159        };
160
161        let label = text(label)
162            .size(text_size::SM)
163            .style(move |theme: &Theme| text::Style {
164                color: Some(colours(&Tokens::of(theme), state, resting).label),
165            });
166        let label = match checkbox.on_toggle {
167            Some(message) => mouse_area(label)
168                .on_press(message)
169                .interaction(mouse::Interaction::Pointer),
170            None => mouse_area(label),
171        };
172
173        row![indicator, label]
174            .spacing(spacing::SM)
175            .align_y(Alignment::Center)
176            .into()
177    }
178}
179
180/// Reports a checkbox, including the mixed state.
181#[cfg(feature = "icedwright")]
182fn annotate<'a, Message: 'a>(
183    element: Element<'a, Message>,
184    name: Option<text::Fragment<'a>>,
185    state: CheckState,
186    enabled: bool,
187) -> Element<'a, Message> {
188    use icedwright_probe::{Checked, role, semantic};
189    let checked = match state {
190        CheckState::Unchecked => Checked::False,
191        CheckState::Checked => Checked::True,
192        CheckState::Indeterminate => Checked::Mixed,
193    };
194    let mut annotated = semantic(element)
195        .role(role::CheckBox)
196        .checked(checked)
197        .component("iced_cube::checkbox");
198    if !enabled {
199        annotated = annotated.disabled(true);
200    }
201    if let Some(name) = name {
202        annotated = annotated.name(name);
203    }
204    annotated.into()
205}
206
207/// Colours of a checkbox in a given state and interaction status.
208#[derive(Debug, Clone, Copy, PartialEq)]
209pub struct Colours {
210    pub background: Color,
211    pub border: Color,
212    pub icon: Color,
213    pub label: Color,
214}
215
216/// Resolves the colours of a checkbox for a value and interaction status.
217pub fn colours(tokens: &Tokens, state: CheckState, status: Status) -> Colours {
218    let hover = matches!(status, Status::Hovered | Status::Pressed);
219    let pressed = status == Status::Pressed;
220
221    let colours = if state.is_filled() {
222        let target = if tokens.is_dark {
223            Color::BLACK
224        } else {
225            Color::WHITE
226        };
227        let amount = match (hover, pressed) {
228            (_, true) => 0.2,
229            (true, false) => 0.1,
230            _ => 0.0,
231        };
232        let fill = mix(tokens.primary, target, amount);
233        Colours {
234            background: fill,
235            border: Color::TRANSPARENT,
236            icon: tokens.primary_foreground,
237            label: tokens.foreground,
238        }
239    } else {
240        Colours {
241            background: if pressed {
242                tokens.accent
243            } else {
244                Color::TRANSPARENT
245            },
246            border: mix(
247                tokens.border,
248                tokens.foreground,
249                if hover { 0.6 } else { 0.3 },
250            ),
251            icon: tokens.primary_foreground,
252            label: tokens.foreground,
253        }
254    };
255
256    if status != Status::Disabled {
257        return colours;
258    }
259    Colours {
260        background: fade(colours.background, 0.5),
261        border: fade(colours.border, 0.5),
262        icon: fade(colours.icon, 0.5),
263        label: fade(colours.label, 0.5),
264    }
265}
266
267/// The iced button style used for the check box itself.
268pub fn style(tokens: &Tokens, state: CheckState, status: Status) -> widget::button::Style {
269    let colours = colours(tokens, state, status);
270    widget::button::Style {
271        background: Some(Background::Color(colours.background)),
272        text_color: colours.icon,
273        border: Border {
274            color: colours.border,
275            width: 1.0,
276            radius: radius::SM.into(),
277        },
278        shadow: Shadow::default(),
279        snap: true,
280    }
281}
282
283/// What a checkbox keyboard shortcut does. Useful when the app tracks
284/// which checkbox is current.
285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
286pub enum Action {
287    Toggle,
288}
289
290impl Action {
291    /// The checked value to send through the checkbox's `on_toggle`
292    /// message, matching a click.
293    pub fn apply(self, state: CheckState) -> bool {
294        match self {
295            Action::Toggle => state.toggled().is_checked(),
296        }
297    }
298}
299
300impl keys::Action for Action {
301    const ALL: &'static [Self] = &[Action::Toggle];
302
303    fn defaults() -> Keymap<Self> {
304        default_keymap()
305    }
306
307    fn name(self) -> &'static str {
308        "Toggle"
309    }
310
311    fn description(self) -> &'static str {
312        "Checks or unchecks the current checkbox. An indeterminate box becomes checked."
313    }
314}
315
316/// The default checkbox shortcuts:
317///
318/// | Keys | Action |
319/// | --- | --- |
320/// | `Space` | [`Action::Toggle`] |
321pub fn default_keymap() -> Keymap<Action> {
322    Keymap::new().bind(Chord::named(Named::Space), Action::Toggle)
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use crate::theme::{dark, light};
329
330    #[test]
331    fn toggle_matches_a_click() {
332        assert!(Action::Toggle.apply(CheckState::Unchecked));
333        assert!(!Action::Toggle.apply(CheckState::Checked));
334        assert!(Action::Toggle.apply(CheckState::Indeterminate));
335    }
336
337    #[test]
338    fn default_keymap_and_overrides() {
339        let keymap = default_keymap();
340        assert_eq!(
341            keymap.resolve(
342                &iced::keyboard::Key::Named(Named::Space),
343                Default::default()
344            ),
345            Some(Action::Toggle)
346        );
347        let custom = keymap
348            .clear()
349            .bind("Enter".parse().unwrap(), Action::Toggle);
350        assert_eq!(custom.len(), 1);
351        assert_eq!(
352            custom.resolve(
353                &iced::keyboard::Key::Named(Named::Enter),
354                Default::default()
355            ),
356            Some(Action::Toggle)
357        );
358    }
359
360    const STATES: [Status; 4] = [
361        Status::Active,
362        Status::Hovered,
363        Status::Pressed,
364        Status::Disabled,
365    ];
366
367    #[test]
368    fn default_builder_is_unchecked_unlabelled_and_disabled() {
369        let c: Checkbox<'_, ()> = checkbox(false);
370        assert_eq!(c.state(), CheckState::Unchecked);
371        assert!(c.label.is_none());
372        assert!(!c.is_enabled());
373    }
374
375    #[test]
376    fn bool_converts_to_two_states() {
377        assert_eq!(CheckState::from(true), CheckState::Checked);
378        assert_eq!(CheckState::from(false), CheckState::Unchecked);
379    }
380
381    #[test]
382    fn toggling_cycles_between_checked_and_unchecked() {
383        assert_eq!(CheckState::Unchecked.toggled(), CheckState::Checked);
384        assert_eq!(CheckState::Checked.toggled(), CheckState::Unchecked);
385        assert_eq!(CheckState::Indeterminate.toggled(), CheckState::Checked);
386    }
387
388    #[test]
389    fn on_toggle_receives_the_next_value() {
390        assert_eq!(checkbox(false).on_toggle(|v| v).on_toggle, Some(true));
391        assert_eq!(checkbox(true).on_toggle(|v| v).on_toggle, Some(false));
392        let mixed = checkbox(CheckState::Indeterminate).on_toggle(|v| v);
393        assert_eq!(mixed.on_toggle, Some(true));
394    }
395
396    #[test]
397    fn on_toggle_maybe_none_disables() {
398        let c = checkbox(true).on_toggle_maybe(None::<fn(bool) -> bool>);
399        assert!(!c.is_enabled());
400    }
401
402    #[test]
403    fn only_filled_states_draw_a_mark() {
404        assert!(CheckState::Unchecked.glyph().is_none());
405        assert_eq!(CheckState::Checked.glyph().map(Glyph::name), Some("check"));
406        assert_eq!(
407            CheckState::Indeterminate.glyph().map(Glyph::name),
408            Some("minus")
409        );
410    }
411
412    #[test]
413    fn filled_states_use_primary_and_unchecked_is_transparent() {
414        for theme in [light(), dark()] {
415            let tokens = Tokens::of(&theme);
416            let checked = colours(&tokens, CheckState::Checked, Status::Active);
417            let mixed = colours(&tokens, CheckState::Indeterminate, Status::Active);
418            let unchecked = colours(&tokens, CheckState::Unchecked, Status::Active);
419            assert_eq!(checked.background, tokens.primary);
420            assert_eq!(checked, mixed);
421            assert_eq!(unchecked.background, Color::TRANSPARENT);
422        }
423    }
424
425    #[test]
426    fn hover_and_press_change_the_box_in_every_state() {
427        for theme in [light(), dark()] {
428            let tokens = Tokens::of(&theme);
429            for state in CheckState::ALL {
430                let active = colours(&tokens, state, Status::Active);
431                let hovered = colours(&tokens, state, Status::Hovered);
432                let pressed = colours(&tokens, state, Status::Pressed);
433                assert_ne!(active, hovered, "{state:?}");
434                assert_ne!(hovered, pressed, "{state:?}");
435            }
436        }
437    }
438
439    #[test]
440    fn disabled_halves_alpha_everywhere() {
441        for theme in [light(), dark()] {
442            let tokens = Tokens::of(&theme);
443            for state in CheckState::ALL {
444                let active = colours(&tokens, state, Status::Active);
445                let disabled = colours(&tokens, state, Status::Disabled);
446                assert!((disabled.border.a - active.border.a * 0.5).abs() < 1e-6);
447                assert!((disabled.label.a - active.label.a * 0.5).abs() < 1e-6);
448                assert!((disabled.icon.a - active.icon.a * 0.5).abs() < 1e-6);
449            }
450        }
451    }
452
453    #[test]
454    fn every_style_has_a_rounded_one_pixel_border() {
455        for theme in [light(), dark()] {
456            let tokens = Tokens::of(&theme);
457            for state in CheckState::ALL {
458                for status in STATES {
459                    let style = style(&tokens, state, status);
460                    assert_eq!(style.border.width, 1.0);
461                    assert!(style.background.is_some());
462                }
463            }
464        }
465    }
466}