Skip to main content

gpui_component/button/
button.rs

1use std::rc::Rc;
2
3use crate::ThemeStyled as _;
4use crate::{
5    ActiveTheme, Colorize as _, Disableable, Icon, RoleOverride, Selectable, Sizable, Size,
6    StyleSized, StyledExt,
7    button::ButtonIcon,
8    h_flex,
9    select::Caret,
10    tooltip::{ManagedTooltipExt as _, Tooltip},
11};
12use gpui::{
13    AnyElement, App, Background, ClickEvent, Corners, Edges, ElementId, Hsla, InteractiveElement,
14    Interactivity, IntoElement, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString,
15    StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
16    prelude::FluentBuilder as _, relative, transparent_white,
17};
18
19#[derive(Default, Clone, Copy)]
20pub enum ButtonRounded {
21    None,
22    Small,
23    #[default]
24    Medium,
25    Large,
26    Size(Pixels),
27}
28
29impl From<Pixels> for ButtonRounded {
30    fn from(px: Pixels) -> Self {
31        ButtonRounded::Size(px)
32    }
33}
34
35#[derive(Clone, Copy, PartialEq, Debug)]
36pub struct ButtonCustomVariant {
37    color: Hsla,
38    foreground: Hsla,
39    shadow: bool,
40    hover: Hsla,
41    active: Hsla,
42}
43
44pub trait ButtonVariants: Sized {
45    fn with_variant(self, variant: ButtonVariant) -> Self;
46
47    /// With the primary style for the Button.
48    fn primary(self) -> Self {
49        self.with_variant(ButtonVariant::Primary)
50    }
51
52    /// With the secondary style for the Button.
53    fn secondary(self) -> Self {
54        self.with_variant(ButtonVariant::Secondary)
55    }
56
57    /// With the danger style for the Button.
58    fn danger(self) -> Self {
59        self.with_variant(ButtonVariant::Danger)
60    }
61
62    /// With the warning style for the Button.
63    fn warning(self) -> Self {
64        self.with_variant(ButtonVariant::Warning)
65    }
66
67    /// With the success style for the Button.
68    fn success(self) -> Self {
69        self.with_variant(ButtonVariant::Success)
70    }
71
72    /// With the info style for the Button.
73    fn info(self) -> Self {
74        self.with_variant(ButtonVariant::Info)
75    }
76
77    /// With the ghost style for the Button.
78    fn ghost(self) -> Self {
79        self.with_variant(ButtonVariant::Ghost)
80    }
81
82    /// With the link style for the Button.
83    fn link(self) -> Self {
84        self.with_variant(ButtonVariant::Link)
85    }
86
87    /// With the text style for the Button, it will no padding look like a normal text.
88    fn text(self) -> Self {
89        self.with_variant(ButtonVariant::Text)
90    }
91
92    /// With the custom style for the Button.
93    fn custom(self, style: ButtonCustomVariant) -> Self {
94        self.with_variant(ButtonVariant::Custom(style))
95    }
96}
97
98impl ButtonCustomVariant {
99    pub fn new(cx: &App) -> Self {
100        Self {
101            color: cx.theme().transparent,
102            foreground: cx.theme().foreground,
103            hover: cx.theme().transparent,
104            active: cx.theme().transparent,
105            shadow: false,
106        }
107    }
108
109    /// Set background color, default is transparent.
110    pub fn color(mut self, color: Hsla) -> Self {
111        self.color = color;
112        self
113    }
114
115    /// Set foreground color, default is theme foreground.
116    pub fn foreground(mut self, color: Hsla) -> Self {
117        self.foreground = color;
118        self
119    }
120
121    /// Set hover background color, default is transparent.
122    pub fn hover(mut self, color: Hsla) -> Self {
123        self.hover = color;
124        self
125    }
126
127    /// Set active background color, default is transparent.
128    pub fn active(mut self, color: Hsla) -> Self {
129        self.active = color;
130        self
131    }
132
133    /// Set shadow, default is false.
134    pub fn shadow(mut self, shadow: bool) -> Self {
135        self.shadow = shadow;
136        self
137    }
138}
139
140/// The variant of the Button.
141#[derive(Clone, Copy, PartialEq, Default, Debug)]
142pub enum ButtonVariant {
143    #[default]
144    Default,
145    Primary,
146    Secondary,
147    Danger,
148    Info,
149    Success,
150    Warning,
151    Ghost,
152    Link,
153    Text,
154    Custom(ButtonCustomVariant),
155}
156
157impl ButtonVariant {
158    #[inline]
159    pub fn is_link(&self) -> bool {
160        matches!(self, Self::Link)
161    }
162
163    #[inline]
164    pub fn is_text(&self) -> bool {
165        matches!(self, Self::Text)
166    }
167
168    #[inline]
169    pub fn is_ghost(&self) -> bool {
170        matches!(self, Self::Ghost)
171    }
172
173    #[inline]
174    fn no_padding(&self) -> bool {
175        self.is_link() || self.is_text()
176    }
177
178    #[inline]
179    fn is_default(&self) -> bool {
180        matches!(self, Self::Default)
181    }
182}
183
184/// A Button element.
185#[derive(IntoElement)]
186pub struct Button {
187    id: ElementId,
188    base: gpui_base::Button,
189    icon: Option<ButtonIcon>,
190    label: Option<SharedString>,
191    /// The announced name, when the visible content is not it.
192    accessibility_label: Option<SharedString>,
193    children: Vec<AnyElement>,
194    disabled: bool,
195    pub(crate) selected: bool,
196    toggled: Option<bool>,
197    role: RoleOverride,
198    variant: ButtonVariant,
199    rounded: ButtonRounded,
200    outline: bool,
201    border_corners: Corners<bool>,
202    border_edges: Edges<bool>,
203    dropdown_caret: bool,
204    size: Size,
205    compact: bool,
206    tooltip: Option<(
207        SharedString,
208        Option<(Rc<Box<dyn gpui::Action>>, Option<SharedString>)>,
209    )>,
210    tooltip_builder: Option<Rc<dyn Fn(&mut Window, &mut App) -> gpui::AnyView>>,
211    on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
212    on_hover: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
213    loading: bool,
214    loading_icon: Option<Icon>,
215    focus_ring_enabled: bool,
216
217    tab_index: isize,
218    tab_stop: bool,
219}
220
221impl From<Button> for AnyElement {
222    fn from(button: Button) -> Self {
223        button.into_any_element()
224    }
225}
226
227impl Button {
228    pub fn new(id: impl Into<ElementId>) -> Self {
229        let id = id.into();
230
231        Self {
232            id: id.clone(),
233            base: gpui_base::Button::new(id),
234            icon: None,
235            label: None,
236            accessibility_label: None,
237            children: Vec::new(),
238            disabled: false,
239            selected: false,
240            toggled: None,
241            role: RoleOverride::default(),
242            variant: ButtonVariant::default(),
243            rounded: ButtonRounded::Medium,
244            border_corners: Corners {
245                top_left: true,
246                top_right: true,
247                bottom_right: true,
248                bottom_left: true,
249            },
250            border_edges: Edges::all(true),
251            size: Size::Medium,
252            tooltip: None,
253            tooltip_builder: None,
254            on_click: None,
255            focus_ring_enabled: true,
256            on_hover: None,
257            loading: false,
258            compact: false,
259            outline: false,
260            loading_icon: None,
261            dropdown_caret: false,
262            tab_index: 0,
263            tab_stop: true,
264        }
265    }
266
267    pub(super) fn variant(&self) -> ButtonVariant {
268        self.variant
269    }
270
271    pub(super) fn button_size(&self) -> Size {
272        self.size
273    }
274
275    pub(super) fn is_disabled(&self) -> bool {
276        self.disabled
277    }
278
279    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
280        self.role = role.into();
281        self
282    }
283
284    /// Set the outline style of the Button.
285    pub fn outline(mut self) -> Self {
286        self.outline = true;
287        self
288    }
289
290    /// Set the border radius of the Button.
291    pub fn rounded(mut self, rounded: impl Into<ButtonRounded>) -> Self {
292        self.rounded = rounded.into();
293        self
294    }
295
296    /// Set the border corners side of the Button.
297    pub(crate) fn border_corners(mut self, corners: impl Into<Corners<bool>>) -> Self {
298        self.border_corners = corners.into();
299        self
300    }
301
302    /// Set the border edges of the Button.
303    pub(crate) fn border_edges(mut self, edges: impl Into<Edges<bool>>) -> Self {
304        self.border_edges = edges.into();
305        self
306    }
307
308    /// Set label to the Button, if no label is set, the button will be in Icon Button mode.
309    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
310        self.label = Some(label.into());
311        self
312    }
313
314    /// Set the developer-assigned identifier exposed to accessibility clients.
315    pub fn accessibility_id(self, id: impl Into<SharedString>) -> Self {
316        // GPUI-CE no longer exposes an accessibility-id setter on elements.
317        // Keep this builder source-compatible while retaining the visible and
318        // announced label configured by the other accessibility builders.
319        let _ = id.into();
320        self
321    }
322
323    /// Set the name a screen reader announces, when the visible content is not
324    /// it.
325    ///
326    /// A button's name comes from its [`label`](Self::label) by default, which
327    /// is right for the ordinary case and wrong for two: an icon-only button has
328    /// no label to read, and a button whose content is a row of cells — a table
329    /// row that is also a control — would be read out cell by cell with no
330    /// statement of what pressing it does. Setting this replaces the announced
331    /// name without adding anything to the screen.
332    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
333        self.accessibility_label = Some(label.into());
334        self
335    }
336
337    /// Set the icon of the button, if the Button have no label, the button well in Icon Button mode.
338    pub fn icon(mut self, icon: impl Into<ButtonIcon>) -> Self {
339        self.icon = Some(icon.into());
340        self
341    }
342
343    /// Set the tooltip of the button.
344    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
345        self.tooltip = Some((tooltip.into(), None));
346        self
347    }
348
349    /// Set the tooltip of the button with action to show keybinding.
350    pub fn tooltip_with_action(
351        mut self,
352        tooltip: impl Into<SharedString>,
353        action: &dyn gpui::Action,
354        context: Option<&str>,
355    ) -> Self {
356        self.tooltip = Some((
357            tooltip.into(),
358            Some((
359                Rc::new(action.boxed_clone()),
360                context.map(|c| c.to_string().into()),
361            )),
362        ));
363        self
364    }
365
366    /// Set true to show the loading indicator.
367    pub fn loading(mut self, loading: bool) -> Self {
368        self.loading = loading;
369        self
370    }
371
372    /// Set the button to compact mode, then padding will be reduced.
373    pub fn compact(mut self) -> Self {
374        self.compact = true;
375        self
376    }
377
378    /// Add click handler.
379    pub fn on_click(
380        mut self,
381        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
382    ) -> Self {
383        self.on_click = Some(Rc::new(handler));
384        self
385    }
386
387    /// Add hover handler, the bool parameter indicates whether the mouse is hovering.
388    pub fn on_hover(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
389        self.on_hover = Some(Rc::new(handler));
390        self
391    }
392
393    /// Set the loading icon of the button, it will be used when loading is true.
394    ///
395    /// Default is a spinner icon.
396    pub fn loading_icon(mut self, icon: impl Into<Icon>) -> Self {
397        self.loading_icon = Some(icon.into());
398        self
399    }
400
401    /// Set the tab index of the button, it will be used to focus the button by tab key.
402    ///
403    /// Default is 0.
404    pub fn tab_index(mut self, tab_index: isize) -> Self {
405        self.tab_index = tab_index;
406        self
407    }
408
409    /// Set the tab stop of the button, if true, the button will be focusable by tab key.
410    ///
411    /// Default is true.
412    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
413        self.tab_stop = tab_stop;
414        self
415    }
416
417    /// Set to show a dropdown caret icon at the end of the button.
418    pub fn dropdown_caret(mut self, dropdown_caret: bool) -> Self {
419        self.dropdown_caret = dropdown_caret;
420        self
421    }
422
423    /// Expose this button as a toggle button to assistive technology, with
424    /// `toggled` as its pressed state.
425    ///
426    /// Only affects accessibility metadata. Use [`Selectable::selected`] for
427    /// the selected styling, and call this in addition when the button really
428    /// is a toggle, otherwise the button stays an ordinary push button.
429    pub fn toggled(mut self, toggled: bool) -> Self {
430        self.toggled = Some(toggled);
431        self
432    }
433
434    /// Whether the button responds to the pointer at all.
435    ///
436    /// A loading button is as inert as a disabled one, it just keeps looking
437    /// like itself instead of taking the disabled styling.
438    #[inline]
439    fn interactive(&self) -> bool {
440        !(self.disabled || self.loading)
441    }
442
443    #[inline]
444    fn hoverable(&self) -> bool {
445        self.interactive() && self.on_hover.is_some()
446    }
447}
448
449impl Disableable for Button {
450    fn disabled(mut self, disabled: bool) -> Self {
451        self.disabled = disabled;
452        self
453    }
454}
455
456impl crate::FocusableExt for Button {
457    fn focus_ring(mut self, enabled: bool) -> Self {
458        self.focus_ring_enabled = enabled;
459        self
460    }
461
462    fn is_focus_ring_enabled(&self) -> bool {
463        self.focus_ring_enabled
464    }
465}
466
467impl Selectable for Button {
468    fn selected(mut self, selected: bool) -> Self {
469        self.selected = selected;
470        self
471    }
472
473    fn is_selected(&self) -> bool {
474        self.selected
475    }
476}
477
478impl Sizable for Button {
479    fn with_size(mut self, size: impl Into<Size>) -> Self {
480        self.size = size.into();
481        self
482    }
483}
484
485impl ButtonVariants for Button {
486    fn with_variant(mut self, variant: ButtonVariant) -> Self {
487        self.variant = variant;
488        self
489    }
490}
491
492impl Styled for Button {
493    fn style(&mut self) -> &mut StyleRefinement {
494        self.base.style()
495    }
496}
497
498impl ParentElement for Button {
499    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
500        self.children.extend(elements)
501    }
502}
503
504impl InteractiveElement for Button {
505    fn interactivity(&mut self) -> &mut Interactivity {
506        self.base.interactivity()
507    }
508}
509
510impl RenderOnce for Button {
511    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
512        let style: ButtonVariant = self.variant;
513        let interactive = self.interactive();
514        let hoverable = self.hoverable();
515        let disabled = self.disabled;
516        let loading = self.loading;
517        let mut base = self.base;
518        let children = self.children;
519        let instance_style = base.style().clone();
520        let normal_style = style.normal(self.outline, cx);
521        let selected_style = style.selected(self.outline, cx);
522        let disabled_style = style.disabled(self.outline, cx);
523        let icon_size = match self.size {
524            Size::Size(v) => Size::Size(v * 0.75),
525            _ => self.size,
526        };
527        let has_content = self.icon.is_some() || self.label.is_some() || !children.is_empty();
528
529        let focus_handle = window
530            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
531            .read(cx)
532            .clone();
533        let is_focused = focus_handle.is_focused(window);
534
535        let rounding = match self.rounded {
536            ButtonRounded::Small => cx.theme().radius * 0.5,
537            ButtonRounded::Medium => cx.theme().radius,
538            ButtonRounded::Large => cx.theme().radius * 2.0,
539            ButtonRounded::Size(px) => px,
540            ButtonRounded::None => Pixels::ZERO,
541        };
542
543        let root = base
544            .cursor_default()
545            .flex()
546            .flex_shrink_0()
547            .items_center()
548            .justify_center()
549            .cursor_default()
550            .when(
551                interactive && (self.variant.is_link() || self.variant.is_text()),
552                |this| this.cursor_pointer(),
553            )
554            .when(
555                !disabled && cx.theme().shadow && normal_style.shadow,
556                |this| this.shadow_xs(),
557            )
558            .when(!style.no_padding(), |this| {
559                if self.label.is_none() && children.is_empty() {
560                    // Icon Button
561                    match self.size {
562                        Size::Size(px) => this.size(px),
563                        Size::XSmall => this.size_5(),
564                        Size::Small => this.size_6(),
565                        Size::Large | Size::Medium => this.size_8(),
566                    }
567                } else {
568                    // Normal Button
569                    match self.size {
570                        Size::Size(size) => this.px(size * 0.2),
571                        Size::XSmall => this.h_5().px_1().when(self.compact, |this| this.min_w_5()),
572                        Size::Small => this
573                            .h_6()
574                            .px_2()
575                            .when(self.compact, |this| this.min_w_6().px_1p5()),
576                        Size::Medium => this
577                            .h_8()
578                            .px_2p5()
579                            .when(self.compact, |this| this.min_w_8().px_2()),
580                        Size::Large => this
581                            .h_8()
582                            .px_3()
583                            .when(self.compact, |this| this.min_w_8().px_2()),
584                    }
585                }
586            })
587            .when(self.border_corners.top_left, |this| {
588                this.rounded_tl(rounding)
589            })
590            .when(self.border_corners.top_right, |this| {
591                this.rounded_tr(rounding)
592            })
593            .when(self.border_corners.bottom_left, |this| {
594                this.rounded_bl(rounding)
595            })
596            .when(self.border_corners.bottom_right, |this| {
597                this.rounded_br(rounding)
598            })
599            .when(self.variant.is_default() || self.outline, |this| {
600                this.when(self.border_edges.left, |this| this.border_l_1())
601                    .when(self.border_edges.right, |this| this.border_r_1())
602                    .when(self.border_edges.top, |this| this.border_t_1())
603                    .when(self.border_edges.bottom, |this| this.border_b_1())
604            })
605            .when(!self.disabled && !self.selected, |this| {
606                this.border_color(normal_style.border)
607                    .bg(normal_style.bg)
608                    .text_color(normal_style.fg)
609                    .when(normal_style.underline, |this| this.text_decoration_1())
610                    // A loading button keeps its normal colors, but must not react
611                    // to the pointer, it is not waiting for another click.
612                    .when(interactive, |this| {
613                        this.hover(|this| {
614                            let hover_style = style.hovered(self.outline, cx);
615                            this.bg(hover_style.bg)
616                                .border_color(hover_style.border)
617                                .text_color(hover_style.fg)
618                        })
619                        .active(|this| {
620                            let active_style = style.active(self.outline, cx);
621                            this.bg(active_style.bg)
622                                .border_color(active_style.border)
623                                .text_color(active_style.fg)
624                        })
625                    })
626            })
627            .refine_style(&instance_style);
628
629        // The explicit name wins: it exists precisely for the cases where the
630        // visible content is not what a listener needs to hear.
631        let accessibility_label = self
632            .accessibility_label
633            .clone()
634            .or_else(|| self.label.clone());
635        let content = h_flex()
636            .id("label")
637            .size_full()
638            .min_w_0()
639            .overflow_hidden()
640            .whitespace_nowrap()
641            .items_center()
642            .justify_center()
643            .button_text_size(self.size)
644            .map(|this| match self.size {
645                Size::XSmall => this.gap_1(),
646                Size::Small => this.gap_1(),
647                _ => this.gap_2(),
648            })
649            .when_some(self.icon, |this, icon| {
650                this.child(
651                    icon.loading_icon(self.loading_icon)
652                        .loading(self.loading)
653                        .with_size(icon_size),
654                )
655            })
656            .when_some(self.label, |this, label| {
657                this.child(
658                    div()
659                        .min_w_0()
660                        .overflow_hidden()
661                        .whitespace_nowrap()
662                        .truncate()
663                        .line_height(relative(1.))
664                        .child(label),
665                )
666            })
667            .children(children)
668            .when(self.dropdown_caret, |this| {
669                this.when(has_content, |this| this.justify_between())
670                    .child(Caret::new(self.size).text_color(normal_style.fg.opacity(0.75)))
671            });
672        root.role(self.role.resolve(|| {
673            if self.variant.is_link() {
674                Role::Link
675            } else {
676                Role::Button
677            }
678        }))
679        .selected(self.selected)
680        .disabled(disabled)
681        // Base layers semantic states over the builder chain, so the caller's
682        // own style is replayed inside each state to keep it the closest layer.
683        .styles(|styles| {
684            styles
685                .selected(|style| {
686                    style
687                        .bg(selected_style.bg)
688                        .border_color(selected_style.border)
689                        .text_color(selected_style.fg)
690                        .refine_style(&instance_style)
691                })
692                .disabled(|style| {
693                    style
694                        .bg(disabled_style.bg)
695                        .text_color(disabled_style.fg)
696                        .border_color(disabled_style.border)
697                        .shadow_none()
698                        .refine_style(&instance_style)
699                })
700        })
701        .when_some(accessibility_label, |this, label| {
702            this.accessibility_label(label)
703        })
704        .when_some(self.toggled, |this, toggled| {
705            this.aria_toggled(if toggled {
706                gpui::accesskit::Toggled::True
707            } else {
708                gpui::accesskit::Toggled::False
709            })
710        })
711        .track_focus(&focus_handle)
712        .tab_index(self.tab_index)
713        .tab_stop(self.tab_stop)
714        .child(content)
715        // Fade the whole button while loading, so every variant is dimmed by
716        // the same amount. Fading `bg`, `border` and `fg` one by one instead
717        // only shows up on variants that have a background to begin with:
718        // `Ghost`, `Link` and `Text` are transparent, so an alpha on their
719        // background changes nothing.
720        .when(loading && !disabled, |this| this.opacity(0.8))
721        .when(!disabled, |this| {
722            this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
723                if loading {
724                    cx.stop_propagation();
725                    return;
726                }
727
728                // Avoid focus on mouse down.
729                window.prevent_default();
730
731                // Pressing a button must not start the window-level text selection.
732                crate::global_state::GlobalState::suppress_text_selection(cx);
733            })
734        })
735        .when_some(self.on_click, |this, on_click| {
736            this.on_click(move |event, window, cx| {
737                if loading {
738                    cx.stop_propagation();
739                    return;
740                }
741
742                on_click(event, window, cx);
743            })
744        })
745        .when_some(self.on_hover.filter(|_| hoverable), |this, on_hover| {
746            this.on_hover(move |hovered, window, cx| {
747                on_hover(hovered, window, cx);
748            })
749        })
750        .map(|this| {
751            if let Some(builder) = self.tooltip_builder {
752                this.managed_tooltip(move |window, cx| builder(window, cx))
753            } else if let Some((tooltip, action)) = self.tooltip {
754                this.managed_tooltip(move |window, cx| {
755                    Tooltip::new(tooltip.clone())
756                        .when_some(action.clone(), |this, (action, context)| {
757                            this.action(
758                                action.boxed_clone().as_ref(),
759                                context.as_ref().map(|c| c.as_ref()),
760                            )
761                        })
762                        .build(window, cx)
763                })
764            } else {
765                this
766            }
767        })
768        .when(is_focused && self.focus_ring_enabled, |this| {
769            this.focus_ring_style(window, cx)
770        })
771    }
772}
773
774struct ButtonVariantStyle {
775    bg: Background,
776    border: Hsla,
777    fg: Hsla,
778    underline: bool,
779    shadow: bool,
780}
781
782#[derive(Clone, Copy)]
783enum ButtonStyleState {
784    Normal,
785    Hovered,
786    Active,
787}
788
789impl ButtonVariant {
790    fn outline_background(&self, state: ButtonStyleState, cx: &mut App) -> Background {
791        match (self, state) {
792            (Self::Default, ButtonStyleState::Normal) => cx.theme().input_background().into(),
793            (Self::Default, ButtonStyleState::Hovered) => cx
794                .theme()
795                .input
796                .mix_oklab(cx.theme().transparent, 0.5)
797                .into(),
798            (Self::Default, ButtonStyleState::Active) => cx
799                .theme()
800                .input
801                .mix_oklab(cx.theme().transparent, 0.7)
802                .into(),
803            (Self::Primary, ButtonStyleState::Normal) => {
804                cx.theme().tokens.primary.background.opacity(0.1)
805            }
806            (Self::Primary, ButtonStyleState::Hovered) => {
807                cx.theme().tokens.primary_hover.background.opacity(0.2)
808            }
809            (Self::Primary, ButtonStyleState::Active) => {
810                cx.theme().tokens.primary_active.background.opacity(0.4)
811            }
812            (Self::Secondary, ButtonStyleState::Normal) => {
813                cx.theme().tokens.secondary.background.opacity(0.1)
814            }
815            (Self::Secondary, ButtonStyleState::Hovered) => {
816                cx.theme().tokens.secondary_hover.background.opacity(0.2)
817            }
818            (Self::Secondary, ButtonStyleState::Active) => {
819                cx.theme().tokens.secondary_active.background.opacity(0.4)
820            }
821            (Self::Danger, ButtonStyleState::Normal) => {
822                cx.theme().tokens.danger.background.opacity(0.1)
823            }
824            (Self::Danger, ButtonStyleState::Hovered) => {
825                cx.theme().tokens.danger_hover.background.opacity(0.2)
826            }
827            (Self::Danger, ButtonStyleState::Active) => {
828                cx.theme().tokens.danger_active.background.opacity(0.4)
829            }
830            (Self::Warning, ButtonStyleState::Normal) => {
831                cx.theme().tokens.warning.background.opacity(0.1)
832            }
833            (Self::Warning, ButtonStyleState::Hovered) => {
834                cx.theme().tokens.warning_hover.background.opacity(0.2)
835            }
836            (Self::Warning, ButtonStyleState::Active) => {
837                cx.theme().tokens.warning_active.background.opacity(0.4)
838            }
839            (Self::Success, ButtonStyleState::Normal) => {
840                cx.theme().tokens.success.background.opacity(0.1)
841            }
842            (Self::Success, ButtonStyleState::Hovered) => {
843                cx.theme().tokens.success_hover.background.opacity(0.2)
844            }
845            (Self::Success, ButtonStyleState::Active) => {
846                cx.theme().tokens.success_active.background.opacity(0.4)
847            }
848            (Self::Info, ButtonStyleState::Normal) => {
849                cx.theme().tokens.info.background.opacity(0.1)
850            }
851            (Self::Info, ButtonStyleState::Hovered) => {
852                cx.theme().tokens.info_hover.background.opacity(0.2)
853            }
854            (Self::Info, ButtonStyleState::Active) => {
855                cx.theme().tokens.info_active.background.opacity(0.4)
856            }
857            (Self::Ghost | Self::Link | Self::Text, _) => cx.theme().transparent.into(),
858            (Self::Custom(colors), _) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(),
859        }
860    }
861
862    fn bg_color(&self, outline: bool, cx: &mut App) -> Background {
863        if outline {
864            return self.outline_background(ButtonStyleState::Normal, cx);
865        }
866
867        match self {
868            Self::Default => cx.theme().tokens.button.into(),
869            Self::Primary => cx.theme().tokens.button_primary.into(),
870            Self::Secondary => cx.theme().tokens.button_secondary.into(),
871            Self::Danger => cx.theme().tokens.button_danger.into(),
872            Self::Warning => cx.theme().tokens.button_warning.into(),
873            Self::Success => cx.theme().tokens.button_success.into(),
874            Self::Info => cx.theme().tokens.button_info.into(),
875            Self::Ghost | Self::Link | Self::Text => cx.theme().transparent.into(),
876            Self::Custom(colors) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(),
877        }
878    }
879
880    fn text_color(&self, outline: bool, cx: &mut App) -> Hsla {
881        match self {
882            Self::Default => cx.theme().button_foreground,
883            Self::Primary => {
884                if outline {
885                    cx.theme().primary
886                } else {
887                    cx.theme().button_primary_foreground
888                }
889            }
890            Self::Secondary => {
891                if outline {
892                    cx.theme().secondary_foreground
893                } else {
894                    cx.theme().button_secondary_foreground
895                }
896            }
897            Self::Ghost => cx.theme().secondary_foreground,
898            Self::Danger => {
899                if outline {
900                    cx.theme().danger
901                } else {
902                    cx.theme().button_danger_foreground
903                }
904            }
905            Self::Warning => {
906                if outline {
907                    cx.theme().warning
908                } else {
909                    cx.theme().button_warning_foreground
910                }
911            }
912            Self::Success => {
913                if outline {
914                    cx.theme().success
915                } else {
916                    cx.theme().button_success_foreground
917                }
918            }
919            Self::Info => {
920                if outline {
921                    cx.theme().info
922                } else {
923                    cx.theme().button_info_foreground
924                }
925            }
926            Self::Link => cx.theme().link,
927            Self::Text => cx.theme().foreground.opacity(0.9),
928            Self::Custom(colors) => colors.foreground,
929        }
930    }
931
932    fn border_color(&self, outline: bool, cx: &mut App) -> Hsla {
933        match self {
934            Self::Default => cx.theme().input,
935            Self::Secondary => cx.theme().border,
936            Self::Primary => cx.theme().primary,
937            Self::Danger => {
938                if outline {
939                    cx.theme().danger.mix_oklab(transparent_white(), 0.4)
940                } else {
941                    cx.theme().button_danger
942                }
943            }
944            Self::Info => {
945                if outline {
946                    cx.theme().info.mix_oklab(transparent_white(), 0.4)
947                } else {
948                    cx.theme().button_info
949                }
950            }
951            Self::Warning => {
952                if outline {
953                    cx.theme().warning.mix_oklab(transparent_white(), 0.4)
954                } else {
955                    cx.theme().button_warning
956                }
957            }
958            Self::Success => {
959                if outline {
960                    cx.theme().success.mix_oklab(transparent_white(), 0.4)
961                } else {
962                    cx.theme().button_success
963                }
964            }
965            Self::Ghost | Self::Link | Self::Text => cx.theme().transparent,
966            Self::Custom(colors) => {
967                if outline {
968                    colors.color.mix_oklab(transparent_white(), 0.4)
969                } else {
970                    colors.color
971                }
972            }
973        }
974    }
975
976    fn underline(&self, _: &App) -> bool {
977        match self {
978            Self::Link => true,
979            _ => false,
980        }
981    }
982
983    fn shadow(&self, _outline: bool, _: &App) -> bool {
984        match self {
985            Self::Custom(c) => c.shadow,
986            _ => false,
987        }
988    }
989
990    fn normal(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
991        let bg = self.bg_color(outline, cx);
992        let border = self.border_color(outline, cx);
993        let fg = self.text_color(outline, cx);
994        let underline = self.underline(cx);
995        let shadow = self.shadow(outline, cx);
996
997        ButtonVariantStyle {
998            bg,
999            border,
1000            fg,
1001            underline,
1002            shadow,
1003        }
1004    }
1005
1006    fn hovered(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1007        let bg: Background = match self {
1008            Self::Default => {
1009                if outline {
1010                    self.outline_background(ButtonStyleState::Hovered, cx)
1011                } else {
1012                    cx.theme().tokens.button_hover.into()
1013                }
1014            }
1015            Self::Primary => {
1016                if outline {
1017                    self.outline_background(ButtonStyleState::Hovered, cx)
1018                } else {
1019                    cx.theme().tokens.button_primary_hover.into()
1020                }
1021            }
1022            Self::Secondary => {
1023                if outline {
1024                    self.outline_background(ButtonStyleState::Hovered, cx)
1025                } else {
1026                    cx.theme().tokens.button_secondary_hover.into()
1027                }
1028            }
1029            Self::Danger => {
1030                if outline {
1031                    self.outline_background(ButtonStyleState::Hovered, cx)
1032                } else {
1033                    cx.theme().tokens.button_danger_hover.into()
1034                }
1035            }
1036            Self::Warning => {
1037                if outline {
1038                    self.outline_background(ButtonStyleState::Hovered, cx)
1039                } else {
1040                    cx.theme().tokens.button_warning_hover.into()
1041                }
1042            }
1043            Self::Success => {
1044                if outline {
1045                    self.outline_background(ButtonStyleState::Hovered, cx)
1046                } else {
1047                    cx.theme().tokens.button_success_hover.into()
1048                }
1049            }
1050            Self::Info => {
1051                if outline {
1052                    self.outline_background(ButtonStyleState::Hovered, cx)
1053                } else {
1054                    cx.theme().tokens.button_info_hover.into()
1055                }
1056            }
1057            Self::Custom(colors) => colors.hover.into(),
1058            Self::Ghost => if cx.theme().mode.is_dark() {
1059                cx.theme().secondary.lighten(0.1).opacity(0.8)
1060            } else {
1061                cx.theme().secondary.darken(0.1).opacity(0.8)
1062            }
1063            .into(),
1064            Self::Link => cx.theme().transparent.into(),
1065            Self::Text => cx.theme().transparent.into(),
1066        };
1067
1068        let border = self.border_color(outline, cx);
1069        let fg = match self {
1070            Self::Link => cx.theme().link_hover,
1071            Self::Text => cx.theme().foreground,
1072            _ => self.text_color(outline, cx),
1073        };
1074
1075        let underline = self.underline(cx);
1076        let shadow = self.shadow(outline, cx);
1077
1078        ButtonVariantStyle {
1079            bg,
1080            border,
1081            fg,
1082            underline,
1083            shadow,
1084        }
1085    }
1086
1087    fn active(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1088        let bg = match self {
1089            Self::Default => {
1090                if outline {
1091                    self.outline_background(ButtonStyleState::Active, cx)
1092                } else {
1093                    cx.theme().tokens.button_active.into()
1094                }
1095            }
1096            Self::Primary => {
1097                if outline {
1098                    self.outline_background(ButtonStyleState::Active, cx)
1099                } else {
1100                    cx.theme().tokens.button_primary_active.into()
1101                }
1102            }
1103            Self::Secondary => {
1104                if outline {
1105                    self.outline_background(ButtonStyleState::Active, cx)
1106                } else {
1107                    cx.theme().tokens.button_secondary_active.into()
1108                }
1109            }
1110            Self::Ghost => if cx.theme().mode.is_dark() {
1111                cx.theme().secondary.lighten(0.2).opacity(0.8)
1112            } else {
1113                cx.theme().secondary.darken(0.2).opacity(0.8)
1114            }
1115            .into(),
1116            Self::Danger => {
1117                if outline {
1118                    self.outline_background(ButtonStyleState::Active, cx)
1119                } else {
1120                    cx.theme().tokens.button_danger_active.into()
1121                }
1122            }
1123            Self::Warning => {
1124                if outline {
1125                    self.outline_background(ButtonStyleState::Active, cx)
1126                } else {
1127                    cx.theme().tokens.button_warning_active.into()
1128                }
1129            }
1130            Self::Success => {
1131                if outline {
1132                    self.outline_background(ButtonStyleState::Active, cx)
1133                } else {
1134                    cx.theme().tokens.button_success_active.into()
1135                }
1136            }
1137            Self::Info => {
1138                if outline {
1139                    self.outline_background(ButtonStyleState::Active, cx)
1140                } else {
1141                    cx.theme().tokens.button_info_active.into()
1142                }
1143            }
1144            Self::Custom(colors) => colors.active.into(),
1145            Self::Link => cx.theme().transparent.into(),
1146            Self::Text => cx.theme().transparent.into(),
1147        };
1148        let border = self.border_color(outline, cx);
1149        let fg = match self {
1150            Self::Link => cx.theme().link_active,
1151            Self::Text => cx.theme().foreground.opacity(0.7),
1152            _ => self.text_color(outline, cx),
1153        };
1154        let underline = self.underline(cx);
1155        let shadow = self.shadow(outline, cx);
1156
1157        ButtonVariantStyle {
1158            bg,
1159            border,
1160            fg,
1161            underline,
1162            shadow,
1163        }
1164    }
1165
1166    fn selected(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1167        if outline {
1168            let active_style = self.active(outline, cx);
1169
1170            return ButtonVariantStyle {
1171                fg: self.text_color(outline, cx),
1172                ..active_style
1173            };
1174        }
1175
1176        let bg = match self {
1177            Self::Default => cx.theme().tokens.button_active.into(),
1178            Self::Primary => cx.theme().tokens.button_primary_active.into(),
1179            Self::Secondary => cx.theme().tokens.button_secondary_active.into(),
1180            Self::Ghost => cx.theme().tokens.secondary_active.into(),
1181            Self::Danger => cx.theme().tokens.button_danger_active.into(),
1182            Self::Warning => cx.theme().tokens.button_warning_active.into(),
1183            Self::Success => cx.theme().tokens.button_success_active.into(),
1184            Self::Info => cx.theme().tokens.button_info_active.into(),
1185            Self::Link => cx.theme().transparent.into(),
1186            Self::Text => cx.theme().transparent.into(),
1187            Self::Custom(colors) => colors.active.into(),
1188        };
1189
1190        let border = self.border_color(outline, cx);
1191        let fg = match self {
1192            Self::Link => cx.theme().link_active,
1193            Self::Text => cx.theme().foreground.opacity(0.7),
1194            _ => self.text_color(false, cx),
1195        };
1196        let underline = self.underline(cx);
1197        let shadow = self.shadow(outline, cx);
1198
1199        ButtonVariantStyle {
1200            bg,
1201            border,
1202            fg,
1203            underline,
1204            shadow,
1205        }
1206    }
1207
1208    fn disabled(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1209        let bg = match self {
1210            Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent.into(),
1211            Self::Primary => cx.theme().tokens.button_primary.background.opacity(0.15),
1212            Self::Danger => cx.theme().tokens.button_danger.background.opacity(0.15),
1213            Self::Warning => cx.theme().tokens.button_warning.background.opacity(0.15),
1214            Self::Success => cx.theme().tokens.button_success.background.opacity(0.15),
1215            Self::Info => cx.theme().tokens.button_info.background.opacity(0.15),
1216            Self::Secondary => cx.theme().tokens.button_secondary.background.opacity(1.5),
1217            Self::Custom(style) => style.color.opacity(0.15).into(),
1218        };
1219        let fg = cx.theme().muted_foreground.opacity(0.5);
1220        let (bg, border) = if outline {
1221            (
1222                self.outline_background(ButtonStyleState::Normal, cx)
1223                    .opacity(0.5),
1224                self.border_color(true, cx).opacity(0.5),
1225            )
1226        } else if let Self::Default = self {
1227            (
1228                cx.theme().input_background().opacity(0.5).into(),
1229                cx.theme().input.opacity(0.5),
1230            )
1231        } else {
1232            let border = match self {
1233                Self::Primary => cx.theme().button_primary.opacity(0.15),
1234                Self::Secondary => cx.theme().button_secondary.opacity(1.5),
1235                Self::Danger => cx.theme().button_danger.opacity(0.15),
1236                Self::Warning => cx.theme().button_warning.opacity(0.15),
1237                Self::Success => cx.theme().button_success.opacity(0.15),
1238                Self::Info => cx.theme().button_info.opacity(0.15),
1239                Self::Custom(style) => style.color.opacity(0.15),
1240                Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent,
1241            };
1242            (bg, border)
1243        };
1244
1245        let underline = self.underline(cx);
1246        let shadow = false;
1247
1248        ButtonVariantStyle {
1249            bg,
1250            border,
1251            fg,
1252            underline,
1253            shadow,
1254        }
1255    }
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use super::*;
1261    use crate::IconName;
1262    use gpui::{linear_color_stop, linear_gradient, px};
1263
1264    /// A button's announced name is its label, unless it was given one — which
1265    /// is the case an icon-only button and a row-shaped button both need.
1266    #[test]
1267    fn an_explicit_accessibility_label_replaces_the_visible_one() {
1268        let plain = Button::new("save").label("Save");
1269        assert_eq!(plain.accessibility_label, None);
1270        assert_eq!(plain.label.as_deref(), Some("Save"));
1271
1272        let named = Button::new("row")
1273            .label("Save")
1274            .accessibility_label("Save the current document");
1275        assert_eq!(
1276            named.accessibility_label.as_deref(),
1277            Some("Save the current document"),
1278            "an explicit name must win over the visible label"
1279        );
1280        assert_eq!(
1281            named.label.as_deref(),
1282            Some("Save"),
1283            "and must not change what is drawn"
1284        );
1285    }
1286
1287    #[gpui::test]
1288    fn disabled_legacy_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) {
1289        use std::{cell::Cell, rc::Rc};
1290
1291        use gpui::{Context, Modifiers, Render, point};
1292
1293        struct Harness(Rc<Cell<usize>>, Rc<Cell<usize>>);
1294
1295        impl Render for Harness {
1296            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1297                let button_clicks = self.0.clone();
1298                let parent_clicks = self.1.clone();
1299                div()
1300                    .id("disabled-button-parent")
1301                    .tab_group()
1302                    .size(px(100.))
1303                    .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
1304                    .child(
1305                        Button::new("disabled-legacy")
1306                            .disabled(true)
1307                            .size_full()
1308                            .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)),
1309                    )
1310            }
1311        }
1312
1313        cx.update(crate::init);
1314        let button_clicks = Rc::new(Cell::new(0));
1315        let parent_clicks = Rc::new(Cell::new(0));
1316        let (_, cx) = cx.add_window_view({
1317            let button_clicks = button_clicks.clone();
1318            let parent_clicks = parent_clicks.clone();
1319            move |_, _| Harness(button_clicks, parent_clicks)
1320        });
1321        cx.update(|window, cx| window.draw(cx).clear(cx));
1322        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1323        cx.update(|window, cx| window.focus_next(cx));
1324        cx.simulate_keystrokes("enter space");
1325
1326        assert_eq!(button_clicks.get(), 0);
1327        assert_eq!(parent_clicks.get(), 0);
1328        cx.update(|window, cx| assert!(window.focused(cx).is_none()));
1329    }
1330
1331    #[gpui::test]
1332    fn enabled_button_delegates_pointer_enter_and_space_once(cx: &mut gpui::TestAppContext) {
1333        use std::{cell::Cell, rc::Rc};
1334
1335        use gpui::{
1336            ClickEvent, Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, point,
1337        };
1338
1339        struct Harness(Rc<Cell<usize>>, Rc<Cell<usize>>);
1340
1341        impl Render for Harness {
1342            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1343                let clicks = self.0.clone();
1344                let keyboard_clicks = self.1.clone();
1345                div().tab_group().size(px(100.)).child(
1346                    Button::new("enabled-legacy")
1347                        .size_full()
1348                        .on_click(move |event, _, _| {
1349                            clicks.set(clicks.get() + 1);
1350                            if matches!(event, ClickEvent::Keyboard(_)) {
1351                                keyboard_clicks.set(keyboard_clicks.get() + 1);
1352                            }
1353                        }),
1354                )
1355            }
1356        }
1357
1358        cx.update(crate::init);
1359        let clicks = Rc::new(Cell::new(0));
1360        let keyboard_clicks = Rc::new(Cell::new(0));
1361        let (_, cx) = cx.add_window_view({
1362            let clicks = clicks.clone();
1363            let keyboard_clicks = keyboard_clicks.clone();
1364            move |_, _| Harness(clicks, keyboard_clicks)
1365        });
1366        cx.update(|window, cx| window.draw(cx).clear(cx));
1367        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1368        cx.update(|window, cx| window.focus_next(cx));
1369        cx.update(|window, cx| {
1370            assert!(window.focused(cx).is_some());
1371            window.draw(cx).clear(cx);
1372        });
1373        for key in ["enter", "space"] {
1374            let keystroke = Keystroke::parse(key).unwrap();
1375            cx.simulate_event(KeyDownEvent {
1376                keystroke: keystroke.clone(),
1377                is_held: false,
1378                prefer_character_input: false,
1379            });
1380            cx.simulate_event(KeyUpEvent { keystroke });
1381        }
1382
1383        assert_eq!(clicks.get(), 3);
1384        assert_eq!(keyboard_clicks.get(), 2);
1385    }
1386
1387    #[gpui::test]
1388    fn loading_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) {
1389        use std::{cell::Cell, rc::Rc};
1390
1391        use gpui::{Context, Modifiers, Render, point};
1392
1393        struct Harness(Rc<Cell<usize>>, Rc<Cell<usize>>);
1394
1395        impl Render for Harness {
1396            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1397                let button_clicks = self.0.clone();
1398                let parent_clicks = self.1.clone();
1399                div()
1400                    .id("loading-button-parent")
1401                    .tab_group()
1402                    .size(px(100.))
1403                    .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
1404                    .child(
1405                        Button::new("loading-legacy")
1406                            .loading(true)
1407                            .size_full()
1408                            .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)),
1409                    )
1410            }
1411        }
1412
1413        cx.update(crate::init);
1414        let button_clicks = Rc::new(Cell::new(0));
1415        let parent_clicks = Rc::new(Cell::new(0));
1416        let (_, cx) = cx.add_window_view({
1417            let button_clicks = button_clicks.clone();
1418            let parent_clicks = parent_clicks.clone();
1419            move |_, _| Harness(button_clicks, parent_clicks)
1420        });
1421        cx.update(|window, cx| window.draw(cx).clear(cx));
1422        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1423        cx.update(|window, cx| window.focus_next(cx));
1424        cx.simulate_keystrokes("enter space");
1425
1426        assert_eq!(button_clicks.get(), 0);
1427        assert_eq!(parent_clicks.get(), 0);
1428        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
1429    }
1430
1431    #[gpui::test]
1432    fn loading_button_without_callback_still_blocks_parent_activation(
1433        cx: &mut gpui::TestAppContext,
1434    ) {
1435        use std::{cell::Cell, rc::Rc};
1436
1437        use gpui::{Context, Modifiers, Render, point};
1438
1439        struct Harness(Rc<Cell<usize>>);
1440
1441        impl Render for Harness {
1442            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1443                let parent_clicks = self.0.clone();
1444                div()
1445                    .id("loading-without-callback-parent")
1446                    .tab_group()
1447                    .size(px(100.))
1448                    .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
1449                    .child(
1450                        Button::new("loading-without-callback")
1451                            .loading(true)
1452                            .size_full(),
1453                    )
1454            }
1455        }
1456
1457        cx.update(crate::init);
1458        let parent_clicks = Rc::new(Cell::new(0));
1459        let (_, cx) = cx.add_window_view({
1460            let parent_clicks = parent_clicks.clone();
1461            move |_, _| Harness(parent_clicks)
1462        });
1463        cx.update(|window, cx| window.draw(cx).clear(cx));
1464        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1465        cx.update(|window, cx| window.focus_next(cx));
1466        cx.simulate_keystrokes("enter space");
1467
1468        assert_eq!(parent_clicks.get(), 0);
1469        cx.update(|window, cx| assert!(window.focused(cx).is_some()));
1470    }
1471
1472    #[gpui::test]
1473    fn test_button_builder(_cx: &mut gpui::TestAppContext) {
1474        let button = Button::new("complex-button")
1475            .label("Save Changes")
1476            .primary()
1477            .outline()
1478            .large()
1479            .tooltip("Click to save")
1480            .compact()
1481            .loading(false)
1482            .disabled(false)
1483            .selected(false)
1484            .tab_index(1)
1485            .tab_stop(true)
1486            .dropdown_caret(false)
1487            .rounded(ButtonRounded::Medium)
1488            .on_click(|_, _, _| {});
1489
1490        assert_eq!(button.label, Some("Save Changes".into()));
1491        assert_eq!(button.variant, ButtonVariant::Primary);
1492        assert!(button.outline);
1493        assert_eq!(button.size, Size::Large);
1494        assert!(button.tooltip.is_some());
1495        assert!(button.compact);
1496        assert!(!button.loading);
1497        assert!(!button.disabled);
1498        assert!(!button.selected);
1499        assert_eq!(button.toggled, None);
1500        assert_eq!(button.tab_index, 1);
1501        assert!(button.tab_stop);
1502        assert!(!button.dropdown_caret);
1503        assert!(matches!(button.rounded, ButtonRounded::Medium));
1504    }
1505
1506    #[test]
1507    fn selected_trigger_presentation_does_not_imply_toggled_accessibility() {
1508        let selected = Button::new("menu-trigger").selected(true);
1509        assert!(selected.selected);
1510        assert_eq!(selected.toggled, None);
1511
1512        let selected_toggle = Button::new("explicit-toggle").selected(true).toggled(true);
1513        assert!(selected_toggle.selected);
1514        assert_eq!(selected_toggle.toggled, Some(true));
1515    }
1516
1517    /// A loading button must be as inert as a disabled one. `interactive` is what
1518    /// gates the hover and active styling, the `cursor_pointer` of link buttons and
1519    /// the `mouse_down` handler, none of which depend on a listener being set.
1520    #[gpui::test]
1521    fn test_button_loading_is_not_interactive(_cx: &mut gpui::TestAppContext) {
1522        assert!(Button::new("test").interactive());
1523        assert!(!Button::new("test").loading(true).interactive());
1524        assert!(!Button::new("test").disabled(true).interactive());
1525        assert!(
1526            !Button::new("test")
1527                .loading(true)
1528                .disabled(true)
1529                .interactive()
1530        );
1531
1532        // Loading gates hovering even when an `on_hover` listener is set.
1533        let loading = Button::new("test").loading(true).on_hover(|_, _, _| {});
1534        assert!(!loading.hoverable());
1535    }
1536
1537    /// `selected` is styling only; the toggle state must be opted into, so that
1538    /// ordinary buttons are not announced as toggle buttons.
1539    #[gpui::test]
1540    fn test_button_variant_methods(_cx: &mut gpui::TestAppContext) {
1541        // Test variant check methods
1542        assert!(ButtonVariant::Link.is_link());
1543        assert!(ButtonVariant::Text.is_text());
1544        assert!(ButtonVariant::Ghost.is_ghost());
1545
1546        // Test no_padding logic
1547        assert!(ButtonVariant::Link.no_padding());
1548        assert!(ButtonVariant::Text.no_padding());
1549        assert!(!ButtonVariant::Ghost.no_padding());
1550    }
1551
1552    #[gpui::test]
1553    fn link_button_prepaints_its_child(cx: &mut gpui::TestAppContext) {
1554        use gpui::{Context, Render};
1555
1556        struct LinkButtonHarness;
1557
1558        impl Render for LinkButtonHarness {
1559            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1560                Button::new("link-button").link().child(
1561                    div()
1562                        .debug_selector(|| "link-button-child".into())
1563                        .child("Visible link button"),
1564                )
1565            }
1566        }
1567
1568        cx.update(crate::init);
1569        let (_, cx) = cx.add_window_view(|_, _| LinkButtonHarness);
1570        cx.update(|window, cx| window.draw(cx).clear(cx));
1571
1572        let bounds = cx
1573            .debug_bounds("link-button-child")
1574            .expect("link button child must participate in layout and prepaint");
1575        assert!(bounds.size.width > px(0.));
1576        assert!(bounds.size.height > px(0.));
1577    }
1578
1579    #[gpui::test]
1580    fn base_slot_prepaints_complete_button_content(cx: &mut gpui::TestAppContext) {
1581        use gpui::{Context, Render};
1582
1583        struct CompleteButtonHarness;
1584
1585        impl Render for CompleteButtonHarness {
1586            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1587                div()
1588                    .child(
1589                        Button::new("complete-button")
1590                            .icon(IconName::Plus)
1591                            .label("Create")
1592                            .child(
1593                                div()
1594                                    .debug_selector(|| "button-custom-content".into())
1595                                    .child("Details"),
1596                            )
1597                            .dropdown_caret(true),
1598                    )
1599                    .child(
1600                        Button::new("loading-button")
1601                            .icon(IconName::Plus)
1602                            .loading_icon(IconName::Loader)
1603                            .loading(true)
1604                            .label("Creating")
1605                            .dropdown_caret(true),
1606                    )
1607            }
1608        }
1609
1610        cx.update(crate::init);
1611        let (_, cx) = cx.add_window_view(|_, _| CompleteButtonHarness);
1612        cx.update(|window, cx| window.draw(cx).clear(cx));
1613
1614        let bounds = cx
1615            .debug_bounds("button-custom-content")
1616            .expect("application content must prepaint through the Base child seam");
1617        assert!(bounds.size.width > px(0.));
1618        assert!(bounds.size.height > px(0.));
1619    }
1620
1621    #[gpui::test]
1622    fn test_outline_selected_uses_outline_active_style(cx: &mut gpui::TestAppContext) {
1623        cx.update(crate::init);
1624        let window = cx.add_empty_window();
1625        window.update(|_, cx| {
1626            let variant = ButtonVariant::Danger;
1627            let active_style = variant.active(true, cx);
1628            let selected_style = variant.selected(true, cx);
1629
1630            assert_eq!(selected_style.bg, active_style.bg);
1631            assert_eq!(selected_style.border, active_style.border);
1632            assert_eq!(selected_style.fg, cx.theme().danger);
1633            assert_ne!(selected_style.bg, cx.theme().tokens.danger_active.into());
1634        });
1635    }
1636
1637    #[gpui::test]
1638    fn test_primary_button_uses_gradient_background_tokens(cx: &mut gpui::TestAppContext) {
1639        cx.update(crate::init);
1640        let window = cx.add_empty_window();
1641        window.update(|_, cx| {
1642            let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1643                "name": "Gradient",
1644                "mode": "light",
1645                "colors": {
1646                    "button.primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)",
1647                    "button.primary.hover.background": "linear-gradient(145deg, #4338CA, #0891B2)",
1648                    "button.primary.active.background": "linear-gradient(155deg, #3730A3, #0E7490)"
1649                }
1650            }))
1651            .unwrap();
1652            crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1653
1654            assert_eq!(
1655                ButtonVariant::Primary.normal(false, cx).bg,
1656                cx.theme().tokens.button_primary.into()
1657            );
1658            assert_eq!(
1659                ButtonVariant::Primary.hovered(false, cx).bg,
1660                cx.theme().tokens.button_primary_hover.into()
1661            );
1662            assert_eq!(
1663                ButtonVariant::Primary.active(false, cx).bg,
1664                cx.theme().tokens.button_primary_active.into()
1665            );
1666        });
1667    }
1668
1669    #[gpui::test]
1670    fn test_outline_primary_keeps_original_depth(cx: &mut gpui::TestAppContext) {
1671        cx.update(crate::init);
1672        let window = cx.add_empty_window();
1673        window.update(|_, cx| {
1674            let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1675                "name": "Outline Depth",
1676                "mode": "light",
1677                "colors": {
1678                    "primary.background": "linear-gradient(180deg, #111827, #020617)",
1679                    "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)",
1680                    "primary.active.background": "linear-gradient(180deg, #020617, #000000)"
1681                }
1682            }))
1683            .unwrap();
1684            crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1685
1686            assert_eq!(
1687                ButtonVariant::Primary.normal(true, cx).bg,
1688                cx.theme().tokens.primary.background.opacity(0.1)
1689            );
1690            assert_eq!(
1691                ButtonVariant::Primary.hovered(true, cx).bg,
1692                cx.theme().tokens.primary_hover.background.opacity(0.2)
1693            );
1694            assert_eq!(
1695                ButtonVariant::Primary.active(true, cx).bg,
1696                cx.theme().tokens.primary_active.background.opacity(0.4)
1697            );
1698        });
1699    }
1700
1701    #[gpui::test]
1702    fn test_outline_buttons_use_semantic_gradient_tokens(cx: &mut gpui::TestAppContext) {
1703        cx.update(crate::init);
1704        let window = cx.add_empty_window();
1705        window.update(|_, cx| {
1706            let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1707                "name": "Outline Gradient",
1708                "mode": "light",
1709                "colors": {
1710                    "primary.background": "linear-gradient(180deg, #111827, #020617)",
1711                    "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)",
1712                    "primary.active.background": "linear-gradient(180deg, #020617, #000000)",
1713                    "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)",
1714                    "button.primary.hover.background": "linear-gradient(180deg, #F9FAFB, #E5E7EB)",
1715                    "button.primary.active.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)",
1716                    "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)",
1717                    "danger.hover.background": "linear-gradient(180deg, #F87171, #EF4444)",
1718                    "danger.active.background": "linear-gradient(180deg, #DC2626, #B91C1C)",
1719                    "button.danger.background": "linear-gradient(180deg, #FEF2F2, #FEE2E2)",
1720                    "button.danger.hover.background": "linear-gradient(180deg, #FEE2E2, #FECACA)",
1721                    "button.danger.active.background": "linear-gradient(180deg, #FECACA, #FCA5A5)"
1722                }
1723            }))
1724            .unwrap();
1725            crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1726
1727            assert_eq!(
1728                ButtonVariant::Primary.normal(true, cx).bg,
1729                cx.theme().tokens.primary.background.opacity(0.1)
1730            );
1731            assert_eq!(
1732                ButtonVariant::Danger.normal(true, cx).bg,
1733                cx.theme().tokens.danger.background.opacity(0.1)
1734            );
1735            assert_eq!(
1736                ButtonVariant::Danger.hovered(true, cx).bg,
1737                cx.theme().tokens.danger_hover.background.opacity(0.2)
1738            );
1739            assert_eq!(
1740                ButtonVariant::Danger.active(true, cx).bg,
1741                cx.theme().tokens.danger_active.background.opacity(0.4)
1742            );
1743            assert_eq!(
1744                ButtonVariant::Primary.normal(false, cx).bg,
1745                cx.theme().tokens.button_primary.into()
1746            );
1747            assert_eq!(
1748                ButtonVariant::Danger.normal(false, cx).bg,
1749                linear_gradient(
1750                    180.,
1751                    linear_color_stop(crate::try_parse_color("#FEF2F2").unwrap(), 0.),
1752                    linear_color_stop(crate::try_parse_color("#FEE2E2").unwrap(), 1.)
1753                )
1754            );
1755        });
1756    }
1757
1758    #[gpui::test]
1759    fn test_disabled_outline_buttons_keep_semantic_backgrounds(cx: &mut gpui::TestAppContext) {
1760        cx.update(crate::init);
1761        let window = cx.add_empty_window();
1762        window.update(|_, cx| {
1763            let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1764                "name": "Disabled Outline Gradient",
1765                "mode": "light",
1766                "colors": {
1767                    "primary.background": "linear-gradient(180deg, #111827, #020617)",
1768                    "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)",
1769                    "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)",
1770                    "button.danger.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)"
1771                }
1772            }))
1773            .unwrap();
1774            crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1775
1776            assert_eq!(
1777                ButtonVariant::Primary.disabled(true, cx).bg,
1778                cx.theme()
1779                    .tokens
1780                    .primary
1781                    .background
1782                    .opacity(0.1)
1783                    .opacity(0.5)
1784            );
1785            assert_eq!(
1786                ButtonVariant::Danger.disabled(true, cx).bg,
1787                cx.theme()
1788                    .tokens
1789                    .danger
1790                    .background
1791                    .opacity(0.1)
1792                    .opacity(0.5)
1793            );
1794            assert_ne!(
1795                ButtonVariant::Danger.disabled(true, cx).bg,
1796                cx.theme().input_background().opacity(0.5).into()
1797            );
1798            assert_ne!(
1799                ButtonVariant::Danger.disabled(true, cx).bg,
1800                cx.theme().tokens.button_danger.background.opacity(0.15)
1801            );
1802        });
1803    }
1804}