Skip to main content

gpui_base/
button.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
5    IntoElement, MouseButton, ParentElement, Refineable as _, RenderOnce, Role, SharedString,
6    Stateful, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
7    prelude::FluentBuilder as _, relative,
8};
9use smallvec::SmallVec;
10
11use crate::{
12    RoleOverride, Selectable, StateStyle, StyledExt as _, TestSupportExt as _,
13    a11y_disabled::A11yDisabledExt as _,
14};
15
16type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
17
18/// An unstyled button that owns interaction, focus, keyboard, and accessibility behavior.
19///
20/// Layout and visual states are intentionally supplied by the application through
21/// GPUI's [`Styled`] API.
22#[derive(IntoElement)]
23pub struct Button {
24    id: ElementId,
25    base: crate::ObservedElement<Stateful<Div>>,
26    style: StyleRefinement,
27    semantic_styles: ButtonStyles,
28    selected: bool,
29    disabled: bool,
30    hover_style: Option<StyleRefinement>,
31    active_style: Option<StyleRefinement>,
32    group_hover_style: Option<(SharedString, StyleRefinement)>,
33    group_active_style: Option<(SharedString, StyleRefinement)>,
34    children: SmallVec<[AnyElement; 2]>,
35    on_click: Option<ClickHandler>,
36    accessibility_label: Option<SharedString>,
37    role: RoleOverride,
38    provided_focus_handle: Option<FocusHandle>,
39    tab_index: isize,
40    tab_stop: bool,
41    focusable: bool,
42}
43
44impl Button {
45    pub fn new(id: impl Into<ElementId>) -> Self {
46        let id = id.into();
47        Self {
48            base: div().id(id.clone()).test_support(),
49            id,
50            style: StyleRefinement::default(),
51            semantic_styles: ButtonStyles::default(),
52            selected: false,
53            disabled: false,
54            hover_style: None,
55            active_style: None,
56            group_hover_style: None,
57            group_active_style: None,
58            children: SmallVec::new(),
59            on_click: None,
60            accessibility_label: None,
61            role: RoleOverride::Implicit,
62            provided_focus_handle: None,
63            tab_index: 0,
64            tab_stop: true,
65            focusable: true,
66        }
67    }
68
69    /// Sets whether the button ignores pointer and keyboard activation.
70    ///
71    /// Disabled buttons are skipped during Tab traversal. If this button already
72    /// owns focus when it becomes disabled, it retains the focus binding until
73    /// focus moves away, so keyboard traversal can continue in either direction.
74    ///
75    /// While disabled, the `hover`, `active`, `group_hover` and `group_active`
76    /// styles are not applied; use [`ButtonStyles::disabled`] for its look.
77    pub fn disabled(mut self, disabled: bool) -> Self {
78        self.disabled = disabled;
79        self
80    }
81
82    /// Whether the button is disabled.
83    pub fn is_disabled(&self) -> bool {
84        self.disabled
85    }
86
87    /// Sets the application-controlled selected presentation state.
88    ///
89    /// This supports persistent trigger presentation while an associated menu
90    /// or popover is open. It is distinct from momentary `active`, Toggle's
91    /// `pressed` state, and accessibility toggle metadata; selecting a Button
92    /// does not automatically set `aria_toggled`.
93    pub fn selected(mut self, selected: bool) -> Self {
94        self.selected = selected;
95        self
96    }
97
98    /// Defines application-owned styles for the button's semantic states.
99    pub fn styles(mut self, build: impl FnOnce(ButtonStyles) -> ButtonStyles) -> Self {
100        self.semantic_styles = build(self.semantic_styles);
101        self
102    }
103
104    /// Sets the label exposed to accessibility clients.
105    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
106        self.accessibility_label = Some(label.into());
107        self
108    }
109
110    /// Overrides the accessibility role. The default is [`Role::Button`].
111    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
112        self.role = role.into();
113        self
114    }
115
116    /// Uses a caller-owned focus handle instead of creating keyed state.
117    pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
118        self.provided_focus_handle = Some(focus_handle.clone());
119        self
120    }
121
122    /// Sets the activation handler for pointer, Enter, and Space input.
123    pub fn on_click(
124        mut self,
125        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
126    ) -> Self {
127        self.on_click = Some(Rc::new(handler));
128        self
129    }
130
131    /// Sets the focus traversal index. The default is `0`.
132    pub fn tab_index(mut self, tab_index: isize) -> Self {
133        self.tab_index = tab_index;
134        self
135    }
136
137    /// Sets whether the button participates in keyboard focus traversal.
138    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
139        self.tab_stop = tab_stop;
140        self
141    }
142
143    /// Sets whether pressing the button moves focus onto it. The default is `true`.
144    ///
145    /// A non-focusable button leaves focus wherever it already is, which keeps a
146    /// composed control from flickering its focus ring on every press. It also
147    /// gives up Enter and Space activation, so only use it for a button that a
148    /// focused sibling already exposes to the keyboard, such as a number input's
149    /// step buttons.
150    pub fn focusable(mut self, focusable: bool) -> Self {
151        self.focusable = focusable;
152        self
153    }
154
155    fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
156        self.provided_focus_handle.clone().unwrap_or_else(|| {
157            window
158                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
159                .read(cx)
160                .clone()
161        })
162    }
163
164    fn resolved_style(&self) -> StyleRefinement {
165        crate::state_style::resolve_style(
166            &self.style,
167            [
168                self.selected.then_some(&self.semantic_styles.selected),
169                self.disabled.then_some(&self.semantic_styles.disabled),
170            ]
171            .into_iter()
172            .flatten(),
173        )
174    }
175}
176
177impl Selectable for Button {
178    fn selected(self, selected: bool) -> Self {
179        Button::selected(self, selected)
180    }
181
182    fn is_selected(&self) -> bool {
183        self.selected
184    }
185}
186
187/// Semantic styles supported by [`Button`].
188#[derive(Default)]
189pub struct ButtonStyles {
190    selected: StyleRefinement,
191    disabled: StyleRefinement,
192}
193
194impl ButtonStyles {
195    /// Refines the root style when the button is selected.
196    pub fn selected(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
197        self.selected
198            .refine(&build(StateStyle::default()).into_refinement());
199        self
200    }
201
202    /// Refines the root style when the button is disabled.
203    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
204        self.disabled
205            .refine(&build(StateStyle::default()).into_refinement());
206        self
207    }
208}
209
210impl Styled for Button {
211    fn style(&mut self) -> &mut StyleRefinement {
212        &mut self.style
213    }
214}
215
216impl ParentElement for Button {
217    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
218        self.children.extend(elements);
219    }
220}
221
222impl InteractiveElement for Button {
223    fn interactivity(&mut self) -> &mut Interactivity {
224        self.base.interactivity()
225    }
226
227    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
228        self.hover_style = Some(f(StyleRefinement::default()));
229        self
230    }
231
232    fn group_hover(
233        mut self,
234        group_name: impl Into<SharedString>,
235        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
236    ) -> Self {
237        self.group_hover_style = Some((group_name.into(), f(StyleRefinement::default())));
238        self
239    }
240}
241
242impl StatefulInteractiveElement for Button {
243    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
244        self.active_style = Some(f(StyleRefinement::default()));
245        self
246    }
247
248    fn group_active(
249        mut self,
250        group_name: impl Into<SharedString>,
251        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
252    ) -> Self {
253        self.group_active_style = Some((group_name.into(), f(StyleRefinement::default())));
254        self
255    }
256}
257
258impl RenderOnce for Button {
259    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
260        let focus_handle = self.focus_handle(window, cx);
261        let disabled = self.disabled;
262        let style = self.resolved_style();
263        let on_click = self.on_click;
264        let pointer_style = move |style: StyleRefinement| {
265            if disabled {
266                StyleRefinement::default()
267            } else {
268                style
269            }
270        };
271
272        self.base
273            // Centering is part of Button's control geometry. Without a flex
274            // formatting context an ordinary child starts at the root's
275            // leading edge, so a fixed-height unstyled Button cannot align its
276            // label even though its neutral line height is correct.
277            .flex()
278            .items_center()
279            .justify_center()
280            // A neutral line height is geometry, not visual policy: with the
281            // inherited value the text box is taller than the glyphs, so the
282            // caller's padding no longer determines the control's height and a
283            // button cannot be sized precisely. `relative(1.)` makes the text
284            // box exactly the font size; anything the caller sets refines over
285            // it, so a product that wants looser text still can.
286            .line_height(relative(1.))
287            .when_some(self.role.resolve(|| Role::Button), |this, role| {
288                this.role(role)
289            })
290            .when_some(self.accessibility_label, |this, label| {
291                this.aria_label(label)
292            })
293            // Keep the current focus in the dispatch tree when activation
294            // disables this button, so Tab can still leave it in either direction.
295            .when(
296                self.focusable && (!disabled || focus_handle.is_focused(window)),
297                |this| {
298                    this.track_focus(
299                        &focus_handle
300                            .tab_index(self.tab_index)
301                            .tab_stop(self.tab_stop && !disabled),
302                    )
303                },
304            )
305            .when(disabled, |this| {
306                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
307                    cx.stop_propagation();
308                })
309            })
310            .when_some(
311                (!disabled).then_some(on_click).flatten(),
312                |this, on_click| {
313                    this.on_click(move |event, window, cx| {
314                        on_click(event, window, cx);
315                    })
316                },
317            )
318            .when_some(self.hover_style, |this, style| {
319                this.hover(|_| pointer_style(style))
320            })
321            .when_some(self.active_style, |this, style| {
322                this.active(|_| pointer_style(style))
323            })
324            .when_some(self.group_hover_style, |this, (group, style)| {
325                this.group_hover(group, |_| pointer_style(style))
326            })
327            .when_some(self.group_active_style, |this, (group, style)| {
328                this.group_active(group, |_| pointer_style(style))
329            })
330            .children(self.children)
331            .refine_style(&style)
332            .a11y_disabled(disabled)
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339    use crate::ElementExt as _;
340    use std::{
341        cell::Cell,
342        rc::Rc,
343        sync::{Arc, Mutex},
344    };
345
346    use gpui::{
347        AppContext as _, ClickEvent, Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke,
348        Modifiers, Render, TestAppContext, VisualTestContext, accesskit, canvas, point, px,
349    };
350
351    struct ButtonHarness {
352        disabled: bool,
353        button_clicks: Rc<Cell<usize>>,
354        parent_clicks: Rc<Cell<usize>>,
355        keyboard_events: Rc<Cell<usize>>,
356    }
357
358    impl Render for ButtonHarness {
359        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
360            let button_clicks = self.button_clicks.clone();
361            let keyboard_events = self.keyboard_events.clone();
362            let parent_clicks = self.parent_clicks.clone();
363
364            div()
365                .id("button-parent")
366                .tab_group()
367                .size(px(100.))
368                .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
369                .child(
370                    Button::new("button")
371                        .disabled(self.disabled)
372                        .size_full()
373                        .on_click(move |event, _, _| {
374                            button_clicks.set(button_clicks.get() + 1);
375                            if matches!(event, ClickEvent::Keyboard(_)) {
376                                keyboard_events.set(keyboard_events.get() + 1);
377                            }
378                        }),
379                )
380        }
381    }
382
383    fn harness(
384        cx: &mut TestAppContext,
385        disabled: bool,
386    ) -> (
387        &mut VisualTestContext,
388        Rc<Cell<usize>>,
389        Rc<Cell<usize>>,
390        Rc<Cell<usize>>,
391    ) {
392        let button_clicks = Rc::new(Cell::new(0));
393        let parent_clicks = Rc::new(Cell::new(0));
394        let keyboard_events = Rc::new(Cell::new(0));
395        let (_, cx) = cx.add_window_view({
396            let button_clicks = button_clicks.clone();
397            let parent_clicks = parent_clicks.clone();
398            let keyboard_events = keyboard_events.clone();
399            move |_, _| ButtonHarness {
400                disabled,
401                button_clicks,
402                parent_clicks,
403                keyboard_events,
404            }
405        });
406        cx.update(|window, cx| {
407            window.draw(cx).clear(cx);
408        });
409        (cx, button_clicks, parent_clicks, keyboard_events)
410    }
411
412    #[gpui::test]
413    fn pointer_activation_fires_once(cx: &mut TestAppContext) {
414        let (cx, button_clicks, _, keyboard_events) = harness(cx, false);
415
416        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
417
418        assert_eq!(button_clicks.get(), 1);
419        assert_eq!(keyboard_events.get(), 0);
420    }
421
422    #[gpui::test]
423    fn enter_and_space_use_one_native_keyboard_click_each(cx: &mut TestAppContext) {
424        let (cx, button_clicks, _, keyboard_events) = harness(cx, false);
425        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
426        button_clicks.set(0);
427        cx.update(|window, cx| {
428            assert!(window.focused(cx).is_some());
429            window.draw(cx).clear(cx);
430        });
431
432        for key in ["enter", "space"] {
433            let keystroke =
434                cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
435            cx.simulate_event(KeyDownEvent {
436                keystroke: keystroke.clone(),
437                is_held: false,
438                prefer_character_input: false,
439            });
440            cx.simulate_event(KeyUpEvent { keystroke });
441        }
442
443        assert_eq!(button_clicks.get(), 2);
444        assert_eq!(keyboard_events.get(), 2);
445    }
446
447    #[gpui::test]
448    fn disabled_button_is_inert_and_blocks_parent_activation(cx: &mut TestAppContext) {
449        let (cx, button_clicks, parent_clicks, _) = harness(cx, true);
450
451        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
452        cx.update(|window, cx| window.focus_next(cx));
453        cx.simulate_keystrokes("enter space");
454
455        assert_eq!(button_clicks.get(), 0);
456        assert_eq!(parent_clicks.get(), 0);
457    }
458
459    struct DisableDuringFocus {
460        handles: [FocusHandle; 3],
461        disabled: bool,
462        activations: usize,
463    }
464
465    impl Render for DisableDuringFocus {
466        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
467            div()
468                .size_full()
469                .flex()
470                .tab_group()
471                .child(
472                    Button::new("before")
473                        .track_focus(&self.handles[0])
474                        .child("Before"),
475                )
476                .child(
477                    Button::new("disable-self")
478                        .track_focus(&self.handles[1])
479                        .disabled(self.disabled)
480                        .child("Disable self")
481                        .on_click(cx.listener(|this, _, _, cx| {
482                            this.disabled = true;
483                            this.activations += 1;
484                            cx.notify();
485                        })),
486                )
487                .child(
488                    Button::new("after")
489                        .track_focus(&self.handles[2])
490                        .child("After"),
491                )
492        }
493    }
494
495    fn press_transition_key(cx: &mut VisualTestContext, key: &str) {
496        let keystroke =
497            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
498        cx.simulate_event(KeyDownEvent {
499            keystroke: keystroke.clone(),
500            is_held: false,
501            prefer_character_input: false,
502        });
503        cx.simulate_event(KeyUpEvent { keystroke });
504        cx.update(|window, cx| window.draw(cx).clear(cx));
505    }
506
507    #[gpui::test]
508    fn disabling_focused_button_preserves_bidirectional_traversal(cx: &mut TestAppContext) {
509        cx.update(crate::init);
510        for (key, expected, back, opposite) in
511            [("tab", 2, "shift-tab", 0), ("shift-tab", 0, "tab", 2)]
512        {
513            let handles = cx.update(|cx| std::array::from_fn(|_| cx.focus_handle()));
514            let controls = cx.new(|_| DisableDuringFocus {
515                handles: handles.clone(),
516                disabled: false,
517                activations: 0,
518            });
519            let (_, cx) =
520                cx.add_window_view(|window, cx| crate::Root::new(controls.clone(), window, cx));
521            cx.update(|window, cx| {
522                window.activate_window();
523                window.draw(cx).clear(cx);
524                handles[0].focus(window, cx);
525                window.draw(cx).clear(cx);
526            });
527            press_transition_key(cx, "tab");
528            cx.update(|window, cx| {
529                window.draw(cx).clear(cx);
530                assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
531            });
532            press_transition_key(cx, "space");
533            cx.update(|window, cx| {
534                window.draw(cx).clear(cx);
535                assert!(controls.read(cx).disabled);
536                assert_eq!(controls.read(cx).activations, 1);
537            });
538            press_transition_key(cx, "enter");
539            press_transition_key(cx, "space");
540            cx.update(|_, cx| {
541                assert_eq!(controls.read(cx).activations, 1, "disabled stays inert");
542            });
543            press_transition_key(cx, key);
544            cx.update(|window, cx| {
545                window.draw(cx).clear(cx);
546                assert_eq!(window.focused(cx).as_ref(), Some(&handles[expected]));
547            });
548            press_transition_key(cx, back);
549            cx.update(|window, cx| {
550                window.draw(cx).clear(cx);
551                assert_eq!(window.focused(cx).as_ref(), Some(&handles[opposite]));
552            });
553            controls.update(cx, |this, cx| {
554                this.disabled = false;
555                cx.notify();
556            });
557            cx.update(|window, cx| window.draw(cx).clear(cx));
558            press_transition_key(cx, key);
559            cx.update(|window, cx| {
560                window.draw(cx).clear(cx);
561                assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
562            });
563        }
564    }
565
566    #[gpui::test]
567    fn fixed_height_button_centers_ordinary_child_geometry(cx: &mut TestAppContext) {
568        type Captured = Arc<
569            Mutex<(
570                Option<gpui::Bounds<gpui::Pixels>>,
571                Option<gpui::Bounds<gpui::Pixels>>,
572            )>,
573        >;
574
575        struct AlignmentProbe {
576            captured: Captured,
577        }
578
579        impl Render for AlignmentProbe {
580            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
581                let root_capture = self.captured.clone();
582                let child_capture = self.captured.clone();
583                Button::new("alignment-button")
584                    .w(px(120.))
585                    .h(px(40.))
586                    .child(
587                        div()
588                            .w(px(48.))
589                            .h(px(12.))
590                            .on_prepaint(move |bounds, _, _| {
591                                child_capture.lock().unwrap().1 = Some(bounds);
592                            }),
593                    )
594                    .on_prepaint(move |bounds, _, _| {
595                        root_capture.lock().unwrap().0 = Some(bounds);
596                    })
597            }
598        }
599
600        let captured = Arc::new(Mutex::new((None, None)));
601        let (_, context) = cx.add_window_view({
602            let captured = captured.clone();
603            move |_, _| AlignmentProbe { captured }
604        });
605        context.update(|window, cx| window.draw(cx).clear(cx));
606
607        let (root, child) = *captured.lock().unwrap();
608        let root = root.expect("button bounds");
609        let child = child.expect("child bounds");
610        assert_eq!(child.center(), root.center());
611    }
612
613    #[test]
614    fn state_styling_methods_are_available_to_applications() {
615        let _ = Button::new("states")
616            .styles(|styles| {
617                styles.disabled(|style| {
618                    style
619                        .opacity(0.5)
620                        .when(true, |style| style.border_1())
621                        .when_some(Some(0.4), |style, opacity| style.opacity(opacity))
622                        .when_none(&None::<f32>, |style| style.rounded_sm())
623                })
624            })
625            .hover(|style| style.opacity(0.9))
626            .active(|style| style.opacity(0.8))
627            .focus_visible(|style| style.opacity(0.7));
628    }
629
630    #[test]
631    fn disabled_style_applies_only_while_disabled_and_then_wins() {
632        let enabled = Button::new("enabled")
633            .opacity(0.9)
634            .styles(|styles| styles.disabled(|style| style.opacity(0.5)));
635        assert_eq!(enabled.resolved_style().opacity, Some(0.9));
636
637        let disabled = Button::new("disabled")
638            .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
639            .opacity(0.9)
640            .disabled(true);
641        assert_eq!(disabled.resolved_style().opacity, Some(0.5));
642
643        let semantic_only = Button::new("semantic-only")
644            .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
645            .disabled(true);
646        assert_eq!(semantic_only.resolved_style().opacity, Some(0.5));
647    }
648
649    #[gpui::test]
650    fn disabled_button_ignores_hover_and_active_styles(cx: &mut TestAppContext) {
651        struct PointerProbe {
652            disabled: bool,
653            text_color: Rc<Cell<Option<gpui::Hsla>>>,
654        }
655
656        impl Render for PointerProbe {
657            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
658                let text_color = self.text_color.clone();
659                Button::new("pointer-probe")
660                    .size(px(40.))
661                    .text_color(gpui::red())
662                    .hover(|style| style.text_color(gpui::green()))
663                    .active(|style| style.text_color(gpui::blue()))
664                    .disabled(self.disabled)
665                    .child(
666                        canvas(
667                            |_, _, _| {},
668                            move |_, _, window, _| text_color.set(Some(window.text_style().color)),
669                        )
670                        .size_full(),
671                    )
672            }
673        }
674
675        let text_color = Rc::new(Cell::new(None));
676        let (view, cx) = cx.add_window_view({
677            let text_color = text_color.clone();
678            move |_, _| PointerProbe {
679                disabled: true,
680                text_color,
681            }
682        });
683        let redraw = |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
684        let position = point(px(10.), px(10.));
685        redraw(cx);
686
687        cx.simulate_mouse_move(position, None, Modifiers::default());
688        redraw(cx);
689        assert_eq!(
690            text_color.get(),
691            Some(gpui::red()),
692            "disabled ignores hover"
693        );
694
695        cx.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
696        redraw(cx);
697        assert_eq!(
698            text_color.get(),
699            Some(gpui::red()),
700            "disabled ignores active"
701        );
702        cx.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
703
704        view.update(cx, |this, cx| {
705            this.disabled = false;
706            cx.notify();
707        });
708        redraw(cx);
709        assert_eq!(text_color.get(), Some(gpui::green()), "enabled shows hover");
710
711        cx.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
712        redraw(cx);
713        assert_eq!(text_color.get(), Some(gpui::blue()), "enabled shows active");
714    }
715
716    #[test]
717    fn is_disabled_reports_the_disabled_state() {
718        assert!(!Button::new("enabled").is_disabled());
719        assert!(Button::new("disabled").disabled(true).is_disabled());
720    }
721
722    #[test]
723    fn selected_disabled_and_instance_styles_follow_the_shared_priority() {
724        let selected_color = gpui::hsla(0.6, 0.7, 0.5, 1.0);
725        let disabled_color = gpui::hsla(0.1, 0.2, 0.3, 0.5);
726        let button = |selected, disabled| {
727            Button::new("button")
728                .selected(selected)
729                .disabled(disabled)
730                .styles(|styles| {
731                    styles
732                        .selected(|style| style.bg(selected_color))
733                        .disabled(|style| style.bg(disabled_color))
734                })
735        };
736
737        assert_eq!(button(false, false).resolved_style().background, None);
738        assert_eq!(
739            button(true, false).resolved_style().background,
740            Some(selected_color.into())
741        );
742        assert_eq!(
743            button(true, true).resolved_style().background,
744            Some(disabled_color.into())
745        );
746        assert_eq!(
747            button(true, true)
748                .bg(selected_color)
749                .resolved_style()
750                .background,
751            Some(disabled_color.into())
752        );
753    }
754
755    #[gpui::test]
756    fn accessibility_role_label_and_disabled_action_surface(cx: &mut TestAppContext) {
757        type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
758
759        struct A11yProbe {
760            captured: Captured,
761        }
762
763        impl Render for A11yProbe {
764            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
765                let captured = self.captured.clone();
766                canvas(
767                    move |_, window, cx| {
768                        let mut info = |button: Button| {
769                            let mut node = accesskit::Node::new(Role::Button);
770                            button
771                                .render(window, cx)
772                                .into_element()
773                                .write_a11y_info(&mut node);
774                            node
775                        };
776                        let enabled = info(
777                            Button::new("enabled")
778                                .accessibility_label("Save")
779                                .on_click(|_, _, _| {}),
780                        );
781                        let disabled = info(
782                            Button::new("disabled")
783                                .disabled(true)
784                                .accessibility_label("Save")
785                                .on_click(|_, _, _| {}),
786                        );
787                        *captured.lock().unwrap() = Some((enabled, disabled));
788                    },
789                    |_, _, _, _| {},
790                )
791            }
792        }
793
794        let captured: Captured = Arc::new(Mutex::new(None));
795        let result = captured.clone();
796        let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
797        cx.update(|window, cx| {
798            window.draw(cx).clear(cx);
799        });
800        let (enabled, disabled) = result.lock().unwrap().take().unwrap();
801        assert_eq!(enabled.role(), Role::Button);
802        assert_eq!(enabled.label(), Some("Save"));
803        assert!(enabled.supports_action(accesskit::Action::Click));
804
805        assert_eq!(disabled.role(), Role::Button);
806        assert!(!disabled.supports_action(accesskit::Action::Click));
807        assert!(!enabled.is_disabled());
808        assert!(disabled.is_disabled());
809    }
810}