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 | Size::Small => this.gap(crate::fluent::BUTTON_ICON_GAP_SMALL),
749 _ => this.gap(crate::fluent::BUTTON_ICON_GAP),
750 })
751 .refine_style(&self.content_style)
752 .when_some(self.icon, |this, icon| {
753 this.child(
754 icon.loading_icon(self.loading_icon)
755 .loading(self.loading)
756 .with_size(icon_size),
757 )
758 })
759 .when_some(self.label, |this, label| {
760 this.child(
761 div()
762 .min_w_0()
763 .whitespace_nowrap()
764 .text_ellipsis()
765 .child(label),
766 )
767 })
768 .children(children)
769 .when(self.dropdown_caret, |this| {
770 this.when(has_content, |this| this.justify_between())
771 .child(Caret::new(self.size).text_color(normal_style.fg.opacity(0.75)))
772 });
773 root.role(self.role.resolve(|| {
774 if self.variant.is_link() {
775 Role::Link
776 } else {
777 Role::Button
778 }
779 }))
780 .selected(selected)
781 .disabled(disabled)
782 // Base layers semantic states over the builder chain, so the caller's
783 // own style is replayed inside each state to keep it the closest layer.
784 .styles(|styles| {
785 styles
786 .selected(|style| {
787 style
788 .bg(selected_style.bg)
789 .border_color(selected_style.border)
790 .text_color(selected_style.fg)
791 .refine_style(&instance_style)
792 })
793 .disabled(|style| {
794 style
795 .bg(disabled_style.bg)
796 .text_color(disabled_style.fg)
797 .border_color(disabled_style.border)
798 .shadow_none()
799 .refine_style(&instance_style)
800 })
801 })
802 .when_some(accessibility_label, |this, label| {
803 this.accessibility_label(label)
804 })
805 .when_some(self.toggled, |this, toggled| {
806 this.aria_toggled(if toggled {
807 gpui::accesskit::Toggled::True
808 } else {
809 gpui::accesskit::Toggled::False
810 })
811 })
812 .track_focus(&focus_handle)
813 .tab_index(self.tab_index)
814 .tab_stop(self.tab_stop)
815 .child(content)
816 // Fade the whole button while loading, so every variant is dimmed by
817 // the same amount. Fading `bg`, `border` and `fg` one by one instead
818 // only shows up on variants that have a background to begin with:
819 // `Ghost`, `Link` and `Text` are transparent, so an alpha on their
820 // background changes nothing.
821 .when(loading && !disabled, |this| this.opacity(0.8))
822 .when(!disabled, |this| {
823 this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
824 if loading {
825 cx.stop_propagation();
826 return;
827 }
828
829 // Avoid focus on mouse down.
830 window.prevent_default();
831
832 // Pressing a button must not start the window-level text selection.
833 crate::global_state::GlobalState::suppress_text_selection(cx);
834 })
835 })
836 .when_some(self.on_click, |this, on_click| {
837 this.on_click(move |event, window, cx| {
838 if loading {
839 cx.stop_propagation();
840 return;
841 }
842
843 on_click(event, window, cx);
844 })
845 })
846 .when(loading, |this| {
847 this.on_click(|_, _, cx| cx.stop_propagation())
848 })
849 .when_some(self.on_hover.filter(|_| hoverable), |this, on_hover| {
850 this.on_hover(move |hovered, window, cx| {
851 on_hover(hovered, window, cx);
852 })
853 })
854 .map(|this| {
855 if let Some(builder) = self.tooltip_builder {
856 this.managed_tooltip_with_placement(tooltip_placement, move |window, cx| {
857 builder(window, cx)
858 })
859 } else if let Some((tooltip, action)) = self.tooltip {
860 this.managed_tooltip_with_placement(tooltip_placement, move |window, cx| {
861 Tooltip::new(tooltip.clone())
862 .when_some(action.clone(), |this, (action, context)| {
863 this.action(
864 action.boxed_clone().as_ref(),
865 context.as_ref().map(|c| c.as_ref()),
866 )
867 })
868 .build(window, cx)
869 })
870 } else {
871 this
872 }
873 })
874 .when(is_focused && self.focus_ring_enabled && window.last_input_was_keyboard(), |this| {
875 focus_style(this, focus_line, window, cx)
876 })
877 }
878}
879
880struct ButtonVariantStyle {
881 bg: Background,
882 border: Hsla,
883 fg: Hsla,
884 underline: bool,
885 shadow: bool,
886}
887
888#[derive(Clone, Copy)]
889enum ButtonStyleState {
890 Normal,
891 Hovered,
892 Active,
893}
894
895impl ButtonVariant {
896 fn outline_background(&self, state: ButtonStyleState, cx: &mut App) -> Background {
897 match (self, state) {
898 (Self::Default, ButtonStyleState::Normal) => cx.theme().input_background().into(),
899 (Self::Default, ButtonStyleState::Hovered) => cx
900 .theme()
901 .input
902 .mix_oklab(cx.theme().transparent, 0.5)
903 .into(),
904 (Self::Default, ButtonStyleState::Active) => cx
905 .theme()
906 .input
907 .mix_oklab(cx.theme().transparent, 0.7)
908 .into(),
909 (Self::Primary, ButtonStyleState::Normal) => {
910 cx.theme().tokens.primary.background.opacity(0.1)
911 }
912 (Self::Primary, ButtonStyleState::Hovered) => {
913 cx.theme().tokens.primary_hover.background.opacity(0.2)
914 }
915 (Self::Primary, ButtonStyleState::Active) => {
916 cx.theme().tokens.primary_active.background.opacity(0.4)
917 }
918 (Self::Secondary, ButtonStyleState::Normal) => {
919 cx.theme().tokens.secondary.background.opacity(0.1)
920 }
921 (Self::Secondary, ButtonStyleState::Hovered) => {
922 cx.theme().tokens.secondary_hover.background.opacity(0.2)
923 }
924 (Self::Secondary, ButtonStyleState::Active) => {
925 cx.theme().tokens.secondary_active.background.opacity(0.4)
926 }
927 (Self::Danger, ButtonStyleState::Normal) => {
928 cx.theme().tokens.danger.background.opacity(0.1)
929 }
930 (Self::Danger, ButtonStyleState::Hovered) => {
931 cx.theme().tokens.danger_hover.background.opacity(0.2)
932 }
933 (Self::Danger, ButtonStyleState::Active) => {
934 cx.theme().tokens.danger_active.background.opacity(0.4)
935 }
936 (Self::Warning, ButtonStyleState::Normal) => {
937 cx.theme().tokens.warning.background.opacity(0.1)
938 }
939 (Self::Warning, ButtonStyleState::Hovered) => {
940 cx.theme().tokens.warning_hover.background.opacity(0.2)
941 }
942 (Self::Warning, ButtonStyleState::Active) => {
943 cx.theme().tokens.warning_active.background.opacity(0.4)
944 }
945 (Self::Success, ButtonStyleState::Normal) => {
946 cx.theme().tokens.success.background.opacity(0.1)
947 }
948 (Self::Success, ButtonStyleState::Hovered) => {
949 cx.theme().tokens.success_hover.background.opacity(0.2)
950 }
951 (Self::Success, ButtonStyleState::Active) => {
952 cx.theme().tokens.success_active.background.opacity(0.4)
953 }
954 (Self::Info, ButtonStyleState::Normal) => {
955 cx.theme().tokens.info.background.opacity(0.1)
956 }
957 (Self::Info, ButtonStyleState::Hovered) => {
958 cx.theme().tokens.info_hover.background.opacity(0.2)
959 }
960 (Self::Info, ButtonStyleState::Active) => {
961 cx.theme().tokens.info_active.background.opacity(0.4)
962 }
963 (Self::Ghost | Self::Link | Self::Text, _) => cx.theme().transparent.into(),
964 (Self::Custom(colors), _) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(),
965 }
966 }
967
968 fn bg_color(&self, outline: bool, cx: &mut App) -> Background {
969 if outline {
970 return self.outline_background(ButtonStyleState::Normal, cx);
971 }
972
973 match self {
974 Self::Default => cx.theme().tokens.button.into(),
975 Self::Primary => cx.theme().tokens.button_primary.into(),
976 Self::Secondary => cx.theme().tokens.button_secondary.into(),
977 Self::Danger => cx.theme().tokens.button_danger.into(),
978 Self::Warning => cx.theme().tokens.button_warning.into(),
979 Self::Success => cx.theme().tokens.button_success.into(),
980 Self::Info => cx.theme().tokens.button_info.into(),
981 Self::Ghost | Self::Link | Self::Text => cx.theme().transparent.into(),
982 Self::Custom(colors) => colors.color.mix_oklab(cx.theme().transparent, 0.2).into(),
983 }
984 }
985
986 fn text_color(&self, outline: bool, cx: &mut App) -> Hsla {
987 match self {
988 Self::Default => cx.theme().button_foreground,
989 Self::Primary => {
990 if outline {
991 cx.theme().primary
992 } else {
993 cx.theme().button_primary_foreground
994 }
995 }
996 Self::Secondary => {
997 if outline {
998 cx.theme().secondary_foreground
999 } else {
1000 cx.theme().button_secondary_foreground
1001 }
1002 }
1003 Self::Ghost => cx.theme().secondary_foreground,
1004 Self::Danger => {
1005 if outline {
1006 cx.theme().danger
1007 } else {
1008 cx.theme().button_danger_foreground
1009 }
1010 }
1011 Self::Warning => {
1012 if outline {
1013 cx.theme().warning
1014 } else {
1015 cx.theme().button_warning_foreground
1016 }
1017 }
1018 Self::Success => {
1019 if outline {
1020 cx.theme().success
1021 } else {
1022 cx.theme().button_success_foreground
1023 }
1024 }
1025 Self::Info => {
1026 if outline {
1027 cx.theme().info
1028 } else {
1029 cx.theme().button_info_foreground
1030 }
1031 }
1032 Self::Link => cx.theme().link,
1033 Self::Text => cx.theme().foreground.opacity(0.9),
1034 Self::Custom(colors) => colors.foreground,
1035 }
1036 }
1037
1038 fn border_color(&self, outline: bool, cx: &mut App) -> Hsla {
1039 match self {
1040 Self::Default => cx.theme().input,
1041 Self::Secondary => cx.theme().border,
1042 Self::Primary => cx.theme().primary,
1043 Self::Danger => {
1044 if outline {
1045 cx.theme().danger.mix_oklab(transparent_white(), 0.4)
1046 } else {
1047 cx.theme().button_danger
1048 }
1049 }
1050 Self::Info => {
1051 if outline {
1052 cx.theme().info.mix_oklab(transparent_white(), 0.4)
1053 } else {
1054 cx.theme().button_info
1055 }
1056 }
1057 Self::Warning => {
1058 if outline {
1059 cx.theme().warning.mix_oklab(transparent_white(), 0.4)
1060 } else {
1061 cx.theme().button_warning
1062 }
1063 }
1064 Self::Success => {
1065 if outline {
1066 cx.theme().success.mix_oklab(transparent_white(), 0.4)
1067 } else {
1068 cx.theme().button_success
1069 }
1070 }
1071 Self::Ghost | Self::Link | Self::Text => cx.theme().transparent,
1072 Self::Custom(colors) => {
1073 if outline {
1074 colors.color.mix_oklab(transparent_white(), 0.4)
1075 } else {
1076 colors.color
1077 }
1078 }
1079 }
1080 }
1081
1082 fn underline(&self, _: &App) -> bool {
1083 match self {
1084 Self::Link => true,
1085 _ => false,
1086 }
1087 }
1088
1089 fn shadow(&self, _outline: bool, _: &App) -> bool {
1090 match self {
1091 Self::Custom(c) => c.shadow,
1092 _ => false,
1093 }
1094 }
1095
1096 fn normal(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1097 let bg = self.bg_color(outline, cx);
1098 let border = self.border_color(outline, cx);
1099 let fg = self.text_color(outline, cx);
1100 let underline = self.underline(cx);
1101 let shadow = self.shadow(outline, cx);
1102
1103 ButtonVariantStyle {
1104 bg,
1105 border,
1106 fg,
1107 underline,
1108 shadow,
1109 }
1110 }
1111
1112 fn hovered(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1113 let bg: Background = match self {
1114 Self::Default => {
1115 if outline {
1116 self.outline_background(ButtonStyleState::Hovered, cx)
1117 } else {
1118 cx.theme().tokens.button_hover.into()
1119 }
1120 }
1121 Self::Primary => {
1122 if outline {
1123 self.outline_background(ButtonStyleState::Hovered, cx)
1124 } else {
1125 cx.theme().tokens.button_primary_hover.into()
1126 }
1127 }
1128 Self::Secondary => {
1129 if outline {
1130 self.outline_background(ButtonStyleState::Hovered, cx)
1131 } else {
1132 cx.theme().tokens.button_secondary_hover.into()
1133 }
1134 }
1135 Self::Danger => {
1136 if outline {
1137 self.outline_background(ButtonStyleState::Hovered, cx)
1138 } else {
1139 cx.theme().tokens.button_danger_hover.into()
1140 }
1141 }
1142 Self::Warning => {
1143 if outline {
1144 self.outline_background(ButtonStyleState::Hovered, cx)
1145 } else {
1146 cx.theme().tokens.button_warning_hover.into()
1147 }
1148 }
1149 Self::Success => {
1150 if outline {
1151 self.outline_background(ButtonStyleState::Hovered, cx)
1152 } else {
1153 cx.theme().tokens.button_success_hover.into()
1154 }
1155 }
1156 Self::Info => {
1157 if outline {
1158 self.outline_background(ButtonStyleState::Hovered, cx)
1159 } else {
1160 cx.theme().tokens.button_info_hover.into()
1161 }
1162 }
1163 Self::Custom(colors) => colors.hover.into(),
1164 Self::Ghost => {
1165 let accent: Background = cx.theme().tokens.accent.into();
1166 if cx.theme().mode.is_dark() {
1167 accent.opacity(0.5)
1168 } else {
1169 accent
1170 }
1171 }
1172 Self::Link => cx.theme().transparent.into(),
1173 Self::Text => cx.theme().transparent.into(),
1174 };
1175
1176 let border = self.border_color(outline, cx);
1177 let fg = match self {
1178 Self::Link => cx.theme().link_hover,
1179 Self::Text => cx.theme().foreground,
1180 Self::Ghost => cx.theme().accent_foreground,
1181 _ => self.text_color(outline, cx),
1182 };
1183
1184 let underline = self.underline(cx);
1185 let shadow = self.shadow(outline, cx);
1186
1187 ButtonVariantStyle {
1188 bg,
1189 border,
1190 fg,
1191 underline,
1192 shadow,
1193 }
1194 }
1195
1196 fn active(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1197 let bg = match self {
1198 Self::Default => {
1199 if outline {
1200 self.outline_background(ButtonStyleState::Active, cx)
1201 } else {
1202 cx.theme().tokens.button_active.into()
1203 }
1204 }
1205 Self::Primary => {
1206 if outline {
1207 self.outline_background(ButtonStyleState::Active, cx)
1208 } else {
1209 cx.theme().tokens.button_primary_active.into()
1210 }
1211 }
1212 Self::Secondary => {
1213 if outline {
1214 self.outline_background(ButtonStyleState::Active, cx)
1215 } else {
1216 cx.theme().tokens.button_secondary_active.into()
1217 }
1218 }
1219 Self::Ghost => cx.theme().tokens.button_active.into(),
1220 Self::Danger => {
1221 if outline {
1222 self.outline_background(ButtonStyleState::Active, cx)
1223 } else {
1224 cx.theme().tokens.button_danger_active.into()
1225 }
1226 }
1227 Self::Warning => {
1228 if outline {
1229 self.outline_background(ButtonStyleState::Active, cx)
1230 } else {
1231 cx.theme().tokens.button_warning_active.into()
1232 }
1233 }
1234 Self::Success => {
1235 if outline {
1236 self.outline_background(ButtonStyleState::Active, cx)
1237 } else {
1238 cx.theme().tokens.button_success_active.into()
1239 }
1240 }
1241 Self::Info => {
1242 if outline {
1243 self.outline_background(ButtonStyleState::Active, cx)
1244 } else {
1245 cx.theme().tokens.button_info_active.into()
1246 }
1247 }
1248 Self::Custom(colors) => colors.active.into(),
1249 Self::Link => cx.theme().transparent.into(),
1250 Self::Text => cx.theme().transparent.into(),
1251 };
1252 let border = self.border_color(outline, cx);
1253 let fg = match self {
1254 Self::Link => cx.theme().link_active,
1255 Self::Text => cx.theme().foreground.opacity(0.7),
1256 _ => self.text_color(outline, cx),
1257 };
1258 let underline = self.underline(cx);
1259 let shadow = self.shadow(outline, cx);
1260
1261 ButtonVariantStyle {
1262 bg,
1263 border,
1264 fg,
1265 underline,
1266 shadow,
1267 }
1268 }
1269
1270 fn selected(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1271 if outline {
1272 let active_style = self.active(outline, cx);
1273
1274 return ButtonVariantStyle {
1275 fg: self.text_color(outline, cx),
1276 ..active_style
1277 };
1278 }
1279
1280 let bg = match self {
1281 Self::Default => cx.theme().tokens.button_active.into(),
1282 Self::Primary => cx.theme().tokens.button_primary_active.into(),
1283 Self::Secondary => cx.theme().tokens.button_secondary_active.into(),
1284 Self::Ghost => cx.theme().tokens.secondary_active.into(),
1285 Self::Danger => cx.theme().tokens.button_danger_active.into(),
1286 Self::Warning => cx.theme().tokens.button_warning_active.into(),
1287 Self::Success => cx.theme().tokens.button_success_active.into(),
1288 Self::Info => cx.theme().tokens.button_info_active.into(),
1289 Self::Link => cx.theme().transparent.into(),
1290 Self::Text => cx.theme().transparent.into(),
1291 Self::Custom(colors) => colors.active.into(),
1292 };
1293
1294 let border = self.border_color(outline, cx);
1295 let fg = match self {
1296 Self::Link => cx.theme().link_active,
1297 Self::Text => cx.theme().foreground.opacity(0.7),
1298 _ => self.text_color(false, cx),
1299 };
1300 let underline = self.underline(cx);
1301 let shadow = self.shadow(outline, cx);
1302
1303 ButtonVariantStyle {
1304 bg,
1305 border,
1306 fg,
1307 underline,
1308 shadow,
1309 }
1310 }
1311
1312 fn disabled(&self, outline: bool, cx: &mut App) -> ButtonVariantStyle {
1313 let bg = match self {
1314 Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent.into(),
1315 Self::Primary => cx.theme().tokens.button_primary.background.opacity(0.15),
1316 Self::Danger => cx.theme().tokens.button_danger.background.opacity(0.15),
1317 Self::Warning => cx.theme().tokens.button_warning.background.opacity(0.15),
1318 Self::Success => cx.theme().tokens.button_success.background.opacity(0.15),
1319 Self::Info => cx.theme().tokens.button_info.background.opacity(0.15),
1320 Self::Secondary => cx.theme().tokens.button_secondary.background.opacity(1.5),
1321 Self::Custom(style) => style.color.opacity(0.15).into(),
1322 };
1323 let fg = cx.theme().muted_foreground.opacity(0.5);
1324 let (bg, border) = if outline {
1325 (
1326 self.outline_background(ButtonStyleState::Normal, cx)
1327 .opacity(0.5),
1328 self.border_color(true, cx).opacity(0.5),
1329 )
1330 } else if let Self::Default = self {
1331 (
1332 cx.theme().input_background().opacity(0.5).into(),
1333 cx.theme().input.opacity(0.5),
1334 )
1335 } else {
1336 let border = match self {
1337 Self::Primary => cx.theme().button_primary.opacity(0.15),
1338 Self::Secondary => cx.theme().button_secondary.opacity(1.5),
1339 Self::Danger => cx.theme().button_danger.opacity(0.15),
1340 Self::Warning => cx.theme().button_warning.opacity(0.15),
1341 Self::Success => cx.theme().button_success.opacity(0.15),
1342 Self::Info => cx.theme().button_info.opacity(0.15),
1343 Self::Custom(style) => style.color.opacity(0.15),
1344 Self::Default | Self::Link | Self::Ghost | Self::Text => cx.theme().transparent,
1345 };
1346 (bg, border)
1347 };
1348
1349 let underline = self.underline(cx);
1350 let shadow = false;
1351
1352 ButtonVariantStyle {
1353 bg,
1354 border,
1355 fg,
1356 underline,
1357 shadow,
1358 }
1359 }
1360}
1361
1362#[cfg(test)]
1363mod tests {
1364 use super::*;
1365 use crate::IconName;
1366 use gpui::{linear_color_stop, linear_gradient, px};
1367
1368 /// A button's announced name is its label, unless it was given one — which
1369 /// is the case an icon-only button and a row-shaped button both need.
1370 #[test]
1371 fn an_explicit_accessibility_label_replaces_the_visible_one() {
1372 let plain = Button::new("save").label("Save");
1373 assert_eq!(plain.accessibility_label, None);
1374 assert_eq!(plain.label.as_deref(), Some("Save"));
1375
1376 let named = Button::new("row")
1377 .label("Save")
1378 .accessibility_label("Save the current document");
1379 assert_eq!(
1380 named.accessibility_label.as_deref(),
1381 Some("Save the current document"),
1382 "an explicit name must win over the visible label"
1383 );
1384 assert_eq!(
1385 named.label.as_deref(),
1386 Some("Save"),
1387 "and must not change what is drawn"
1388 );
1389 }
1390
1391 #[gpui::test]
1392 fn disabled_legacy_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) {
1393 use std::{cell::Cell, rc::Rc};
1394
1395 use gpui::{Context, Modifiers, Render, point};
1396
1397 struct Harness(Rc<Cell<usize>>, Rc<Cell<usize>>);
1398
1399 impl Render for Harness {
1400 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1401 let button_clicks = self.0.clone();
1402 let parent_clicks = self.1.clone();
1403 div()
1404 .id("disabled-button-parent")
1405 .tab_group()
1406 .size(px(100.))
1407 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
1408 .child(
1409 Button::new("disabled-legacy")
1410 .disabled(true)
1411 .size_full()
1412 .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)),
1413 )
1414 }
1415 }
1416
1417 cx.update(crate::init);
1418 let button_clicks = Rc::new(Cell::new(0));
1419 let parent_clicks = Rc::new(Cell::new(0));
1420 let (_, cx) = cx.add_window_view({
1421 let button_clicks = button_clicks.clone();
1422 let parent_clicks = parent_clicks.clone();
1423 move |_, _| Harness(button_clicks, parent_clicks)
1424 });
1425 cx.update(|window, cx| window.draw(cx).clear(cx));
1426 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1427 cx.update(|window, cx| window.focus_next(cx));
1428 cx.simulate_keystrokes("enter space");
1429
1430 assert_eq!(button_clicks.get(), 0);
1431 assert_eq!(parent_clicks.get(), 0);
1432 cx.update(|window, cx| assert!(window.focused(cx).is_none()));
1433 }
1434
1435 #[gpui::test]
1436 fn enabled_button_delegates_pointer_enter_and_space_once(cx: &mut gpui::TestAppContext) {
1437 use std::{cell::Cell, rc::Rc};
1438
1439 use gpui::{
1440 ClickEvent, Context, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, Render, point,
1441 };
1442
1443 struct Harness(Rc<Cell<usize>>, Rc<Cell<usize>>);
1444
1445 impl Render for Harness {
1446 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1447 let clicks = self.0.clone();
1448 let keyboard_clicks = self.1.clone();
1449 div().tab_group().size(px(100.)).child(
1450 Button::new("enabled-legacy")
1451 .size_full()
1452 .on_click(move |event, _, _| {
1453 clicks.set(clicks.get() + 1);
1454 if matches!(event, ClickEvent::Keyboard(_)) {
1455 keyboard_clicks.set(keyboard_clicks.get() + 1);
1456 }
1457 }),
1458 )
1459 }
1460 }
1461
1462 cx.update(crate::init);
1463 let clicks = Rc::new(Cell::new(0));
1464 let keyboard_clicks = Rc::new(Cell::new(0));
1465 let (_, cx) = cx.add_window_view({
1466 let clicks = clicks.clone();
1467 let keyboard_clicks = keyboard_clicks.clone();
1468 move |_, _| Harness(clicks, keyboard_clicks)
1469 });
1470 cx.update(|window, cx| window.draw(cx).clear(cx));
1471 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1472 cx.update(|window, cx| window.focus_next(cx));
1473 cx.update(|window, cx| {
1474 assert!(window.focused(cx).is_some());
1475 window.draw(cx).clear(cx);
1476 });
1477 for key in ["enter", "space"] {
1478 let keystroke = Keystroke::parse(key).unwrap();
1479 cx.simulate_event(KeyDownEvent {
1480 keystroke: keystroke.clone(),
1481 is_held: false,
1482 prefer_character_input: false,
1483 });
1484 cx.simulate_event(KeyUpEvent { keystroke });
1485 }
1486
1487 assert_eq!(clicks.get(), 3);
1488 assert_eq!(keyboard_clicks.get(), 2);
1489 }
1490
1491 #[gpui::test]
1492 fn loading_button_keeps_existing_pointer_blocking(cx: &mut gpui::TestAppContext) {
1493 use std::{cell::Cell, rc::Rc};
1494
1495 use gpui::{Context, Modifiers, Render, point};
1496
1497 struct Harness(Rc<Cell<usize>>, Rc<Cell<usize>>);
1498
1499 impl Render for Harness {
1500 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1501 let button_clicks = self.0.clone();
1502 let parent_clicks = self.1.clone();
1503 div()
1504 .id("loading-button-parent")
1505 .tab_group()
1506 .size(px(100.))
1507 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
1508 .child(
1509 Button::new("loading-legacy")
1510 .loading(true)
1511 .size_full()
1512 .on_click(move |_, _, _| button_clicks.set(button_clicks.get() + 1)),
1513 )
1514 }
1515 }
1516
1517 cx.update(crate::init);
1518 let button_clicks = Rc::new(Cell::new(0));
1519 let parent_clicks = Rc::new(Cell::new(0));
1520 let (_, cx) = cx.add_window_view({
1521 let button_clicks = button_clicks.clone();
1522 let parent_clicks = parent_clicks.clone();
1523 move |_, _| Harness(button_clicks, parent_clicks)
1524 });
1525 cx.update(|window, cx| window.draw(cx).clear(cx));
1526 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1527 cx.update(|window, cx| window.focus_next(cx));
1528 cx.simulate_keystrokes("enter space");
1529
1530 assert_eq!(button_clicks.get(), 0);
1531 assert_eq!(parent_clicks.get(), 0);
1532 cx.update(|window, cx| assert!(window.focused(cx).is_some()));
1533 }
1534
1535 #[gpui::test]
1536 fn loading_button_without_callback_still_blocks_parent_activation(
1537 cx: &mut gpui::TestAppContext,
1538 ) {
1539 use std::{cell::Cell, rc::Rc};
1540
1541 use gpui::{Context, Modifiers, Render, point};
1542
1543 struct Harness(Rc<Cell<usize>>);
1544
1545 impl Render for Harness {
1546 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1547 let parent_clicks = self.0.clone();
1548 div()
1549 .id("loading-without-callback-parent")
1550 .tab_group()
1551 .size(px(100.))
1552 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
1553 .child(
1554 Button::new("loading-without-callback")
1555 .loading(true)
1556 .size_full(),
1557 )
1558 }
1559 }
1560
1561 cx.update(crate::init);
1562 let parent_clicks = Rc::new(Cell::new(0));
1563 let (_, cx) = cx.add_window_view({
1564 let parent_clicks = parent_clicks.clone();
1565 move |_, _| Harness(parent_clicks)
1566 });
1567 cx.update(|window, cx| window.draw(cx).clear(cx));
1568 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
1569 cx.update(|window, cx| window.focus_next(cx));
1570 cx.simulate_keystrokes("enter space");
1571
1572 assert_eq!(parent_clicks.get(), 0);
1573 cx.update(|window, cx| assert!(window.focused(cx).is_some()));
1574 }
1575
1576 #[gpui::test]
1577 fn base_activation_is_preserved_and_blocked_while_loading(cx: &mut gpui::TestAppContext) {
1578 use gpui::{Context, Render, point};
1579 use std::{cell::Cell, rc::Rc};
1580
1581 struct Harness {
1582 clicks: Rc<Cell<usize>>,
1583 loading: bool,
1584 }
1585 impl Render for Harness {
1586 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1587 let clicks = self.clicks.clone();
1588 div().tab_group().child(
1589 Button::new("close")
1590 .with_base(
1591 gpui_base::Button::new("close")
1592 .on_click(move |_, _, _| clicks.set(clicks.get() + 1)),
1593 )
1594 .loading(self.loading)
1595 .size(px(100.)),
1596 )
1597 }
1598 }
1599
1600 cx.update(crate::init);
1601 let clicks = Rc::new(Cell::new(0));
1602 let (view, cx) = cx.add_window_view({
1603 let clicks = clicks.clone();
1604 move |_, _| Harness {
1605 clicks,
1606 loading: false,
1607 }
1608 });
1609 cx.update(|window, cx| window.draw(cx).clear(cx));
1610 cx.simulate_click(point(px(10.), px(10.)), Default::default());
1611 assert_eq!(clicks.get(), 1);
1612
1613 view.update(cx, |view, cx| {
1614 view.loading = true;
1615 cx.notify();
1616 });
1617 cx.update(|window, cx| window.draw(cx).clear(cx));
1618 cx.simulate_click(point(px(10.), px(10.)), Default::default());
1619 cx.update(|window, cx| window.focus_next(cx));
1620 cx.simulate_keystrokes("enter space");
1621 assert_eq!(clicks.get(), 1);
1622 }
1623
1624 #[gpui::test]
1625 fn test_button_builder(_cx: &mut gpui::TestAppContext) {
1626 let button = Button::new("complex-button")
1627 .label("Save Changes")
1628 .primary()
1629 .outline()
1630 .large()
1631 .tooltip("Click to save")
1632 .compact()
1633 .loading(false)
1634 .disabled(false)
1635 .selected(false)
1636 .tab_index(1)
1637 .tab_stop(true)
1638 .dropdown_caret(false)
1639 .rounded(ButtonRounded::Medium)
1640 .on_click(|_, _, _| {});
1641
1642 assert_eq!(button.label, Some("Save Changes".into()));
1643 assert_eq!(button.variant, ButtonVariant::Primary);
1644 assert!(button.outline);
1645 assert_eq!(button.size, Size::Large);
1646 assert!(button.tooltip.is_some());
1647 assert!(button.compact);
1648 assert!(!button.loading);
1649 assert!(!button.disabled);
1650 assert!(!button.selected);
1651 assert_eq!(button.toggled, None);
1652 assert_eq!(button.tab_index, 1);
1653 assert!(button.tab_stop);
1654 assert!(!button.dropdown_caret);
1655 assert!(matches!(button.rounded, ButtonRounded::Medium));
1656 }
1657
1658 /// A button paints an open popup the way it paints a selection, but the
1659 /// two states are stored apart, so a caller can read back which one it set
1660 /// and a later design can tell them apart visually.
1661 #[test]
1662 fn an_open_trigger_is_stored_apart_from_a_selected_one() {
1663 let open = Button::new("trigger").open(true);
1664 assert!(open.is_open());
1665 assert!(!open.is_selected());
1666 assert!(open.shows_selected_style());
1667
1668 let selected = Button::new("trigger").selected(true);
1669 assert!(selected.is_selected());
1670 assert!(!selected.is_open());
1671 assert!(selected.shows_selected_style());
1672
1673 assert!(!Button::new("trigger").shows_selected_style());
1674 }
1675
1676 #[test]
1677 fn selected_trigger_presentation_does_not_imply_toggled_accessibility() {
1678 let selected = Button::new("menu-trigger").selected(true);
1679 assert!(selected.selected);
1680 assert_eq!(selected.toggled, None);
1681
1682 let selected_toggle = Button::new("explicit-toggle").selected(true).toggled(true);
1683 assert!(selected_toggle.selected);
1684 assert_eq!(selected_toggle.toggled, Some(true));
1685 }
1686
1687 /// A loading button must be as inert as a disabled one. `interactive` is what
1688 /// gates the hover and active styling, the `cursor_pointer` of link buttons and
1689 /// the `mouse_down` handler, none of which depend on a listener being set.
1690 #[gpui::test]
1691 fn test_button_loading_is_not_interactive(_cx: &mut gpui::TestAppContext) {
1692 assert!(Button::new("test").interactive());
1693 assert!(!Button::new("test").loading(true).interactive());
1694 assert!(!Button::new("test").disabled(true).interactive());
1695 assert!(
1696 !Button::new("test")
1697 .loading(true)
1698 .disabled(true)
1699 .interactive()
1700 );
1701
1702 // Loading gates hovering even when an `on_hover` listener is set.
1703 let loading = Button::new("test").loading(true).on_hover(|_, _, _| {});
1704 assert!(!loading.hoverable());
1705 }
1706
1707 /// `selected` is styling only; the toggle state must be opted into, so that
1708 /// ordinary buttons are not announced as toggle buttons.
1709 #[gpui::test]
1710 fn test_button_variant_methods(_cx: &mut gpui::TestAppContext) {
1711 // Test variant check methods
1712 assert!(ButtonVariant::Link.is_link());
1713 assert!(ButtonVariant::Text.is_text());
1714 assert!(ButtonVariant::Ghost.is_ghost());
1715
1716 // Test no_padding logic
1717 assert!(ButtonVariant::Link.no_padding());
1718 assert!(ButtonVariant::Text.no_padding());
1719 assert!(!ButtonVariant::Ghost.no_padding());
1720 }
1721
1722 #[gpui::test]
1723 fn link_button_prepaints_its_child(cx: &mut gpui::TestAppContext) {
1724 use gpui::{Context, Render};
1725
1726 struct LinkButtonHarness;
1727
1728 impl Render for LinkButtonHarness {
1729 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1730 Button::new("link-button").link().child(
1731 div()
1732 .debug_selector(|| "link-button-child".into())
1733 .child("Visible link button"),
1734 )
1735 }
1736 }
1737
1738 cx.update(crate::init);
1739 let (_, cx) = cx.add_window_view(|_, _| LinkButtonHarness);
1740 cx.update(|window, cx| window.draw(cx).clear(cx));
1741
1742 let bounds = cx
1743 .debug_bounds("link-button-child")
1744 .expect("link button child must participate in layout and prepaint");
1745 assert!(bounds.size.width > px(0.));
1746 assert!(bounds.size.height > px(0.));
1747 }
1748
1749 #[gpui::test]
1750 fn base_slot_prepaints_complete_button_content(cx: &mut gpui::TestAppContext) {
1751 use gpui::{Context, Render};
1752
1753 struct CompleteButtonHarness;
1754
1755 impl Render for CompleteButtonHarness {
1756 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1757 div()
1758 .child(
1759 Button::new("complete-button")
1760 .icon(IconName::Plus)
1761 .label("Create")
1762 .child(
1763 div()
1764 .debug_selector(|| "button-custom-content".into())
1765 .child("Details"),
1766 )
1767 .dropdown_caret(true),
1768 )
1769 .child(
1770 Button::new("loading-button")
1771 .icon(IconName::Plus)
1772 .loading_icon(IconName::Loader)
1773 .loading(true)
1774 .label("Creating")
1775 .dropdown_caret(true),
1776 )
1777 }
1778 }
1779
1780 cx.update(crate::init);
1781 let (_, cx) = cx.add_window_view(|_, _| CompleteButtonHarness);
1782 cx.update(|window, cx| window.draw(cx).clear(cx));
1783
1784 let bounds = cx
1785 .debug_bounds("button-custom-content")
1786 .expect("application content must prepaint through the Base child seam");
1787 assert!(bounds.size.width > px(0.));
1788 assert!(bounds.size.height > px(0.));
1789 }
1790
1791 #[gpui::test]
1792 fn test_outline_selected_uses_outline_active_style(cx: &mut gpui::TestAppContext) {
1793 cx.update(crate::init);
1794 let window = cx.add_empty_window();
1795 window.update(|_, cx| {
1796 let variant = ButtonVariant::Danger;
1797 let active_style = variant.active(true, cx);
1798 let selected_style = variant.selected(true, cx);
1799
1800 assert_eq!(selected_style.bg, active_style.bg);
1801 assert_eq!(selected_style.border, active_style.border);
1802 assert_eq!(selected_style.fg, cx.theme().danger);
1803 assert_ne!(selected_style.bg, cx.theme().tokens.danger_active.into());
1804 });
1805 }
1806
1807 #[gpui::test]
1808 fn test_primary_button_uses_gradient_background_tokens(cx: &mut gpui::TestAppContext) {
1809 cx.update(crate::init);
1810 let window = cx.add_empty_window();
1811 window.update(|_, cx| {
1812 let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1813 "name": "Gradient",
1814 "mode": "light",
1815 "colors": {
1816 "button.primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)",
1817 "button.primary.hover.background": "linear-gradient(145deg, #4338CA, #0891B2)",
1818 "button.primary.active.background": "linear-gradient(155deg, #3730A3, #0E7490)"
1819 }
1820 }))
1821 .unwrap();
1822 crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1823
1824 assert_eq!(
1825 ButtonVariant::Primary.normal(false, cx).bg,
1826 cx.theme().tokens.button_primary.into()
1827 );
1828 assert_eq!(
1829 ButtonVariant::Primary.hovered(false, cx).bg,
1830 cx.theme().tokens.button_primary_hover.into()
1831 );
1832 assert_eq!(
1833 ButtonVariant::Primary.active(false, cx).bg,
1834 cx.theme().tokens.button_primary_active.into()
1835 );
1836 });
1837 }
1838
1839 #[gpui::test]
1840 fn test_outline_primary_keeps_original_depth(cx: &mut gpui::TestAppContext) {
1841 cx.update(crate::init);
1842 let window = cx.add_empty_window();
1843 window.update(|_, cx| {
1844 let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1845 "name": "Outline Depth",
1846 "mode": "light",
1847 "colors": {
1848 "primary.background": "linear-gradient(180deg, #111827, #020617)",
1849 "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)",
1850 "primary.active.background": "linear-gradient(180deg, #020617, #000000)"
1851 }
1852 }))
1853 .unwrap();
1854 crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1855
1856 assert_eq!(
1857 ButtonVariant::Primary.normal(true, cx).bg,
1858 cx.theme().tokens.primary.background.opacity(0.1)
1859 );
1860 assert_eq!(
1861 ButtonVariant::Primary.hovered(true, cx).bg,
1862 cx.theme().tokens.primary_hover.background.opacity(0.2)
1863 );
1864 assert_eq!(
1865 ButtonVariant::Primary.active(true, cx).bg,
1866 cx.theme().tokens.primary_active.background.opacity(0.4)
1867 );
1868 });
1869 }
1870
1871 #[gpui::test]
1872 fn test_outline_buttons_use_semantic_gradient_tokens(cx: &mut gpui::TestAppContext) {
1873 cx.update(crate::init);
1874 let window = cx.add_empty_window();
1875 window.update(|_, cx| {
1876 let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1877 "name": "Outline Gradient",
1878 "mode": "light",
1879 "colors": {
1880 "primary.background": "linear-gradient(180deg, #111827, #020617)",
1881 "primary.hover.background": "linear-gradient(180deg, #1F2937, #111827)",
1882 "primary.active.background": "linear-gradient(180deg, #020617, #000000)",
1883 "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)",
1884 "button.primary.hover.background": "linear-gradient(180deg, #F9FAFB, #E5E7EB)",
1885 "button.primary.active.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)",
1886 "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)",
1887 "danger.hover.background": "linear-gradient(180deg, #F87171, #EF4444)",
1888 "danger.active.background": "linear-gradient(180deg, #DC2626, #B91C1C)",
1889 "button.danger.background": "linear-gradient(180deg, #FEF2F2, #FEE2E2)",
1890 "button.danger.hover.background": "linear-gradient(180deg, #FEE2E2, #FECACA)",
1891 "button.danger.active.background": "linear-gradient(180deg, #FECACA, #FCA5A5)"
1892 }
1893 }))
1894 .unwrap();
1895 crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1896
1897 assert_eq!(
1898 ButtonVariant::Primary.normal(true, cx).bg,
1899 cx.theme().tokens.primary.background.opacity(0.1)
1900 );
1901 assert_eq!(
1902 ButtonVariant::Danger.normal(true, cx).bg,
1903 cx.theme().tokens.danger.background.opacity(0.1)
1904 );
1905 assert_eq!(
1906 ButtonVariant::Danger.hovered(true, cx).bg,
1907 cx.theme().tokens.danger_hover.background.opacity(0.2)
1908 );
1909 assert_eq!(
1910 ButtonVariant::Danger.active(true, cx).bg,
1911 cx.theme().tokens.danger_active.background.opacity(0.4)
1912 );
1913 assert_eq!(
1914 ButtonVariant::Primary.normal(false, cx).bg,
1915 cx.theme().tokens.button_primary.into()
1916 );
1917 assert_eq!(
1918 ButtonVariant::Danger.normal(false, cx).bg,
1919 linear_gradient(
1920 180.,
1921 linear_color_stop(crate::try_parse_color("#FEF2F2").unwrap(), 0.),
1922 linear_color_stop(crate::try_parse_color("#FEE2E2").unwrap(), 1.)
1923 )
1924 );
1925 });
1926 }
1927
1928 #[gpui::test]
1929 fn test_disabled_outline_buttons_keep_semantic_backgrounds(cx: &mut gpui::TestAppContext) {
1930 cx.update(crate::init);
1931 let window = cx.add_empty_window();
1932 window.update(|_, cx| {
1933 let config = serde_json::from_value::<crate::ThemeConfig>(serde_json::json!({
1934 "name": "Disabled Outline Gradient",
1935 "mode": "light",
1936 "colors": {
1937 "primary.background": "linear-gradient(180deg, #111827, #020617)",
1938 "button.primary.background": "linear-gradient(180deg, #FFFFFF, #E5E7EB)",
1939 "danger.background": "linear-gradient(180deg, #EF4444, #DC2626)",
1940 "button.danger.background": "linear-gradient(180deg, #E5E7EB, #D1D5DB)"
1941 }
1942 }))
1943 .unwrap();
1944 crate::Theme::global_mut(cx).apply_config(&std::rc::Rc::new(config));
1945
1946 assert_eq!(
1947 ButtonVariant::Primary.disabled(true, cx).bg,
1948 cx.theme()
1949 .tokens
1950 .primary
1951 .background
1952 .opacity(0.1)
1953 .opacity(0.5)
1954 );
1955 assert_eq!(
1956 ButtonVariant::Danger.disabled(true, cx).bg,
1957 cx.theme()
1958 .tokens
1959 .danger
1960 .background
1961 .opacity(0.1)
1962 .opacity(0.5)
1963 );
1964 assert_ne!(
1965 ButtonVariant::Danger.disabled(true, cx).bg,
1966 cx.theme().input_background().opacity(0.5).into()
1967 );
1968 assert_ne!(
1969 ButtonVariant::Danger.disabled(true, cx).bg,
1970 cx.theme().tokens.button_danger.background.opacity(0.15)
1971 );
1972 });
1973 }
1974}