Skip to main content

gpui_deck/input/base/
mod.rs

1// Modified for GPUI Deck: observe public input wrappers and update crate references.
2use crate::{StateStyle, StyledExt as _, TestSupportExt as _, a11y_disabled::A11yDisabledExt as _};
3use gpui::{
4    AnyElement, App, Div, ElementId, InteractiveElement, Interactivity, IntoElement, ParentElement,
5    Refineable as _, RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement,
6    Styled, Window, div, prelude::FluentBuilder as _,
7};
8
9/// What the input can offer to its context menu, at the moment it is opened.
10///
11/// Built by the input and read by the menu, the fields are private and reached
12/// through the methods below, so that a new capability can be added without
13/// breaking the menu builders.
14///
15/// ```
16/// use gpui_deck::input::InputContextMenuCapabilities;
17///
18/// let capabilities = InputContextMenuCapabilities::new()
19///     .code_editor(true)
20///     .selection(true);
21///
22/// assert!(capabilities.is_editable());
23/// assert!(capabilities.has_selection());
24/// ```
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub struct InputContextMenuCapabilities {
27    disabled: bool,
28    readonly: bool,
29    code_editor: bool,
30    selection: bool,
31    masked: bool,
32    go_to_definition: bool,
33    code_actions: bool,
34}
35
36impl InputContextMenuCapabilities {
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    pub fn disabled(mut self, disabled: bool) -> Self {
42        self.disabled = disabled;
43        self
44    }
45
46    pub fn readonly(mut self, readonly: bool) -> Self {
47        self.readonly = readonly;
48        self
49    }
50
51    pub fn code_editor(mut self, code_editor: bool) -> Self {
52        self.code_editor = code_editor;
53        self
54    }
55
56    /// Set whether the input has a non-empty selection.
57    pub fn selection(mut self, selection: bool) -> Self {
58        self.selection = selection;
59        self
60    }
61
62    /// Set whether the input renders its value masked.
63    pub fn masked(mut self, masked: bool) -> Self {
64        self.masked = masked;
65        self
66    }
67
68    pub fn go_to_definition(mut self, go_to_definition: bool) -> Self {
69        self.go_to_definition = go_to_definition;
70        self
71    }
72
73    pub fn code_actions(mut self, code_actions: bool) -> Self {
74        self.code_actions = code_actions;
75        self
76    }
77
78    pub fn is_disabled(&self) -> bool {
79        self.disabled
80    }
81
82    pub fn is_readonly(&self) -> bool {
83        self.readonly
84    }
85
86    /// Returns true if the user is allowed to change the text.
87    ///
88    /// The items that write to the input (Cut, Paste, Code Actions) belong to
89    /// this, the reading ones (Copy, Go to Definition) do not.
90    pub fn is_editable(&self) -> bool {
91        !self.disabled && !self.readonly
92    }
93
94    pub fn is_code_editor(&self) -> bool {
95        self.code_editor
96    }
97
98    pub fn has_selection(&self) -> bool {
99        self.selection
100    }
101
102    pub fn is_masked(&self) -> bool {
103        self.masked
104    }
105
106    /// Returns true if the user is allowed to copy the text out.
107    ///
108    /// A masked input keeps its value out of the clipboard, so Copy and Cut
109    /// are both unavailable while the value is hidden.
110    pub fn is_copyable(&self) -> bool {
111        self.selection && !self.masked
112    }
113
114    pub fn has_definition(&self) -> bool {
115        self.go_to_definition
116    }
117
118    pub fn has_code_actions(&self) -> bool {
119        self.code_actions
120    }
121}
122
123/// The foundational input frame.
124///
125/// It intentionally owns only input semantics, interaction forwarding, and
126/// normal children. Applications remain responsible for all presentation.
127#[derive(IntoElement)]
128pub struct InputBase {
129    base: crate::ObservedElement<gpui::Stateful<Div>>,
130    style: StyleRefinement,
131    semantic_styles: InputStyles,
132    children: Vec<AnyElement>,
133    focused: bool,
134    disabled: bool,
135    role: crate::RoleOverride,
136}
137
138impl InputBase {
139    pub fn new(id: impl Into<ElementId>) -> Self {
140        Self {
141            base: div().id(id).test_support(),
142            style: StyleRefinement::default(),
143            semantic_styles: InputStyles::default(),
144            children: Vec::new(),
145            focused: false,
146            disabled: false,
147            role: crate::RoleOverride::Implicit,
148        }
149    }
150    pub fn role(mut self, role: impl Into<crate::RoleOverride>) -> Self {
151        self.role = role.into();
152        self
153    }
154
155    pub fn focused(mut self, focused: bool) -> Self {
156        self.focused = focused;
157        self
158    }
159
160    pub fn disabled(mut self, disabled: bool) -> Self {
161        self.disabled = disabled;
162        self
163    }
164
165    /// Exposes an editor's native semantics through this frame's component ID.
166    ///
167    /// `E` must name the rendered wrapper, such as [`super::Input`] or
168    /// [`super::Textarea`], and `editor` must identify its state below this frame,
169    /// without additional identified wrappers. Anonymous layout wrappers are
170    /// allowed. ID queries retain the frame's path, bounds and visibility.
171    /// Role, label, value, checked/indeterminate, selected, expanded, disabled
172    /// and focus facts come from the editor's existing native node and observed
173    /// focus scope, not independently focusable addon controls. Native snapshot
174    /// enumeration is unchanged, so role/label queries do not duplicate editors.
175    ///
176    /// This only declares an observation relationship with `test-support`; it
177    /// never adds a native accessibility node or registers a focus handle. The
178    /// relationship follows the frame's GPUI element-state lifetime.
179    pub fn semantic_owner<E: RenderOnce>(self, editor: gpui::EntityId) -> Self {
180        #[cfg(feature = "test-support")]
181        {
182            Self {
183                base: self.base.semantic_owner([
184                    std::any::type_name::<E>().into(),
185                    ElementId::View(editor),
186                    super::state::EDITOR_ELEMENT_ID.into(),
187                ]),
188                ..self
189            }
190        }
191        #[cfg(not(feature = "test-support"))]
192        {
193            let _ = editor;
194            self
195        }
196    }
197
198    pub fn styles(mut self, build: impl FnOnce(InputStyles) -> InputStyles) -> Self {
199        self.semantic_styles = build(self.semantic_styles);
200        self
201    }
202
203    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
204        self.base = self.base.aria_label(label.into());
205        self
206    }
207
208    fn resolved_style(&self) -> StyleRefinement {
209        crate::state_style::resolve_style(
210            &self.style,
211            [
212                self.focused.then_some(&self.semantic_styles.focused),
213                self.disabled.then_some(&self.semantic_styles.disabled),
214            ]
215            .into_iter()
216            .flatten(),
217        )
218    }
219}
220
221#[derive(Default)]
222pub struct InputStyles {
223    focused: StyleRefinement,
224    disabled: StyleRefinement,
225}
226
227impl InputStyles {
228    pub fn focused(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
229        self.focused
230            .refine(&build(StateStyle::default()).into_refinement());
231        self
232    }
233
234    pub fn disabled(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
235        self.disabled
236            .refine(&build(StateStyle::default()).into_refinement());
237        self
238    }
239}
240
241impl Styled for InputBase {
242    fn style(&mut self) -> &mut StyleRefinement {
243        &mut self.style
244    }
245}
246
247impl ParentElement for InputBase {
248    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
249        self.children.extend(elements);
250    }
251}
252
253impl InteractiveElement for InputBase {
254    fn track_focus(mut self, focus: &gpui::FocusHandle) -> Self {
255        self.base = self.base.track_focus(focus);
256        self
257    }
258
259    fn interactivity(&mut self) -> &mut Interactivity {
260        self.base.interactivity()
261    }
262}
263
264impl StatefulInteractiveElement for InputBase {}
265
266impl RenderOnce for InputBase {
267    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
268        let style = self.resolved_style();
269        self.base
270            .when_some(self.role.resolve(|| Role::TextInput), |this, role| {
271                this.role(role)
272            })
273            .children(self.children)
274            .refine_style(&style)
275            .a11y_disabled(self.disabled)
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn frame_accepts_application_owned_content_and_style() {
285        let _ = InputBase::new("input")
286            .focused(true)
287            .disabled(false)
288            .styles(|styles| {
289                styles
290                    .focused(|style| style.border_1())
291                    .disabled(|style| style.opacity(0.5))
292            })
293            .child("value")
294            .opacity(0.8);
295    }
296
297    /// A disabled frame reports itself disabled on the text-input node it writes.
298    #[gpui::test]
299    fn a_disabled_frame_is_disabled_for_assistive_technology(cx: &mut gpui::TestAppContext) {
300        use gpui::Element as _;
301
302        let cx = cx.add_empty_window();
303        cx.update(|window, cx| {
304            for disabled in [false, true] {
305                let element = InputBase::new("input")
306                    .disabled(disabled)
307                    .render(window, cx)
308                    .into_element();
309                let mut node = gpui::accesskit::Node::new(element.a11y_role().unwrap());
310                element.write_a11y_info(&mut node);
311                assert_eq!(node.role(), Role::TextInput);
312                assert_eq!(node.is_disabled(), disabled);
313            }
314        });
315    }
316
317    #[test]
318    fn semantic_state_styles_override_the_normal_style() {
319        let focused = InputBase::new("focused")
320            .focused(true)
321            .border_color(gpui::red())
322            .styles(|styles| styles.focused(|style| style.border_color(gpui::blue())));
323        assert_eq!(focused.resolved_style().border_color, Some(gpui::blue()));
324
325        let disabled = InputBase::new("disabled")
326            .focused(true)
327            .disabled(true)
328            .opacity(1.)
329            .styles(|styles| {
330                styles
331                    .focused(|style| style.opacity(0.8))
332                    .disabled(|style| style.opacity(0.5))
333            });
334        assert_eq!(disabled.resolved_style().opacity, Some(0.5));
335    }
336}