Skip to main content

gpui_deck/
field.rs

1//! Label, help, and validation presentation associated with one retained input.
2
3use std::rc::Rc;
4
5use gpui::{
6    AnyElement, App, Div, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement,
7    MouseButton, ParentElement, Refineable as _, RenderOnce, Role, SharedString,
8    StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
9    prelude::FluentBuilder as _,
10};
11
12use crate::{
13    StateStyle, StyledExt as _, TestSupportExt as _,
14    a11y_disabled::A11yDisabledExt as _,
15    input::{InputAccessibility, InputBaseState, InputModeKind},
16};
17
18/// An unstyled field associated with an existing Input or Textarea state.
19///
20/// The field renders its label, application-provided control children, help,
21/// and optional error in that order. Applications supply layout, styles, and
22/// validation; this component neither stores text nor validates it. Clicking
23/// the label focuses the live enabled input without introducing another Tab
24/// stop. The label's element ID is `(field_id, "label")`.
25///
26/// Label, error/help description, required, and invalid metadata are projected
27/// onto the input's existing native node before its child renderer runs. Its
28/// role, placeholder, external identifier, value exposure, and popup metadata
29/// are preserved. An error is announced before help text. When no semantics
30/// were configured, the input's mode supplies its natural text-input role.
31///
32/// Keep the associated input among this field's children. A composed input
33/// renderer must likewise preserve metadata it does not own. Host application
34/// content in [`crate::Root`] for normal form traversal.
35#[derive(IntoElement)]
36pub struct Field<M: InputModeKind> {
37    id: ElementId,
38    base: crate::ObservedElement<gpui::Stateful<Div>>,
39    input: Entity<InputBaseState<M>>,
40    label: SharedString,
41    description: Option<SharedString>,
42    error: Option<SharedString>,
43    required: bool,
44    styles: FieldStyles,
45    children: Vec<AnyElement>,
46}
47
48impl<M: InputModeKind> Field<M> {
49    pub fn new(
50        id: impl Into<ElementId>,
51        input: &Entity<InputBaseState<M>>,
52        label: impl Into<SharedString>,
53    ) -> Self {
54        let id = id.into();
55        Self {
56            base: div().id(id.clone()).test_support(),
57            id,
58            input: input.clone(),
59            label: label.into(),
60            description: None,
61            error: None,
62            required: false,
63            styles: FieldStyles::default(),
64            children: Vec::new(),
65        }
66    }
67
68    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
69        self.description = Some(description.into());
70        self
71    }
72
73    /// Supplies an application validation error; `None` clears invalid state.
74    pub fn error(mut self, error: Option<SharedString>) -> Self {
75        self.error = error;
76        self
77    }
78
79    /// Reports the requirement to accessibility clients; does not reject input.
80    pub fn required(mut self, required: bool) -> Self {
81        self.required = required;
82        self
83    }
84
85    pub fn styles(mut self, build: impl FnOnce(FieldStyles) -> FieldStyles) -> Self {
86        self.styles = build(self.styles);
87        self
88    }
89}
90
91/// Application-owned presentation of the field's text parts.
92#[derive(Default)]
93pub struct FieldStyles {
94    label: StyleRefinement,
95    description: StyleRefinement,
96    error: StyleRefinement,
97}
98
99impl FieldStyles {
100    pub fn label(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
101        self.label
102            .refine(&build(StateStyle::default()).into_refinement());
103        self
104    }
105
106    pub fn description(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
107        self.description
108            .refine(&build(StateStyle::default()).into_refinement());
109        self
110    }
111
112    pub fn error(mut self, build: impl FnOnce(StateStyle) -> StateStyle) -> Self {
113        self.error
114            .refine(&build(StateStyle::default()).into_refinement());
115        self
116    }
117}
118
119impl<M: InputModeKind> Styled for Field<M> {
120    fn style(&mut self) -> &mut StyleRefinement {
121        self.base.style()
122    }
123}
124
125impl<M: InputModeKind> ParentElement for Field<M> {
126    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
127        self.children.extend(elements);
128    }
129}
130
131impl<M: InputModeKind> RenderOnce for Field<M> {
132    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
133        let description = match (&self.error, &self.description) {
134            (Some(error), Some(help)) => Some(format!("{error} {help}").into()),
135            (Some(error), None) => Some(error.clone()),
136            (None, help) => help.clone(),
137        };
138        self.input.update(cx, |state, _| {
139            let accessibility = state.accessibility().cloned().unwrap_or_else(|| {
140                InputAccessibility::new(Some(if M::MULTI_LINE {
141                    Role::MultilineTextInput
142                } else {
143                    Role::TextInput
144                }))
145            });
146            state.set_accessibility(
147                accessibility
148                    .with_label(Some(self.label.clone()))
149                    .with_description(description)
150                    .with_required(self.required)
151                    .with_invalid(self.error.is_some()),
152            );
153        });
154
155        let disabled = self.input.read(cx).presentation().is_disabled();
156        let label_input = self.input;
157        let label = div()
158            .id((self.id.clone(), "label"))
159            .test_support()
160            .role(Role::Label)
161            .aria_label(self.label.clone())
162            .refine_style(&self.styles.label)
163            .child(self.label)
164            .when(disabled, |label| {
165                label.on_mouse_down(MouseButton::Left, |_, _, cx| {
166                    cx.stop_propagation();
167                })
168            })
169            .when(!disabled, |label| {
170                label.on_click(move |_, window, cx| {
171                    label_input.update(cx, |state, cx| {
172                        if !state.presentation().is_disabled() {
173                            state.focus(window, cx);
174                        }
175                    });
176                    cx.stop_propagation();
177                })
178            })
179            .a11y_disabled(disabled);
180
181        self.base
182            .role(Role::Group)
183            .child(label)
184            .children(self.children)
185            .when_some(self.description, |this, description| {
186                this.child(
187                    div()
188                        .id((self.id.clone(), "description"))
189                        .test_support()
190                        .role(Role::Label)
191                        .aria_label(description.clone())
192                        .refine_style(&self.styles.description)
193                        .child(description),
194                )
195            })
196            .when_some(self.error, |this, error| {
197                this.child(
198                    div()
199                        .id((self.id, "error"))
200                        .test_support()
201                        .role(Role::Label)
202                        .aria_label(error.clone())
203                        .refine_style(&self.styles.error)
204                        .child(error),
205                )
206            })
207    }
208}
209
210/// Native metadata a [`ControlField`] hands to its non-text control.
211///
212/// Checkbox, Switch, RadioGroup and Select accept it through `.field(...)`,
213/// which names the control, describes it with the error then help text, and
214/// marks it required or invalid on its existing accessibility node.
215#[derive(Clone, Debug, Default, PartialEq)]
216pub struct FieldMetadata {
217    pub label: Option<SharedString>,
218    pub description: Option<SharedString>,
219    pub required: bool,
220    pub invalid: bool,
221}
222
223/// An unstyled field for a checkbox, switch, radio group, select or other
224/// non-text control.
225///
226/// It renders the label, the control built from [`FieldMetadata`], help and an
227/// optional error. Clicking the label focuses `focus` without adding a Tab stop,
228/// then runs the optional label activation, for example toggling a checkbox as
229/// an HTML `label` does. Validation and layout belong to the application; use
230/// [`Field`] for Input and Textarea.
231#[derive(IntoElement)]
232pub struct ControlField {
233    id: ElementId,
234    base: crate::ObservedElement<gpui::Stateful<Div>>,
235    focus: FocusHandle,
236    label: SharedString,
237    description: Option<SharedString>,
238    error: Option<SharedString>,
239    required: bool,
240    disabled: bool,
241    control_first: bool,
242    activate: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
243    control: Option<Box<dyn FnOnce(FieldMetadata) -> AnyElement>>,
244    styles: FieldStyles,
245}
246
247impl ControlField {
248    pub fn new(
249        id: impl Into<ElementId>,
250        focus: &FocusHandle,
251        label: impl Into<SharedString>,
252    ) -> Self {
253        let id = id.into();
254        Self {
255            base: div().id(id.clone()).test_support(),
256            id,
257            focus: focus.clone(),
258            label: label.into(),
259            description: None,
260            error: None,
261            required: false,
262            disabled: false,
263            control_first: false,
264            activate: None,
265            control: None,
266            styles: FieldStyles::default(),
267        }
268    }
269
270    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
271        self.description = Some(description.into());
272        self
273    }
274
275    /// Supplies an application validation error; `None` clears invalid state.
276    pub fn error(mut self, error: Option<SharedString>) -> Self {
277        self.error = error;
278        self
279    }
280
281    /// Reports the requirement to accessibility clients; does not reject values.
282    pub fn required(mut self, required: bool) -> Self {
283        self.required = required;
284        self
285    }
286
287    /// Mirrors the control's disabled state so the label neither focuses nor
288    /// activates it.
289    pub fn disabled(mut self, disabled: bool) -> Self {
290        self.disabled = disabled;
291        self
292    }
293
294    /// Renders the control before its label, as for a checkbox or switch.
295    pub fn control_first(mut self, control_first: bool) -> Self {
296        self.control_first = control_first;
297        self
298    }
299
300    /// Runs after a label click focuses the control.
301    pub fn on_label_activate(mut self, activate: impl Fn(&mut Window, &mut App) + 'static) -> Self {
302        self.activate = Some(Rc::new(activate));
303        self
304    }
305
306    /// Builds the control from this field's metadata; pass it to `.field(...)`.
307    pub fn control<E: IntoElement>(
308        mut self,
309        build: impl FnOnce(FieldMetadata) -> E + 'static,
310    ) -> Self {
311        self.control = Some(Box::new(move |metadata| build(metadata).into_any_element()));
312        self
313    }
314
315    pub fn styles(mut self, build: impl FnOnce(FieldStyles) -> FieldStyles) -> Self {
316        self.styles = build(self.styles);
317        self
318    }
319}
320
321impl Styled for ControlField {
322    fn style(&mut self) -> &mut StyleRefinement {
323        self.base.style()
324    }
325}
326
327impl RenderOnce for ControlField {
328    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
329        let metadata = FieldMetadata {
330            label: Some(self.label.clone()),
331            description: match (&self.error, &self.description) {
332                (Some(error), Some(help)) => Some(format!("{error} {help}").into()),
333                (Some(error), None) => Some(error.clone()),
334                (None, help) => help.clone(),
335            },
336            required: self.required,
337            invalid: self.error.is_some(),
338        };
339        let control = self.control.map(|build| build(metadata));
340        let disabled = self.disabled;
341        let focus = self.focus;
342        let activate = self.activate;
343        let label = div()
344            .id((self.id.clone(), "label"))
345            .test_support()
346            .role(Role::Label)
347            .aria_label(self.label.clone())
348            .refine_style(&self.styles.label)
349            .child(self.label)
350            .when(disabled, |label| {
351                label.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
352            })
353            .when(!disabled, |label| {
354                label.on_click(move |_, window, cx| {
355                    focus.focus(window, cx);
356                    if let Some(activate) = &activate {
357                        activate(window, cx);
358                    }
359                    cx.stop_propagation();
360                })
361            })
362            .a11y_disabled(disabled);
363        let (first, second): (AnyElement, Option<AnyElement>) = if self.control_first {
364            match control {
365                Some(control) => (control, Some(label.into_any_element())),
366                None => (label.into_any_element(), None),
367            }
368        } else {
369            (label.into_any_element(), control)
370        };
371        self.base
372            .role(Role::Group)
373            .child(first)
374            .children(second)
375            .when_some(self.description, |this, description| {
376                this.child(
377                    div()
378                        .id((self.id.clone(), "description"))
379                        .test_support()
380                        .role(Role::Label)
381                        .aria_label(description.clone())
382                        .refine_style(&self.styles.description)
383                        .child(description),
384                )
385            })
386            .when_some(self.error, |this, error| {
387                this.child(
388                    div()
389                        .id((self.id, "error"))
390                        .test_support()
391                        .role(Role::Label)
392                        .aria_label(error.clone())
393                        .refine_style(&self.styles.error)
394                        .child(error),
395                )
396            })
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use gpui::{
403        AppContext as _, Context, Element as _, FocusHandle, Modifiers, Render, TestAppContext,
404        accesskit, point, px,
405    };
406
407    use super::*;
408    use crate::InputState;
409
410    #[gpui::test]
411    fn feedback_preserves_the_native_inputs_existing_capabilities(cx: &mut TestAppContext) {
412        cx.update(crate::init);
413        let window = cx.add_empty_window();
414        window.update(|window, cx| {
415            let input = cx.new(|cx| {
416                let mut input = InputState::new(window, cx).default_value("private value");
417                input.set_accessibility(
418                    InputAccessibility::new(Some(Role::ComboBox))
419                        .with_placeholder(Some("Find a session".into()))
420                        .with_accessibility_id(Some("session-editor".into()))
421                        .with_expanded(Some(true))
422                        .with_value_exposed(false),
423                );
424                input
425            });
426
427            for invalid in [true, false] {
428                let _ = Field::new("session", &input, "Session name")
429                    .description("Choose a recognizable name.")
430                    .required(true)
431                    .error(invalid.then(|| "A name is required.".into()))
432                    .render(window, cx);
433
434                input.update(cx, |state, cx| {
435                    let element = state.render(window, cx).into_element();
436                    assert_eq!(element.a11y_role(), Some(Role::ComboBox));
437                    let mut node = accesskit::Node::new(Role::ComboBox);
438                    element.write_a11y_info(&mut node);
439                    assert_eq!(node.label(), Some("Session name"));
440                    assert_eq!(
441                        node.description(),
442                        Some(if invalid {
443                            "A name is required. Choose a recognizable name."
444                        } else {
445                            "Choose a recognizable name."
446                        }),
447                    );
448                    assert_eq!(node.placeholder(), Some("Find a session"));
449                    assert_eq!(node.author_id(), Some("session-editor"));
450                    assert_eq!(node.is_expanded(), Some(true));
451                    assert!(node.is_required());
452                    assert_eq!(node.invalid(), invalid.then_some(accesskit::Invalid::True));
453                    assert_eq!(node.value(), None, "field must preserve hidden values");
454                    assert_eq!(state.value(), "private value");
455                });
456            }
457
458            input.update(cx, |state, cx| state.set_disabled(true, cx));
459            let _ = Field::new("session", &input, "Session name").render(window, cx);
460            input.update(cx, |state, cx| {
461                let element = state.render(window, cx).into_element();
462                let mut node = accesskit::Node::new(Role::ComboBox);
463                element.write_a11y_info(&mut node);
464                assert!(node.is_disabled());
465                assert!(!node.is_required());
466                assert_eq!(node.invalid(), None);
467                assert_eq!(node.description(), None);
468            });
469        });
470    }
471
472    #[gpui::test]
473    fn label_disabled_state_blocks_parent_focus_but_readonly_remains_focusable(
474        cx: &mut TestAppContext,
475    ) {
476        struct Harness {
477            input: Entity<InputState>,
478            outside: FocusHandle,
479            parent: FocusHandle,
480        }
481        impl Render for Harness {
482            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
483                div()
484                    .flex()
485                    .flex_col()
486                    .w(px(200.))
487                    .child(
488                        div().id("parent").track_focus(&self.parent).child(
489                            Field::new("field", &self.input, "Name")
490                                .flex()
491                                .flex_col()
492                                .styles(|styles| styles.label(|style| style.h(px(32.))))
493                                .child(
494                                    crate::InputBase::new("input")
495                                        .h(px(32.))
496                                        .child(crate::Input::new(&self.input)),
497                                ),
498                        ),
499                    )
500                    .child(
501                        crate::Button::new("outside")
502                            .track_focus(&self.outside)
503                            .h(px(32.))
504                            .child("Outside"),
505                    )
506            }
507        }
508        cx.update(crate::init);
509        let (root, cx) = cx.add_window_view(|window, cx| {
510            let view = cx.new(|cx| Harness {
511                input: cx.new(|cx| InputState::new(window, cx).default_value("Name")),
512                outside: cx.focus_handle(),
513                parent: cx.focus_handle(),
514            });
515            crate::Root::new(view, window, cx)
516        });
517        let view = root
518            .read_with(cx, |root, _| root.view().clone())
519            .downcast::<Harness>()
520            .unwrap();
521        for (disabled, readonly) in [(true, false), (false, true), (false, false)] {
522            view.update(cx, |view, cx| {
523                view.input.update(cx, |input, cx| {
524                    input.set_disabled(disabled, cx);
525                    input.set_readonly(readonly, cx);
526                });
527                cx.notify();
528            });
529            cx.update(|window, cx| {
530                window.activate_window();
531                view.read(cx).outside.clone().focus(window, cx);
532                window.draw(cx).clear(cx);
533            });
534            cx.simulate_click(point(px(20.), px(16.)), Modifiers::default());
535            cx.update(|window, cx| {
536                window.draw(cx).clear(cx);
537                let view = view.read(cx);
538                if disabled {
539                    assert!(
540                        view.outside.is_focused(window),
541                        "a disabled field label must not focus its parent"
542                    );
543                } else {
544                    assert!(
545                        view.input
546                            .read(cx)
547                            .presentation()
548                            .focus_handle()
549                            .is_focused(window)
550                    );
551                }
552                #[cfg(feature = "test-support")]
553                {
554                    let label = crate::test_support::find(
555                        window,
556                        &[],
557                        &(ElementId::from("field"), "label").into(),
558                    )
559                    .unwrap();
560                    assert_eq!(label.disabled(), disabled.then_some(true));
561                    assert_eq!(label.focused(), None);
562                }
563            });
564        }
565    }
566
567    #[gpui::test]
568    fn control_fields_describe_choice_controls_and_forward_label_clicks(cx: &mut TestAppContext) {
569        use crate::{Checkbox, Root, SelectItem, SelectState, Switch};
570        use std::cell::Cell;
571
572        cx.update(crate::init);
573        let window = cx.add_empty_window();
574        window.update(|window, cx| {
575            let metadata = FieldMetadata {
576                label: Some("Share recordings".into()),
577                description: Some("Pick one. Viewers can comment.".into()),
578                required: true,
579                invalid: true,
580            };
581            let select = cx.new(|cx| SelectState::new([SelectItem::new("team", "Team")], cx));
582            let radio = cx
583                .new(|cx| crate::RadioGroupState::new([crate::RadioItem::new("team", "Team")], cx));
584            fn check(element: impl IntoElement, role: Role) {
585                let element = element.into_element();
586                let mut node = accesskit::Node::new(role);
587                element.write_a11y_info(&mut node);
588                assert_eq!(node.label(), Some("Share recordings"), "{role:?}");
589                assert_eq!(node.description(), Some("Pick one. Viewers can comment."));
590                assert!(node.is_required());
591                assert_eq!(node.invalid(), Some(accesskit::Invalid::True));
592            }
593            check(
594                Checkbox::new("share")
595                    .track_focus(&cx.focus_handle())
596                    .accessibility_label("Ignored")
597                    .field(metadata.clone())
598                    .render(window, cx),
599                Role::CheckBox,
600            );
601            check(
602                Switch::new("share-switch")
603                    .track_focus(&cx.focus_handle())
604                    .field(metadata.clone())
605                    .render(window, cx),
606                Role::Switch,
607            );
608            check(
609                crate::RadioGroup::new("share-radio", &radio)
610                    .field(metadata.clone())
611                    .render(window, cx),
612                Role::RadioGroup,
613            );
614            check(
615                crate::Select::new("share-select", &select)
616                    .field(metadata.clone())
617                    .render(window, cx),
618                Role::ComboBox,
619            );
620        });
621
622        struct Form {
623            focus: FocusHandle,
624            checked: Rc<Cell<bool>>,
625            disabled: bool,
626        }
627        impl Render for Form {
628            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
629                let checked = self.checked.clone();
630                let toggle = self.checked.clone();
631                let focus = self.focus.clone();
632                ControlField::new("notify-field", &self.focus, "Email me")
633                    .description("Sends one summary a day.")
634                    .disabled(self.disabled)
635                    .control_first(true)
636                    .on_label_activate(move |_, _| toggle.set(!toggle.get()))
637                    .control(move |metadata| {
638                        Checkbox::new("notify")
639                            .track_focus(&focus)
640                            .checked(checked.get())
641                            .field(metadata)
642                            .w(px(16.))
643                            .h(px(16.))
644                    })
645                    .flex()
646                    .gap(px(8.))
647            }
648        }
649        let (root, cx) = cx.add_window_view(|window, cx| {
650            let form = cx.new(|cx| Form {
651                focus: cx.focus_handle(),
652                checked: Rc::default(),
653                disabled: false,
654            });
655            Root::new(form, window, cx)
656        });
657        let form = root
658            .read_with(cx, |root, _| root.view().clone())
659            .downcast::<Form>()
660            .unwrap();
661        cx.update(|window, cx| {
662            window.activate_window();
663            window.draw(cx).clear(cx);
664        });
665        let label = cx.update(|window, _| {
666            let label = crate::test_support::find(
667                window,
668                &[],
669                &(ElementId::from("notify-field"), "label").into(),
670            )
671            .unwrap();
672            let control = crate::test_support::find(window, &[], &"notify".into()).unwrap();
673            assert!(
674                control.bounds().right() <= label.bounds().left(),
675                "control first"
676            );
677            label.bounds().center()
678        });
679        cx.simulate_click(label, Modifiers::default());
680        cx.update(|window, cx| {
681            let form = form.read(cx);
682            assert!(
683                form.focus.is_focused(window),
684                "the label focuses the control"
685            );
686            assert!(form.checked.get(), "and activates it");
687        });
688        form.update(cx, |form, cx| {
689            form.disabled = true;
690            cx.notify();
691        });
692        cx.update(|window, cx| {
693            window.draw(cx).clear(cx);
694            window.blur(cx);
695        });
696        cx.simulate_click(label, Modifiers::default());
697        cx.update(|window, cx| {
698            let form = form.read(cx);
699            assert!(!form.focus.is_focused(window));
700            assert!(form.checked.get(), "a disabled field ignores label clicks");
701        });
702    }
703}