1use gpui::{div, prelude::*, ElementId, IntoElement, Styled, WindowContext};
2
3use crate::prelude::*;
4use crate::{Color, Icon, IconName, Selection};
5
6/// # Checkbox
7///
8/// Checkboxes are used for multiple choices, not for mutually exclusive choices.
9/// Each checkbox works independently from other checkboxes in the list,
10/// therefore checking an additional box does not affect any other selections.
11#[derive(IntoElement)]
12pub struct Checkbox {
13 id: ElementId,
14 checked: Selection,
15 disabled: bool,
16 on_click: Option<Box<dyn Fn(&Selection, &mut WindowContext) + 'static>>,
17}
18
19impl Checkbox {
20 pub fn new(id: impl Into<ElementId>, checked: Selection) -> Self {
21 Self {
22 id: id.into(),
23 checked,
24 disabled: false,
25 on_click: None,
26 }
27 }
28
29 pub fn disabled(mut self, disabled: bool) -> Self {
30 self.disabled = disabled;
31 self
32 }
33
34 pub fn on_click(mut self, handler: impl Fn(&Selection, &mut WindowContext) + 'static) -> Self {
35 self.on_click = Some(Box::new(handler));
36 self
37 }
38}
39
40impl RenderOnce for Checkbox {
41 fn render(self, cx: &mut WindowContext) -> impl IntoElement {
42 let group_id = format!("checkbox_group_{:?}", self.id);
43
44 let icon = match self.checked {
45 Selection::Selected => Some(Icon::new(IconName::Check).size(IconSize::Small).color(
46 if self.disabled {
47 Color::Disabled
48 } else {
49 Color::Selected
50 },
51 )),
52 Selection::Indeterminate => Some(
53 Icon::new(IconName::Dash)
54 .size(IconSize::Small)
55 .color(if self.disabled {
56 Color::Disabled
57 } else {
58 Color::Selected
59 }),
60 ),
61 Selection::Unselected => None,
62 };
63
64 let selected =
65 self.checked == Selection::Selected || self.checked == Selection::Indeterminate;
66
67 let (bg_color, border_color) = match (self.disabled, selected) {
68 (true, _) => (
69 cx.theme().colors().ghost_element_disabled,
70 cx.theme().colors().border_disabled,
71 ),
72 (false, true) => (
73 cx.theme().colors().element_selected,
74 cx.theme().colors().border,
75 ),
76 (false, false) => (
77 cx.theme().colors().element_background,
78 cx.theme().colors().border,
79 ),
80 };
81
82 h_flex()
83 .id(self.id)
84 .justify_center()
85 .items_center()
86 .size(crate::styles::custom_spacing(cx, 20.))
87 .group(group_id.clone())
88 .child(
89 div()
90 .flex()
91 .flex_none()
92 .justify_center()
93 .items_center()
94 .m(Spacing::Small.px(cx))
95 .size(crate::styles::custom_spacing(cx, 16.))
96 .rounded_sm()
97 .bg(bg_color)
98 .border_1()
99 .border_color(border_color)
100 .when(!self.disabled, |this| {
101 this.group_hover(group_id.clone(), |el| {
102 el.bg(cx.theme().colors().element_hover)
103 })
104 })
105 .children(icon),
106 )
107 .when_some(
108 self.on_click.filter(|_| !self.disabled),
109 |this, on_click| this.on_click(move |_, cx| on_click(&self.checked.inverse(), cx)),
110 )
111 }
112}