1use std::rc::Rc;
2
3use smallvec::SmallVec;
4use wgpui::{
5 AnyElement, App, ClickEvent, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
6 IntoElement, MouseButton, ParentElement, Refineable as _, RenderOnce, Role, SharedString,
7 Stateful, StatefulInteractiveElement, StyleRefinement, Styled, Window, div,
8 prelude::FluentBuilder as _, relative,
9};
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 disabled: bool,
30 children: SmallVec<[AnyElement; 2]>,
31 on_click: Option<ClickHandler>,
32 accessibility_label: Option<SharedString>,
33 role: RoleOverride,
34 provided_focus_handle: Option<FocusHandle>,
35 tab_index: isize,
36 tab_stop: bool,
37 focusable: bool,
38}
39
40impl Button {
41 pub fn new(id: impl Into<ElementId>) -> Self {
42 let id = id.into();
43 Self {
44 base: div().id(id.clone()).test_support(),
45 id,
46 style: StyleRefinement::default(),
47 semantic_styles: ButtonStyles::default(),
48 selected: false,
49 disabled: false,
50 children: SmallVec::new(),
51 on_click: None,
52 accessibility_label: None,
53 role: RoleOverride::Implicit,
54 provided_focus_handle: None,
55 tab_index: 0,
56 tab_stop: true,
57 focusable: true,
58 }
59 }
60
61 pub fn disabled(mut self, disabled: bool) -> Self {
67 self.disabled = disabled;
68 self
69 }
70
71 pub fn selected(mut self, selected: bool) -> Self {
78 self.selected = selected;
79 self
80 }
81
82 pub fn styles(mut self, build: impl FnOnce(ButtonStyles) -> ButtonStyles) -> Self {
84 self.semantic_styles = build(self.semantic_styles);
85 self
86 }
87
88 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
90 self.accessibility_label = Some(label.into());
91 self
92 }
93
94 pub fn accessibility_id(mut self, id: impl Into<SharedString>) -> Self {
96 self.base = self.base.accessibility_id(id);
97 self
98 }
99
100 pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
102 self.role = role.into();
103 self
104 }
105
106 pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
108 self.provided_focus_handle = Some(focus_handle.clone());
109 self
110 }
111
112 pub fn on_click(
114 mut self,
115 handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
116 ) -> Self {
117 self.on_click = Some(Rc::new(handler));
118 self
119 }
120
121 pub fn tab_index(mut self, tab_index: isize) -> Self {
123 self.tab_index = tab_index;
124 self
125 }
126
127 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
129 self.tab_stop = tab_stop;
130 self
131 }
132
133 pub fn focusable(mut self, focusable: bool) -> Self {
141 self.focusable = focusable;
142 self
143 }
144
145 fn focus_handle(&self, window: &mut Window, cx: &mut App) -> FocusHandle {
146 self.provided_focus_handle.clone().unwrap_or_else(|| {
147 window
148 .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
149 .read(cx)
150 .clone()
151 })
152 }
153
154 fn resolved_style(&self) -> StyleRefinement {
155 crate::state_style::resolve_style(
156 &self.style,
157 [
158 self.selected.then_some(&self.semantic_styles.selected),
159 self.disabled.then_some(&self.semantic_styles.disabled),
160 ]
161 .into_iter()
162 .flatten(),
163 )
164 }
165}
166
167impl Selectable for Button {
168 fn selected(self, selected: bool) -> Self {
169 Button::selected(self, selected)
170 }
171
172 fn is_selected(&self) -> bool {
173 self.selected
174 }
175}
176
177#[derive(Default)]
179pub struct ButtonStyles {
180 selected: StyleRefinement,
181 disabled: StyleRefinement,
182}
183
184impl ButtonStyles {
185 pub fn selected(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
187 self.selected
188 .refine(&build(StateStyle::default()).into_refinement());
189 self
190 }
191
192 pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
194 self.disabled
195 .refine(&build(StateStyle::default()).into_refinement());
196 self
197 }
198}
199
200impl Styled for Button {
201 fn style(&mut self) -> &mut StyleRefinement {
202 &mut self.style
203 }
204}
205
206impl ParentElement for Button {
207 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
208 self.children.extend(elements);
209 }
210}
211
212impl InteractiveElement for Button {
213 fn interactivity(&mut self) -> &mut Interactivity {
214 self.base.interactivity()
215 }
216}
217
218impl StatefulInteractiveElement for Button {}
219
220impl RenderOnce for Button {
221 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
222 let focus_handle = self.focus_handle(window, cx);
223 let disabled = self.disabled;
224 let style = self.resolved_style();
225 let on_click = self.on_click;
226
227 self.base
228 .flex()
233 .items_center()
234 .justify_center()
235 .line_height(relative(1.))
242 .when_some(self.role.resolve(|| Role::Button), |this, role| {
243 this.role(role)
244 })
245 .when_some(self.accessibility_label, |this, label| {
246 this.aria_label(label)
247 })
248 .when(
251 self.focusable && (!disabled || focus_handle.is_focused(window)),
252 |this| {
253 this.track_focus(
254 &focus_handle
255 .tab_index(self.tab_index)
256 .tab_stop(self.tab_stop && !disabled),
257 )
258 },
259 )
260 .when(disabled, |this| {
261 this.on_mouse_down(MouseButton::Left, |_, _, cx| {
262 cx.stop_propagation();
263 })
264 })
265 .when_some(
266 (!disabled).then_some(on_click).flatten(),
267 |this, on_click| {
268 this.on_click(move |event, window, cx| {
269 on_click(event, window, cx);
270 })
271 },
272 )
273 .children(self.children)
274 .refine_style(&style)
275 .a11y_disabled(disabled)
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282 use crate::ElementExt as _;
283 use std::{
284 cell::Cell,
285 rc::Rc,
286 sync::{Arc, Mutex},
287 };
288
289 use wgpui::{
290 AppContext as _, ClickEvent, Context, Element as _, KeyDownEvent, KeyUpEvent, Keystroke,
291 Modifiers, Render, TestAppContext, VisualTestContext, accesskit, canvas, point, px,
292 };
293
294 struct ButtonHarness {
295 disabled: bool,
296 button_clicks: Rc<Cell<usize>>,
297 parent_clicks: Rc<Cell<usize>>,
298 keyboard_events: Rc<Cell<usize>>,
299 }
300
301 impl Render for ButtonHarness {
302 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
303 let button_clicks = self.button_clicks.clone();
304 let keyboard_events = self.keyboard_events.clone();
305 let parent_clicks = self.parent_clicks.clone();
306
307 div()
308 .id("button-parent")
309 .tab_group()
310 .size(px(100.))
311 .on_click(move |_, _, _| parent_clicks.set(parent_clicks.get() + 1))
312 .child(
313 Button::new("button")
314 .disabled(self.disabled)
315 .size_full()
316 .on_click(move |event, _, _| {
317 button_clicks.set(button_clicks.get() + 1);
318 if matches!(event, ClickEvent::Keyboard(_)) {
319 keyboard_events.set(keyboard_events.get() + 1);
320 }
321 }),
322 )
323 }
324 }
325
326 fn harness(
327 cx: &mut TestAppContext,
328 disabled: bool,
329 ) -> (
330 &mut VisualTestContext,
331 Rc<Cell<usize>>,
332 Rc<Cell<usize>>,
333 Rc<Cell<usize>>,
334 ) {
335 let button_clicks = Rc::new(Cell::new(0));
336 let parent_clicks = Rc::new(Cell::new(0));
337 let keyboard_events = Rc::new(Cell::new(0));
338 let (_, cx) = cx.add_window_view({
339 let button_clicks = button_clicks.clone();
340 let parent_clicks = parent_clicks.clone();
341 let keyboard_events = keyboard_events.clone();
342 move |_, _| ButtonHarness {
343 disabled,
344 button_clicks,
345 parent_clicks,
346 keyboard_events,
347 }
348 });
349 cx.update(|window, cx| {
350 window.draw(cx).clear();
351 });
352 (cx, button_clicks, parent_clicks, keyboard_events)
353 }
354
355 #[wgpui::test]
356 fn pointer_activation_fires_once(cx: &mut TestAppContext) {
357 let (cx, button_clicks, _, keyboard_events) = harness(cx, false);
358
359 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
360
361 assert_eq!(button_clicks.get(), 1);
362 assert_eq!(keyboard_events.get(), 0);
363 }
364
365 #[wgpui::test]
366 fn enter_and_space_use_one_native_keyboard_click_each(cx: &mut TestAppContext) {
367 let (cx, button_clicks, _, keyboard_events) = harness(cx, false);
368 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
369 button_clicks.set(0);
370 cx.update(|window, cx| {
371 assert!(window.focused(cx).is_some());
372 window.draw(cx).clear();
373 });
374
375 for key in ["enter", "space"] {
376 let keystroke =
377 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
378 cx.simulate_event(KeyDownEvent {
379 keystroke: keystroke.clone(),
380 is_held: false,
381 prefer_character_input: false,
382 });
383 cx.simulate_event(KeyUpEvent { keystroke });
384 }
385
386 assert_eq!(button_clicks.get(), 2);
387 assert_eq!(keyboard_events.get(), 2);
388 }
389
390 #[wgpui::test]
391 fn disabled_button_is_inert_and_blocks_parent_activation(cx: &mut TestAppContext) {
392 let (cx, button_clicks, parent_clicks, _) = harness(cx, true);
393
394 cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
395 cx.update(|window, cx| window.focus_next(cx));
396 cx.simulate_keystrokes("enter space");
397
398 assert_eq!(button_clicks.get(), 0);
399 assert_eq!(parent_clicks.get(), 0);
400 }
401
402 struct DisableDuringFocus {
403 handles: [FocusHandle; 3],
404 disabled: bool,
405 activations: usize,
406 }
407
408 impl Render for DisableDuringFocus {
409 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
410 div()
411 .size_full()
412 .flex()
413 .tab_group()
414 .child(
415 Button::new("before")
416 .track_focus(&self.handles[0])
417 .child("Before"),
418 )
419 .child(
420 Button::new("disable-self")
421 .track_focus(&self.handles[1])
422 .disabled(self.disabled)
423 .child("Disable self")
424 .on_click(cx.listener(|this, _, _, cx| {
425 this.disabled = true;
426 this.activations += 1;
427 cx.notify();
428 })),
429 )
430 .child(
431 Button::new("after")
432 .track_focus(&self.handles[2])
433 .child("After"),
434 )
435 }
436 }
437
438 fn press_transition_key(cx: &mut VisualTestContext, key: &str) {
439 let keystroke =
440 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
441 cx.simulate_event(KeyDownEvent {
442 keystroke: keystroke.clone(),
443 is_held: false,
444 prefer_character_input: false,
445 });
446 cx.simulate_event(KeyUpEvent { keystroke });
447 cx.update(|window, cx| window.draw(cx).clear());
448 }
449
450 #[wgpui::test]
451 fn disabling_focused_button_preserves_bidirectional_traversal(cx: &mut TestAppContext) {
452 cx.update(crate::init);
453 for (key, expected, back, opposite) in
454 [("tab", 2, "shift-tab", 0), ("shift-tab", 0, "tab", 2)]
455 {
456 let handles = cx.update(|cx| std::array::from_fn(|_| cx.focus_handle()));
457 let controls = cx.new(|_| DisableDuringFocus {
458 handles: handles.clone(),
459 disabled: false,
460 activations: 0,
461 });
462 let (_, cx) =
463 cx.add_window_view(|window, cx| crate::Root::new(controls.clone(), window, cx));
464 cx.update(|window, cx| {
465 window.activate_window();
466 window.draw(cx).clear();
467 handles[0].focus(window, cx);
468 window.draw(cx).clear();
469 });
470 press_transition_key(cx, "tab");
471 cx.update(|window, cx| {
472 window.draw(cx).clear();
473 assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
474 });
475 press_transition_key(cx, "space");
476 cx.update(|window, cx| {
477 window.draw(cx).clear();
478 assert!(controls.read(cx).disabled);
479 assert_eq!(controls.read(cx).activations, 1);
480 });
481 press_transition_key(cx, "enter");
482 press_transition_key(cx, "space");
483 cx.update(|_, cx| {
484 assert_eq!(controls.read(cx).activations, 1, "disabled stays inert");
485 });
486 press_transition_key(cx, key);
487 cx.update(|window, cx| {
488 window.draw(cx).clear();
489 assert_eq!(window.focused(cx).as_ref(), Some(&handles[expected]));
490 });
491 press_transition_key(cx, back);
492 cx.update(|window, cx| {
493 window.draw(cx).clear();
494 assert_eq!(window.focused(cx).as_ref(), Some(&handles[opposite]));
495 });
496 controls.update(cx, |this, cx| {
497 this.disabled = false;
498 cx.notify();
499 });
500 cx.update(|window, cx| window.draw(cx).clear());
501 press_transition_key(cx, key);
502 cx.update(|window, cx| {
503 window.draw(cx).clear();
504 assert_eq!(window.focused(cx).as_ref(), Some(&handles[1]));
505 });
506 }
507 }
508
509 #[wgpui::test]
510 fn fixed_height_button_centers_ordinary_child_geometry(cx: &mut TestAppContext) {
511 type Captured = Arc<
512 Mutex<(
513 Option<wgpui::Bounds<wgpui::Pixels>>,
514 Option<wgpui::Bounds<wgpui::Pixels>>,
515 )>,
516 >;
517
518 struct AlignmentProbe {
519 captured: Captured,
520 }
521
522 impl Render for AlignmentProbe {
523 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
524 let root_capture = self.captured.clone();
525 let child_capture = self.captured.clone();
526 Button::new("alignment-button")
527 .w(px(120.))
528 .h(px(40.))
529 .child(
530 div()
531 .w(px(48.))
532 .h(px(12.))
533 .on_prepaint(move |bounds, _, _| {
534 child_capture.lock().unwrap().1 = Some(bounds);
535 }),
536 )
537 .on_prepaint(move |bounds, _, _| {
538 root_capture.lock().unwrap().0 = Some(bounds);
539 })
540 }
541 }
542
543 let captured = Arc::new(Mutex::new((None, None)));
544 let (_, context) = cx.add_window_view({
545 let captured = captured.clone();
546 move |_, _| AlignmentProbe { captured }
547 });
548 context.update(|window, cx| window.draw(cx).clear());
549
550 let (root, child) = *captured.lock().unwrap();
551 let root = root.expect("button bounds");
552 let child = child.expect("child bounds");
553 assert_eq!(child.center(), root.center());
554 }
555
556 #[test]
557 fn state_styling_methods_are_available_to_applications() {
558 let _ = Button::new("states")
559 .styles(|styles| {
560 styles.disabled(|style| {
561 style
562 .opacity(0.5)
563 .when(true, |style| style.border_1())
564 .when_some(Some(0.4), |style, opacity| style.opacity(opacity))
565 .when_none(&None::<f32>, |style| style.rounded_sm())
566 })
567 })
568 .hover(|style| style.opacity(0.9))
569 .active(|style| style.opacity(0.8))
570 .focus_visible(|style| style.opacity(0.7));
571 }
572
573 #[test]
574 fn disabled_style_applies_only_while_disabled_and_then_wins() {
575 let enabled = Button::new("enabled")
576 .opacity(0.9)
577 .styles(|styles| styles.disabled(|style| style.opacity(0.5)));
578 assert_eq!(enabled.resolved_style().opacity, Some(0.9));
579
580 let disabled = Button::new("disabled")
581 .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
582 .opacity(0.9)
583 .disabled(true);
584 assert_eq!(disabled.resolved_style().opacity, Some(0.5));
585
586 let semantic_only = Button::new("semantic-only")
587 .styles(|styles| styles.disabled(|style| style.opacity(0.5)))
588 .disabled(true);
589 assert_eq!(semantic_only.resolved_style().opacity, Some(0.5));
590 }
591
592 #[test]
593 fn selected_disabled_and_instance_styles_follow_the_shared_priority() {
594 let selected_color = wgpui::hsla(0.6, 0.7, 0.5, 1.0);
595 let disabled_color = wgpui::hsla(0.1, 0.2, 0.3, 0.5);
596 let button = |selected, disabled| {
597 Button::new("button")
598 .selected(selected)
599 .disabled(disabled)
600 .styles(|styles| {
601 styles
602 .selected(|style| style.bg(selected_color))
603 .disabled(|style| style.bg(disabled_color))
604 })
605 };
606
607 assert_eq!(button(false, false).resolved_style().background, None);
608 assert_eq!(
609 button(true, false).resolved_style().background,
610 Some(selected_color.into())
611 );
612 assert_eq!(
613 button(true, true).resolved_style().background,
614 Some(disabled_color.into())
615 );
616 assert_eq!(
617 button(true, true)
618 .bg(selected_color)
619 .resolved_style()
620 .background,
621 Some(disabled_color.into())
622 );
623 }
624
625 #[wgpui::test]
626 fn accessibility_role_label_and_disabled_action_surface(cx: &mut TestAppContext) {
627 type Captured = Arc<Mutex<Option<(accesskit::Node, accesskit::Node)>>>;
628
629 struct A11yProbe {
630 captured: Captured,
631 }
632
633 impl Render for A11yProbe {
634 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
635 let captured = self.captured.clone();
636 canvas(
637 move |_, window, cx| {
638 let mut info = |button: Button| {
639 let mut node = accesskit::Node::new(Role::Button);
640 button
641 .render(window, cx)
642 .into_element()
643 .write_a11y_info(&mut node);
644 node
645 };
646 let enabled = info(
647 Button::new("enabled")
648 .accessibility_label("Save")
649 .on_click(|_, _, _| {}),
650 );
651 let disabled = info(
652 Button::new("disabled")
653 .disabled(true)
654 .accessibility_label("Save")
655 .on_click(|_, _, _| {}),
656 );
657 *captured.lock().unwrap() = Some((enabled, disabled));
658 },
659 |_, _, _, _| {},
660 )
661 }
662 }
663
664 let captured: Captured = Arc::new(Mutex::new(None));
665 let result = captured.clone();
666 let (_, cx) = cx.add_window_view(move |_, _| A11yProbe { captured });
667 cx.update(|window, cx| {
668 window.draw(cx).clear();
669 });
670 let (enabled, disabled) = result.lock().unwrap().take().unwrap();
671 assert_eq!(enabled.role(), Role::Button);
672 assert_eq!(enabled.label(), Some("Save"));
673 assert!(enabled.supports_action(accesskit::Action::Click));
674
675 assert_eq!(disabled.role(), Role::Button);
676 assert!(!disabled.supports_action(accesskit::Action::Click));
677 assert!(!enabled.is_disabled());
678 assert!(disabled.is_disabled());
679 }
680}