gpui-material-extras 0.3.1

Optional Material 3 Expressive component families for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use std::rc::Rc;

use gpui::{
    AnyElement, App, ElementId, Entity, IntoElement, Pixels, SharedString, Window,
    prelude::FluentBuilder,
};
use gpui_material_components::{
    ButtonBorder, ButtonColors, ButtonElevations, ButtonPadding, ButtonShape, ButtonShapes,
    ButtonVariant, ControlSize, IconButtonWidth, SemanticTone,
    button_composition::{ButtonPart, Segment},
};
use gpui_material_foundation::InteractionSource;

mod layout;
mod render;

use layout::nonnegative;

type Command = Rc<dyn Fn(&mut Window, &mut App)>;
type SelectionChange = Rc<dyn Fn(Vec<SharedString>, &mut Window, &mut App)>;
type ToggleChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type Decoration = Rc<dyn Fn() -> AnyElement>;
type TriggerContent = Box<dyn FnOnce(bool) -> AnyElement>;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonGroupVariant {
    #[default]
    Standard,
    Connected,
}

/// Logical horizontal arrangement of visible members and the overflow trigger.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ButtonGroupAlignment {
    #[default]
    Start,
    Center,
    End,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ButtonGroupVerticalAlignment {
    #[default]
    Top,
    Center,
    Bottom,
}

/// Overrides connected shapes by a segment's logical position in the visible row.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ButtonGroupConnectedShapes {
    pub leading: ButtonShapes,
    pub middle: ButtonShapes,
    pub trailing: ButtonShapes,
    pub only: ButtonShapes,
}

impl ButtonGroupConnectedShapes {
    fn for_segment(self, segment: Option<Segment>) -> ButtonShapes {
        match segment {
            Some(Segment::Leading) => self.leading,
            Some(Segment::Middle) => self.middle,
            Some(Segment::Trailing) => self.trailing,
            Some(Segment::Only) => self.only,
            _ => ButtonShapes::default(),
        }
    }
}

/// Per-member appearance overrides. Omitted fields keep group or Material defaults.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ButtonGroupItemStyle {
    pub shapes: ButtonShapes,
    pub colors: ButtonColors,
    pub border: Option<ButtonBorder>,
    pub elevations: ButtonElevations,
    pub padding: Option<ButtonPadding>,
}

impl ButtonGroupItemStyle {
    fn apply(self, button: ButtonPart, shapes: ButtonShapes) -> ButtonPart {
        button
            .shapes(ButtonShapes {
                resting: self.shapes.resting.or(shapes.resting),
                pressed: self.shapes.pressed.or(shapes.pressed),
                checked: self.shapes.checked.or(shapes.checked),
            })
            .colors(self.colors)
            .elevations(self.elevations)
            .when_some(self.border, ButtonPart::border)
            .when_some(self.padding, ButtonPart::content_padding)
    }
}

/// Selection is controlled by the caller. Required selection preserves the
/// last active choice once the caller has supplied or accepted a choice.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonGroupSelection {
    #[default]
    Actions,
    Single,
    SingleRequired,
    Multiple,
    MultipleRequired,
}

impl ButtonGroupSelection {
    fn next(self, selection: &[SharedString], id: &SharedString) -> Option<Vec<SharedString>> {
        let contains = selection.contains(id);
        let required = matches!(self, Self::SingleRequired | Self::MultipleRequired);
        match self {
            Self::Actions => None,
            _ if contains && required && selection.len() == 1 => None,
            _ if contains => Some(
                selection
                    .iter()
                    .filter(|value| *value != id)
                    .cloned()
                    .collect(),
            ),
            Self::Single | Self::SingleRequired => Some(vec![id.clone()]),
            Self::Multiple | Self::MultipleRequired => {
                let mut next = selection.to_vec();
                next.push(id.clone());
                Some(next)
            }
        }
    }
}

/// One entry with a stable, caller-provided identifier.
pub struct ButtonGroupItem {
    id: SharedString,
    label: SharedString,
    disabled: bool,
    behavior: ItemBehavior,
    content: ItemContent,
    overflow_content: Option<Decoration>,
    appearance: Option<ButtonVariant>,
    tone: Option<SemanticTone>,
    icon_width: IconButtonWidth,
    style: ButtonGroupItemStyle,
    weight: f32,
    compression_limit: Option<Pixels>,
    vertical_alignment: Option<ButtonGroupVerticalAlignment>,
    source: Option<Entity<InteractionSource>>,
}

enum ItemBehavior {
    Grouped(Option<Command>),
    Action(Command),
    Toggle(bool, ToggleChange),
}

enum ItemContent {
    Label,
    LeadingIcon(Decoration),
    Icon(Decoration),
    Custom(Pixels, Decoration),
}

