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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub enum ButtonGroupVariant {
28 #[default]
30 Standard,
31 Connected,
33}
34
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
37pub enum ButtonGroupAlignment {
38 #[default]
40 Start,
41 Center,
43 End,
45 SpaceBetween,
47 SpaceAround,
49 SpaceEvenly,
51}
52
53#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
55pub enum ButtonGroupVerticalAlignment {
56 #[default]
58 Top,
59 Center,
61 Bottom,
63}
64
65#[derive(Clone, Copy, Debug, Default, PartialEq)]
67pub struct ButtonGroupConnectedShapes {
68 pub leading: ButtonShapes,
70 pub middle: ButtonShapes,
72 pub trailing: ButtonShapes,
74 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
92pub struct ButtonGroupItemStyle {
93 pub shapes: ButtonShapes,
95 pub colors: ButtonColors,
97 pub border: Option<ButtonBorder>,
99 pub elevations: ButtonElevations,
101 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub enum ButtonGroupSelection {
124 #[default]
126 Actions,
127 Single,
129 SingleRequired,
131 Multiple,
133 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
161pub 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 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 pub fn disabled(mut self, disabled: bool) -> Self {
215 self.disabled = disabled;
216 self
217 }
218
219 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 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 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 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 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 pub fn icon_width(mut self, width: IconButtonWidth) -> Self {
255 self.icon_width = width;
256 self
257 }
258
259 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 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 pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
280 self.appearance = Some(appearance);
281 self
282 }
283
284 pub fn tone(mut self, tone: SemanticTone) -> Self {
286 self.tone = Some(tone);
287 self
288 }
289
290 pub fn style(mut self, style: ButtonGroupItemStyle) -> Self {
292 self.style = style;
293 self
294 }
295
296 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 pub fn compression_limit(mut self, limit: Pixels) -> Self {
308 self.compression_limit = nonnegative(limit);
309 self
310 }
311
312 pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
314 self.vertical_alignment = Some(alignment);
315 self
316 }
317
318 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
320 self.source = Some(source.clone());
321 self
322 }
323}
324
325#[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 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 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 pub fn variant(mut self, variant: ButtonGroupVariant) -> Self {
395 self.variant = variant;
396 self
397 }
398
399 pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
401 self.appearance = appearance;
402 self
403 }
404
405 pub fn tone(mut self, tone: SemanticTone) -> Self {
407 self.tone = tone;
408 self
409 }
410
411 pub fn size(mut self, size: ControlSize) -> Self {
413 self.size = size;
414 self
415 }
416
417 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 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 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 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 pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
471 self.overflow_label = label.into();
472 self
473 }
474
475 pub fn shape(mut self, shape: ButtonShape) -> Self {
477 self.shape = shape;
478 self
479 }
480
481 pub fn connected_shapes(mut self, shapes: ButtonGroupConnectedShapes) -> Self {
483 self.shapes = shapes;
484 self
485 }
486
487 pub fn alignment(mut self, alignment: ButtonGroupAlignment) -> Self {
489 self.alignment = alignment;
490 self
491 }
492
493 pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
495 self.vertical_alignment = alignment;
496 self
497 }
498
499 pub fn spacing(mut self, spacing: Pixels) -> Self {
501 self.spacing = nonnegative(spacing);
502 self
503 }
504
505 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 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 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 pub fn overflow_open(mut self, open: bool) -> Self {
536 self.overflow_open = Some(open);
537 self
538 }
539
540 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}