Skip to main content

gpui_component/button/
button.rs

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