impl ButtonGroupItem {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            disabled: false,
            behavior: ItemBehavior::Grouped(None),
            content: ItemContent::Label,
            overflow_content: None,
            appearance: None,
            tone: None,
            icon_width: IconButtonWidth::Uniform,
            style: ButtonGroupItemStyle::default(),
            weight: 0.,
            compression_limit: None,
            vertical_alignment: None,
            source: None,
        }
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Runs in action groups. Selection groups use the group's on_change callback.
    pub fn on_activate(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.behavior = ItemBehavior::Grouped(Some(Rc::new(callback)));
        self
    }

    /// Adds a command that remains independent of the group's selection mode.
    pub fn action(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.behavior = ItemBehavior::Action(Rc::new(callback));
        self
    }

    /// Adds a toggle whose checked value is controlled independently of the group.
    pub fn toggle(
        mut self,
        selected: bool,
        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.behavior = ItemBehavior::Toggle(selected, Rc::new(callback));
        self
    }

    pub fn leading_icon<E: IntoElement>(mut self, icon: impl Fn() -> E + 'static) -> Self {
        self.content = ItemContent::LeadingIcon(Rc::new(move || icon().into_any_element()));
        self
    }

    pub fn icon_only<E: IntoElement>(mut self, icon: impl Fn() -> E + 'static) -> Self {
        self.content = ItemContent::Icon(Rc::new(move || icon().into_any_element()));
        self
    }

    pub fn icon_width(mut self, width: IconButtonWidth) -> Self {
        self.icon_width = width;
        self
    }

    /// Replaces row content with decorative artwork of the supplied preferred width.
    pub fn content<E: IntoElement>(
        mut self,
        width: Pixels,
        content: impl Fn() -> E + 'static,
    ) -> Self {
        self.content = ItemContent::Custom(width, Rc::new(move || content().into_any_element()));
        self
    }

    /// Replaces the menu row's visible label. The member owns activation and its accessible name.
    pub fn overflow_item_content<E: IntoElement>(
        mut self,
        content: impl Fn() -> E + 'static,
    ) -> Self {
        self.overflow_content = Some(Rc::new(move || content().into_any_element()));
        self
    }

    pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
        self.appearance = Some(appearance);
        self
    }

    /// Overrides the semantic tone for this member (both inline and in the overflow menu).
    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.tone = Some(tone);
        self
    }

    pub fn style(mut self, style: ButtonGroupItemStyle) -> Self {
        self.style = style;
        self
    }

    /// Shares available space with other weighted members. Zero weight keeps intrinsic sizing.
    pub fn weight(mut self, weight: f32) -> Self {
        self.weight = if weight.is_finite() {
            weight.max(0.)
        } else {
            0.
        };
        self
    }

    /// Limits how many logical pixels a neighbor can borrow from this member.
    pub fn compression_limit(mut self, limit: Pixels) -> Self {
        self.compression_limit = nonnegative(limit);
        self
    }

    pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
        self.vertical_alignment = Some(alignment);
        self
    }

    /// Shares the member's interaction state, including press-driven width changes.
    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.source = Some(source.clone());
        self
    }
}

/// An expressive row with controlled selection and a Material menu for
/// items that do not fit. Arrow keys move focus without changing selection.
#[derive(IntoElement)]
pub struct ButtonGroup {
    id: ElementId,
    label: SharedString,
    items: Vec<ButtonGroupItem>,
    variant: ButtonGroupVariant,
    appearance: ButtonVariant,
    tone: SemanticTone,
    size: ControlSize,
    selection: ButtonGroupSelection,
    selected: Vec<SharedString>,
    on_change: Option<SelectionChange>,
    overflow_label: SharedString,
    shape: ButtonShape,
    shapes: ButtonGroupConnectedShapes,
    alignment: ButtonGroupAlignment,
    vertical_alignment: ButtonGroupVerticalAlignment,
    spacing: Option<Pixels>,
    expanded_ratio: f32,
    overflow_trigger: Option<(Pixels, TriggerContent)>,
    overflow_content: Option<Decoration>,
    overflow_open: Option<bool>,
    on_overflow_open_change: Option<ToggleChange>,
}

