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