Skip to main content

gpui_material_extras/
groups.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, IntoElement, Pixels, SharedString, Window,
5    prelude::FluentBuilder,
6};
7use gpui_material_components::{
8    ButtonBorder, ButtonColors, ButtonElevations, ButtonPadding, ButtonShape, ButtonShapes,
9    ButtonVariant, ControlSize, IconButtonWidth, SemanticTone,
10    button_composition::{ButtonPart, Segment},
11};
12use gpui_material_foundation::InteractionSource;
13
14mod layout;
15mod render;
16
17use layout::nonnegative;
18
19type Command = Rc<dyn Fn(&mut Window, &mut App)>;
20type SelectionChange = Rc<dyn Fn(Vec<SharedString>, &mut Window, &mut App)>;
21type ToggleChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
22type Decoration = Rc<dyn Fn() -> AnyElement>;
23type TriggerContent = Box<dyn FnOnce(bool) -> AnyElement>;
24
25/// Visual layout style for a [`ButtonGroup`].
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub enum ButtonGroupVariant {
28    /// Separate pill/rounded buttons with dynamic neighbor expansion on press.
29    #[default]
30    Standard,
31    /// Adjoining segmented buttons with shared inner corners.
32    Connected,
33}
34
35/// Logical horizontal arrangement of visible members and the overflow trigger.
36#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
37pub enum ButtonGroupAlignment {
38    /// Packs members toward the leading edge (respects RTL).
39    #[default]
40    Start,
41    /// Centers members within the available horizontal space.
42    Center,
43    /// Packs members toward the trailing edge (respects RTL).
44    End,
45    /// Distributes remaining space evenly between members.
46    SpaceBetween,
47    /// Distributes remaining space around each member, with half-size outer margins.
48    SpaceAround,
49    /// Distributes remaining space equally between members and both outer edges.
50    SpaceEvenly,
51}
52
53/// Vertical cross-axis alignment for members inside a [`ButtonGroup`] row.
54#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
55pub enum ButtonGroupVerticalAlignment {
56    /// Aligns the member to the top edge of the row.
57    #[default]
58    Top,
59    /// Centers the member vertically within the row.
60    Center,
61    /// Aligns the member to the bottom edge of the row.
62    Bottom,
63}
64
65/// Overrides connected shapes by a segment's logical position in the visible row.
66#[derive(Clone, Copy, Debug, Default, PartialEq)]
67pub struct ButtonGroupConnectedShapes {
68    /// Corner shapes for the first visible segment in a connected group.
69    pub leading: ButtonShapes,
70    /// Corner shapes for interior segments in a connected group.
71    pub middle: ButtonShapes,
72    /// Corner shapes for the last visible segment in a connected group.
73    pub trailing: ButtonShapes,
74    /// Corner shapes when only a single segment is visible.
75    pub only: ButtonShapes,
76}
77
78impl ButtonGroupConnectedShapes {
79    fn for_segment(self, segment: Option<Segment>) -> ButtonShapes {
80        match segment {
81            Some(Segment::Leading) => self.leading,
82            Some(Segment::Middle) => self.middle,
83            Some(Segment::Trailing) => self.trailing,
84            Some(Segment::Only) => self.only,
85            _ => ButtonShapes::default(),
86        }
87    }
88}
89
90/// Per-member appearance overrides. Omitted fields keep group or Material defaults.
91#[derive(Clone, Copy, Debug, Default, PartialEq)]
92pub struct ButtonGroupItemStyle {
93    /// Corner shape overrides for resting, pressed, and checked states.
94    pub shapes: ButtonShapes,
95    /// Container and content color overrides.
96    pub colors: ButtonColors,
97    /// Optional border override.
98    pub border: Option<ButtonBorder>,
99    /// Elevation overrides across interaction states.
100    pub elevations: ButtonElevations,
101    /// Optional content padding override.
102    pub padding: Option<ButtonPadding>,
103}
104
105impl ButtonGroupItemStyle {
106    fn apply(self, button: ButtonPart, shapes: ButtonShapes) -> ButtonPart {
107        button
108            .shapes(ButtonShapes {
109                resting: self.shapes.resting.or(shapes.resting),
110                pressed: self.shapes.pressed.or(shapes.pressed),
111                checked: self.shapes.checked.or(shapes.checked),
112            })
113            .colors(self.colors)
114            .elevations(self.elevations)
115            .when_some(self.border, ButtonPart::border)
116            .when_some(self.padding, ButtonPart::content_padding)
117    }
118}
119
120/// Selection is controlled by the caller. Required selection preserves the
121/// last active choice once the caller has supplied or accepted a choice.
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub enum ButtonGroupSelection {
124    /// No group-managed selection; members act as standalone command buttons.
125    #[default]
126    Actions,
127    /// At most one member may be selected; clicking the active member clears it.
128    Single,
129    /// Exactly one member remains selected once a selection exists.
130    SingleRequired,
131    /// Any number of members (including zero) may be selected simultaneously.
132    Multiple,
133    /// One or more members may be selected; the last active member cannot be cleared.
134    MultipleRequired,
135}
136
137impl ButtonGroupSelection {
138    fn next(self, selection: &[SharedString], id: &SharedString) -> Option<Vec<SharedString>> {
139        let contains = selection.contains(id);
140        let required = matches!(self, Self::SingleRequired | Self::MultipleRequired);
141        match self {
142            Self::Actions => None,
143            _ if contains && required && selection.len() == 1 => None,
144            _ if contains => Some(
145                selection
146                    .iter()
147                    .filter(|value| *value != id)
148                    .cloned()
149                    .collect(),
150            ),
151            Self::Single | Self::SingleRequired => Some(vec![id.clone()]),
152            Self::Multiple | Self::MultipleRequired => {
153                let mut next = selection.to_vec();
154                next.push(id.clone());
155                Some(next)
156            }
157        }
158    }
159}
160
161/// One entry with a stable, caller-provided identifier.
162pub struct ButtonGroupItem {
163    id: SharedString,
164    label: SharedString,
165    disabled: bool,
166    behavior: ItemBehavior,
167    content: ItemContent,
168    overflow_content: Option<Decoration>,
169    appearance: Option<ButtonVariant>,
170    tone: Option<SemanticTone>,
171    icon_width: IconButtonWidth,
172    style: ButtonGroupItemStyle,
173    weight: f32,
174    compression_limit: Option<Pixels>,
175    vertical_alignment: Option<ButtonGroupVerticalAlignment>,
176    source: Option<Entity<InteractionSource>>,
177}
178
179enum ItemBehavior {
180    Grouped(Option<Command>),
181    Action(Command),
182    Toggle(bool, ToggleChange),
183}
184
185enum ItemContent {
186    Label,
187    LeadingIcon(Decoration),
188    Icon(Decoration),
189    Custom(Pixels, Decoration),
190}
191
192impl ButtonGroupItem {
193    /// Creates a button group member with a stable `id` and visible/accessible `label`.
194    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
195        Self {
196            id: id.into(),
197            label: label.into(),
198            disabled: false,
199            behavior: ItemBehavior::Grouped(None),
200            content: ItemContent::Label,
201            overflow_content: None,
202            appearance: None,
203            tone: None,
204            icon_width: IconButtonWidth::Uniform,
205            style: ButtonGroupItemStyle::default(),
206            weight: 0.,
207            compression_limit: None,
208            vertical_alignment: None,
209            source: None,
210        }
211    }
212
213    /// Disables activation and selection toggling for this member when `true`.
214    pub fn disabled(mut self, disabled: bool) -> Self {
215        self.disabled = disabled;
216        self
217    }
218
219    /// Runs in action groups. Selection groups use the group's on_change callback.
220    pub fn on_activate(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
221        self.behavior = ItemBehavior::Grouped(Some(Rc::new(callback)));
222        self
223    }
224
225    /// Adds a command that remains independent of the group's selection mode.
226    pub fn action(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
227        self.behavior = ItemBehavior::Action(Rc::new(callback));
228        self
229    }
230
231    /// Adds a toggle whose checked value is controlled independently of the group.
232    pub fn toggle(
233        mut self,
234        selected: bool,
235        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
236    ) -> Self {
237        self.behavior = ItemBehavior::Toggle(selected, Rc::new(callback));
238        self
239    }
240
241    /// Displays a leading icon alongside the member's label.
242    pub fn leading_icon<E: IntoElement>(mut self, icon: impl Fn() -> E + 'static) -> Self {
243        self.content = ItemContent::LeadingIcon(Rc::new(move || icon().into_any_element()));
244        self
245    }
246
247    /// Renders this member as an icon-only button while retaining `label` for accessibility and overflow.
248    pub fn icon_only<E: IntoElement>(mut self, icon: impl Fn() -> E + 'static) -> Self {
249        self.content = ItemContent::Icon(Rc::new(move || icon().into_any_element()));
250        self
251    }
252
253    /// Sets the width preset used when this member is rendered as an icon-only button.
254    pub fn icon_width(mut self, width: IconButtonWidth) -> Self {
255        self.icon_width = width;
256        self
257    }
258
259    /// Replaces row content with decorative artwork of the supplied preferred width.
260    pub fn content<E: IntoElement>(
261        mut self,
262        width: Pixels,
263        content: impl Fn() -> E + 'static,
264    ) -> Self {
265        self.content = ItemContent::Custom(width, Rc::new(move || content().into_any_element()));
266        self
267    }
268
269    /// Replaces the menu row's visible label. The member owns activation and its accessible name.
270    pub fn overflow_item_content<E: IntoElement>(
271        mut self,
272        content: impl Fn() -> E + 'static,
273    ) -> Self {
274        self.overflow_content = Some(Rc::new(move || content().into_any_element()));
275        self
276    }
277
278    /// Overrides the group's default [`ButtonVariant`] for this member.
279    pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
280        self.appearance = Some(appearance);
281        self
282    }
283
284    /// Overrides the semantic tone for this member (both inline and in the overflow menu).
285    pub fn tone(mut self, tone: SemanticTone) -> Self {
286        self.tone = Some(tone);
287        self
288    }
289
290    /// Applies per-member visual style overrides.
291    pub fn style(mut self, style: ButtonGroupItemStyle) -> Self {
292        self.style = style;
293        self
294    }
295
296    /// Shares available space with other weighted members. Zero weight keeps intrinsic sizing.
297    pub fn weight(mut self, weight: f32) -> Self {
298        self.weight = if weight.is_finite() {
299            weight.max(0.)
300        } else {
301            0.
302        };
303        self
304    }
305
306    /// Limits how many logical pixels a neighbor can borrow from this member.
307    pub fn compression_limit(mut self, limit: Pixels) -> Self {
308        self.compression_limit = nonnegative(limit);
309        self
310    }
311
312    /// Overrides the group's vertical cross-axis alignment for this member.
313    pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
314        self.vertical_alignment = Some(alignment);
315        self
316    }
317
318    /// Shares the member's interaction state, including press-driven width changes.
319    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
320        self.source = Some(source.clone());
321        self
322    }
323}
324
325/// An expressive row with controlled selection and a Material menu for
326/// items that do not fit. Arrow keys move focus without changing selection.
327#[derive(IntoElement)]
328pub struct ButtonGroup {
329    id: ElementId,
330    label: SharedString,
331    items: Vec<ButtonGroupItem>,
332    variant: ButtonGroupVariant,
333    appearance: ButtonVariant,
334    tone: SemanticTone,
335    size: ControlSize,
336    selection: ButtonGroupSelection,
337    selected: Vec<SharedString>,
338    on_change: Option<SelectionChange>,
339    overflow_label: SharedString,
340    shape: ButtonShape,
341    shapes: ButtonGroupConnectedShapes,
342    alignment: ButtonGroupAlignment,
343    vertical_alignment: ButtonGroupVerticalAlignment,
344    spacing: Option<Pixels>,
345    expanded_ratio: f32,
346    overflow_trigger: Option<(Pixels, TriggerContent)>,
347    overflow_content: Option<Decoration>,
348    overflow_open: Option<bool>,
349    on_overflow_open_change: Option<ToggleChange>,
350}
351
352impl ButtonGroup {
353    /// Creates a standard button group with an element `id`, accessible `label`, and `items`.
354    pub fn new(
355        id: impl Into<ElementId>,
356        label: impl Into<SharedString>,
357        items: impl IntoIterator<Item = ButtonGroupItem>,
358    ) -> Self {
359        Self {
360            id: id.into(),
361            label: label.into(),
362            items: items.into_iter().collect(),
363            variant: ButtonGroupVariant::default(),
364            appearance: ButtonVariant::default(),
365            tone: SemanticTone::Default,
366            size: ControlSize::default(),
367            selection: ButtonGroupSelection::default(),
368            selected: Vec::new(),
369            on_change: None,
370            overflow_label: "More actions".into(),
371            shape: ButtonShape::Round,
372            shapes: ButtonGroupConnectedShapes::default(),
373            alignment: ButtonGroupAlignment::default(),
374            vertical_alignment: ButtonGroupVerticalAlignment::default(),
375            spacing: None,
376            expanded_ratio: 0.15,
377            overflow_trigger: None,
378            overflow_content: None,
379            overflow_open: None,
380            on_overflow_open_change: None,
381        }
382    }
383
384    /// Creates a connected Material 3 Expressive button group.
385    pub fn connected(
386        id: impl Into<ElementId>,
387        label: impl Into<SharedString>,
388        items: impl IntoIterator<Item = ButtonGroupItem>,
389    ) -> Self {
390        Self::new(id, label, items).variant(ButtonGroupVariant::Connected)
391    }
392
393    /// Sets whether members are rendered as separate (`Standard`) or adjoining (`Connected`) buttons.
394    pub fn variant(mut self, variant: ButtonGroupVariant) -> Self {
395        self.variant = variant;
396        self
397    }
398
399    /// Sets the default [`ButtonVariant`] applied to group members.
400    pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
401        self.appearance = appearance;
402        self
403    }
404
405    /// Applies a default semantic tone across members and overflow menu items unless overridden per item.
406    pub fn tone(mut self, tone: SemanticTone) -> Self {
407        self.tone = tone;
408        self
409    }
410
411    /// Sets the [`ControlSize`] shared by all members and the overflow trigger.
412    pub fn size(mut self, size: ControlSize) -> Self {
413        self.size = size;
414        self
415    }
416
417    /// Configures caller-controlled selection `mode` and the currently `selected` item IDs.
418    pub fn selection(
419        mut self,
420        mode: ButtonGroupSelection,
421        selected: impl IntoIterator<Item = SharedString>,
422    ) -> Self {
423        self.selection = mode;
424        self.selected = selected.into_iter().collect();
425        self
426    }
427
428    /// Registers a callback invoked with the next list of selected item IDs when selection changes.
429    pub fn on_change(
430        mut self,
431        callback: impl Fn(Vec<SharedString>, &mut Window, &mut App) + 'static,
432    ) -> Self {
433        self.on_change = Some(Rc::new(callback));
434        self
435    }
436
437    /// Configures required single selection (`ButtonGroupSelection::SingleRequired`) and
438    /// delivers the newly selected item ID directly.
439    pub fn single_select(
440        mut self,
441        selected: impl Into<SharedString>,
442        on_select: impl Fn(SharedString, &mut Window, &mut App) + 'static,
443    ) -> Self {
444        self.selection = ButtonGroupSelection::SingleRequired;
445        self.selected = vec![selected.into()];
446        self.on_change = Some(Rc::new(move |next, window, cx| {
447            if let Some(id) = next.into_iter().next() {
448                on_select(id, window, cx);
449            }
450        }));
451        self
452    }
453
454    /// Configures deselectable single selection (`ButtonGroupSelection::Single`) and
455    /// delivers the newly selected item ID, or `None` when the active option is cleared.
456    pub fn single_optional_select(
457        mut self,
458        selected: Option<SharedString>,
459        on_select: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
460    ) -> Self {
461        self.selection = ButtonGroupSelection::Single;
462        self.selected = selected.into_iter().collect();
463        self.on_change = Some(Rc::new(move |next, window, cx| {
464            on_select(next.into_iter().next(), window, cx);
465        }));
466        self
467    }
468
469    /// Sets the accessible name for the overflow menu trigger button. Defaults to `"More actions"`.
470    pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
471        self.overflow_label = label.into();
472        self
473    }
474
475    /// Sets the base [`ButtonShape`] for standard button groups.
476    pub fn shape(mut self, shape: ButtonShape) -> Self {
477        self.shape = shape;
478        self
479    }
480
481    /// Overrides segment corner shapes for [`ButtonGroupVariant::Connected`].
482    pub fn connected_shapes(mut self, shapes: ButtonGroupConnectedShapes) -> Self {
483        self.shapes = shapes;
484        self
485    }
486
487    /// Sets the horizontal alignment of visible members within the group row.
488    pub fn alignment(mut self, alignment: ButtonGroupAlignment) -> Self {
489        self.alignment = alignment;
490        self
491    }
492
493    /// Sets the default vertical cross-axis alignment of members within the group row.
494    pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
495        self.vertical_alignment = alignment;
496        self
497    }
498
499    /// Overrides the horizontal gap between members in logical pixels.
500    pub fn spacing(mut self, spacing: Pixels) -> Self {
501        self.spacing = nonnegative(spacing);
502        self
503    }
504
505    /// Sets the press-expansion width ratio for [`ButtonGroupVariant::Standard`] members. Defaults to `0.15`.
506    pub fn expanded_ratio(mut self, ratio: f32) -> Self {
507        self.expanded_ratio = if ratio.is_finite() {
508            ratio.max(0.)
509        } else {
510            0.15
511        };
512        self
513    }
514
515    /// Supplies decorative content for the named overflow trigger.
516    pub fn overflow_trigger<E: IntoElement>(
517        mut self,
518        width: Pixels,
519        content: impl FnOnce(bool) -> E + 'static,
520    ) -> Self {
521        self.overflow_trigger = Some((
522            width,
523            Box::new(move |open| content(open).into_any_element()),
524        ));
525        self
526    }
527
528    /// Adds repeatable decorative content before the overflow rows.
529    pub fn overflow_content<E: IntoElement>(mut self, content: impl Fn() -> E + 'static) -> Self {
530        self.overflow_content = Some(Rc::new(move || content().into_any_element()));
531        self
532    }
533
534    /// Supplies the caller-owned open value for the overflow menu.
535    pub fn overflow_open(mut self, open: bool) -> Self {
536        self.overflow_open = Some(open);
537        self
538    }
539
540    /// Registers a callback invoked when the overflow menu requests to open or close.
541    pub fn on_overflow_open_change(
542        mut self,
543        on_change: impl Fn(bool, &mut Window, &mut App) + 'static,
544    ) -> Self {
545        self.on_overflow_open_change = Some(Rc::new(on_change));
546        self
547    }
548}
549
550#[cfg(test)]
551mod tests {
552    use super::*;
553
554    #[test]
555    fn connected_and_single_select_shortcuts_configure_expected_fields() {
556        let required = ButtonGroup::connected(
557            "period",
558            "Period",
559            [
560                ButtonGroupItem::new("day", "Day"),
561                ButtonGroupItem::new("week", "Week"),
562            ],
563        )
564        .single_select("week", |_, _, _| {});
565        assert_eq!(required.variant, ButtonGroupVariant::Connected);
566        assert_eq!(required.selection, ButtonGroupSelection::SingleRequired);
567        assert_eq!(required.selected, vec![SharedString::from("week")]);
568        assert!(required.on_change.is_some());
569
570        let optional_selected = ButtonGroup::connected(
571            "filter",
572            "Filter",
573            [
574                ButtonGroupItem::new("open", "Open"),
575                ButtonGroupItem::new("closed", "Closed"),
576            ],
577        )
578        .single_optional_select(Some("open".into()), |_, _, _| {});
579        assert_eq!(optional_selected.variant, ButtonGroupVariant::Connected);
580        assert_eq!(optional_selected.selection, ButtonGroupSelection::Single);
581        assert_eq!(optional_selected.selected, vec![SharedString::from("open")]);
582        assert!(optional_selected.on_change.is_some());
583
584        let optional_empty = ButtonGroup::connected("filter-empty", "Filter", [])
585            .single_optional_select(None, |_, _, _| {});
586        assert_eq!(optional_empty.selection, ButtonGroupSelection::Single);
587        assert!(optional_empty.selected.is_empty());
588        assert!(optional_empty.on_change.is_some());
589    }
590}