Skip to main content

gpui_material_components/
button.rs

1mod appearance;
2
3use std::rc::Rc;
4
5use gpui::{
6    AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, ParentElement, Pixels,
7    RenderOnce, SharedString, Styled, Window, div, px,
8};
9use gpui_material_foundation::{InteractionSource, current_material_theme};
10use gpui_material_theme::{
11    CornerRole, Direction, MotionKind, MotionSpeed, TypeRole, TypographyEmphasis,
12};
13
14use crate::action::{
15    Action, ActionControl, ActionLayout, ActionStyle, Activate, Change, SegmentShape, icon_slot,
16};
17use crate::button_style::{
18    ButtonBorder, ButtonColors, ButtonElevations, ButtonPadding, ButtonShapes, ButtonStyle,
19    ControlSize, finite_length,
20};
21
22use appearance::{button_appearance, icon_appearance};
23
24#[derive(Clone, Copy)]
25struct Metrics {
26    height: f32,
27    icon: f32,
28    gap: f32,
29    padding: f32,
30    outline: f32,
31    square: CornerRole,
32    pressed: CornerRole,
33    label: TypeRole,
34}
35
36impl ControlSize {
37    // Button{XSmall,Small,Medium,Large,XLarge}Tokens in Compose Material 3 1.5.0-rc01.
38    fn metrics(self) -> Metrics {
39        use CornerRole::*;
40        use TypeRole::*;
41        let (height, icon, gap, padding, outline, square, pressed, label) = match self {
42            Self::ExtraSmall => (32., 20., 8., 16., 1., Medium, Small, LabelLarge),
43            Self::Small => (40., 20., 8., 16., 1., Medium, Small, LabelLarge),
44            Self::Medium => (56., 24., 8., 24., 1., Large, Medium, TitleMedium),
45            Self::Large => (96., 32., 12., 48., 2., ExtraLarge, Large, HeadlineSmall),
46            Self::ExtraLarge => (136., 40., 16., 64., 3., ExtraLarge, Large, HeadlineLarge),
47        };
48        Metrics {
49            height,
50            icon,
51            gap,
52            padding,
53            outline,
54            square,
55            pressed,
56            label,
57        }
58    }
59
60    fn icon_metrics(self, width: IconButtonWidth) -> (Metrics, f32) {
61        // Expressive icon buttons have their own icon and horizontal space.
62        let mut metrics = self.metrics();
63        let (icon, narrow, uniform, wide) = match self {
64            Self::ExtraSmall => (20., 4., 6., 10.),
65            Self::Small => (24., 4., 8., 14.),
66            Self::Medium => (24., 12., 16., 24.),
67            Self::Large => (32., 16., 32., 48.),
68            Self::ExtraLarge => (40., 32., 48., 72.),
69        };
70        metrics.icon = icon;
71        let space = match width {
72            IconButtonWidth::Narrow => narrow,
73            IconButtonWidth::Uniform => uniform,
74            IconButtonWidth::Wide => wide,
75        };
76        (metrics, icon + 2. * space)
77    }
78}
79
80#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
81pub enum ButtonShape {
82    #[default]
83    Round,
84    Square,
85}
86
87impl ButtonShape {
88    fn corner(self, square: CornerRole, invert: bool) -> CornerRole {
89        if (self == Self::Round) != invert {
90            CornerRole::Full
91        } else {
92            square
93        }
94    }
95}
96
97#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
98pub enum ButtonVariant {
99    Elevated,
100    #[default]
101    Filled,
102    FilledTonal,
103    Outlined,
104    Text,
105}
106
107#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
108pub enum ToggleButtonVariant {
109    Elevated,
110    #[default]
111    Filled,
112    FilledTonal,
113    Outlined,
114}
115
116#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
117pub enum IconButtonVariant {
118    #[default]
119    Standard,
120    Filled,
121    FilledTonal,
122    Outlined,
123}
124
125#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
126pub enum IconButtonWidth {
127    Narrow,
128    #[default]
129    Uniform,
130    Wide,
131}
132
133struct Common {
134    id: ElementId,
135    label: SharedString,
136    disabled: bool,
137    focus: Option<FocusHandle>,
138    interaction_source: Option<Entity<InteractionSource>>,
139    appearance: ButtonStyle,
140    size: ControlSize,
141    shape: ButtonShape,
142}
143
144impl Common {
145    fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
146        Self {
147            id: id.into(),
148            label: label.into(),
149            disabled: false,
150            focus: None,
151            interaction_source: None,
152            appearance: ButtonStyle::default(),
153            size: ControlSize::default(),
154            shape: ButtonShape::default(),
155        }
156    }
157
158    fn render(
159        self,
160        content: AnyElement,
161        style: ActionStyle,
162        action: Action,
163        window: &mut Window,
164        cx: &mut App,
165    ) -> AnyElement {
166        self.render_scaled(content, style, action, 1., window, cx)
167    }
168
169    fn render_scaled(
170        self,
171        content: AnyElement,
172        style: ActionStyle,
173        action: Action,
174        scale: f32,
175        window: &mut Window,
176        cx: &mut App,
177    ) -> AnyElement {
178        ActionControl {
179            id: self.id,
180            label: self.label,
181            focus: self.focus,
182            disabled: self.disabled,
183            action,
184            style,
185            content,
186        }
187        .render_scaled(
188            scale,
189            self.interaction_source.as_ref(),
190            self.appearance,
191            window,
192            cx,
193        )
194    }
195}
196
197// All four buttons expose the same shape, size, and focus contract.
198macro_rules! common_builders {
199    () => {
200        /// Sets the Material size tier. Small is the default.
201        pub fn size(mut self, size: ControlSize) -> Self {
202            self.common.size = size;
203            self
204        }
205
206        /// Sets the resting shape. Round is the default.
207        pub fn shape(mut self, shape: ButtonShape) -> Self {
208            self.common.shape = shape;
209            self
210        }
211
212        /// Controls availability and keyboard traversal.
213        pub fn disabled(mut self, disabled: bool) -> Self {
214            self.common.disabled = disabled;
215            self
216        }
217
218        /// Uses the caller's stable focus handle.
219        pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
220            self.common.focus = Some(focus.clone());
221            self
222        }
223    };
224}
225
226#[derive(Default)]
227struct Slots {
228    leading: Option<AnyElement>,
229    trailing: Option<AnyElement>,
230    content: Option<AnyElement>,
231    padding: Option<ButtonPadding>,
232    width: Option<Pixels>,
233}
234
235impl Slots {
236    fn render(
237        self,
238        label: SharedString,
239        metrics: Metrics,
240        scale: f32,
241        window: &Window,
242        tint: gpui::Hsla,
243        cx: &App,
244    ) -> AnyElement {
245        let direction = current_material_theme(window, cx).layout.direction;
246        let typography = metrics.label.style(TypographyEmphasis::Baseline);
247        let max_padding = self.width.map_or_else(
248            || f32::from(window.viewport_size().width) * 0.125,
249            |width| (f32::from(width) - 16.).max(0.) / 2.,
250        );
251        let horizontal = px(metrics.padding.min(max_padding));
252        let ButtonPadding {
253            top,
254            end,
255            bottom,
256            start,
257        } = self.padding.unwrap_or(ButtonPadding {
258            top: px(4.),
259            end: horizontal,
260            bottom: px(4.),
261            start: horizontal,
262        });
263        let (left, right) = if direction == Direction::Rtl {
264            (end, start)
265        } else {
266            (start, end)
267        };
268        let icons = usize::from(self.leading.is_some()) + usize::from(self.trailing.is_some());
269        let label_width = self.width.map(|width| {
270            (width
271                - finite_length(left)
272                - finite_length(right)
273                - px((metrics.icon + metrics.gap) * icons as f32))
274            .max(px(0.))
275        });
276        let row_typography = current_material_theme(window, cx)
277            .typography
278            .scale_style(typography);
279        let mut row = div()
280            .flex()
281            .items_center()
282            .justify_center()
283            .min_w_0()
284            .max_w_full()
285            .gap(px(metrics.gap * scale))
286            .pl(finite_length(left) * scale)
287            .pr(finite_length(right) * scale)
288            .pt(finite_length(top) * scale)
289            .pb(finite_length(bottom) * scale)
290            .text_size(px(row_typography.size * scale))
291            .line_height(px(row_typography.line_height * scale));
292        if direction == Direction::Rtl {
293            row = row.flex_row_reverse();
294        }
295        if let Some(width) = self.width {
296            row = row.w(width).overflow_hidden();
297        }
298        row.children(
299            self.leading
300                .map(|icon| icon_slot(icon, metrics.icon * scale)),
301        )
302        .child(self.content.unwrap_or_else(|| {
303            crate::text::single_line(
304                label,
305                typography,
306                scale,
307                tint,
308                (label_width, 1., 1.),
309                window,
310                cx,
311            )
312            .into_any_element()
313        }))
314        .children(
315            self.trailing
316                .map(|icon| icon_slot(icon, metrics.icon * scale)),
317        )
318        .into_any_element()
319    }
320}
321
322macro_rules! appearance_builders {
323    () => {
324        /// Observes this button's interaction presentation through a caller-owned source.
325        /// The source does not handle input or change selection.
326        pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
327            self.common.interaction_source = Some(source.clone());
328            self
329        }
330
331        /// Overrides state-specific corners. Unspecified states use the size and variant defaults.
332        pub fn shapes(mut self, shapes: ButtonShapes) -> Self {
333            self.common.appearance.shapes = shapes;
334            self
335        }
336
337        /// Overrides container and content colors for individual states.
338        pub fn colors(mut self, colors: ButtonColors) -> Self {
339            self.common.appearance.colors = colors;
340            self
341        }
342
343        /// Supplies a border in place of the variant's outline.
344        pub fn border(mut self, border: ButtonBorder) -> Self {
345            self.common.appearance.border = Some(border);
346            self
347        }
348    };
349}
350
351macro_rules! slot_builders {
352    () => {
353        /// Replaces the visible label with an element. The constructor's label
354        /// remains the accessible name. Keep interactive children outside the button.
355        pub fn content(mut self, content: impl IntoElement) -> Self {
356            self.slots.content = Some(content.into_any_element());
357            self
358        }
359
360        /// Sets logical insets around the label, content and icon slots.
361        pub fn content_padding(mut self, padding: ButtonPadding) -> Self {
362            self.slots.padding = Some(padding);
363            self
364        }
365
366        /// Overrides elevation levels for individual interaction states.
367        pub fn elevations(mut self, elevations: ButtonElevations) -> Self {
368            self.common.appearance.elevations = elevations;
369            self
370        }
371
372        /// Supplies a decorative leading icon in the Material icon slot.
373        pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
374            self.slots.leading = Some(icon.into_any_element());
375            self
376        }
377
378        /// Supplies a decorative trailing icon in the Material icon slot.
379        pub fn trailing_icon(mut self, icon: impl IntoElement) -> Self {
380            self.slots.trailing = Some(icon.into_any_element());
381            self
382        }
383    };
384}
385
386/// Internal composition hooks shared with the optional Material extras crate.
387#[doc(hidden)]
388pub mod composition;
389
390/// A labeled Material action. Activation uses Base's pointer, keyboard and
391/// accessibility behavior and invokes the application callback once.
392#[derive(IntoElement)]
393pub struct Button {
394    common: Common,
395    variant: ButtonVariant,
396    slots: Slots,
397    on_activate: Option<Activate>,
398    scale: f32,
399}
400
401impl Button {
402    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
403        Self {
404            common: Common::new(id, label),
405            variant: ButtonVariant::default(),
406            slots: Slots::default(),
407            on_activate: None,
408            scale: 1.,
409        }
410    }
411
412    common_builders!();
413    appearance_builders!();
414    slot_builders!();
415
416    pub fn variant(mut self, variant: ButtonVariant) -> Self {
417        self.variant = variant;
418        self
419    }
420
421    #[cfg(feature = "feedback")]
422    pub(crate) fn scale(mut self, scale: f32) -> Self {
423        self.scale = scale;
424        self
425    }
426
427    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
428        self.on_activate = Some(Rc::new(handler));
429        self
430    }
431}
432
433impl RenderOnce for Button {
434    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
435        let metrics = self.common.size.metrics();
436        let appearance = button_appearance(self.variant, None);
437        let style = appearance.style(
438            metrics,
439            self.common.shape.corner(metrics.square, false),
440            58.,
441        );
442        let content = self.slots.render(
443            self.common.label.clone(),
444            metrics,
445            self.scale,
446            window,
447            self.common
448                .appearance
449                .colors
450                .content(self.common.disabled, false)
451                .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx)),
452            cx,
453        );
454        self.common.render_scaled(
455            content,
456            style,
457            Action::Invoke(self.on_activate),
458            self.scale,
459            window,
460            cx,
461        )
462    }
463}
464
465/// A controlled labeled toggle. The caller re-renders with the selected value
466/// after accepting a requested change.
467#[derive(IntoElement)]
468pub struct ToggleButton {
469    common: Common,
470    variant: ToggleButtonVariant,
471    selected: bool,
472    slots: Slots,
473    on_change: Option<Change>,
474}
475
476impl ToggleButton {
477    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, selected: bool) -> Self {
478        Self {
479            common: Common::new(id, label),
480            variant: ToggleButtonVariant::default(),
481            selected,
482            slots: Slots::default(),
483            on_change: None,
484        }
485    }
486
487    common_builders!();
488    appearance_builders!();
489    slot_builders!();
490
491    pub fn variant(mut self, variant: ToggleButtonVariant) -> Self {
492        self.variant = variant;
493        self
494    }
495
496    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
497        self.on_change = Some(Rc::new(handler));
498        self
499    }
500}
501
502impl RenderOnce for ToggleButton {
503    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
504        let metrics = self.common.size.metrics();
505        let variant = match self.variant {
506            ToggleButtonVariant::Elevated => ButtonVariant::Elevated,
507            ToggleButtonVariant::Filled => ButtonVariant::Filled,
508            ToggleButtonVariant::FilledTonal => ButtonVariant::FilledTonal,
509            ToggleButtonVariant::Outlined => ButtonVariant::Outlined,
510        };
511        let mut style = button_appearance(variant, Some(self.selected)).style(
512            metrics,
513            self.common.shape.corner(metrics.square, false),
514            0.,
515        );
516        style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
517        let content = self.slots.render(
518            self.common.label.clone(),
519            metrics,
520            1.,
521            window,
522            self.common
523                .appearance
524                .colors
525                .content(self.common.disabled, self.selected)
526                .unwrap_or_else(|| style.foreground(self.common.disabled, window, cx)),
527            cx,
528        );
529        self.common.render(
530            content,
531            style,
532            Action::Toggle {
533                selected: self.selected,
534                on_change: self.on_change,
535            },
536            window,
537            cx,
538        )
539    }
540}
541
542/// An icon-only action with a required accessibility name.
543#[derive(IntoElement)]
544pub struct IconButton {
545    common: Common,
546    icon: AnyElement,
547    variant: IconButtonVariant,
548    width: IconButtonWidth,
549    on_activate: Option<Activate>,
550}
551
552impl IconButton {
553    pub fn new(
554        id: impl Into<ElementId>,
555        name: impl Into<SharedString>,
556        icon: impl IntoElement,
557    ) -> Self {
558        Self {
559            common: Common::new(id, name),
560            icon: icon.into_any_element(),
561            variant: IconButtonVariant::default(),
562            width: IconButtonWidth::default(),
563            on_activate: None,
564        }
565    }
566
567    common_builders!();
568    appearance_builders!();
569
570    pub fn variant(mut self, variant: IconButtonVariant) -> Self {
571        self.variant = variant;
572        self
573    }
574
575    pub fn width(mut self, width: IconButtonWidth) -> Self {
576        self.width = width;
577        self
578    }
579
580    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
581        self.on_activate = Some(Rc::new(handler));
582        self
583    }
584}
585
586impl RenderOnce for IconButton {
587    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
588        let (metrics, width) = self.common.size.icon_metrics(self.width);
589        let mut style = icon_appearance(self.variant, None).style(
590            metrics,
591            self.common.shape.corner(metrics.square, false),
592            width,
593        );
594        style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
595        self.common.render(
596            icon_slot(self.icon, metrics.icon).into_any_element(),
597            style,
598            Action::Invoke(self.on_activate),
599            window,
600            cx,
601        )
602    }
603}
604
605/// An icon-only controlled toggle. The selected icon and native toggle state
606/// both reflect the caller's value.
607#[derive(IntoElement)]
608pub struct IconToggleButton {
609    common: Common,
610    icon: AnyElement,
611    selected_icon: Option<AnyElement>,
612    selected: bool,
613    variant: IconButtonVariant,
614    width: IconButtonWidth,
615    on_change: Option<Change>,
616}
617
618impl IconToggleButton {
619    pub fn new(
620        id: impl Into<ElementId>,
621        name: impl Into<SharedString>,
622        icon: impl IntoElement,
623        selected: bool,
624    ) -> Self {
625        Self {
626            common: Common::new(id, name),
627            icon: icon.into_any_element(),
628            selected_icon: None,
629            selected,
630            variant: IconButtonVariant::default(),
631            width: IconButtonWidth::default(),
632            on_change: None,
633        }
634    }
635
636    common_builders!();
637    appearance_builders!();
638
639    pub fn selected_icon(mut self, icon: impl IntoElement) -> Self {
640        self.selected_icon = Some(icon.into_any_element());
641        self
642    }
643
644    pub fn variant(mut self, variant: IconButtonVariant) -> Self {
645        self.variant = variant;
646        self
647    }
648
649    pub fn width(mut self, width: IconButtonWidth) -> Self {
650        self.width = width;
651        self
652    }
653
654    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
655        self.on_change = Some(Rc::new(handler));
656        self
657    }
658}
659
660impl RenderOnce for IconToggleButton {
661    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
662        let (metrics, width) = self.common.size.icon_metrics(self.width);
663        let mut style = icon_appearance(self.variant, Some(self.selected)).style(
664            metrics,
665            self.common.shape.corner(metrics.square, false),
666            width,
667        );
668        style.selected_corner = Some(self.common.shape.corner(metrics.square, true));
669        style.corner_motion = (MotionKind::Effects, MotionSpeed::Default);
670        let icon = if self.selected {
671            self.selected_icon.unwrap_or(self.icon)
672        } else {
673            self.icon
674        };
675        self.common.render(
676            icon_slot(icon, metrics.icon).into_any_element(),
677            style,
678            Action::Toggle {
679                selected: self.selected,
680                on_change: self.on_change,
681            },
682            window,
683            cx,
684        )
685    }
686}