1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, ParentElement, Pixels,
5 RenderOnce, SharedString, Styled, Window, div, px,
6};
7use gpui_material_foundation::{InteractionSource, window_material_theme};
8use gpui_material_theme::{
9 ColorRole, CornerRole, Direction, Elevation, MotionKind, MotionSpeed, TypeRole,
10 TypographyEmphasis,
11};
12
13use crate::action::{
14 Action, ActionControl, ActionLayout, ActionStyle, Activate, Change, DisabledStyle,
15 SegmentShape, icon_slot,
16};
17use crate::button_style::{
18 ButtonBorder, ButtonColors, ButtonElevations, ButtonPadding, ButtonShapes, ButtonStyle,
19 finite_length,
20};
21
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum ControlSize {
25 ExtraSmall,
26 #[default]
27 Small,
28 Medium,
29 Large,
30 ExtraLarge,
31}
32
33#[derive(Clone, Copy)]
34struct Metrics {
35 height: f32,
36 icon: f32,
37 gap: f32,
38 padding: f32,
39 outline: f32,
40 square: CornerRole,
41 pressed: CornerRole,
42 label: TypeRole,
43}
44
45impl ControlSize {
46 fn metrics(self) -> Metrics {
48 use CornerRole::*;
49 use TypeRole::*;
50 let (height, icon, gap, padding, outline, square, pressed, label) = match self {
51 Self::ExtraSmall => (32., 20., 8., 16., 1., Medium, Small, LabelLarge),
52 Self::Small => (40., 20., 8., 16., 1., Medium, Small, LabelLarge),
53 Self::Medium => (56., 24., 8., 24., 1., Large, Medium, TitleMedium),
54 Self::Large => (96., 32., 12., 48., 2., ExtraLarge, Large, HeadlineSmall),
55 Self::ExtraLarge => (136., 40., 16., 64., 3., ExtraLarge, Large, HeadlineLarge),
56 };
57 Metrics {
58 height,
59 icon,
60 gap,
61 padding,
62 outline,
63 square,
64 pressed,
65 label,
66 }
67 }
68
69 fn icon_metrics(self, width: IconButtonWidth) -> (Metrics, f32) {
70 let mut metrics = self.metrics();
72 let (icon, narrow, uniform, wide) = match self {
73 Self::ExtraSmall => (20., 4., 6., 10.),
74 Self::Small => (24., 4., 8., 14.),
75 Self::Medium => (24., 12., 16., 24.),
76 Self::Large => (32., 16., 32., 48.),
77 Self::ExtraLarge => (40., 32., 48., 72.),
78 };
79 metrics.icon = icon;
80 let space = match width {
81 IconButtonWidth::Narrow => narrow,
82 IconButtonWidth::Uniform => uniform,
83 IconButtonWidth::Wide => wide,
84 };
85 (metrics, icon + 2. * space)
86 }
87}
88
89#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
90pub enum ButtonShape {
91 #[default]
92 Round,
93 Square,
94}
95
96impl ButtonShape {
97 fn corner(self, square: CornerRole, invert: bool) -> CornerRole {
98 if (self == Self::Round) != invert {
99 CornerRole::Full
100 } else {
101 square
102 }
103 }
104}
105
106#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
107pub enum ButtonVariant {
108 Elevated,
109 #[default]
110 Filled,
111 FilledTonal,
112 Outlined,
113 Text,
114}
115
116#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
117pub enum ToggleButtonVariant {
118 Elevated,
119 #[default]
120 Filled,
121 FilledTonal,
122 Outlined,
123}
124
125#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
126pub enum IconButtonVariant {
127 #[default]
128 Standard,
129 Filled,
130 FilledTonal,
131 Outlined,
132}
133
134#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
135pub enum IconButtonWidth {
136 Narrow,
137 #[default]
138 Uniform,
139 Wide,
140}
141
142struct Common {
143 id: ElementId,
144 label: SharedString,
145 disabled: bool,
146 focus: Option<FocusHandle>,
147 interaction_source: Option<Entity<InteractionSource>>,
148 appearance: ButtonStyle,
149 size: ControlSize,
150 shape: ButtonShape,
151}
152
153impl Common {
154 fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
155 Self {
156 id: id.into(),
157 label: label.into(),
158 disabled: false,
159 focus: None,
160 interaction_source: None,
161 appearance: ButtonStyle::default(),
162 size: ControlSize::default(),
163 shape: ButtonShape::default(),
164 }
165 }
166
167 fn render(
168 self,
169 content: AnyElement,
170 style: ActionStyle,
171 action: Action,
172 window: &mut Window,
173 cx: &mut App,
174 ) -> AnyElement {
175 self.render_scaled(content, style, action, 1., window, cx)
176 }
177
178 fn render_scaled(
179 self,
180 content: AnyElement,
181 style: ActionStyle,
182 action: Action,
183 scale: f32,
184 window: &mut Window,
185 cx: &mut App,
186 ) -> AnyElement {
187 ActionControl {
188 id: self.id,
189 label: self.label,
190 focus: self.focus,
191 disabled: self.disabled,
192 action,
193 style,
194 content,
195 }
196 .render_scaled(
197 scale,
198 self.interaction_source.as_ref(),
199 self.appearance,
200 window,
201 cx,
202 )
203 }
204}
205
206macro_rules! common_builders {
208 () => {
209 pub fn size(mut self, size: ControlSize) -> Self {
211 self.common.size = size;
212 self
213 }
214
215 pub fn shape(mut self, shape: ButtonShape) -> Self {
217 self.common.shape = shape;
218 self
219 }
220
221 pub fn disabled(mut self, disabled: bool) -> Self {
223 self.common.disabled = disabled;
224 self
225 }
226
227 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
229 self.common.focus = Some(focus.clone());
230 self
231 }
232 };
233}
234
235#[derive(Default)]
236struct Slots {
237 leading: Option<AnyElement>,
238 trailing: Option<AnyElement>,
239 content: Option<AnyElement>,
240 padding: Option<ButtonPadding>,
241 width: Option<Pixels>,
242}
243
244impl Slots {
245 fn render(
246 self,
247 label: SharedString,
248 metrics: Metrics,
249 scale: f32,
250 window: &Window,
251 tint: gpui::Hsla,
252 cx: &App,
253 ) -> AnyElement {
254 let direction = window_material_theme(window, cx).layout.direction;
255 let typography = metrics.label.style(TypographyEmphasis::Baseline);
256 let max_padding = self.width.map_or_else(
257 || f32::from(window.viewport_size().width) * 0.125,
258 |width| (f32::from(width) - 16.).max(0.) / 2.,
259 );
260 let horizontal = px(metrics.padding.min(max_padding));
261 let ButtonPadding {
262 top,
263 end,
264 bottom,
265 start,
266 } = self.padding.unwrap_or(ButtonPadding {
267 top: px(4.),
268 end: horizontal,
269 bottom: px(4.),
270 start: horizontal,
271 });
272 let (left, right) = if direction == Direction::Rtl {
273 (end, start)
274 } else {
275 (start, end)
276 };
277 let icons = usize::from(self.leading.is_some()) + usize::from(self.trailing.is_some());
278 let label_width = self.width.map(|width| {
279 (width
280 - finite_length(left)
281 - finite_length(right)
282 - px((metrics.icon + metrics.gap) * icons as f32))
283 .max(px(0.))
284 });
285 let mut row = div()
286 .flex()
287 .items_center()
288 .justify_center()
289 .min_w_0()
290 .max_w_full()
291 .gap(px(metrics.gap * scale))
292 .pl(finite_length(left) * scale)
293 .pr(finite_length(right) * scale)
294 .pt(finite_length(top) * scale)
295 .pb(finite_length(bottom) * scale)
296 .text_size(px(typography.size * scale))
297 .line_height(px(typography.line_height * scale));
298 if direction == Direction::Rtl {
299 row = row.flex_row_reverse();
300 }
301 if let Some(width) = self.width {
302 row = row.w(width).overflow_hidden();
303 }
304 row.children(
305 self.leading
306 .map(|icon| icon_slot(icon, metrics.icon * scale)),
307 )
308 .child(self.content.unwrap_or_else(|| {
309 crate::text::single_line(
310 label,
311 typography,
312 scale,
313 tint,
314 (label_width, 1., 1.),
315 window,
316 cx,
317 )
318 .into_any_element()
319 }))
320 .children(
321 self.trailing
322 .map(|icon| icon_slot(icon, metrics.icon * scale)),
323 )
324 .into_any_element()
325 }
326}
327
328macro_rules! appearance_builders {
329 () => {
330 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
333 self.common.interaction_source = Some(source.clone());
334 self
335 }
336
337 pub fn shapes(mut self, shapes: ButtonShapes) -> Self {
339 self.common.appearance.shapes = shapes;
340 self
341 }
342
343 pub fn colors(mut self, colors: ButtonColors) -> Self {
345 self.common.appearance.colors = colors;
346 self
347 }
348
349 pub fn border(mut self, border: ButtonBorder) -> Self {
351 self.common.appearance.border = Some(border);
352 self
353 }
354 };
355}
356
357macro_rules! slot_builders {
358 () => {
359 pub fn content(mut self, content: impl IntoElement) -> Self {
362 self.slots.content = Some(content.into_any_element());
363 self
364 }
365
366 pub fn content_padding(mut self, padding: ButtonPadding) -> Self {
368 self.slots.padding = Some(padding);
369 self
370 }
371
372 pub fn elevations(mut self, elevations: ButtonElevations) -> Self {
374 self.common.appearance.elevations = elevations;
375 self
376 }
377
378 pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
380 self.slots.leading = Some(icon.into_any_element());
381 self
382 }
383
384 pub fn trailing_icon(mut self, icon: impl IntoElement) -> Self {
386 self.slots.trailing = Some(icon.into_any_element());
387 self
388 }
389 };
390}
391
392#[derive(IntoElement)]
395pub struct Button {
396 common: Common,
397 variant: ButtonVariant,
398 slots: Slots,
399 on_activate: Option<Activate>,
400 scale: f32,
401}
402
403impl Button {
404 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
405 Self {
406 common: Common::new(id, label),
407 variant: ButtonVariant::default(),
408 slots: Slots::default(),
409 on_activate: None,
410 scale: 1.,
411 }
412 }
413
414 common_builders!();
415 appearance_builders!();
416 slot_builders!();
417
418 pub fn variant(mut self, variant: ButtonVariant) -> Self {
419 self.variant = variant;
420 self
421 }
422
423 pub(crate) fn scale(mut self, scale: f32) -> Self {
424 self.scale = scale;
425 self
426 }
427
428 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
429 self.on_activate = Some(Rc::new(handler));
430 self
431 }
432}
433
434impl RenderOnce for Button {
435 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
436 let metrics = self.common.size.metrics();
437 let appearance = button_appearance(self.variant, None);
438 let style = appearance.style(
439 metrics,
440 self.common.shape.corner(metrics.square, false),
441 58.,
442 );
443 let content = self.slots.render(
444 self.common.label.clone(),
445 metrics,
446 self.scale,
447 window,
448 self.common
449 .appearance
450 .colors
451 .content(self.common.disabled, false)
452 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx)),
453 cx,
454 );
455 self.common.render_scaled(
456 content,
457 style,
458 Action::Invoke(self.on_activate),
459 self.scale,
460 window,
461 cx,
462 )
463 }
464}
465
466#[derive(IntoElement)]
469pub struct ToggleButton {
470 common: Common,
471 variant: ToggleButtonVariant,
472 selected: bool,
473 slots: Slots,
474 on_change: Option<Change>,
475}
476
477impl ToggleButton {
478 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, selected: bool) -> Self {
479 Self {
480 common: Common::new(id, label),
481 variant: ToggleButtonVariant::default(),
482 selected,
483 slots: Slots::default(),
484 on_change: None,
485 }
486 }
487
488 common_builders!();
489 appearance_builders!();
490 slot_builders!();
491
492 pub fn variant(mut self, variant: ToggleButtonVariant) -> Self {
493 self.variant = variant;
494 self
495 }
496
497 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
498 self.on_change = Some(Rc::new(handler));
499 self
500 }
501}
502
503impl RenderOnce for ToggleButton {
504 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
505 let metrics = self.common.size.metrics();
506 let variant = match self.variant {
507 ToggleButtonVariant::Elevated => ButtonVariant::Elevated,
508 ToggleButtonVariant::Filled => ButtonVariant::Filled,
509 ToggleButtonVariant::FilledTonal => ButtonVariant::FilledTonal,
510 ToggleButtonVariant::Outlined => ButtonVariant::Outlined,
511 };
512 let mut style = button_appearance(variant, Some(self.selected)).style(
513 metrics,
514 self.common.shape.corner(metrics.square, false),
515 0.,
516 );
517 style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
518 let content = self.slots.render(
519 self.common.label.clone(),
520 metrics,
521 1.,
522 window,
523 self.common
524 .appearance
525 .colors
526 .content(self.common.disabled, self.selected)
527 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx)),
528 cx,
529 );
530 self.common.render(
531 content,
532 style,
533 Action::Toggle {
534 selected: self.selected,
535 on_change: self.on_change,
536 },
537 window,
538 cx,
539 )
540 }
541}
542
543#[derive(IntoElement)]
545pub struct IconButton {
546 common: Common,
547 icon: AnyElement,
548 variant: IconButtonVariant,
549 width: IconButtonWidth,
550 on_activate: Option<Activate>,
551}
552
553impl IconButton {
554 pub fn new(
555 id: impl Into<ElementId>,
556 name: impl Into<SharedString>,
557 icon: impl IntoElement,
558 ) -> Self {
559 Self {
560 common: Common::new(id, name),
561 icon: icon.into_any_element(),
562 variant: IconButtonVariant::default(),
563 width: IconButtonWidth::default(),
564 on_activate: None,
565 }
566 }
567
568 common_builders!();
569 appearance_builders!();
570
571 pub fn variant(mut self, variant: IconButtonVariant) -> Self {
572 self.variant = variant;
573 self
574 }
575
576 pub fn width(mut self, width: IconButtonWidth) -> Self {
577 self.width = width;
578 self
579 }
580
581 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
582 self.on_activate = Some(Rc::new(handler));
583 self
584 }
585}
586
587impl RenderOnce for IconButton {
588 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
589 let (metrics, width) = self.common.size.icon_metrics(self.width);
590 let mut style = icon_appearance(self.variant, None).style(
591 metrics,
592 self.common.shape.corner(metrics.square, false),
593 width,
594 );
595 style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
596 self.common.render(
597 icon_slot(self.icon, metrics.icon).into_any_element(),
598 style,
599 Action::Invoke(self.on_activate),
600 window,
601 cx,
602 )
603 }
604}
605
606#[derive(IntoElement)]
609pub struct IconToggleButton {
610 common: Common,
611 icon: AnyElement,
612 selected_icon: Option<AnyElement>,
613 selected: bool,
614 variant: IconButtonVariant,
615 width: IconButtonWidth,
616 on_change: Option<Change>,
617}
618
619impl IconToggleButton {
620 pub fn new(
621 id: impl Into<ElementId>,
622 name: impl Into<SharedString>,
623 icon: impl IntoElement,
624 selected: bool,
625 ) -> Self {
626 Self {
627 common: Common::new(id, name),
628 icon: icon.into_any_element(),
629 selected_icon: None,
630 selected,
631 variant: IconButtonVariant::default(),
632 width: IconButtonWidth::default(),
633 on_change: None,
634 }
635 }
636
637 common_builders!();
638 appearance_builders!();
639
640 pub fn selected_icon(mut self, icon: impl IntoElement) -> Self {
641 self.selected_icon = Some(icon.into_any_element());
642 self
643 }
644
645 pub fn variant(mut self, variant: IconButtonVariant) -> Self {
646 self.variant = variant;
647 self
648 }
649
650 pub fn width(mut self, width: IconButtonWidth) -> Self {
651 self.width = width;
652 self
653 }
654
655 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
656 self.on_change = Some(Rc::new(handler));
657 self
658 }
659}
660
661impl RenderOnce for IconToggleButton {
662 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
663 let (metrics, width) = self.common.size.icon_metrics(self.width);
664 let mut style = icon_appearance(self.variant, Some(self.selected)).style(
665 metrics,
666 self.common.shape.corner(metrics.square, false),
667 width,
668 );
669 style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
670 style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
671 let icon = if self.selected {
672 self.selected_icon.unwrap_or(self.icon)
673 } else {
674 self.icon
675 };
676 self.common.render(
677 icon_slot(icon, metrics.icon).into_any_element(),
678 style,
679 Action::Toggle {
680 selected: self.selected,
681 on_change: self.on_change,
682 },
683 window,
684 cx,
685 )
686 }
687}
688
689#[doc(hidden)]
691pub mod composition {
692 use super::*;
693
694 #[derive(Clone, Copy)]
696 pub enum Segment {
697 Only,
698 Leading,
699 Middle,
700 Trailing,
701 SplitLeading,
702 SplitTrailing,
703 }
704
705 #[derive(IntoElement)]
707 pub struct ButtonPart {
708 common: Common,
709 variant: ButtonVariant,
710 selected: Option<bool>,
711 presentation_selected: Option<bool>,
712 on_activate: Option<Activate>,
713 on_change: Option<Change>,
714 segment: Option<Segment>,
715 icon: Option<AnyElement>,
716 slots: Slots,
717 width: Option<Pixels>,
718 tab_stop: bool,
719 semantic_only: bool,
720 icon_width: Option<IconButtonWidth>,
721 }
722
723 impl ButtonPart {
724 pub fn new(
725 id: impl Into<ElementId>,
726 label: impl Into<SharedString>,
727 width: Pixels,
728 ) -> Self {
729 Self {
730 common: Common::new(id, label),
731 variant: ButtonVariant::default(),
732 selected: None,
733 presentation_selected: None,
734 on_activate: None,
735 on_change: None,
736 segment: None,
737 icon: None,
738 slots: Slots::default(),
739 width: Some(width),
740 tab_stop: true,
741 semantic_only: false,
742 icon_width: None,
743 }
744 }
745
746 pub fn intrinsic(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
747 let mut part = Self::new(id, label, px(0.));
748 part.width = None;
749 part
750 }
751
752 common_builders!();
753 appearance_builders!();
754 slot_builders!();
755
756 pub fn variant(mut self, variant: ButtonVariant) -> Self {
757 self.variant = variant;
758 self
759 }
760
761 pub fn segment(mut self, segment: Option<Segment>) -> Self {
762 self.segment = segment;
763 self
764 }
765
766 pub fn selected(mut self, selected: Option<bool>) -> Self {
767 self.selected = selected;
768 self
769 }
770
771 pub fn presentation_selected(mut self, selected: bool) -> Self {
772 self.presentation_selected = Some(selected);
773 self
774 }
775
776 pub fn on_change(
777 mut self,
778 callback: impl Fn(bool, &mut Window, &mut App) + 'static,
779 ) -> Self {
780 self.on_change = Some(Rc::new(callback));
781 self
782 }
783
784 pub fn icon(mut self, icon: impl IntoElement) -> Self {
785 self.icon = Some(icon.into_any_element());
786 self
787 }
788
789 pub fn icon_width(mut self, width: IconButtonWidth) -> Self {
790 self.icon_width = Some(width);
791 self
792 }
793
794 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
795 self.tab_stop = tab_stop;
796 self
797 }
798
799 pub fn on_activate(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
800 self.on_activate = Some(Rc::new(callback));
801 self
802 }
803
804 pub fn on_accessible_activate(
805 mut self,
806 callback: impl Fn(&mut Window, &mut App) + 'static,
807 ) -> Self {
808 self.on_activate = Some(Rc::new(callback));
809 self.semantic_only = true;
810 self
811 }
812 }
813
814 impl RenderOnce for ButtonPart {
815 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
816 let mut metrics = self.icon_width.map_or_else(
817 || self.common.size.metrics(),
818 |width| self.common.size.icon_metrics(width).0,
819 );
820 let segment = self.segment.map(|segment| {
821 use CornerRole::*;
822 let (inner, pressed) = match segment {
823 Segment::SplitLeading | Segment::SplitTrailing => match self.common.size {
824 ControlSize::ExtraSmall => (ExtraSmall, Small),
825 ControlSize::Small | ControlSize::Medium => (ExtraSmall, Medium),
826 ControlSize::Large => (Small, LargeIncreased),
827 ControlSize::ExtraLarge => (Medium, LargeIncreased),
828 },
829 _ => (Small, ExtraSmall),
830 };
831 SegmentShape {
832 leading: matches!(
833 segment,
834 Segment::Only | Segment::Leading | Segment::SplitLeading
835 ),
836 trailing: matches!(
837 segment,
838 Segment::Only | Segment::Trailing | Segment::SplitTrailing
839 ),
840 outer: self.common.shape.corner(metrics.square, false),
841 inner,
842 pressed,
843 }
844 });
845 let split = matches!(
846 self.segment,
847 Some(Segment::SplitLeading | Segment::SplitTrailing)
848 );
849 let palette_selection = if split { None } else { self.selected };
850 let mut style = button_appearance(self.variant, palette_selection).style(
851 metrics,
852 self.common.shape.corner(metrics.square, false),
853 0.,
854 );
855 if self.selected.is_some() || self.presentation_selected.is_some() {
856 style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
857 }
858 if matches!(self.segment, Some(Segment::SplitTrailing)) {
859 metrics.icon = split_trailing_size(self.common.size).0;
860 }
861 if split {
862 let colors = &mut self.common.appearance.colors;
863 colors.checked_content = colors.checked_content.or(colors.content);
864 colors.checked_container = colors.checked_container.or(colors.container);
865 }
866 let checked = self
867 .presentation_selected
868 .or(self.selected)
869 .unwrap_or(false);
870 let tint = self
871 .common
872 .appearance
873 .colors
874 .content(self.common.disabled, checked)
875 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
876 let has_slots = self.slots.content.is_some()
877 || self.slots.leading.is_some()
878 || self.slots.trailing.is_some()
879 || self.slots.padding.is_some();
880 let content = if let Some(width) = self.width.filter(|_| !has_slots) {
881 if let Some(icon) = self.icon {
882 icon_slot(icon, metrics.icon).into_any_element()
883 } else {
884 let typography = metrics.label.style(TypographyEmphasis::Baseline);
885 let padding = metrics.padding.min((f32::from(width) - 16.).max(0.) / 2.);
886 let label_width = (width - px(2. * padding)).max(px(0.));
887 div()
888 .flex()
889 .min_w_0()
890 .max_w_full()
891 .w(width)
892 .justify_center()
893 .px(px(padding))
894 .child(crate::text::single_line(
895 self.common.label.clone(),
896 typography,
897 1.,
898 tint,
899 (Some(label_width), 1., 1.),
900 window,
901 cx,
902 ))
903 .into_any_element()
904 }
905 } else {
906 self.slots.width = self.width;
907 if let Some(icon) = self.icon {
908 self.slots.content = Some(icon_slot(icon, metrics.icon).into_any_element());
909 }
910 self.slots.padding = self
911 .slots
912 .padding
913 .or_else(|| split_padding(self.common.size, self.segment));
914 self.slots
915 .render(self.common.label.clone(), metrics, 1., window, tint, cx)
916 };
917 let action = if let Some(selected) = self.selected {
918 Action::Toggle {
919 selected,
920 on_change: self.on_change.or_else(|| {
921 self.on_activate.map(|callback| {
922 Rc::new(move |_, window: &mut Window, cx: &mut App| {
923 callback(window, cx)
924 }) as Change
925 })
926 }),
927 }
928 } else {
929 Action::Invoke(self.on_activate)
930 };
931 ActionControl {
932 id: self.common.id,
933 label: self.common.label,
934 focus: self.common.focus,
935 disabled: self.common.disabled,
936 action,
937 style,
938 content,
939 }
940 .render_layout(
941 1.,
942 ActionLayout {
943 segment,
944 width: self.width,
945 tab_stop: self.tab_stop,
946 semantic_only: self.semantic_only,
947 appearance: self.common.appearance,
948 presentation_selected: self.presentation_selected,
949 ..Default::default()
950 },
951 self.common.interaction_source.as_ref(),
952 window,
953 cx,
954 )
955 }
956 }
957
958 fn split_padding(size: ControlSize, segment: Option<Segment>) -> Option<ButtonPadding> {
959 let (start, end) = match segment {
960 Some(Segment::SplitLeading) => match size {
961 ControlSize::ExtraSmall => (12., 10.),
962 ControlSize::Small => (16., 12.),
963 ControlSize::Medium => (24., 24.),
964 ControlSize::Large => (48., 48.),
965 ControlSize::ExtraLarge => (64., 64.),
966 },
967 Some(Segment::SplitTrailing) => {
968 let (icon, footprint) = split_trailing_size(size);
969 let edge = (footprint - icon) / 2.;
970 (edge, edge)
971 }
972 _ => return None,
973 };
974 Some(ButtonPadding {
975 start: px(start),
976 end: px(end),
977 ..Default::default()
978 })
979 }
980
981 pub fn label_width(
982 size: ControlSize,
983 label: SharedString,
984 window: &Window,
985 cx: &App,
986 ) -> Pixels {
987 group_label_width(size, label, None, false, window, cx)
988 }
989
990 pub fn group_label_width(
991 size: ControlSize,
992 label: SharedString,
993 padding: Option<ButtonPadding>,
994 icon: bool,
995 window: &Window,
996 cx: &App,
997 ) -> Pixels {
998 let metrics = size.metrics();
999 let theme = window_material_theme(window, cx);
1000 let style = metrics.label.style(TypographyEmphasis::Baseline);
1001 let width = gpui_material_foundation::shape_text(
1002 if label.contains(['\r', '\n']) {
1003 label.replace(['\r', '\n'], " ").into()
1004 } else {
1005 label
1006 },
1007 style,
1008 &theme.typography,
1009 1.,
1010 gpui::transparent_black(),
1011 window,
1012 cx,
1013 )
1014 .map_or(px(0.), |text| text.line().width.ceil());
1015 let padding = padding.map_or(px(metrics.padding * 2.), |padding| {
1016 finite_length(padding.start) + finite_length(padding.end)
1017 });
1018 (width
1019 + padding
1020 + if icon {
1021 px(metrics.icon + metrics.gap)
1022 } else {
1023 px(0.)
1024 })
1025 .max(px(theme.layout.density.interactive_size(1.)))
1026 }
1027
1028 pub fn group_icon_width(
1029 size: ControlSize,
1030 width: IconButtonWidth,
1031 padding: Option<ButtonPadding>,
1032 ) -> Pixels {
1033 let (metrics, width) = size.icon_metrics(width);
1034 padding.map_or(px(width), |padding| {
1035 px(metrics.icon) + finite_length(padding.start) + finite_length(padding.end)
1036 })
1037 }
1038
1039 pub fn split_trailing_size(size: ControlSize) -> (f32, f32) {
1040 match size {
1042 ControlSize::ExtraSmall | ControlSize::Small => (22., 48.),
1043 ControlSize::Medium => (26., 56.),
1044 ControlSize::Large => (38., 96.),
1045 ControlSize::ExtraLarge => (50., 136.),
1046 }
1047 }
1048}
1049
1050struct Appearance {
1051 background: Option<ColorRole>,
1052 foreground: ColorRole,
1053 outlined: bool,
1054 disabled: DisabledStyle,
1055 elevation: Elevation,
1056 hover_elevation: Elevation,
1057}
1058
1059impl Appearance {
1060 fn style(self, metrics: Metrics, corner: CornerRole, min_width: f32) -> ActionStyle {
1061 ActionStyle {
1062 background: self.background,
1063 background_color: None,
1064 foreground: self.foreground,
1065 disabled: self.disabled,
1066 height: metrics.height,
1067 min_width,
1068 corner,
1069 pressed_corner: metrics.pressed,
1070 selected_corner: None,
1071 corner_motion: (MotionKind::Spatial, MotionSpeed::Fast),
1072 outline: if self.outlined { metrics.outline } else { 0. },
1073 elevation: self.elevation,
1074 hover_elevation: self.hover_elevation,
1075 }
1076 }
1077}
1078
1079fn button_appearance(variant: ButtonVariant, selected: Option<bool>) -> Appearance {
1080 use ColorRole::*;
1081 use Elevation::*;
1082 let (background, foreground, outlined, elevation, hover_elevation) = match (variant, selected) {
1083 (ButtonVariant::Elevated, Some(true)) => (Some(Primary), OnPrimary, false, Level1, Level2),
1084 (ButtonVariant::Elevated, _) => (Some(SurfaceContainerLow), Primary, false, Level1, Level2),
1085 (ButtonVariant::Filled, Some(false)) => (
1086 Some(SurfaceContainer),
1087 OnSurfaceVariant,
1088 false,
1089 Level0,
1090 Level1,
1091 ),
1092 (ButtonVariant::Filled, _) => (Some(Primary), OnPrimary, false, Level0, Level1),
1093 (ButtonVariant::FilledTonal, Some(true)) => {
1094 (Some(Secondary), OnSecondary, false, Level0, Level1)
1095 }
1096 (ButtonVariant::FilledTonal, _) => (
1097 Some(SecondaryContainer),
1098 OnSecondaryContainer,
1099 false,
1100 Level0,
1101 Level1,
1102 ),
1103 (ButtonVariant::Outlined, Some(true)) => (
1104 Some(InverseSurface),
1105 InverseOnSurface,
1106 false,
1107 Level0,
1108 Level0,
1109 ),
1110 (ButtonVariant::Outlined, _) => (None, OnSurfaceVariant, true, Level0, Level0),
1111 (ButtonVariant::Text, _) => (None, Primary, false, Level0, Level0),
1113 };
1114 Appearance {
1115 background,
1116 foreground,
1117 outlined,
1118 disabled: DisabledStyle {
1119 foreground: if variant == ButtonVariant::FilledTonal && selected.is_none() {
1122 OnSurface
1123 } else {
1124 OnSurfaceVariant
1125 },
1126 background: match (variant, selected) {
1127 (ButtonVariant::Outlined, Some(_)) => Some((OutlineVariant, 0.10)),
1128 (ButtonVariant::Outlined | ButtonVariant::Text, _) => None,
1129 (ButtonVariant::FilledTonal, None) => Some((OnSurface, 0.12)),
1130 _ => Some((OnSurface, 0.10)),
1131 },
1132 outline: (OutlineVariant, 0.10),
1133 },
1134 elevation,
1135 hover_elevation,
1136 }
1137}
1138
1139fn icon_appearance(variant: IconButtonVariant, selected: Option<bool>) -> Appearance {
1140 let mut appearance = match variant {
1141 IconButtonVariant::Standard => button_appearance(ButtonVariant::Text, selected),
1142 IconButtonVariant::Filled => button_appearance(ButtonVariant::Filled, selected),
1143 IconButtonVariant::FilledTonal => button_appearance(ButtonVariant::FilledTonal, selected),
1144 IconButtonVariant::Outlined => button_appearance(ButtonVariant::Outlined, selected),
1145 };
1146 if variant == IconButtonVariant::Standard {
1147 appearance.foreground = if selected == Some(true) {
1148 ColorRole::Primary
1149 } else {
1150 ColorRole::OnSurfaceVariant
1151 };
1152 }
1153 appearance.disabled = DisabledStyle {
1154 foreground: ColorRole::OnSurface,
1155 background: match variant {
1157 IconButtonVariant::Filled | IconButtonVariant::FilledTonal => {
1158 Some((ColorRole::OnSurface, 0.10))
1159 }
1160 IconButtonVariant::Standard | IconButtonVariant::Outlined => None,
1161 },
1162 outline: (ColorRole::OutlineVariant, 0.38),
1163 };
1164 appearance.hover_elevation = Elevation::Level0;
1165 appearance
1166}
1167
1168#[cfg(test)]
1169mod tests {
1170 use super::*;
1171
1172 #[test]
1173 fn text_action_and_standard_icon_keep_distinct_compose_colors() {
1174 assert_eq!(
1177 button_appearance(ButtonVariant::Text, None).foreground,
1178 ColorRole::Primary
1179 );
1180 for selected in [None, Some(false)] {
1181 assert_eq!(
1182 icon_appearance(IconButtonVariant::Standard, selected).foreground,
1183 ColorRole::OnSurfaceVariant
1184 );
1185 }
1186 assert_eq!(
1187 icon_appearance(IconButtonVariant::Standard, Some(true)).foreground,
1188 ColorRole::Primary
1189 );
1190 }
1191
1192 #[test]
1193 fn disabled_tokens_are_not_inferred_from_enabled_selection_colors() {
1194 use ColorRole::*;
1195 for selected in [Some(false), Some(true)] {
1196 let outlined = button_appearance(ButtonVariant::Outlined, selected);
1197 assert_eq!(outlined.disabled.background, Some((OutlineVariant, 0.10)));
1198 assert_eq!(outlined.disabled.foreground, OnSurfaceVariant);
1199 assert_eq!(outlined.disabled.outline, (OutlineVariant, 0.10));
1200 let icon = icon_appearance(IconButtonVariant::Outlined, selected);
1201 assert_eq!(icon.disabled.background, None);
1202 assert_eq!(icon.disabled.foreground, OnSurface);
1203 assert_eq!(icon.disabled.outline, (OutlineVariant, 0.38));
1204 }
1205 assert_eq!(
1206 button_appearance(ButtonVariant::Outlined, None)
1207 .disabled
1208 .background,
1209 None
1210 );
1211 assert_eq!(
1212 button_appearance(ButtonVariant::Filled, None)
1213 .disabled
1214 .background,
1215 Some((OnSurface, 0.10))
1216 );
1217 assert_eq!(
1220 button_appearance(ButtonVariant::FilledTonal, None)
1221 .disabled
1222 .background,
1223 Some((OnSurface, 0.12))
1224 );
1225 assert_eq!(
1226 button_appearance(ButtonVariant::FilledTonal, Some(false))
1227 .disabled
1228 .background,
1229 Some((OnSurface, 0.10))
1230 );
1231 assert_eq!(
1232 icon_appearance(IconButtonVariant::FilledTonal, None)
1233 .disabled
1234 .background,
1235 Some((OnSurface, 0.10))
1236 );
1237 }
1238}