BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / button / button.rs

button.rs

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