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