Skip to main content

gpui_component/button/
button_group.rs

1use gpui::Corners;
2use gpui::InteractiveElement;
3use gpui::ParentElement;
4use gpui::{App, Axis, Edges, ElementId, IntoElement, Window};
5use gpui::{
6    RenderOnce, StatefulInteractiveElement as _, StyleRefinement, Styled, div,
7    prelude::FluentBuilder as _,
8};
9use gpui_base::LogicalStyledExt as _;
10use std::{cell::Cell, rc::Rc};
11
12use crate::{
13    Disableable, Sizable, Size, StyledExt,
14    button::{Button, ButtonVariant, ButtonVariants},
15};
16
17/// A ButtonGroup element, to wrap multiple buttons in a group.
18#[derive(IntoElement)]
19pub struct ButtonGroup {
20    id: ElementId,
21    style: StyleRefinement,
22    children: Vec<Button>,
23    pub(super) multiple: bool,
24    pub(super) disabled: bool,
25    pub(super) layout: Axis,
26
27    // The button props
28    pub(super) compact: bool,
29    pub(super) outline: bool,
30    pub(super) variant: Option<ButtonVariant>,
31    pub(super) size: Option<Size>,
32
33    on_click: Option<Box<dyn Fn(&Vec<usize>, &mut Window, &mut App) + 'static>>,
34}
35
36impl Disableable for ButtonGroup {
37    fn disabled(mut self, disabled: bool) -> Self {
38        self.disabled = disabled;
39        self
40    }
41}
42
43impl ButtonGroup {
44    /// Creates a new ButtonGroup.
45    pub fn new(id: impl Into<ElementId>) -> Self {
46        Self {
47            id: id.into(),
48            style: StyleRefinement::default(),
49            children: Vec::new(),
50            variant: None,
51            size: None,
52            compact: false,
53            outline: false,
54            multiple: false,
55            disabled: false,
56            layout: Axis::Horizontal,
57            on_click: None,
58        }
59    }
60
61    /// Adds a button as a child to the ButtonGroup.
62    pub fn child(mut self, child: Button) -> Self {
63        self.children.push(child.disabled(self.disabled));
64        self
65    }
66
67    /// Adds multiple buttons as children to the ButtonGroup.
68    pub fn children(mut self, children: impl IntoIterator<Item = Button>) -> Self {
69        self.children.extend(children);
70        self
71    }
72
73    /// With the multiple selection mode, default is false (single selection).
74    pub fn multiple(mut self, multiple: bool) -> Self {
75        self.multiple = multiple;
76        self
77    }
78
79    /// Set the layout of the button group. Default is `Axis::Horizontal`.
80    pub fn layout(mut self, layout: Axis) -> Self {
81        self.layout = layout;
82        self
83    }
84
85    /// With the compact mode for the ButtonGroup.
86    ///
87    /// See also: [`Button::compact()`]
88    pub fn compact(mut self) -> Self {
89        self.compact = true;
90        self
91    }
92
93    /// With the outline mode for the ButtonGroup.
94    ///
95    /// See also: [`Button::outline()`]
96    pub fn outline(mut self) -> Self {
97        self.outline = true;
98        self
99    }
100
101    /// Sets the on_click handler for the ButtonGroup.
102    ///
103    /// The handler first argument is a vector of the selected button indices.
104    ///
105    /// The `&Vec<usize>` is the indices of the clicked (selected in `multiple` mode) buttons.
106    /// For example: `[0, 2, 3]` is means the first, third and fourth buttons are clicked.
107    ///
108    /// ```ignore
109    /// ButtonGroup::new("size-button")
110    ///    .child(Button::new("large").label("Large").selected(self.size == Size::Large))
111    ///    .child(Button::new("medium").label("Medium").selected(self.size == Size::Medium))
112    ///    .child(Button::new("small").label("Small").selected(self.size == Size::Small))
113    ///    .on_click(cx.listener(|view, clicks: &Vec<usize>, _, cx| {
114    ///        if clicks.contains(&0) {
115    ///            view.size = Size::Large;
116    ///        } else if clicks.contains(&1) {
117    ///            view.size = Size::Medium;
118    ///        } else if clicks.contains(&2) {
119    ///            view.size = Size::Small;
120    ///        }
121    ///        cx.notify();
122    ///    }))
123    /// ```
124    pub fn on_click(
125        mut self,
126        handler: impl Fn(&Vec<usize>, &mut Window, &mut App) + 'static,
127    ) -> Self {
128        self.on_click = Some(Box::new(handler));
129        self
130    }
131}
132
133impl Sizable for ButtonGroup {
134    fn with_size(mut self, size: impl Into<Size>) -> Self {
135        self.size = Some(size.into());
136        self
137    }
138}
139
140impl Styled for ButtonGroup {
141    fn style(&mut self) -> &mut gpui::StyleRefinement {
142        &mut self.style
143    }
144}
145
146impl ButtonVariants for ButtonGroup {
147    fn with_variant(mut self, variant: ButtonVariant) -> Self {
148        self.variant = Some(variant);
149        self
150    }
151}
152
153impl RenderOnce for ButtonGroup {
154    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
155        let children_len = self.children.len();
156        let mut selected_ixs: Vec<usize> = Vec::new();
157        let state = Rc::new(Cell::new(None));
158
159        for (ix, child) in self.children.iter().enumerate() {
160            if child.selected {
161                selected_ixs.push(ix);
162            }
163        }
164
165        let vertical = self.layout == Axis::Vertical;
166
167        div()
168            .id(self.id)
169            .flex()
170            .when(vertical, |this| this.flex_col().justify_center())
171            .when(!vertical, |this| this.flex_row_dir(cx).items_center())
172            .refine_style(&self.style)
173            .children(
174                self.children
175                    .into_iter()
176                    .enumerate()
177                    .map(|(child_index, child)| {
178                        let state = Rc::clone(&state);
179                        // The group as a whole is a toggle control, so every
180                        // child advertises its pressed state.
181                        let selected = child.selected;
182                        let child = child.toggled(selected);
183                        let child = if children_len == 1 {
184                            child
185                        } else if child_index == 0 {
186                            // First
187                            child
188                                .border_corners(Corners {
189                                    top_left: true,
190                                    top_right: vertical,
191                                    bottom_left: !vertical,
192                                    bottom_right: false,
193                                })
194                                .border_edges(Edges {
195                                    left: true,
196                                    top: true,
197                                    right: true,
198                                    bottom: true,
199                                })
200                        } else if child_index == children_len - 1 {
201                            // Last
202                            child
203                                .border_edges(Edges {
204                                    left: vertical,
205                                    top: !vertical,
206                                    right: true,
207                                    bottom: true,
208                                })
209                                .border_corners(Corners {
210                                    top_left: false,
211                                    top_right: !vertical,
212                                    bottom_left: vertical,
213                                    bottom_right: true,
214                                })
215                        } else {
216                            // Middle
217                            child
218                                .border_corners(Corners {
219                                    top_left: false,
220                                    top_right: false,
221                                    bottom_left: false,
222                                    bottom_right: false,
223                                })
224                                .border_edges(Edges {
225                                    left: vertical,
226                                    top: !vertical,
227                                    right: true,
228                                    bottom: true,
229                                })
230                        }
231                        .when_some(self.size, |this, size| this.with_size(size))
232                        .when_some(self.variant, |this, variant| this.with_variant(variant))
233                        .when(self.compact, |this| this.compact())
234                        .when(self.outline, |this| this.outline())
235                        .when(self.on_click.is_some(), |this| {
236                            this.on_click(move |_, _, _| {
237                                state.set(Some(child_index));
238                            })
239                        });
240
241                        child
242                    }),
243            )
244            .when_some(
245                self.on_click.filter(|_| !self.disabled),
246                move |this, on_click| {
247                    this.on_click(move |_, window, cx| {
248                        let mut selected_ixs = selected_ixs.clone();
249                        if let Some(ix) = state.get() {
250                            if self.multiple {
251                                if let Some(pos) = selected_ixs.iter().position(|&i| i == ix) {
252                                    selected_ixs.remove(pos);
253                                } else {
254                                    selected_ixs.push(ix);
255                                }
256                            } else {
257                                selected_ixs.clear();
258                                selected_ixs.push(ix);
259                            }
260                        }
261
262                        on_click(&selected_ixs, window, cx);
263                    })
264                },
265            )
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use crate::Selectable as _;
273    use gpui::{
274        Axis, Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, TestAppContext,
275        VisualTestContext, point, px,
276    };
277    use std::{cell::Cell, rc::Rc};
278
279    struct GroupHarness {
280        multiple: bool,
281        install_group_callback: bool,
282        child_clicks: Rc<Cell<usize>>,
283        group_changes: Rc<std::cell::RefCell<Vec<Vec<usize>>>>,
284    }
285
286    impl Render for GroupHarness {
287        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
288            let child_clicks = self.child_clicks.clone();
289            let mut group = ButtonGroup::new("group")
290                .multiple(self.multiple)
291                .size(px(120.))
292                .child(
293                    Button::new("one")
294                        .label("One")
295                        .on_click(move |_, _, _| child_clicks.set(child_clicks.get() + 1)),
296                )
297                .child(Button::new("two").label("Two").selected(true));
298            if self.install_group_callback {
299                let changes = self.group_changes.clone();
300                group = group.on_click(move |next, _, _| changes.borrow_mut().push(next.clone()));
301            }
302            group
303        }
304    }
305
306    fn group_harness(
307        cx: &mut TestAppContext,
308        multiple: bool,
309        install_group_callback: bool,
310    ) -> (
311        &mut VisualTestContext,
312        Rc<Cell<usize>>,
313        Rc<std::cell::RefCell<Vec<Vec<usize>>>>,
314    ) {
315        cx.update(crate::init);
316        let child_clicks = Rc::new(Cell::new(0));
317        let changes = Rc::new(std::cell::RefCell::new(Vec::new()));
318        let (_, cx) = cx.add_window_view({
319            let child_clicks = child_clicks.clone();
320            let group_changes = changes.clone();
321            move |_, _| GroupHarness {
322                multiple,
323                install_group_callback,
324                child_clicks,
325                group_changes,
326            }
327        });
328        cx.update(|window, cx| window.draw(cx).clear(cx));
329        (cx, child_clicks, changes)
330    }
331
332    fn activate_key(cx: &mut VisualTestContext, key: &str) {
333        let keystroke =
334            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
335        cx.simulate_event(KeyDownEvent {
336            keystroke: keystroke.clone(),
337            is_held: false,
338            prefer_character_input: false,
339        });
340        cx.simulate_event(KeyUpEvent { keystroke });
341    }
342
343    fn click_first(cx: &mut VisualTestContext) {
344        cx.simulate_click(point(px(10.), px(60.)), Modifiers::default());
345    }
346
347    #[gpui::test]
348    fn legacy_group_callback_overrides_the_child_callback(cx: &mut TestAppContext) {
349        let (cx, child_clicks, changes) = group_harness(cx, false, true);
350        click_first(cx);
351        assert_eq!(child_clicks.get(), 0);
352        assert_eq!(changes.borrow().as_slice(), &[vec![0]]);
353    }
354
355    #[gpui::test]
356    fn legacy_child_callback_survives_without_a_group_callback(cx: &mut TestAppContext) {
357        let (cx, child_clicks, changes) = group_harness(cx, false, false);
358        click_first(cx);
359        assert_eq!(child_clicks.get(), 1);
360        assert!(changes.borrow().is_empty());
361    }
362
363    #[gpui::test]
364    fn legacy_single_and_multiple_results_use_the_rendered_selection(cx: &mut TestAppContext) {
365        let (cx, _, single) = group_harness(cx, false, true);
366        click_first(cx);
367        assert_eq!(single.borrow().as_slice(), &[vec![0]]);
368
369        let (cx, _, multiple) = group_harness(cx, true, true);
370        click_first(cx);
371        assert_eq!(multiple.borrow().as_slice(), &[vec![1, 0]]);
372    }
373
374    #[gpui::test]
375    fn legacy_keyboard_click_does_not_reach_the_group_callback(cx: &mut TestAppContext) {
376        let (cx, _, changes) = group_harness(cx, false, true);
377        cx.update(|window, cx| window.focus_next(cx));
378        activate_key(cx, "enter");
379        assert!(changes.borrow().is_empty());
380    }
381
382    #[gpui::test]
383    fn legacy_disabled_state_depends_on_builder_order(cx: &mut TestAppContext) {
384        struct DisabledOrderHarness(Rc<Cell<usize>>);
385
386        impl Render for DisabledOrderHarness {
387            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
388                let first = self.0.clone();
389                let second = self.0.clone();
390                crate::v_flex()
391                    .child(
392                        ButtonGroup::new("disabled-before-child")
393                            .size(px(120.))
394                            .disabled(true)
395                            .child(
396                                Button::new("first")
397                                    .label("First")
398                                    .on_click(move |_, _, _| first.set(first.get() + 1)),
399                            ),
400                    )
401                    .child(
402                        ButtonGroup::new("disabled-after-child")
403                            .size(px(120.))
404                            .child(
405                                Button::new("second")
406                                    .label("Second")
407                                    .on_click(move |_, _, _| second.set(second.get() + 1)),
408                            )
409                            .disabled(true),
410                    )
411            }
412        }
413
414        cx.update(crate::init);
415        let clicks = Rc::new(Cell::new(0));
416        let (_, cx) = cx.add_window_view({
417            let clicks = clicks.clone();
418            move |_, _| DisabledOrderHarness(clicks)
419        });
420        cx.update(|window, cx| window.draw(cx).clear(cx));
421        cx.simulate_click(point(px(10.), px(60.)), Modifiers::default());
422        assert_eq!(clicks.get(), 0);
423        cx.simulate_click(point(px(10.), px(180.)), Modifiers::default());
424        assert_eq!(clicks.get(), 1);
425    }
426
427    #[gpui::test]
428    fn test_button_group_builder(_cx: &mut gpui::TestAppContext) {
429        let group = ButtonGroup::new("complex-group")
430            .child(Button::new("btn1").label("One"))
431            .child(Button::new("btn2").label("Two"))
432            .child(Button::new("btn3").label("Three"))
433            .primary()
434            .large()
435            .outline()
436            .compact()
437            .multiple(true)
438            .layout(Axis::Vertical)
439            .disabled(false)
440            .on_click(|_, _, _| {});
441
442        assert_eq!(group.children.len(), 3);
443        assert_eq!(group.variant, Some(ButtonVariant::Primary));
444        assert_eq!(group.size, Some(Size::Large));
445        assert!(group.outline);
446        assert!(group.compact);
447        assert!(group.multiple);
448        assert_eq!(group.layout, Axis::Vertical);
449        assert!(!group.disabled);
450        assert!(group.on_click.is_some());
451    }
452}