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#[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 current: bool,
30 disabled: bool,
31 focus_when_disabled: bool,
32 pointer_styles: PointerStyles,
33 children: SmallVec<[AnyElement; 2]>,
34 on_click: Option<ClickHandler>,
35 accessibility_label: Option<SharedString>,
36 role: RoleOverride,
37 provided_focus_handle: Option<FocusHandle>,
38 tab_index: isize,
39 tab_stop: bool,
40 focusable: bool,
41}
42
43impl Button {
44 pub fn new(id: impl Into<ElementId>) -> Self {
45 let id = id.into();
46 Self {
47 base: div().id(id.clone()).test_support(),
48 id,
49 style: StyleRefinement::default(),
50 semantic_styles: ButtonStyles::default(),
51 selected: false,
52 current: false,
53 disabled: false,
54 focus_when_disabled: false,
55 pointer_styles: PointerStyles::default(),
56 children: SmallVec::new(),
57 on_click: None,
58 accessibility_label: None,
59 role: RoleOverride::Implicit,
60 provided_focus_handle: None,
61 tab_index: 0,
62 tab_stop: true,
63 focusable: true,
64 }
65 }
66
67 pub fn disabled(mut self, disabled: bool) -> Self {
76 self.disabled = disabled;
77 self
78 }
79
80 pub(crate) fn focus_when_disabled(mut self, focusable: bool) -> Self {
83 self.focus_when_disabled = focusable;
84 self
85 }
86
87 pub fn selected(mut self, selected: bool) -> Self {
94 self.selected = selected;
95 self
96 }
97
98 pub fn current(mut self, current: bool) -> Self {
104 self.current = current;
105 self
106 }
107
108 pub fn styles(mut self, build: impl FnOnce(ButtonStyles) -> ButtonStyles) -> Self {
110 self.semantic_styles = build(self.semantic_styles);
111 self
112 }
113
114 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
116 self.accessibility_label = Some(label.into());
117 self
118 }
119
120 pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
122 self.role = role.into();
123 self
124 }
125
126 pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
128 self.provided_focus_handle = Some(focus_handle.clone());
129 self
130 }
131
132 pub fn on_click(
134 mut self,
135 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
136 ) -> Self {
137 self.on_click = Some(Rc::new(handler));
138 self
139 }
140
141 pub fn tab_index(mut self, tab_index: isize) -> Self {
143 self.tab_index = tab_index;
144 self
145 }
146
147 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
149 self.tab_stop = tab_stop;
150 self
151 }
152
153 pub fn focusable(mut self, focusable: bool) -> Self {
161 self.focusable = focusable;
162 self
163 }
164
165 fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
166 self.provided_focus_handle.clone().unwrap_or_else(|| {
167 window
168 .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
169 .read(cx)
170 .clone()
171 })
172 }
173
174 fn resolved_style(&self) -> StyleRefinement {
175 crate::state_style::resolve_style(
176 &self.style,
177 [
178 self.selected.then_some(&self.semantic_styles.selected),
179 self.disabled.then_some(&self.semantic_styles.disabled),
180 ]
181 .into_iter()
182 .flatten(),
183 )
184 }
185}
186
187impl Selectable for Button {
188 fn selected(self, selected: bool) -> Self {
189 Button::selected(self, selected)
190 }
191
192 fn is_selected(&self) -> bool {
193 self.selected
194 }
195}
196
197#[derive(Default)]
199pub struct ButtonStyles {
200 selected: StyleRefinement,
201 disabled: StyleRefinement,
202}
203
204impl ButtonStyles {
205 pub fn selected(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
207 self.selected
208 .refine(&build(StateStyle::default()).into_refinement());
209 self
210 }
211
212 pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
214 self.disabled
215 .refine(&build(StateStyle::default()).into_refinement());
216 self
217 }
218}
219
220impl Styled for Button {
221 fn style(&mut self) -> &mut StyleRefinement {
222 &mut self.style
223 }
224}
225
226impl ParentElement for Button {
227 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
228 self.children.extend(elements);
229 }
230}
231
232#[derive(Default)]
234struct PointerStyles {
235 hover: Option<StyleRefinement>,
236 active: Option<StyleRefinement>,
237 group_hover: Option<(SharedString, StyleRefinement)>,
238 group_active: Option<(SharedString, StyleRefinement)>,
239}
240
241impl InteractiveElement for Button {
242 fn interactivity(&mut self) -> &mut Interactivity {
243 self.base.interactivity()
244 }
245
246 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
247 self.pointer_styles.hover = Some(f(StyleRefinement::default()));
248 self
249 }
250
251 fn group_hover(
252 mut self,
253 group_name: impl Into<SharedString>,
254 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
255 ) -> Self {
256 self.pointer_styles.group_hover = Some((group_name.into(), f(StyleRefinement::default())));
257 self
258 }
259}
260
261impl StatefulInteractiveElement for Button {
262 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
263 self.pointer_styles.active = Some(f(StyleRefinement::default()));
264 self
265 }
266
267 fn group_active(
268 mut self,
269 group_name: impl Into<SharedString>,
270 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
271 ) -> Self {
272 self.pointer_styles.group_active = Some((group_name.into(), f(StyleRefinement::default())));
273 self
274 }
275}
276
277macro_rules! forward_hover_styles {
280 ($field:ident) => {
281 fn hover(mut self, f: impl FnOnce(gpui::StyleRefinement) -> gpui::StyleRefinement) -> Self {
282 self.$field = gpui::InteractiveElement::hover(self.$field, f);
283 self
284 }
285
286 fn group_hover(
287 mut self,
288 group_name: impl Into<gpui::SharedString>,
289 f: impl FnOnce(gpui::StyleRefinement) -> gpui::StyleRefinement,
290 ) -> Self {
291 self.$field = gpui::InteractiveElement::group_hover(self.$field, group_name, f);
292 self
293 }
294 };
295}
296
297macro_rules! forward_active_styles {
300 ($field:ident) => {
301 fn active(
302 mut self,
303 f: impl FnOnce(gpui::StyleRefinement) -> gpui::StyleRefinement,
304 ) -> Self {
305 self.$field = gpui::StatefulInteractiveElement::active(self.$field, f);
306 self
307 }
308
309 fn group_active(
310 mut self,
311 group_name: impl Into<gpui::SharedString>,
312 f: impl FnOnce(gpui::StyleRefinement) -> gpui::StyleRefinement,
313 ) -> Self {
314 self.$field =
315 gpui::StatefulInteractiveElement::group_active(self.$field, group_name, f);
316 self
317 }
318 };
319}
320
321pub(crate) use {forward_active_styles, forward_hover_styles};
322
323impl RenderOnce for Button {
324 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
325 let focus_handle = self.focus_handle(window, cx);
326 let disabled = self.disabled;
327 let style = self.resolved_style();
328 let on_click = self.on_click;
329 let pointer_styles = if disabled {
330 PointerStyles::default()
331 } else {
332 self.pointer_styles
333 };
334
335 let base = self
336 .base
337 .flex()
342 .items_center()
343 .justify_center()
344 .line_height(relative(1.))
351 .when_some(self.role.resolve(|| Role::Button), |this, role| {
352 this.role(role)
353 })
354 .when_some(self.accessibility_label, |this, label| {
355 this.aria_label(label)
356 })
357 .when(
360 self.focusable
361 && (!disabled || self.focus_when_disabled || focus_handle.is_focused(window)),
362 |this| {
363 this.track_focus(
364 &focus_handle
365 .clone()
366 .tab_index(self.tab_index)
367 .tab_stop(self.tab_stop && (!disabled || self.focus_when_disabled)),
368 )
369 },
370 )
371 .when(self.focusable, |this| {
372 this.on_any_mouse_down(|event, window, _| {
375 if event.button != MouseButton::Left {
376 window.prevent_default();
377 }
378 })
379 })
380 .when(disabled, |this| {
381 this.on_mouse_down(MouseButton::Left, |_, _, cx| {
382 cx.stop_propagation();
383 })
384 })
385 .when_some(pointer_styles.hover, |this, style| this.hover(|_| style))
386 .when_some(pointer_styles.active, |this, style| this.active(|_| style))
387 .when_some(pointer_styles.group_hover, |this, (group, style)| {
388 this.group_hover(group, |_| style)
389 })
390 .when_some(pointer_styles.group_active, |this, (group, style)| {
391 this.group_active(group, |_| style)
392 })
393 .when_some(
394 (!disabled).then_some(on_click).flatten(),
395 |this, on_click| {
396 this.on_click(move |event, window, cx| {
397 on_click(event, window, cx);
398 })
399 },
400 )
401 .children(self.children)
402 .when(self.focusable, |this| {
403 crate::ElementExt::on_prepaint(this, move |bounds, window, _| {
407 window.with_global_id("button-focus-reveal".into(), |id, window| {
408 window.with_element_state(id, |was_focused: Option<bool>, window| {
409 let focused = focus_handle.is_focused(window);
410 if focused && was_focused != Some(true) {
411 window.request_autoscroll(bounds);
412 }
413 ((), focused)
414 });
415 });
416 })
417 })
418 .refine_style(&style)
419 .a11y_disabled(disabled);
420 crate::a11y_current::current_page(base, self.current)
421 }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427 use crate::ElementExt as _;
428 use std::{
429 cell::Cell,
430 rc::Rc,
431 sync::{Arc, Mutex},
432 };
433
434 use gpui::{
435 AppContext as _, ClickEvent, Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke,
436 Modifiers, Render, TestAppContext, VisualTestContext, accesskit, canvas, point, px,
437 };
438
439 struct ButtonHarness {
440 disabled: bool,
441 button_clicks: Rc<Cell<usize>>,
442 parent_clicks: Rc<Cell<usize>>,
443 keyboard_events: Rc<Cell<usize>>,
444 }
445
446 impl Render for ButtonHarness {
447 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
448 let button_clicks = self.button_clicks.clone();
449 let keyboard_events = self.keyboard_events.clone();
450 let parent_clicks = self.parent_clicks.clone();
451
452 div()
453 .id("button-parent")
454 .tab_group()
455 .size(px(100.))
456 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
457 .child(
458 Button::new("button")
459 .disabled(self.disabled)
460 .size_full()
461 .on_click(move |event, _, _| {
462 button_clicks.set(button_clicks.get() + 1);
463 if matches!(event, ClickEvent::Keyboard(_)) {
464 keyboard_events.set(keyboard_events.get() + 1);
465 }
466 }),
467 )
468 }
469 }
470
471 fn harness(
472 cx: &mut TestAppContext,
473 disabled: bool,
474 ) -> (
475 &mut VisualTestContext,
476 Rc<Cell<usize>>,
477 Rc<Cell<usize>>,
478 Rc<Cell<usize>>,
479 ) {
480 let button_clicks = Rc::new(Cell::new(0));
481 let parent_clicks = Rc::new(Cell::new(0));
482 let keyboard_events = Rc::new(Cell::new(0));
483 let (_, cx) = cx.add_window_view({
484 let button_clicks = button_clicks.clone();
485 let parent_clicks = parent_clicks.clone();
486 let keyboard_events = keyboard_events.clone();
487 move |_, _| ButtonHarness {
488 disabled,
489 button_clicks,
490 parent_clicks,
491 keyboard_events,
492 }
493 });
494 cx.update(|window, cx| {
495 window.draw(cx).clear(cx);
496 });
497 (cx, button_clicks, parent_clicks, keyboard_events)
498 }
499
500 #[gpui::test]
501 fn pointer_enter_and_space_use_one_native_click_each(cx: &mut TestAppContext) {
502 let (cx, button_clicks, _, keyboard_events) = harness(cx, false);
503 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
504 assert_eq!(button_clicks.get(), 1);
505 assert_eq!(keyboard_events.get(), 0);
506 button_clicks.set(0);
507 cx.update(|window, cx| {
508 assert!(window.focused(cx).is_some());
509 window.draw(cx).clear(cx);
510 });
511
512 for key in ["enter", "space"] {
513 let keystroke =
514 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
515 cx.simulate_event(KeyDownEvent {
516 keystroke: keystroke.clone(),
517 is_held: false,
518 prefer_character_input: false,
519 });
520 cx.simulate_event(KeyUpEvent { keystroke });
521 }
522
523 assert_eq!(button_clicks.get(), 2);
524 assert_eq!(keyboard_events.get(), 2);
525 }
526
527 #[gpui::test]
528 fn disabled_button_is_inert_and_blocks_parent_activation(cx: &mut TestAppContext) {
529 let (cx, button_clicks, parent_clicks, _) = harness(cx, true);
530
531 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
532 cx.update(|window, cx| window.focus_next(cx));
533 cx.simulate_keystrokes("enter space");
534
535 assert_eq!(button_clicks.get(), 0);
536 assert_eq!(parent_clicks.get(), 0);
537 }
538
539 struct DisableDuringFocus {
540 handles: [FocusHandle; 3],
541 disabled: bool,
542 activations: usize,
543 scroll: gpui::ScrollHandle,
544 }
545
546 impl Render for DisableDuringFocus {
547 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
548 div().size_full().tab_group().child(
549 crate::ScrollArea::new("button-scroll", &self.scroll)
550 .w(px(180.))
551 .h(px(60.))
552 .content_styles(|style| style.flex().flex_col().gap(px(40.)))
553 .child(
554 Button::new("before")
555 .track_focus(&self.handles[0])
556 .h(px(40.))
557 .flex_shrink_0()
558 .child("Before"),
559 )
560 .child(
561 Button::new("disable-self")
562 .track_focus(&self.handles[1])
563 .h(px(40.))
564 .flex_shrink_0()
565 .disabled(self.disabled)
566 .child("Disable self")
567 .on_click(cx.listener(|this, _, _, cx| {
568 this.disabled = true;
569 this.activations += 1;
570 cx.notify();
571 })),
572 )
573 .child(
574 Button::new("after")
575 .track_focus(&self.handles[2])
576 .h(px(40.))
577 .flex_shrink_0()
578 .child("After"),
579 ),
580 )
581 }
582 }
583
584 fn press_transition_key(cx: &mut VisualTestContext, key: &str) {
585 let keystroke =
586 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
587 cx.simulate_event(KeyDownEvent {
588 keystroke: keystroke.clone(),
589 is_held: false,
590 prefer_character_input: false,
591 });
592 cx.simulate_event(KeyUpEvent { keystroke });
593 cx.update(|window, cx| window.draw(cx).clear(cx));
594 }
595
596 #[gpui::test]
597 fn disabling_focused_button_preserves_bidirectional_traversal(cx: &mut TestAppContext) {
598 cx.update(crate::init);
599 for (key, expected, back, opposite) in
600 [("tab", 2, "shift-tab", 0), ("shift-tab", 0, "tab", 2)]
601 {
602 let handles = cx.update(|cx| std::array::from_fn(|_| cx.focus_handle()));
603 let scroll = gpui::ScrollHandle::new();
604 let controls = cx.new(|_| DisableDuringFocus {
605 handles: handles.clone(),
606 disabled: false,
607 activations: 0,
608 scroll: scroll.clone(),
609 });
610 let (_, cx) =
611 cx.add_window_view(|window, cx| crate::Root::new(controls.clone(), window, cx));
612 cx.update(|window, cx| {
613 window.activate_window();
614 window.draw(cx).clear(cx);
615 handles[0].focus(window, cx);
616 window.draw(cx).clear(cx);
617 });
618 press_transition_key(cx, "tab");
619 cx.update(|window, cx| {
620 window.draw(cx).clear(cx);
621 assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
622 });
623 assert!(
624 scroll.offset().y < px(0.),
625 "new focus reveals the hidden button"
626 );
627 scroll.set_offset(point(px(0.), px(0.)));
628 cx.update(|window, cx| {
629 window.draw(cx).clear(cx);
630 window.draw(cx).clear(cx);
631 });
632 assert_eq!(
633 scroll.offset().y,
634 px(0.),
635 "redrawing retained focus preserves manual scroll position"
636 );
637 press_transition_key(cx, "space");
638 cx.update(|window, cx| {
639 window.draw(cx).clear(cx);
640 assert!(controls.read(cx).disabled);
641 assert_eq!(controls.read(cx).activations, 1);
642 });
643 press_transition_key(cx, "enter");
644 press_transition_key(cx, "space");
645 cx.update(|_, cx| {
646 assert_eq!(controls.read(cx).activations, 1, "disabled stays inert");
647 });
648 press_transition_key(cx, key);
649 cx.update(|window, cx| {
650 window.draw(cx).clear(cx);
651 assert_eq!(window.focused(cx).as_ref(), Some(&handles[expected]));
652 });
653 press_transition_key(cx, back);
654 cx.update(|window, cx| {
655 window.draw(cx).clear(cx);
656 assert_eq!(window.focused(cx).as_ref(), Some(&handles[opposite]));
657 });
658 controls.update(cx, |this, cx| {
659 this.disabled = false;
660 cx.notify();
661 });
662 cx.update(|window, cx| window.draw(cx).clear(cx));
663 press_transition_key(cx, key);
664 cx.update(|window, cx| {
665 window.draw(cx).clear(cx);
666 assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
667 });
668 }
669 }
670
671 #[gpui::test]
672 fn disabled_button_and_wrappers_ignore_hover_and_active_styles(cx: &mut TestAppContext) {
673 struct PointerProbe {
674 disabled: bool,
675 toggle: bool,
676 text_color: Rc<Cell<Option<gpui::Hsla>>>,
677 }
678
679 impl Render for PointerProbe {
680 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
681 let text_color = self.text_color.clone();
682 let probe = canvas(
683 |_, _, _| {},
684 move |_, _, window, _| text_color.set(Some(window.text_style().color)),
685 )
686 .size_full();
687 if self.toggle {
688 crate::Toggle::new("pointer-probe")
689 .size(px(40.))
690 .text_color(gpui::red())
691 .hover(|style| style.text_color(gpui::green()))
692 .active(|style| style.text_color(gpui::blue()))
693 .disabled(self.disabled)
694 .child(probe)
695 .into_any_element()
696 } else {
697 Button::new("pointer-probe")
698 .size(px(40.))
699 .text_color(gpui::red())
700 .hover(|style| style.text_color(gpui::green()))
701 .active(|style| style.text_color(gpui::blue()))
702 .disabled(self.disabled)
703 .child(probe)
704 .into_any_element()
705 }
706 }
707 }
708
709 for toggle in [false, true] {
710 let text_color = Rc::new(Cell::new(None));
711 let (view, cx) = cx.add_window_view({
712 let text_color = text_color.clone();
713 move |_, _| PointerProbe {
714 disabled: true,
715 toggle,
716 text_color,
717 }
718 });
719 let redraw =
720 |cx: &mut VisualTestContext| cx.update(|window, cx| window.draw(cx).clear(cx));
721 let position = point(px(10.), px(10.));
722 redraw(cx);
723
724 cx.simulate_mouse_move(position, None, Modifiers::default());
725 redraw(cx);
726 assert_eq!(
727 text_color.get(),
728 Some(gpui::red()),
729 "disabled ignores hover"
730 );
731 cx.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
732 redraw(cx);
733 assert_eq!(
734 text_color.get(),
735 Some(gpui::red()),
736 "disabled ignores active"
737 );
738 cx.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
739
740 view.update(cx, |this, cx| {
741 this.disabled = false;
742 cx.notify();
743 });
744 redraw(cx);
745 assert_eq!(text_color.get(), Some(gpui::green()), "enabled shows hover");
746 cx.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
747 redraw(cx);
748 assert_eq!(text_color.get(), Some(gpui::blue()), "enabled shows active");
749 cx.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
750 }
751 }
752
753 #[gpui::test]
754 fn secondary_and_middle_presses_do_not_focus_but_reach_the_parent(cx: &mut TestAppContext) {
755 struct Harness {
756 focus_handle: FocusHandle,
757 parent_presses: Rc<Cell<usize>>,
758 }
759
760 impl Render for Harness {
761 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
762 let parent_presses = self.parent_presses.clone();
763 div()
764 .size(px(100.))
765 .on_any_mouse_down(move |_, _, _| parent_presses.set(parent_presses.get() + 1))
766 .child(
767 Button::new("non-primary")
768 .size_full()
769 .track_focus(&self.focus_handle),
770 )
771 }
772 }
773
774 let parent_presses = Rc::new(Cell::new(0));
775 let (view, cx) = cx.add_window_view({
776 let parent_presses = parent_presses.clone();
777 move |_, cx| Harness {
778 focus_handle: cx.focus_handle(),
779 parent_presses,
780 }
781 });
782 let focus_handle = cx.update(|_, cx| view.read(cx).focus_handle.clone());
783 cx.update(|window, cx| window.draw(cx).clear(cx));
784
785 let position = point(px(10.), px(10.));
786 for button in [MouseButton::Right, MouseButton::Middle, MouseButton::Left] {
787 cx.simulate_mouse_down(position, button, Modifiers::default());
788 cx.simulate_mouse_up(position, button, Modifiers::default());
789 cx.update(|window, cx| {
790 window.draw(cx).clear(cx);
791 assert_eq!(
792 focus_handle.is_focused(window),
793 button == MouseButton::Left,
794 "only a primary press focuses the button ({button:?})"
795 );
796 });
797 }
798 assert_eq!(parent_presses.get(), 3);
799 }
800
801 #[gpui::test]
802 fn fixed_height_button_centers_ordinary_child_geometry(cx: &mut TestAppContext) {
803 type Captured = Arc<
804 Mutex<(
805 Option<gpui::Bounds<gpui::Pixels>>,
806 Option<gpui::Bounds<gpui::Pixels>>,
807 )>,
808 >;
809
810 struct AlignmentProbe {
811 captured: Captured,
812 }
813
814 impl Render for AlignmentProbe {
815 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
816 let root_capture = self.captured.clone();
817 let child_capture = self.captured.clone();
818 Button::new("alignment-button")
819 .w(px(120.))
820 .h(px(40.))
821 .child(
822 div()
823 .w(px(48.))
824 .h(px(12.))
825 .on_prepaint(move |bounds, _, _| {
826 child_capture.lock().unwrap().1 = Some(bounds);
827 }),
828 )
829 .on_prepaint(move |bounds, _, _| {
830 root_capture.lock().unwrap().0 = Some(bounds);
831 })
832 }
833 }
834
835 let captured = Arc::new(Mutex::new((None, None)));
836 let (_, context) = cx.add_window_view({
837 let captured = captured.clone();
838 move |_, _| AlignmentProbe { captured }
839 });
840 context.update(|window, cx| window.draw(cx).clear(cx));
841
842 let (root, child) = *captured.lock().unwrap();
843 let root = root.expect("button bounds");
844 let child = child.expect("child bounds");
845 assert_eq!(child.center(), root.center());
846 }
847
848 #[test]
849 fn selected_disabled_and_instance_styles_follow_the_shared_priority() {
850 let selected_color = gpui::hsla(0.6, 0.7, 0.5, 1.0);
851 let disabled_color = gpui::hsla(0.1, 0.2, 0.3, 0.5);
852 let button = |selected, disabled| {
853 Button::new("button")
854 .selected(selected)
855 .disabled(disabled)
856 .styles(|styles| {
857 styles
858 .selected(|style| style.bg(selected_color))
859 .disabled(|style| style.bg(disabled_color))
860 })
861 };
862
863 assert_eq!(button(false, false).resolved_style().background, None);
864 assert_eq!(
865 button(true, false).resolved_style().background,
866 Some(selected_color.into())
867 );
868 assert_eq!(
869 button(true, true).resolved_style().background,
870 Some(disabled_color.into())
871 );
872 assert_eq!(
873 button(true, true)
874 .bg(selected_color)
875 .resolved_style()
876 .background,
877 Some(disabled_color.into())
878 );
879 }
880
881 #[gpui::test]
882 fn accessibility_role_label_and_disabled_action_surface(cx: &mut TestAppContext) {
883 type Captured = Arc<Mutex<Vec<(bool, bool, accesskit::Node)>>>;
884
885 struct A11yProbe {
886 captured: Captured,
887 }
888
889 impl Render for A11yProbe {
890 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
891 let captured = self.captured.clone();
892 canvas(
893 move |_, window, cx| {
894 let mut nodes = captured.lock().unwrap();
895 nodes.clear();
896 for (index, (disabled, current)) in
897 [(false, false), (false, true), (true, false), (true, true)]
898 .into_iter()
899 .enumerate()
900 {
901 let element = Button::new(("button", index))
902 .accessibility_label("Settings")
903 .selected(true)
904 .current(current)
905 .disabled(disabled)
906 .on_click(|_, _, _| {})
907 .render(window, cx)
908 .into_element();
909 let mut node = accesskit::Node::new(element.a11y_role().unwrap());
910 element.write_a11y_info(&mut node);
911 nodes.push((disabled, current, node));
912 }
913 },
914 |_, _, _, _| {},
915 )
916 }
917 }
918
919 let captured: Captured = Arc::default();
920 let result = captured.clone();
921 let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
922 cx.update(|window, cx| {
923 window.draw(cx).clear(cx);
924 });
925 let nodes = result.lock().unwrap();
926 assert_eq!(nodes.len(), 4);
927 for (disabled, current, node) in nodes.iter() {
928 assert_eq!(node.role(), Role::Button);
929 assert_eq!(node.label(), Some("Settings"));
930 assert_eq!(node.supports_action(accesskit::Action::Click), !disabled);
931 assert_eq!(node.is_disabled(), *disabled);
932 assert_eq!(
933 node.aria_current(),
934 current.then_some(accesskit::AriaCurrent::Page)
935 );
936 assert_eq!(node.is_selected(), None);
937 }
938 }
939}