Skip to main content

gpui_material_components/settings_tiles/
checkbox.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, RenderOnce, Role, SharedString,
5    Window, accesskit::Toggled,
6};
7use gpui_material_foundation::InteractionSource;
8
9use crate::{Checkbox, CheckboxColors, CheckboxState, ListItem, ListItemColors, ListVariant};
10
11use super::common::{TileFields, apply_standalone_variant};
12
13type CheckboxTileChange = Rc<dyn Fn(CheckboxState, &mut Window, &mut App)>;
14
15/// Settings convenience row wrapping [`ListItem`] with a synchronized decorative [`Checkbox`].
16///
17/// Clicking anywhere on the row or pressing Enter or Space requests the next [`CheckboxState`]
18/// with a single focus stop and `Role::CheckBox` semantics.
19#[derive(IntoElement)]
20pub struct CheckboxTile {
21    fields: TileFields,
22    state: CheckboxState,
23    trailing: Option<AnyElement>,
24    trailing_checkbox: bool,
25    error: bool,
26    checkbox_colors: CheckboxColors,
27    on_change: Option<CheckboxTileChange>,
28}
29
30impl CheckboxTile {
31    /// Creates a checkbox settings row with an element ID, headline label, and controlled [`CheckboxState`].
32    pub fn new(
33        id: impl Into<ElementId>,
34        label: impl Into<SharedString>,
35        state: CheckboxState,
36    ) -> Self {
37        Self {
38            fields: TileFields::new(id, label),
39            state,
40            trailing: None,
41            trailing_checkbox: true,
42            error: false,
43            checkbox_colors: CheckboxColors::default(),
44            on_change: None,
45        }
46    }
47
48    /// Convenience constructor for a two-state boolean checkbox tile.
49    pub fn bool(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
50        Self::new(
51            id,
52            label,
53            if checked {
54                CheckboxState::Checked
55            } else {
56                CheckboxState::Unchecked
57            },
58        )
59    }
60
61    /// Sets secondary supporting text displayed below the headline.
62    pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
63        self.fields.supporting = Some(text.into());
64        self
65    }
66
67    /// Sets overline text displayed above the headline.
68    pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
69        self.fields.overline = Some(text.into());
70        self
71    }
72
73    /// Sets an optional leading icon or graphic when the checkbox is in the trailing slot.
74    pub fn leading(mut self, leading: impl IntoElement) -> Self {
75        self.fields.leading = Some(leading.into_any_element());
76        self
77    }
78
79    /// Trailing decorative content used when `.trailing_checkbox(false)` places the checkbox
80    /// in the leading slot.
81    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
82        self.trailing = Some(trailing.into_any_element());
83        self
84    }
85
86    /// Places the decorative checkbox in the trailing slot (`true`, default) or leading slot (`false`).
87    pub fn trailing_checkbox(mut self, trailing: bool) -> Self {
88        self.trailing_checkbox = trailing;
89        self
90    }
91
92    /// Marks the checkbox tile as invalid, applying error styling and `aria-invalid` semantics.
93    pub fn error(mut self, error: bool) -> Self {
94        self.error = error;
95        self
96    }
97
98    /// Disables row interaction and dims the checkbox when `true`.
99    pub fn disabled(mut self, disabled: bool) -> Self {
100        self.fields.disabled = disabled;
101        self
102    }
103
104    /// Sets standalone row styling (`Standard` or `Segmented`).
105    pub fn variant(mut self, variant: ListVariant) -> Self {
106        self.fields.variant = variant;
107        self
108    }
109
110    /// Overrides container and slot colors on the underlying [`ListItem`].
111    pub fn colors(mut self, colors: ListItemColors) -> Self {
112        self.fields.colors = colors;
113        self
114    }
115
116    /// Overrides checkmark, box, and border colors on the decorative [`Checkbox`].
117    pub fn checkbox_colors(mut self, colors: CheckboxColors) -> Self {
118        self.checkbox_colors = colors;
119        self
120    }
121
122    /// Uses a caller-owned focus handle for this tile.
123    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
124        self.fields.focus = Some(focus.clone());
125        self
126    }
127
128    /// Reports hover, focus, press, and disabled states through a caller-owned source.
129    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
130        self.fields.source = Some(source.clone());
131        self
132    }
133
134    /// Invoked with the requested next [`CheckboxState`] when the tile is toggled.
135    pub fn on_change(
136        mut self,
137        handler: impl Fn(CheckboxState, &mut Window, &mut App) + 'static,
138    ) -> Self {
139        self.on_change = Some(Rc::new(handler));
140        self
141    }
142
143    pub(super) fn into_list_item(mut self) -> ListItem {
144        let checkbox = Checkbox::new(
145            (self.fields.id.clone(), "checkbox"),
146            self.fields.label.clone(),
147            self.state,
148        )
149        .error(self.error)
150        .disabled(self.fields.disabled)
151        .colors(self.checkbox_colors)
152        .decorative(true);
153
154        let toggled = match self.state {
155            CheckboxState::Unchecked => Toggled::False,
156            CheckboxState::Checked => Toggled::True,
157            CheckboxState::Indeterminate => Toggled::Mixed,
158        };
159
160        let leading = self.fields.leading.take();
161        let mut item = self
162            .fields
163            .into_list_item()
164            .checked_toggled(toggled)
165            .checked_role(Role::CheckBox)
166            .checked_selects_row(false)
167            .invalid(self.error);
168
169        if self.trailing_checkbox {
170            item = item.trailing(checkbox);
171            if let Some(leading) = leading {
172                item = item.leading(leading);
173            }
174        } else {
175            item = item.leading(checkbox);
176            if let Some(trailing) = self.trailing {
177                item = item.trailing(trailing);
178            }
179        }
180
181        if let Some(on_change) = self.on_change {
182            let next = if self.state == CheckboxState::Checked {
183                CheckboxState::Unchecked
184            } else {
185                CheckboxState::Checked
186            };
187            item = item.on_activate(move |window, cx| on_change(next, window, cx));
188        }
189        item
190    }
191}
192
193impl RenderOnce for CheckboxTile {
194    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
195        let variant = self.fields.variant;
196        apply_standalone_variant(self.into_list_item(), variant)
197    }
198}