1mod appearance;
2mod spinner;
3
4use std::rc::Rc;
5
6use gpui::{
7 AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
8 ParentElement, Pixels, RenderOnce, SharedString, Styled, Window, div, px,
9};
10use gpui_base::TestSupportExt;
11use gpui_material_foundation::{InteractionSource, current_material_theme};
12use gpui_material_theme::{
13 CornerRole, Direction, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
14};
15
16use crate::action::{
17 Action, ActionControl, ActionLayout, ActionStyle, Activate, Change, SegmentShape, icon_slot,
18};
19use crate::button_style::{
20 ButtonBorder, ButtonColors, ButtonElevations, ButtonPadding, ButtonShapes, ButtonStyle,
21 ControlSize, finite_length,
22};
23
24use appearance::{button_appearance, icon_appearance};
25use spinner::render_loading_spinner;
26
27#[derive(Clone, Copy)]
28struct Metrics {
29 height: f32,
30 icon: f32,
31 gap: f32,
32 padding: f32,
33 outline: f32,
34 square: CornerRole,
35 pressed: CornerRole,
36 label: TypeRole,
37}
38
39impl ControlSize {
40 fn metrics(self) -> Metrics {
42 use CornerRole::*;
43 use TypeRole::*;
44 let (height, icon, gap, padding, outline, square, pressed, label) = match self {
45 Self::ExtraSmall => (32., 20., 8., 16., 1., Medium, Small, LabelLarge),
46 Self::Small => (40., 20., 8., 16., 1., Medium, Small, LabelLarge),
47 Self::Medium => (56., 24., 8., 24., 1., Large, Medium, TitleMedium),
48 Self::Large => (96., 32., 12., 48., 2., ExtraLarge, Large, HeadlineSmall),
49 Self::ExtraLarge => (136., 40., 16., 64., 3., ExtraLarge, Large, HeadlineLarge),
50 };
51 Metrics {
52 height,
53 icon,
54 gap,
55 padding,
56 outline,
57 square,
58 pressed,
59 label,
60 }
61 }
62
63 fn icon_metrics(self, width: IconButtonWidth) -> (Metrics, f32) {
64 let mut metrics = self.metrics();
66 let (icon, narrow, uniform, wide) = match self {
67 Self::ExtraSmall => (20., 4., 6., 10.),
68 Self::Small => (24., 4., 8., 14.),
69 Self::Medium => (24., 12., 16., 24.),
70 Self::Large => (32., 16., 32., 48.),
71 Self::ExtraLarge => (40., 32., 48., 72.),
72 };
73 metrics.icon = icon;
74 let space = match width {
75 IconButtonWidth::Narrow => narrow,
76 IconButtonWidth::Uniform => uniform,
77 IconButtonWidth::Wide => wide,
78 };
79 (metrics, icon + 2. * space)
80 }
81}
82
83#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
85pub enum ButtonShape {
86 #[default]
88 Round,
89 Square,
91}
92
93impl ButtonShape {
94 fn corner(self, square: CornerRole, invert: bool) -> CornerRole {
95 if (self == Self::Round) != invert {
96 CornerRole::Full
97 } else {
98 square
99 }
100 }
101}
102
103pub type ButtonTone = crate::SemanticTone;
107
108#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
110pub enum ButtonVariant {
111 Elevated,
113 #[default]
115 Filled,
116 FilledTonal,
118 Outlined,
120 Text,
122}
123
124#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
126pub enum ToggleButtonVariant {
127 Elevated,
129 #[default]
131 Filled,
132 FilledTonal,
134 Outlined,
136}
137
138#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
140pub enum IconButtonVariant {
141 #[default]
143 Standard,
144 Filled,
146 FilledTonal,
148 Outlined,
150}
151
152#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
154pub enum IconButtonWidth {
155 Narrow,
157 #[default]
159 Uniform,
160 Wide,
162}
163
164struct Common {
165 id: ElementId,
166 label: SharedString,
167 disabled: bool,
168 loading: bool,
169 focus: Option<FocusHandle>,
170 interaction_source: Option<Entity<InteractionSource>>,
171 appearance: ButtonStyle,
172 size: ControlSize,
173 shape: ButtonShape,
174 tone: ButtonTone,
175}
176
177impl Common {
178 fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
179 Self {
180 id: id.into(),
181 label: label.into(),
182 disabled: false,
183 loading: false,
184 focus: None,
185 interaction_source: None,
186 appearance: ButtonStyle::default(),
187 size: ControlSize::default(),
188 shape: ButtonShape::default(),
189 tone: ButtonTone::default(),
190 }
191 }
192
193 fn render(
194 self,
195 content: AnyElement,
196 style: ActionStyle,
197 action: Action,
198 window: &mut Window,
199 cx: &mut App,
200 ) -> AnyElement {
201 self.render_scaled(content, style, action, 1., window, cx)
202 }
203
204 fn render_scaled(
205 self,
206 content: AnyElement,
207 style: ActionStyle,
208 action: Action,
209 scale: f32,
210 window: &mut Window,
211 cx: &mut App,
212 ) -> AnyElement {
213 ActionControl {
214 id: self.id,
215 label: self.label,
216 focus: self.focus,
217 disabled: self.disabled,
218 action,
219 style,
220 content,
221 }
222 .render_layout(
223 scale,
224 ActionLayout {
225 tab_stop: true,
226 loading: self.loading,
227 appearance: self.appearance,
228 ..Default::default()
229 },
230 self.interaction_source.as_ref(),
231 window,
232 cx,
233 )
234 }
235}
236
237macro_rules! common_builders {
239 () => {
240 pub fn size(mut self, size: ControlSize) -> Self {
242 self.common.size = size;
243 self
244 }
245
246 pub fn shape(mut self, shape: ButtonShape) -> Self {
248 self.common.shape = shape;
249 self
250 }
251
252 pub fn tone(mut self, tone: ButtonTone) -> Self {
255 self.common.tone = tone;
256 self
257 }
258
259 pub fn disabled(mut self, disabled: bool) -> Self {
261 self.common.disabled = disabled;
262 self
263 }
264
265 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
267 self.common.focus = Some(focus.clone());
268 self
269 }
270 };
271}
272
273const MIN_COMPRESSED_HORIZONTAL_PADDING: f32 = 4.;
274
275fn compress_horizontal_padding(
276 left: Pixels,
277 right: Pixels,
278 width: Pixels,
279 icon_extent: Pixels,
280 natural_label_width: Pixels,
281) -> (Pixels, Pixels, Pixels) {
282 let mut left_pad = finite_length(left);
283 let mut right_pad = finite_length(right);
284 let available = (width - left_pad - right_pad - icon_extent).max(px(0.));
285 let deficit = (natural_label_width - available).max(px(0.));
286 if deficit > px(0.) {
287 let floor_left = left_pad.min(px(MIN_COMPRESSED_HORIZONTAL_PADDING));
288 let floor_right = right_pad.min(px(MIN_COMPRESSED_HORIZONTAL_PADDING));
289 let slack_left = (left_pad - floor_left).max(px(0.));
290 let slack_right = (right_pad - floor_right).max(px(0.));
291 let total_slack = slack_left + slack_right;
292 let absorb = deficit.min(total_slack);
293 if absorb > px(0.) && total_slack > px(0.) {
294 let left_cut = absorb * (f32::from(slack_left) / f32::from(total_slack));
295 let right_cut = absorb - left_cut;
296 left_pad -= left_cut;
297 right_pad -= right_cut;
298 }
299 }
300 let label_width = (width - left_pad - right_pad - icon_extent).max(px(0.));
301 (left_pad, right_pad, label_width)
302}
303
304#[derive(Default)]
305struct Slots {
306 leading: Option<AnyElement>,
307 trailing: Option<AnyElement>,
308 content: Option<AnyElement>,
309 padding: Option<ButtonPadding>,
310 width: Option<Pixels>,
311}
312
313impl Slots {
314 fn render(
315 self,
316 label: SharedString,
317 metrics: Metrics,
318 scale: f32,
319 window: &Window,
320 tint: gpui::Hsla,
321 cx: &App,
322 ) -> AnyElement {
323 let direction = current_material_theme(window, cx).layout.direction;
324 let typography = metrics.label.style(TypographyEmphasis::Baseline);
325 let max_padding = self.width.map_or_else(
326 || f32::from(window.viewport_size().width) * 0.125,
327 |width| (f32::from(width) - 16.).max(0.) / 2.,
328 );
329 let horizontal = px(metrics.padding.min(max_padding));
330 let ButtonPadding {
331 top,
332 end,
333 bottom,
334 start,
335 } = self.padding.unwrap_or(ButtonPadding {
336 top: px(4.),
337 end: horizontal,
338 bottom: px(4.),
339 start: horizontal,
340 });
341 let (mut left_pad, mut right_pad) = if direction == Direction::Rtl {
342 (finite_length(end), finite_length(start))
343 } else {
344 (finite_length(start), finite_length(end))
345 };
346 let icons = usize::from(self.leading.is_some()) + usize::from(self.trailing.is_some());
347 let icon_extent = px((metrics.icon + metrics.gap) * icons as f32);
348 let mut shaped_label = None;
349 let label_width = self.width.map(|width| {
350 if self.content.is_none() {
351 let shaped = crate::text::shape_single_line(
352 label.clone(),
353 typography,
354 scale,
355 tint,
356 window,
357 cx,
358 );
359 let natural_width = if scale.is_finite() && scale > 0. {
360 shaped.1.line().width.ceil() / scale
361 } else {
362 shaped.1.line().width.ceil()
363 };
364 let (next_left, next_right, next_label_width) = compress_horizontal_padding(
365 left_pad,
366 right_pad,
367 width,
368 icon_extent,
369 natural_width,
370 );
371 left_pad = next_left;
372 right_pad = next_right;
373 shaped_label = Some(shaped);
374 next_label_width
375 } else {
376 (width - left_pad - right_pad - icon_extent).max(px(0.))
377 }
378 });
379 let row_typography = current_material_theme(window, cx)
380 .typography
381 .scale_style(typography);
382 let mut row = div()
383 .flex()
384 .items_center()
385 .justify_center()
386 .min_w_0()
387 .max_w_full()
388 .gap(px(metrics.gap * scale))
389 .pl(left_pad * scale)
390 .pr(right_pad * scale)
391 .pt(finite_length(top) * scale)
392 .pb(finite_length(bottom) * scale)
393 .text_size(px(row_typography.size * scale))
394 .line_height(px(row_typography.line_height * scale));
395 if direction == Direction::Rtl {
396 row = row.flex_row_reverse();
397 }
398 if let Some(width) = self.width {
399 row = row.w(width).overflow_hidden();
400 }
401 row.children(
402 self.leading
403 .map(|icon| icon_slot(icon, metrics.icon * scale)),
404 )
405 .child(self.content.unwrap_or_else(|| {
406 if let Some(shaped) = shaped_label {
407 crate::text::single_line_with_shaped(
408 shaped,
409 typography,
410 scale,
411 tint,
412 (label_width, 1., 1.),
413 window,
414 cx,
415 )
416 } else {
417 crate::text::single_line(
418 label,
419 typography,
420 scale,
421 tint,
422 (label_width, 1., 1.),
423 window,
424 cx,
425 )
426 }
427 .into_any_element()
428 }))
429 .children(
430 self.trailing
431 .map(|icon| icon_slot(icon, metrics.icon * scale)),
432 )
433 .into_any_element()
434 }
435}
436
437macro_rules! appearance_builders {
438 () => {
439 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
442 self.common.interaction_source = Some(source.clone());
443 self
444 }
445
446 pub fn shapes(mut self, shapes: ButtonShapes) -> Self {
448 self.common.appearance.shapes = shapes;
449 self
450 }
451
452 pub fn colors(mut self, colors: ButtonColors) -> Self {
454 self.common.appearance.colors = colors;
455 self
456 }
457
458 pub fn border(mut self, border: ButtonBorder) -> Self {
460 self.common.appearance.border = Some(border);
461 self
462 }
463 };
464}
465
466macro_rules! slot_builders {
467 () => {
468 pub fn content(mut self, content: impl IntoElement) -> Self {
471 self.slots.content = Some(content.into_any_element());
472 self
473 }
474
475 pub fn content_padding(mut self, padding: ButtonPadding) -> Self {
477 self.slots.padding = Some(padding);
478 self
479 }
480
481 pub fn elevations(mut self, elevations: ButtonElevations) -> Self {
483 self.common.appearance.elevations = elevations;
484 self
485 }
486
487 pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
489 self.slots.leading = Some(icon.into_any_element());
490 self
491 }
492
493 pub fn trailing_icon(mut self, icon: impl IntoElement) -> Self {
495 self.slots.trailing = Some(icon.into_any_element());
496 self
497 }
498 };
499}
500
501#[doc(hidden)]
503pub mod composition;
504
505#[derive(IntoElement)]
508pub struct Button {
509 common: Common,
510 variant: ButtonVariant,
511 slots: Slots,
512 on_activate: Option<Activate>,
513 scale: f32,
514}
515
516impl Button {
517 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
519 Self {
520 common: Common::new(id, label),
521 variant: ButtonVariant::default(),
522 slots: Slots::default(),
523 on_activate: None,
524 scale: 1.,
525 }
526 }
527
528 pub fn filled(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
530 Self::new(id, label).variant(ButtonVariant::Filled)
531 }
532
533 pub fn tonal(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
535 Self::new(id, label).variant(ButtonVariant::FilledTonal)
536 }
537
538 pub fn elevated(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
540 Self::new(id, label).variant(ButtonVariant::Elevated)
541 }
542
543 pub fn outlined(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
545 Self::new(id, label).variant(ButtonVariant::Outlined)
546 }
547
548 pub fn text(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
550 Self::new(id, label).variant(ButtonVariant::Text)
551 }
552
553 common_builders!();
554 appearance_builders!();
555 slot_builders!();
556
557 pub fn variant(mut self, variant: ButtonVariant) -> Self {
559 self.variant = variant;
560 self
561 }
562
563 pub fn loading(mut self, loading: bool) -> Self {
566 self.common.loading = loading;
567 self
568 }
569
570 #[cfg(feature = "feedback")]
571 pub(crate) fn scale(mut self, scale: f32) -> Self {
572 self.scale = scale;
573 self
574 }
575
576 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
578 self.on_activate = Some(Rc::new(handler));
579 self
580 }
581}
582
583fn loading_overlay(
584 id: &ElementId,
585 resting_content: AnyElement,
586 icon_size: f32,
587 tint: gpui::Hsla,
588 window: &mut Window,
589 cx: &mut App,
590) -> AnyElement {
591 div()
592 .relative()
593 .flex()
594 .items_center()
595 .justify_center()
596 .child(div().opacity(0.).child(resting_content))
597 .child(
598 div()
599 .id((id.clone(), "loading-spinner"))
600 .test_support()
601 .absolute()
602 .inset_0()
603 .flex()
604 .items_center()
605 .justify_center()
606 .child(render_loading_spinner(id, icon_size, tint, window, cx)),
607 )
608 .into_any_element()
609}
610
611fn loading_icon_spinner(
612 id: &ElementId,
613 icon_size: f32,
614 tint: gpui::Hsla,
615 window: &mut Window,
616 cx: &mut App,
617) -> AnyElement {
618 div()
619 .id((id.clone(), "loading-spinner"))
620 .test_support()
621 .flex()
622 .items_center()
623 .justify_center()
624 .child(render_loading_spinner(id, icon_size, tint, window, cx))
625 .into_any_element()
626}
627
628impl RenderOnce for Button {
629 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
630 let metrics = self.common.size.metrics();
631 let appearance = button_appearance(self.variant, None, self.common.tone);
632 let style = appearance.style(
633 metrics,
634 self.common.shape.corner(metrics.square, false),
635 58.,
636 );
637 let tint = self
638 .common
639 .appearance
640 .colors
641 .content(self.common.disabled, false)
642 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
643 let resting_content = self.slots.render(
644 self.common.label.clone(),
645 metrics,
646 self.scale,
647 window,
648 tint,
649 cx,
650 );
651 let content = if self.common.loading {
652 loading_overlay(
653 &self.common.id,
654 resting_content,
655 metrics.icon * self.scale,
656 tint,
657 window,
658 cx,
659 )
660 } else {
661 resting_content
662 };
663 self.common.render_scaled(
664 content,
665 style,
666 Action::Invoke(self.on_activate),
667 self.scale,
668 window,
669 cx,
670 )
671 }
672}
673
674#[derive(IntoElement)]
677pub struct ToggleButton {
678 common: Common,
679 variant: ToggleButtonVariant,
680 selected: bool,
681 slots: Slots,
682 on_change: Option<Change>,
683}
684
685impl ToggleButton {
686 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, selected: bool) -> Self {
688 Self {
689 common: Common::new(id, label),
690 variant: ToggleButtonVariant::default(),
691 selected,
692 slots: Slots::default(),
693 on_change: None,
694 }
695 }
696
697 pub fn filled(
699 id: impl Into<ElementId>,
700 label: impl Into<SharedString>,
701 selected: bool,
702 ) -> Self {
703 Self::new(id, label, selected).variant(ToggleButtonVariant::Filled)
704 }
705
706 pub fn tonal(id: impl Into<ElementId>, label: impl Into<SharedString>, selected: bool) -> Self {
708 Self::new(id, label, selected).variant(ToggleButtonVariant::FilledTonal)
709 }
710
711 pub fn elevated(
713 id: impl Into<ElementId>,
714 label: impl Into<SharedString>,
715 selected: bool,
716 ) -> Self {
717 Self::new(id, label, selected).variant(ToggleButtonVariant::Elevated)
718 }
719
720 pub fn outlined(
722 id: impl Into<ElementId>,
723 label: impl Into<SharedString>,
724 selected: bool,
725 ) -> Self {
726 Self::new(id, label, selected).variant(ToggleButtonVariant::Outlined)
727 }
728
729 common_builders!();
730 appearance_builders!();
731 slot_builders!();
732
733 pub fn variant(mut self, variant: ToggleButtonVariant) -> Self {
735 self.variant = variant;
736 self
737 }
738
739 pub fn loading(mut self, loading: bool) -> Self {
742 self.common.loading = loading;
743 self
744 }
745
746 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
748 self.on_change = Some(Rc::new(handler));
749 self
750 }
751}
752
753impl RenderOnce for ToggleButton {
754 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
755 let metrics = self.common.size.metrics();
756 let variant = match self.variant {
757 ToggleButtonVariant::Elevated => ButtonVariant::Elevated,
758 ToggleButtonVariant::Filled => ButtonVariant::Filled,
759 ToggleButtonVariant::FilledTonal => ButtonVariant::FilledTonal,
760 ToggleButtonVariant::Outlined => ButtonVariant::Outlined,
761 };
762 let mut style = button_appearance(variant, Some(self.selected), self.common.tone).style(
763 metrics,
764 self.common.shape.corner(metrics.square, false),
765 0.,
766 );
767 style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
768 let tint = self
769 .common
770 .appearance
771 .colors
772 .content(self.common.disabled, self.selected)
773 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
774 let resting_content =
775 self.slots
776 .render(self.common.label.clone(), metrics, 1., window, tint, cx);
777 let content = if self.common.loading {
778 loading_overlay(
779 &self.common.id,
780 resting_content,
781 metrics.icon,
782 tint,
783 window,
784 cx,
785 )
786 } else {
787 resting_content
788 };
789 self.common.render(
790 content,
791 style,
792 Action::Toggle {
793 selected: self.selected,
794 on_change: self.on_change,
795 },
796 window,
797 cx,
798 )
799 }
800}
801
802#[derive(IntoElement)]
804pub struct IconButton {
805 common: Common,
806 icon: AnyElement,
807 variant: IconButtonVariant,
808 width: IconButtonWidth,
809 on_activate: Option<Activate>,
810}
811
812impl IconButton {
813 pub fn new(
815 id: impl Into<ElementId>,
816 name: impl Into<SharedString>,
817 icon: impl IntoElement,
818 ) -> Self {
819 Self {
820 common: Common::new(id, name),
821 icon: icon.into_any_element(),
822 variant: IconButtonVariant::default(),
823 width: IconButtonWidth::default(),
824 on_activate: None,
825 }
826 }
827
828 pub fn standard(
830 id: impl Into<ElementId>,
831 name: impl Into<SharedString>,
832 icon: impl IntoElement,
833 ) -> Self {
834 Self::new(id, name, icon).variant(IconButtonVariant::Standard)
835 }
836
837 pub fn filled(
839 id: impl Into<ElementId>,
840 name: impl Into<SharedString>,
841 icon: impl IntoElement,
842 ) -> Self {
843 Self::new(id, name, icon).variant(IconButtonVariant::Filled)
844 }
845
846 pub fn tonal(
848 id: impl Into<ElementId>,
849 name: impl Into<SharedString>,
850 icon: impl IntoElement,
851 ) -> Self {
852 Self::new(id, name, icon).variant(IconButtonVariant::FilledTonal)
853 }
854
855 pub fn outlined(
857 id: impl Into<ElementId>,
858 name: impl Into<SharedString>,
859 icon: impl IntoElement,
860 ) -> Self {
861 Self::new(id, name, icon).variant(IconButtonVariant::Outlined)
862 }
863
864 common_builders!();
865 appearance_builders!();
866
867 pub fn variant(mut self, variant: IconButtonVariant) -> Self {
869 self.variant = variant;
870 self
871 }
872
873 pub fn width(mut self, width: IconButtonWidth) -> Self {
875 self.width = width;
876 self
877 }
878
879 pub fn loading(mut self, loading: bool) -> Self {
882 self.common.loading = loading;
883 self
884 }
885
886 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
888 self.on_activate = Some(Rc::new(handler));
889 self
890 }
891}
892
893impl RenderOnce for IconButton {
894 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
895 let (metrics, width) = self.common.size.icon_metrics(self.width);
896 let mut style = icon_appearance(self.variant, None, self.common.tone).style(
897 metrics,
898 self.common.shape.corner(metrics.square, false),
899 width,
900 );
901 style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
902 let content = if self.common.loading {
903 let tint = self
904 .common
905 .appearance
906 .colors
907 .content(self.common.disabled, false)
908 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
909 loading_icon_spinner(&self.common.id, metrics.icon, tint, window, cx)
910 } else {
911 icon_slot(self.icon, metrics.icon).into_any_element()
912 };
913 self.common
914 .render(content, style, Action::Invoke(self.on_activate), window, cx)
915 }
916}
917
918#[derive(IntoElement)]
921pub struct IconToggleButton {
922 common: Common,
923 icon: AnyElement,
924 selected_icon: Option<AnyElement>,
925 selected: bool,
926 variant: IconButtonVariant,
927 width: IconButtonWidth,
928 on_change: Option<Change>,
929}
930
931impl IconToggleButton {
932 pub fn new(
934 id: impl Into<ElementId>,
935 name: impl Into<SharedString>,
936 icon: impl IntoElement,
937 selected: bool,
938 ) -> Self {
939 Self {
940 common: Common::new(id, name),
941 icon: icon.into_any_element(),
942 selected_icon: None,
943 selected,
944 variant: IconButtonVariant::default(),
945 width: IconButtonWidth::default(),
946 on_change: None,
947 }
948 }
949
950 pub fn standard(
952 id: impl Into<ElementId>,
953 name: impl Into<SharedString>,
954 icon: impl IntoElement,
955 selected: bool,
956 ) -> Self {
957 Self::new(id, name, icon, selected).variant(IconButtonVariant::Standard)
958 }
959
960 pub fn filled(
962 id: impl Into<ElementId>,
963 name: impl Into<SharedString>,
964 icon: impl IntoElement,
965 selected: bool,
966 ) -> Self {
967 Self::new(id, name, icon, selected).variant(IconButtonVariant::Filled)
968 }
969
970 pub fn tonal(
972 id: impl Into<ElementId>,
973 name: impl Into<SharedString>,
974 icon: impl IntoElement,
975 selected: bool,
976 ) -> Self {
977 Self::new(id, name, icon, selected).variant(IconButtonVariant::FilledTonal)
978 }
979
980 pub fn outlined(
982 id: impl Into<ElementId>,
983 name: impl Into<SharedString>,
984 icon: impl IntoElement,
985 selected: bool,
986 ) -> Self {
987 Self::new(id, name, icon, selected).variant(IconButtonVariant::Outlined)
988 }
989
990 common_builders!();
991 appearance_builders!();
992
993 pub fn selected_icon(mut self, icon: impl IntoElement) -> Self {
995 self.selected_icon = Some(icon.into_any_element());
996 self
997 }
998
999 pub fn variant(mut self, variant: IconButtonVariant) -> Self {
1001 self.variant = variant;
1002 self
1003 }
1004
1005 pub fn width(mut self, width: IconButtonWidth) -> Self {
1007 self.width = width;
1008 self
1009 }
1010
1011 pub fn loading(mut self, loading: bool) -> Self {
1014 self.common.loading = loading;
1015 self
1016 }
1017
1018 pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
1020 self.on_change = Some(Rc::new(handler));
1021 self
1022 }
1023}
1024
1025impl RenderOnce for IconToggleButton {
1026 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
1027 let (metrics, width) = self.common.size.icon_metrics(self.width);
1028 let mut style = icon_appearance(self.variant, Some(self.selected), self.common.tone).style(
1029 metrics,
1030 self.common.shape.corner(metrics.square, false),
1031 width,
1032 );
1033 style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
1034 style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
1035 let content = if self.common.loading {
1036 let tint = self
1037 .common
1038 .appearance
1039 .colors
1040 .content(self.common.disabled, self.selected)
1041 .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
1042 loading_icon_spinner(&self.common.id, metrics.icon, tint, window, cx)
1043 } else {
1044 let icon = if self.selected {
1045 self.selected_icon.unwrap_or(self.icon)
1046 } else {
1047 self.icon
1048 };
1049 icon_slot(icon, metrics.icon).into_any_element()
1050 };
1051 self.common.render(
1052 content,
1053 style,
1054 Action::Toggle {
1055 selected: self.selected,
1056 on_change: self.on_change,
1057 },
1058 window,
1059 cx,
1060 )
1061 }
1062}
1063
1064#[cfg(test)]
1065mod tests {
1066 use super::*;
1067
1068 #[test]
1069 fn button_and_icon_button_variant_shorthands_set_expected_variants() {
1070 assert_eq!(
1071 Button::filled("b1", "Filled").variant,
1072 ButtonVariant::Filled
1073 );
1074 assert_eq!(
1075 Button::tonal("b2", "Tonal").variant,
1076 ButtonVariant::FilledTonal
1077 );
1078 assert_eq!(
1079 Button::elevated("b3", "Elevated").variant,
1080 ButtonVariant::Elevated
1081 );
1082 assert_eq!(
1083 Button::outlined("b4", "Outlined").variant,
1084 ButtonVariant::Outlined
1085 );
1086 assert_eq!(Button::text("b5", "Text").variant, ButtonVariant::Text);
1087
1088 assert_eq!(
1089 ToggleButton::filled("tb1", "Filled", true).variant,
1090 ToggleButtonVariant::Filled
1091 );
1092 assert_eq!(
1093 ToggleButton::tonal("tb2", "Tonal", false).variant,
1094 ToggleButtonVariant::FilledTonal
1095 );
1096 assert_eq!(
1097 ToggleButton::elevated("tb3", "Elevated", true).variant,
1098 ToggleButtonVariant::Elevated
1099 );
1100 assert_eq!(
1101 ToggleButton::outlined("tb4", "Outlined", false).variant,
1102 ToggleButtonVariant::Outlined
1103 );
1104
1105 assert_eq!(
1106 IconButton::standard("i1", "Std", div()).variant,
1107 IconButtonVariant::Standard
1108 );
1109 assert_eq!(
1110 IconButton::filled("i2", "Fill", div()).variant,
1111 IconButtonVariant::Filled
1112 );
1113 assert_eq!(
1114 IconButton::tonal("i3", "Tonal", div()).variant,
1115 IconButtonVariant::FilledTonal
1116 );
1117 assert_eq!(
1118 IconButton::outlined("i4", "Out", div()).variant,
1119 IconButtonVariant::Outlined
1120 );
1121
1122 assert_eq!(
1123 IconToggleButton::standard("it1", "Std", div(), false).variant,
1124 IconButtonVariant::Standard
1125 );
1126 assert_eq!(
1127 IconToggleButton::filled("it2", "Fill", div(), true).variant,
1128 IconButtonVariant::Filled
1129 );
1130 assert_eq!(
1131 IconToggleButton::tonal("it3", "Tonal", div(), false).variant,
1132 IconButtonVariant::FilledTonal
1133 );
1134 assert_eq!(
1135 IconToggleButton::outlined("it4", "Out", div(), true).variant,
1136 IconButtonVariant::Outlined
1137 );
1138
1139 let tone: ButtonTone = crate::SemanticTone::Danger;
1140 assert_eq!(tone, ButtonTone::Danger);
1141 }
1142
1143 #[test]
1144 fn compressed_button_shrinks_horizontal_padding_before_truncating_label() {
1145 let (left, right, label_width) =
1147 compress_horizontal_padding(px(16.), px(16.), px(54.), px(0.), px(28.));
1148 assert_eq!(left, px(13.));
1149 assert_eq!(right, px(13.));
1150 assert_eq!(label_width, px(28.));
1151
1152 let (left, right, label_width) =
1154 compress_horizontal_padding(px(16.), px(16.), px(72.), px(0.), px(28.));
1155 assert_eq!(left, px(16.));
1156 assert_eq!(right, px(16.));
1157 assert_eq!(label_width, px(40.));
1158
1159 let (left, right, label_width) =
1161 compress_horizontal_padding(px(16.), px(16.), px(30.), px(0.), px(28.));
1162 assert_eq!(left, px(4.));
1163 assert_eq!(right, px(4.));
1164 assert_eq!(label_width, px(22.));
1165
1166 let (left, right, label_width) =
1168 compress_horizontal_padding(px(2.), px(10.), px(30.), px(0.), px(28.));
1169 assert_eq!(left, px(2.));
1170 assert_eq!(right, px(4.));
1171 assert_eq!(label_width, px(24.));
1172 }
1173}