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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub enum ButtonGroupVariant {
30 #[default]
32 Standard,
33 Connected,
35}
36
37#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
39pub enum ButtonGroupVerticalAlignment {
40 #[default]
42 Top,
43 Center,
45 Bottom,
47}
48
49#[derive(Clone, Copy, Debug, Default, PartialEq)]
51pub struct ButtonGroupConnectedShapes {
52 pub leading: ControlShapes,
54 pub middle: ControlShapes,
56 pub trailing: ControlShapes,
58 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
77pub struct ButtonSegmentStyle {
78 pub shapes: ControlShapes,
80 pub colors: ButtonColors,
82 pub border: Option<ControlBorder>,
84 pub elevations: ControlElevations,
86 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
108pub enum ButtonGroupSelection {
109 #[default]
111 Actions,
112 Single,
114 SingleRequired,
116 Multiple,
118 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
146pub 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 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 pub fn disabled(mut self, disabled: bool) -> Self {
200 self.disabled = disabled;
201 self
202 }
203
204 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 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 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 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 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 pub fn icon_width(mut self, width: IconButtonWidth) -> Self {
240 self.icon_width = width;
241 self
242 }
243
244 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 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 pub fn variant(mut self, variant: ButtonVariant) -> Self {
265 self.variant = Some(variant);
266 self
267 }
268
269 pub fn tone(mut self, tone: SemanticTone) -> Self {
271 self.tone = Some(tone);
272 self
273 }
274
275 pub fn style(mut self, style: ButtonSegmentStyle) -> Self {
277 self.style = style;
278 self
279 }
280
281 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 pub fn compression_limit(mut self, limit: Pixels) -> Self {
293 self.compression_limit = nonnegative(limit);
294 self
295 }
296
297 pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
299 self.vertical_alignment = Some(alignment);
300 self
301 }
302
303 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
305 self.source = Some(source.clone());
306 self
307 }
308}
309
310#[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 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 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 pub fn variant(mut self, variant: ButtonGroupVariant) -> Self {
380 self.variant = variant;
381 self
382 }
383
384 pub fn appearance(mut self, appearance: ButtonVariant) -> Self {
386 self.appearance = appearance;
387 self
388 }
389
390 pub fn tone(mut self, tone: SemanticTone) -> Self {
392 self.tone = tone;
393 self
394 }
395
396 pub fn size(mut self, size: ControlSize) -> Self {
398 self.size = size;
399 self
400 }
401
402 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 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 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 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 pub fn overflow_label(mut self, label: impl Into<SharedString>) -> Self {
456 self.overflow_label = label.into();
457 self
458 }
459
460 pub fn shape(mut self, shape: ButtonShape) -> Self {
462 self.shape = shape;
463 self
464 }
465
466 pub fn connected_shapes(mut self, shapes: ButtonGroupConnectedShapes) -> Self {
468 self.shapes = shapes;
469 self
470 }
471
472 pub fn alignment(mut self, alignment: ContentArrangement) -> Self {
474 self.alignment = alignment;
475 self
476 }
477
478 pub fn vertical_alignment(mut self, alignment: ButtonGroupVerticalAlignment) -> Self {
480 self.vertical_alignment = alignment;
481 self
482 }
483
484 pub fn spacing(mut self, spacing: Pixels) -> Self {
486 self.spacing = nonnegative(spacing);
487 self
488 }
489
490 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 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 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 pub fn overflow_open(mut self, open: bool) -> Self {
521 self.overflow_open = Some(open);
522 self
523 }
524
525 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}