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