Skip to main content

gpui_deck/
label.rs

1//! Standalone labels that focus an existing control without activating it.
2
3use 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/// An unstyled text label that focuses an application-supplied control.
12///
13/// Clicking the enabled label focuses its target without changing its value,
14/// toggling it, or opening a popup. The label itself has no focus handle or Tab
15/// stop. Keep the target mounted in the same window and supply its rendered
16/// disabled state through [`Self::disabled`].
17///
18/// The label exposes its own native Label role and name. Set the target's
19/// accessible name separately, normally from the same text; this component
20/// does not establish a native `labelled_by` relationship. Text-input labels
21/// with help and validation metadata are provided by [`crate::Field`].
22#[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    /// Mirrors the target's disabled state, suppressing label activation.
45    ///
46    /// The caller owns this state and must update it when the target changes.
47    /// A disabled label neither moves focus nor activates a containing control.
48    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}