Skip to main content

gpui_material_components/
button.rs

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    // Button{XSmall,Small,Medium,Large,XLarge}Tokens in Compose Material 3 1.5.0-rc01.
41    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        // Expressive icon buttons have their own icon and horizontal space.
65        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)]
84pub enum ButtonShape {
85    #[default]
86    Round,
87    Square,
88}
89
90impl ButtonShape {
91    fn corner(self, square: CornerRole, invert: bool) -> CornerRole {
92        if (self == Self::Round) != invert {
93            CornerRole::Full
94        } else {
95            square
96        }
97    }
98}
99
100/// Semantic palette shortcut for Material buttons and icon buttons.
101/// Backwards-compatible alias for [`crate::SemanticTone`].
102/// Per-instance [`ButtonColors`] and [`ButtonBorder`] overrides still take precedence.
103pub type ButtonTone = crate::SemanticTone;
104
105#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
106pub enum ButtonVariant {
107    Elevated,
108    #[default]
109    Filled,
110    FilledTonal,
111    Outlined,
112    Text,
113}
114
115#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
116pub enum ToggleButtonVariant {
117    Elevated,
118    #[default]
119    Filled,
120    FilledTonal,
121    Outlined,
122}
123
124#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
125pub enum IconButtonVariant {
126    #[default]
127    Standard,
128    Filled,
129    FilledTonal,
130    Outlined,
131}
132
133#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
134pub enum IconButtonWidth {
135    Narrow,
136    #[default]
137    Uniform,
138    Wide,
139}
140
141struct Common {
142    id: ElementId,
143    label: SharedString,
144    disabled: bool,
145    loading: bool,
146    focus: Option<FocusHandle>,
147    interaction_source: Option<Entity<InteractionSource>>,
148    appearance: ButtonStyle,
149    size: ControlSize,
150    shape: ButtonShape,
151    tone: ButtonTone,
152}
153
154impl Common {
155    fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
156        Self {
157            id: id.into(),
158            label: label.into(),
159            disabled: false,
160            loading: false,
161            focus: None,
162            interaction_source: None,
163            appearance: ButtonStyle::default(),
164            size: ControlSize::default(),
165            shape: ButtonShape::default(),
166            tone: ButtonTone::default(),
167        }
168    }
169
170    fn render(
171        self,
172        content: AnyElement,
173        style: ActionStyle,
174        action: Action,
175        window: &mut Window,
176        cx: &mut App,
177    ) -> AnyElement {
178        self.render_scaled(content, style, action, 1., window, cx)
179    }
180
181    fn render_scaled(
182        self,
183        content: AnyElement,
184        style: ActionStyle,
185        action: Action,
186        scale: f32,
187        window: &mut Window,
188        cx: &mut App,
189    ) -> AnyElement {
190        ActionControl {
191            id: self.id,
192            label: self.label,
193            focus: self.focus,
194            disabled: self.disabled,
195            action,
196            style,
197            content,
198        }
199        .render_layout(
200            scale,
201            ActionLayout {
202                tab_stop: true,
203                loading: self.loading,
204                appearance: self.appearance,
205                ..Default::default()
206            },
207            self.interaction_source.as_ref(),
208            window,
209            cx,
210        )
211    }
212}
213
214// All four buttons expose the same shape, size, and focus contract.
215macro_rules! common_builders {
216    () => {
217        /// Sets the Material size tier. Small is the default.
218        pub fn size(mut self, size: ControlSize) -> Self {
219            self.common.size = size;
220            self
221        }
222
223        /// Sets the resting shape. Round is the default.
224        pub fn shape(mut self, shape: ButtonShape) -> Self {
225            self.common.shape = shape;
226            self
227        }
228
229        /// Applies a Material 3 semantic tone shortcut. Explicit `.colors` and `.border`
230        /// overrides still take precedence.
231        pub fn tone(mut self, tone: ButtonTone) -> Self {
232            self.common.tone = tone;
233            self
234        }
235
236        /// Controls availability and keyboard traversal.
237        pub fn disabled(mut self, disabled: bool) -> Self {
238            self.common.disabled = disabled;
239            self
240        }
241
242        /// Uses the caller's stable focus handle.
243        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
244            self.common.focus = Some(focus.clone());
245            self
246        }
247    };
248}
249
250#[derive(Default)]
251struct Slots {
252    leading: Option<AnyElement>,
253    trailing: Option<AnyElement>,
254    content: Option<AnyElement>,
255    padding: Option<ButtonPadding>,
256    width: Option<Pixels>,
257}
258
259impl Slots {
260    fn render(
261        self,
262        label: SharedString,
263        metrics: Metrics,
264        scale: f32,
265        window: &Window,
266        tint: gpui::Hsla,
267        cx: &App,
268    ) -> AnyElement {
269        let direction = current_material_theme(window, cx).layout.direction;
270        let typography = metrics.label.style(TypographyEmphasis::Baseline);
271        let max_padding = self.width.map_or_else(
272            || f32::from(window.viewport_size().width) * 0.125,
273            |width| (f32::from(width) - 16.).max(0.) / 2.,
274        );
275        let horizontal = px(metrics.padding.min(max_padding));
276        let ButtonPadding {
277            top,
278            end,
279            bottom,
280            start,
281        } = self.padding.unwrap_or(ButtonPadding {
282            top: px(4.),
283            end: horizontal,
284            bottom: px(4.),
285            start: horizontal,
286        });
287        let (left, right) = if direction == Direction::Rtl {
288            (end, start)
289        } else {
290            (start, end)
291        };
292        let icons = usize::from(self.leading.is_some()) + usize::from(self.trailing.is_some());
293        let label_width = self.width.map(|width| {
294            (width
295                - finite_length(left)
296                - finite_length(right)
297                - px((metrics.icon + metrics.gap) * icons as f32))
298            .max(px(0.))
299        });
300        let row_typography = current_material_theme(window, cx)
301            .typography
302            .scale_style(typography);
303        let mut row = div()
304            .flex()
305            .items_center()
306            .justify_center()
307            .min_w_0()
308            .max_w_full()
309            .gap(px(metrics.gap * scale))
310            .pl(finite_length(left) * scale)
311            .pr(finite_length(right) * scale)
312            .pt(finite_length(top) * scale)
313            .pb(finite_length(bottom) * scale)
314            .text_size(px(row_typography.size * scale))
315            .line_height(px(row_typography.line_height * scale));
316        if direction == Direction::Rtl {
317            row = row.flex_row_reverse();
318        }
319        if let Some(width) = self.width {
320            row = row.w(width).overflow_hidden();
321        }
322        row.children(
323            self.leading
324                .map(|icon| icon_slot(icon, metrics.icon * scale)),
325        )
326        .child(self.content.unwrap_or_else(|| {
327            crate::text::single_line(
328                label,
329                typography,
330                scale,
331                tint,
332                (label_width, 1., 1.),
333                window,
334                cx,
335            )
336            .into_any_element()
337        }))
338        .children(
339            self.trailing
340                .map(|icon| icon_slot(icon, metrics.icon * scale)),
341        )
342        .into_any_element()
343    }
344}
345
346macro_rules! appearance_builders {
347    () => {
348        /// Observes this button's interaction presentation through a caller-owned source.
349        /// The source does not handle input or change selection.
350        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
351            self.common.interaction_source = Some(source.clone());
352            self
353        }
354
355        /// Overrides state-specific corners. Unspecified states use the size and variant defaults.
356        pub fn shapes(mut self, shapes: ButtonShapes) -> Self {
357            self.common.appearance.shapes = shapes;
358            self
359        }
360
361        /// Overrides container and content colors for individual states.
362        pub fn colors(mut self, colors: ButtonColors) -> Self {
363            self.common.appearance.colors = colors;
364            self
365        }
366
367        /// Supplies a border in place of the variant's outline.
368        pub fn border(mut self, border: ButtonBorder) -> Self {
369            self.common.appearance.border = Some(border);
370            self
371        }
372    };
373}
374
375macro_rules! slot_builders {
376    () => {
377        /// Replaces the visible label with an element. The constructor's label
378        /// remains the accessible name. Keep interactive children outside the button.
379        pub fn content(mut self, content: impl IntoElement) -> Self {
380            self.slots.content = Some(content.into_any_element());
381            self
382        }
383
384        /// Sets logical insets around the label, content and icon slots.
385        pub fn content_padding(mut self, padding: ButtonPadding) -> Self {
386            self.slots.padding = Some(padding);
387            self
388        }
389
390        /// Overrides elevation levels for individual interaction states.
391        pub fn elevations(mut self, elevations: ButtonElevations) -> Self {
392            self.common.appearance.elevations = elevations;
393            self
394        }
395
396        /// Supplies a decorative leading icon in the Material icon slot.
397        pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
398            self.slots.leading = Some(icon.into_any_element());
399            self
400        }
401
402        /// Supplies a decorative trailing icon in the Material icon slot.
403        pub fn trailing_icon(mut self, icon: impl IntoElement) -> Self {
404            self.slots.trailing = Some(icon.into_any_element());
405            self
406        }
407    };
408}
409
410/// Internal composition hooks shared with the optional Material extras crate.
411#[doc(hidden)]
412pub mod composition;
413
414/// A labeled Material action. Activation uses Base's pointer, keyboard and
415/// accessibility behavior and invokes the application callback once.
416#[derive(IntoElement)]
417pub struct Button {
418    common: Common,
419    variant: ButtonVariant,
420    slots: Slots,
421    on_activate: Option<Activate>,
422    scale: f32,
423}
424
425impl Button {
426    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
427        Self {
428            common: Common::new(id, label),
429            variant: ButtonVariant::default(),
430            slots: Slots::default(),
431            on_activate: None,
432            scale: 1.,
433        }
434    }
435
436    /// Creates a Filled button.
437    pub fn filled(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
438        Self::new(id, label).variant(ButtonVariant::Filled)
439    }
440
441    /// Creates a Filled Tonal button.
442    pub fn tonal(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
443        Self::new(id, label).variant(ButtonVariant::FilledTonal)
444    }
445
446    /// Creates an Elevated button.
447    pub fn elevated(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
448        Self::new(id, label).variant(ButtonVariant::Elevated)
449    }
450
451    /// Creates an Outlined button.
452    pub fn outlined(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
453        Self::new(id, label).variant(ButtonVariant::Outlined)
454    }
455
456    /// Creates a Text button.
457    pub fn text(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
458        Self::new(id, label).variant(ButtonVariant::Text)
459    }
460
461    common_builders!();
462    appearance_builders!();
463    slot_builders!();
464
465    pub fn variant(mut self, variant: ButtonVariant) -> Self {
466        self.variant = variant;
467        self
468    }
469
470    /// Shows a centered inline circular spinner while suppressing activation and preserving the
471    /// button's resting width. Keeps the active palette unless `.disabled(true)` is also set.
472    pub fn loading(mut self, loading: bool) -> Self {
473        self.common.loading = loading;
474        self
475    }
476
477    #[cfg(feature = "feedback")]
478    pub(crate) fn scale(mut self, scale: f32) -> Self {
479        self.scale = scale;
480        self
481    }
482
483    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
484        self.on_activate = Some(Rc::new(handler));
485        self
486    }
487}
488
489impl RenderOnce for Button {
490    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
491        let metrics = self.common.size.metrics();
492        let appearance = button_appearance(self.variant, None, self.common.tone);
493        let style = appearance.style(
494            metrics,
495            self.common.shape.corner(metrics.square, false),
496            58.,
497        );
498        let tint = self
499            .common
500            .appearance
501            .colors
502            .content(self.common.disabled, false)
503            .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
504        let resting_content = self.slots.render(
505            self.common.label.clone(),
506            metrics,
507            self.scale,
508            window,
509            tint,
510            cx,
511        );
512        let content = if self.common.loading {
513            div()
514                .relative()
515                .flex()
516                .items_center()
517                .justify_center()
518                .child(div().opacity(0.).child(resting_content))
519                .child(
520                    div()
521                        .id((self.common.id.clone(), "loading-spinner"))
522                        .test_support()
523                        .absolute()
524                        .inset_0()
525                        .flex()
526                        .items_center()
527                        .justify_center()
528                        .child(render_loading_spinner(
529                            &self.common.id,
530                            metrics.icon * self.scale,
531                            tint,
532                            window,
533                            cx,
534                        )),
535                )
536                .into_any_element()
537        } else {
538            resting_content
539        };
540        self.common.render_scaled(
541            content,
542            style,
543            Action::Invoke(self.on_activate),
544            self.scale,
545            window,
546            cx,
547        )
548    }
549}
550
551/// A controlled labeled toggle. The caller re-renders with the selected value
552/// after accepting a requested change.
553#[derive(IntoElement)]
554pub struct ToggleButton {
555    common: Common,
556    variant: ToggleButtonVariant,
557    selected: bool,
558    slots: Slots,
559    on_change: Option<Change>,
560}
561
562impl ToggleButton {
563    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, selected: bool) -> Self {
564        Self {
565            common: Common::new(id, label),
566            variant: ToggleButtonVariant::default(),
567            selected,
568            slots: Slots::default(),
569            on_change: None,
570        }
571    }
572
573    common_builders!();
574    appearance_builders!();
575    slot_builders!();
576
577    pub fn variant(mut self, variant: ToggleButtonVariant) -> Self {
578        self.variant = variant;
579        self
580    }
581
582    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
583        self.on_change = Some(Rc::new(handler));
584        self
585    }
586}
587
588impl RenderOnce for ToggleButton {
589    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
590        let metrics = self.common.size.metrics();
591        let variant = match self.variant {
592            ToggleButtonVariant::Elevated => ButtonVariant::Elevated,
593            ToggleButtonVariant::Filled => ButtonVariant::Filled,
594            ToggleButtonVariant::FilledTonal => ButtonVariant::FilledTonal,
595            ToggleButtonVariant::Outlined => ButtonVariant::Outlined,
596        };
597        let mut style = button_appearance(variant, Some(self.selected), self.common.tone).style(
598            metrics,
599            self.common.shape.corner(metrics.square, false),
600            0.,
601        );
602        style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
603        let content = self.slots.render(
604            self.common.label.clone(),
605            metrics,
606            1.,
607            window,
608            self.common
609                .appearance
610                .colors
611                .content(self.common.disabled, self.selected)
612                .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx)),
613            cx,
614        );
615        self.common.render(
616            content,
617            style,
618            Action::Toggle {
619                selected: self.selected,
620                on_change: self.on_change,
621            },
622            window,
623            cx,
624        )
625    }
626}
627
628/// An icon-only action with a required accessibility name.
629#[derive(IntoElement)]
630pub struct IconButton {
631    common: Common,
632    icon: AnyElement,
633    variant: IconButtonVariant,
634    width: IconButtonWidth,
635    on_activate: Option<Activate>,
636}
637
638impl IconButton {
639    pub fn new(
640        id: impl Into<ElementId>,
641        name: impl Into<SharedString>,
642        icon: impl IntoElement,
643    ) -> Self {
644        Self {
645            common: Common::new(id, name),
646            icon: icon.into_any_element(),
647            variant: IconButtonVariant::default(),
648            width: IconButtonWidth::default(),
649            on_activate: None,
650        }
651    }
652
653    /// Creates a Standard icon button.
654    pub fn standard(
655        id: impl Into<ElementId>,
656        name: impl Into<SharedString>,
657        icon: impl IntoElement,
658    ) -> Self {
659        Self::new(id, name, icon).variant(IconButtonVariant::Standard)
660    }
661
662    /// Creates a Filled icon button.
663    pub fn filled(
664        id: impl Into<ElementId>,
665        name: impl Into<SharedString>,
666        icon: impl IntoElement,
667    ) -> Self {
668        Self::new(id, name, icon).variant(IconButtonVariant::Filled)
669    }
670
671    /// Creates a Filled Tonal icon button.
672    pub fn tonal(
673        id: impl Into<ElementId>,
674        name: impl Into<SharedString>,
675        icon: impl IntoElement,
676    ) -> Self {
677        Self::new(id, name, icon).variant(IconButtonVariant::FilledTonal)
678    }
679
680    /// Creates an Outlined icon button.
681    pub fn outlined(
682        id: impl Into<ElementId>,
683        name: impl Into<SharedString>,
684        icon: impl IntoElement,
685    ) -> Self {
686        Self::new(id, name, icon).variant(IconButtonVariant::Outlined)
687    }
688
689    common_builders!();
690    appearance_builders!();
691
692    pub fn variant(mut self, variant: IconButtonVariant) -> Self {
693        self.variant = variant;
694        self
695    }
696
697    pub fn width(mut self, width: IconButtonWidth) -> Self {
698        self.width = width;
699        self
700    }
701
702    /// Shows an inline circular spinner in place of the icon while suppressing activation.
703    /// Keeps the active palette unless `.disabled(true)` is also set.
704    pub fn loading(mut self, loading: bool) -> Self {
705        self.common.loading = loading;
706        self
707    }
708
709    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
710        self.on_activate = Some(Rc::new(handler));
711        self
712    }
713}
714
715impl RenderOnce for IconButton {
716    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
717        let (metrics, width) = self.common.size.icon_metrics(self.width);
718        let mut style = icon_appearance(self.variant, None, self.common.tone).style(
719            metrics,
720            self.common.shape.corner(metrics.square, false),
721            width,
722        );
723        style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
724        let content = if self.common.loading {
725            let tint = self
726                .common
727                .appearance
728                .colors
729                .content(self.common.disabled, false)
730                .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx));
731            div()
732                .id((self.common.id.clone(), "loading-spinner"))
733                .test_support()
734                .flex()
735                .items_center()
736                .justify_center()
737                .child(render_loading_spinner(
738                    &self.common.id,
739                    metrics.icon,
740                    tint,
741                    window,
742                    cx,
743                ))
744                .into_any_element()
745        } else {
746            icon_slot(self.icon, metrics.icon).into_any_element()
747        };
748        self.common
749            .render(content, style, Action::Invoke(self.on_activate), window, cx)
750    }
751}
752
753/// An icon-only controlled toggle. The selected icon and native toggle state
754/// both reflect the caller's value.
755#[derive(IntoElement)]
756pub struct IconToggleButton {
757    common: Common,
758    icon: AnyElement,
759    selected_icon: Option<AnyElement>,
760    selected: bool,
761    variant: IconButtonVariant,
762    width: IconButtonWidth,
763    on_change: Option<Change>,
764}
765
766impl IconToggleButton {
767    pub fn new(
768        id: impl Into<ElementId>,
769        name: impl Into<SharedString>,
770        icon: impl IntoElement,
771        selected: bool,
772    ) -> Self {
773        Self {
774            common: Common::new(id, name),
775            icon: icon.into_any_element(),
776            selected_icon: None,
777            selected,
778            variant: IconButtonVariant::default(),
779            width: IconButtonWidth::default(),
780            on_change: None,
781        }
782    }
783
784    common_builders!();
785    appearance_builders!();
786
787    pub fn selected_icon(mut self, icon: impl IntoElement) -> Self {
788        self.selected_icon = Some(icon.into_any_element());
789        self
790    }
791
792    pub fn variant(mut self, variant: IconButtonVariant) -> Self {
793        self.variant = variant;
794        self
795    }
796
797    pub fn width(mut self, width: IconButtonWidth) -> Self {
798        self.width = width;
799        self
800    }
801
802    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
803        self.on_change = Some(Rc::new(handler));
804        self
805    }
806}
807
808impl RenderOnce for IconToggleButton {
809    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
810        let (metrics, width) = self.common.size.icon_metrics(self.width);
811        let mut style = icon_appearance(self.variant, Some(self.selected), self.common.tone).style(
812            metrics,
813            self.common.shape.corner(metrics.square, false),
814            width,
815        );
816        style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
817        style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
818        let icon = if self.selected {
819            self.selected_icon.unwrap_or(self.icon)
820        } else {
821            self.icon
822        };
823        self.common.render(
824            icon_slot(icon, metrics.icon).into_any_element(),
825            style,
826            Action::Toggle {
827                selected: self.selected,
828                on_change: self.on_change,
829            },
830            window,
831            cx,
832        )
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839
840    #[test]
841    fn button_and_icon_button_variant_shorthands_set_expected_variants() {
842        assert_eq!(
843            Button::filled("b1", "Filled").variant,
844            ButtonVariant::Filled
845        );
846        assert_eq!(
847            Button::tonal("b2", "Tonal").variant,
848            ButtonVariant::FilledTonal
849        );
850        assert_eq!(
851            Button::elevated("b3", "Elevated").variant,
852            ButtonVariant::Elevated
853        );
854        assert_eq!(
855            Button::outlined("b4", "Outlined").variant,
856            ButtonVariant::Outlined
857        );
858        assert_eq!(Button::text("b5", "Text").variant, ButtonVariant::Text);
859
860        assert_eq!(
861            IconButton::standard("i1", "Std", div()).variant,
862            IconButtonVariant::Standard
863        );
864        assert_eq!(
865            IconButton::filled("i2", "Fill", div()).variant,
866            IconButtonVariant::Filled
867        );
868        assert_eq!(
869            IconButton::tonal("i3", "Tonal", div()).variant,
870            IconButtonVariant::FilledTonal
871        );
872        assert_eq!(
873            IconButton::outlined("i4", "Out", div()).variant,
874            IconButtonVariant::Outlined
875        );
876
877        let tone: ButtonTone = crate::SemanticTone::Danger;
878        assert_eq!(tone, ButtonTone::Danger);
879    }
880}