1/// A trait for elements that can be toggled.
2///
3/// Implement this for elements that are visually distinct
4/// when in two opposing states, like checkboxes or switches.
5pub trait Toggleable {
6 /// Sets whether the element is selected.
7 fn toggle_state(self, selected: bool) -> Self;
8}
9
10/// Represents the selection status of an element.
11#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy)]
12pub enum ToggleState {
13 /// The element is not selected.
14 #[default]
15 Unselected,
16 /// The selection state of the element is indeterminate.
17 Indeterminate,
18 /// The element is selected.
19 Selected,
20}
21
22impl ToggleState {
23 /// Returns the inverse of the current selection status.
24 ///
25 /// Indeterminate states become selected if inverted.
26 pub fn inverse(&self) -> Self {
27 match self {
28 Self::Unselected | Self::Indeterminate => Self::Selected,
29 Self::Selected => Self::Unselected,
30 }
31 }
32}
33
34impl From<bool> for ToggleState {
35 fn from(selected: bool) -> Self {
36 if selected {
37 Self::Selected
38 } else {
39 Self::Unselected
40 }
41 }
42}
43
44impl From<Option<bool>> for ToggleState {
45 fn from(selected: Option<bool>) -> Self {
46 match selected {
47 Some(true) => Self::Selected,
48 Some(false) => Self::Unselected,
49 None => Self::Unselected,
50 }
51 }
52}