1use gpui::{
4 App, Div, ElementId, FocusHandle, InteractiveElement as _, IntoElement, MouseButton,
5 ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
6 StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,
7};
8
9use crate::{TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
10
11#[derive(IntoElement)]
23pub struct Label {
24 base: crate::ObservedElement<gpui::Stateful<Div>>,
25 target: FocusHandle,
26 text: SharedString,
27 disabled: bool,
28}
29
30impl Label {
31 pub fn new(
32 id: impl Into<ElementId>,
33 target: &FocusHandle,
34 text: impl Into<SharedString>,
35 ) -> Self {
36 Self {
37 base: div().id(id).test_support(),
38 target: target.clone(),
39 text: text.into(),
40 disabled: false,
41 }
42 }
43
44 pub fn disabled(mut self, disabled: bool) -> Self {
49 self.disabled = disabled;
50 self
51 }
52}
53
54impl Styled for Label {
55 fn style(&mut self) -> &mut StyleRefinement {
56 self.base.style()
57 }
58}
59
60impl RenderOnce for Label {
61 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
62 let disabled = self.disabled;
63 let target = self.target;
64 self.base
65 .role(Role::Label)
66 .aria_label(self.text.clone())
67 .child(self.text)
68 .when(disabled, |label| {
69 label.on_mouse_down(MouseButton::Left, |_, _, cx| {
70 cx.stop_propagation();
71 })
72 })
73 .when(!disabled, |label| {
74 label.on_click(move |_, window, cx| {
75 target.focus(window, cx);
76 cx.stop_propagation();
77 })
78 })
79 .a11y_disabled(disabled)
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use gpui::{Element as _, TestAppContext, accesskit};
86
87 use super::*;
88
89 #[gpui::test]
90 fn native_label_has_a_name_and_only_an_enabled_click_action(cx: &mut TestAppContext) {
91 let window = cx.add_empty_window();
92 window.update(|window, cx| {
93 let target = cx.focus_handle();
94 for disabled in [false, true] {
95 let element = Label::new("label", &target, "Drawing tool")
96 .disabled(disabled)
97 .render(window, cx)
98 .into_element();
99 assert_eq!(element.a11y_role(), Some(Role::Label));
100 let mut node = accesskit::Node::new(Role::Label);
101 element.write_a11y_info(&mut node);
102 assert_eq!(node.label(), Some("Drawing tool"));
103 assert_eq!(node.is_disabled(), disabled);
104 assert_eq!(node.supports_action(accesskit::Action::Click), !disabled);
105 assert!(!node.supports_action(accesskit::Action::Focus));
106 }
107 });
108 }
109}