Skip to main content

fc_ui/capabilities/controls/
toggle_group.rs

1//! Toggle group component - Grouped toggle buttons for toolbars and view switchers.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6use crate::capabilities::foundation::theme::use_theme;
7use crate::capabilities::primitives::icon::{Icon, IconSize};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
10pub enum ToggleGroupVariant {
11    #[default]
12    Single,
13    Multiple,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
17pub enum ToggleGroupSize {
18    Sm,
19    #[default]
20    Md,
21    Lg,
22}
23
24impl ToggleGroupSize {
25    fn height(&self) -> Pixels {
26        match self {
27            Self::Sm => px(32.0),
28            Self::Md => px(36.0),
29            Self::Lg => px(40.0),
30        }
31    }
32
33    fn px_value(&self) -> Pixels {
34        match self {
35            Self::Sm => px(8.0),
36            Self::Md => px(12.0),
37            Self::Lg => px(16.0),
38        }
39    }
40
41    fn text_size(&self) -> Pixels {
42        match self {
43            Self::Sm => px(12.0),
44            Self::Md => px(14.0),
45            Self::Lg => px(16.0),
46        }
47    }
48}
49
50#[derive(Clone, Debug)]
51pub struct ToggleGroupItem {
52    value: SharedString,
53    label: SharedString,
54    icon: Option<SharedString>,
55    disabled: bool,
56}
57
58impl ToggleGroupItem {
59    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
60        Self {
61            value: value.into(),
62            label: label.into(),
63            icon: None,
64            disabled: false,
65        }
66    }
67
68    pub fn icon(mut self, icon: impl Into<SharedString>) -> Self {
69        self.icon = Some(icon.into());
70        self
71    }
72
73    pub fn disabled(mut self, disabled: bool) -> Self {
74        self.disabled = disabled;
75        self
76    }
77}
78
79#[derive(IntoElement)]
80pub struct ToggleGroup {
81    variant: ToggleGroupVariant,
82    size: ToggleGroupSize,
83    items: Vec<ToggleGroupItem>,
84    value: Option<SharedString>, // For single selection
85    values: Vec<SharedString>,   // For multiple selection
86    disabled: bool,
87    on_change: Option<Rc<dyn Fn(&SharedString, &mut Window, &mut App)>>,
88    on_multiple_change: Option<Rc<dyn Fn(&Vec<SharedString>, &mut Window, &mut App)>>,
89    style: StyleRefinement,
90}
91
92impl ToggleGroup {
93    /// Create a new toggle group
94    pub fn new() -> Self {
95        Self {
96            variant: ToggleGroupVariant::default(),
97            size: ToggleGroupSize::default(),
98            items: Vec::new(),
99            value: None,
100            values: Vec::new(),
101            disabled: false,
102            on_change: None,
103            on_multiple_change: None,
104            style: StyleRefinement::default(),
105        }
106    }
107
108    /// Set the selection behavior variant
109    pub fn variant(mut self, variant: ToggleGroupVariant) -> Self {
110        self.variant = variant;
111        self
112    }
113
114    /// Set the size of toggle buttons
115    pub fn size(mut self, size: ToggleGroupSize) -> Self {
116        self.size = size;
117        self
118    }
119
120    /// Add an item to the group
121    pub fn item(mut self, item: ToggleGroupItem) -> Self {
122        self.items.push(item);
123        self
124    }
125
126    /// Add multiple items to the group
127    pub fn items(mut self, items: Vec<ToggleGroupItem>) -> Self {
128        self.items.extend(items);
129        self
130    }
131
132    /// Set the selected value (for single selection)
133    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
134        self.value = Some(value.into());
135        self
136    }
137
138    /// Set the selected values (for multiple selection)
139    pub fn values(mut self, values: Vec<SharedString>) -> Self {
140        self.values = values;
141        self
142    }
143
144    /// Set whether the entire group is disabled
145    pub fn disabled(mut self, disabled: bool) -> Self {
146        self.disabled = disabled;
147        self
148    }
149
150    /// Set the change handler for single selection
151    pub fn on_change<F>(mut self, handler: F) -> Self
152    where
153        F: Fn(&SharedString, &mut Window, &mut App) + 'static,
154    {
155        self.on_change = Some(Rc::new(handler));
156        self
157    }
158
159    /// Set the change handler for multiple selection
160    pub fn on_multiple_change<F>(mut self, handler: F) -> Self
161    where
162        F: Fn(&Vec<SharedString>, &mut Window, &mut App) + 'static,
163    {
164        self.on_multiple_change = Some(Rc::new(handler));
165        self
166    }
167}
168
169impl Default for ToggleGroup {
170    fn default() -> Self {
171        Self::new()
172    }
173}
174
175impl Styled for ToggleGroup {
176    fn style(&mut self) -> &mut StyleRefinement {
177        &mut self.style
178    }
179}
180
181impl RenderOnce for ToggleGroup {
182    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
183        let theme = use_theme(cx);
184
185        let variant = self.variant;
186        let current_value = self.value;
187        let current_values = self.values;
188        let disabled = self.disabled;
189        let size = self.size;
190        let on_change = self.on_change;
191        let on_multiple_change = self.on_multiple_change;
192        let user_style = self.style;
193
194        div()
195            .flex()
196            .items_center()
197            .gap(px(2.0))
198            .p(px(2.0))
199            .bg(theme.tokens.muted.opacity(0.3))
200            .rounded(theme.tokens.radius_md)
201            .children(self.items.into_iter().map(move |item| {
202                let is_selected = match variant {
203                    ToggleGroupVariant::Single => {
204                        current_value.as_ref().is_some_and(|v| v == &item.value)
205                    }
206                    ToggleGroupVariant::Multiple => current_values.contains(&item.value),
207                };
208                let is_disabled = disabled || item.disabled;
209                let value = item.value.clone();
210                let handler = on_change.clone();
211                let multiple_handler = on_multiple_change.clone();
212                let values = current_values.clone();
213
214                div()
215                    .flex()
216                    .items_center()
217                    .justify_center()
218                    .gap(px(6.0))
219                    .h(size.height())
220                    .px(size.px_value())
221                    .rounded(theme.tokens.radius_sm)
222                    .text_size(size.text_size())
223                    .font_weight(FontWeight::MEDIUM)
224                    .cursor(if is_disabled {
225                        CursorStyle::Arrow
226                    } else {
227                        CursorStyle::PointingHand
228                    })
229                    .when(is_selected, |this: Div| {
230                        this.bg(theme.tokens.background)
231                            .text_color(theme.tokens.foreground)
232                            .shadow(smallvec::smallvec![BoxShadow {
233                                color: hsla(0.0, 0.0, 0.0, 0.05),
234                                offset: point(px(0.0), px(1.0)),
235                                blur_radius: px(2.0),
236                                spread_radius: px(0.0),
237                                inset: false,
238                            }])
239                    })
240                    .when(!is_selected, |this: Div| {
241                        this.text_color(theme.tokens.muted_foreground)
242                    })
243                    .when(is_disabled, |this: Div| this.opacity(0.5))
244                    .when(!is_disabled && !is_selected, |this: Div| {
245                        this.hover(|style| {
246                            style
247                                .bg(theme.tokens.muted.opacity(0.5))
248                                .text_color(theme.tokens.foreground)
249                        })
250                    })
251                    .when(!is_disabled, |this: Div| {
252                        this.on_mouse_down(MouseButton::Left, move |_, window, cx| match variant {
253                            ToggleGroupVariant::Single => {
254                                if let Some(h) = &handler {
255                                    h(&value, window, cx);
256                                }
257                            }
258                            ToggleGroupVariant::Multiple => {
259                                let mut new_values = values.clone();
260                                if let Some(index) = new_values.iter().position(|v| v == &value) {
261                                    new_values.remove(index);
262                                } else {
263                                    new_values.push(value.clone());
264                                }
265                                if let Some(h) = &multiple_handler {
266                                    h(&new_values, window, cx);
267                                }
268                            }
269                        })
270                    })
271                    .when_some(item.icon.clone(), |this: Div, icon| {
272                        this.child(Icon::new(icon).size(IconSize::Small))
273                    })
274                    .child(item.label)
275            }))
276            .map(|this| {
277                let mut div = this;
278                div.style().refine(&user_style);
279                div
280            })
281    }
282}