impl ButtonGroup {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        items: impl IntoIterator<Item = ButtonGroupItem>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            items: items.into_iter().collect(),
            variant: ButtonGroupVariant::default(),
            appearance: ButtonVariant::default(),
            tone: SemanticTone::Default,
            size: ControlSize::default(),
            selection: ButtonGroupSelection::default(),
            selected: Vec::new(),
            on_change: None,
            overflow_label: "More actions".into(),
            shape: ButtonShape::Round,
            shapes: ButtonGroupConnectedShapes::default(),
            alignment: ButtonGroupAlignment::default(),
            vertical_alignment: ButtonGroupVerticalAlignment::default(),
            spacing: None,
            expanded_ratio: 0.15,
            overflow_trigger: None,
            overflow_content: None,
            overflow_open: None,
            on_overflow_open_change: None,
        }
    }

    /// Creates a connected Material 3 Expressive button group.
    pub fn connected(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        items: impl IntoIterator<Item = ButtonGroupItem>,
    ) -> Self {
        Self::new(id, label, items).variant(ButtonGroupVariant::Connected)
    }

    pub fn variant(mut self, variant: ButtonGroupVariant) -> Self {
        self.variant = variant;
        self
    }

    pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
        self.appearance = appearance;
        self
    }

    /// Applies a default semantic tone across members and overflow menu items unless overridden per item.
    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.tone = tone;
        self
    }

    pub fn size(mut self, size: ControlSize) -> Self {
        self.size = size;
        self
    }

    pub fn selection(
        mut self,
        mode: ButtonGroupSelection,
        selected: impl IntoIterator<Item = SharedString>,
    ) -> Self {
        self.selection = mode;
        self.selected = selected.into_iter().collect();
        self
    }

    pub fn on_change(
        mut self,
        callback: impl Fn(Vec<SharedString>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(callback));
        self
    }

    /// Configures required single selection (`ButtonGroupSelection::SingleRequired`) and
    /// delivers the newly selected item ID directly.
    pub fn single_select(
        mut self,
        selected: impl Into<SharedString>,
        on_select: impl Fn(SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.selection = ButtonGroupSelection::SingleRequired;
        self.selected = vec![selected.into()];
        self.on_change = Some(Rc::new(move |next, window, cx| {
            if let Some(id) = next.into_iter().next() {
                on_select(id, window, cx);
            }
        }));
        self
    }

    /// Configures deselectable single selection (`ButtonGroupSelection::Single`) and
    /// delivers the newly selected item ID, or `None` when the active option is cleared.
    pub fn single_optional_select(
        mut self,
        selected: Option<SharedString>,
        on_select: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.selection = ButtonGroupSelection::Single;
        self.selected = selected.into_iter().collect();
        self.on_change = Some(Rc::new(move |next, window, cx| {
            on_select(next.into_iter().next(), window, cx);
        }));
        self
    }

    pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
        self.overflow_label = label.into();
        self
    }

    pub fn shape(mut self, shape: ButtonShape) -> Self {
        self.shape = shape;
        self
    }

    pub fn connected_shapes(mut self, shapes: ButtonGroupConnectedShapes) -> Self {
        self.shapes = shapes;
        self
    }

    pub fn alignment(mut self, alignment: ButtonGroupAlignment) -> Self {
        self.alignment = alignment;
        self
    }

    pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
        self.vertical_alignment = alignment;
        self
    }

    pub fn spacing(mut self, spacing: Pixels) -> Self {
        self.spacing = nonnegative(spacing);
        self
    }

    pub fn expanded_ratio(mut self, ratio: f32) -> Self {
        self.expanded_ratio = if ratio.is_finite() {
            ratio.max(0.)
        } else {
            0.15
        };
        self
    }

    /// Supplies decorative content for the named overflow trigger.
    pub fn overflow_trigger<E: IntoElement>(
        mut self,
        width: Pixels,
        content: impl FnOnce(bool) -> E + 'static,
    ) -> Self {
        self.overflow_trigger = Some((
            width,
            Box::new(move |open| content(open).into_any_element()),
        ));
        self
    }

    /// Adds repeatable decorative content before the overflow rows.
    pub fn overflow_content<E: IntoElement>(mut self, content: impl Fn() -> E + 'static) -> Self {
        self.overflow_content = Some(Rc::new(move || content().into_any_element()));
        self
    }

    /// Supplies the caller-owned open value for the overflow menu.
    pub fn overflow_open(mut self, open: bool) -> Self {
        self.overflow_open = Some(open);
        self
    }

    pub fn on_overflow_open_change(
        mut self,
        on_change: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_overflow_open_change = Some(Rc::new(on_change));
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn connected_and_single_select_shortcuts_configure_expected_fields() {
        let required = ButtonGroup::connected(
            "period",
            "Period",
            [
                ButtonGroupItem::new("day", "Day"),
                ButtonGroupItem::new("week", "Week"),
            ],
        )
        .single_select("week", |_, _, _| {});
        assert_eq!(required.variant, ButtonGroupVariant::Connected);
        assert_eq!(required.selection, ButtonGroupSelection::SingleRequired);
        assert_eq!(required.selected, vec![SharedString::from("week")]);
        assert!(required.on_change.is_some());

        let optional_selected = ButtonGroup::connected(
            "filter",
            "Filter",
            [
                ButtonGroupItem::new("open", "Open"),
                ButtonGroupItem::new("closed", "Closed"),
            ],
        )
        .single_optional_select(Some("open".into()), |_, _, _| {});
        assert_eq!(optional_selected.variant, ButtonGroupVariant::Connected);
        assert_eq!(optional_selected.selection, ButtonGroupSelection::Single);
        assert_eq!(optional_selected.selected, vec![SharedString::from("open")]);
        assert!(optional_selected.on_change.is_some());

        let optional_empty = ButtonGroup::connected("filter-empty", "Filter", [])
            .single_optional_select(None, |_, _, _| {});
        assert_eq!(optional_empty.selection, ButtonGroupSelection::Single);
        assert!(optional_empty.selected.is_empty());
        assert!(optional_empty.on_change.is_some());
    }
}