BlueGit

ict rusty-teams

Files

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

button.rs

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