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