Skip to main content

fc_ui/capabilities/controls/
form.rs

1use crate::capabilities::controls::input::InputEvent;
2use crate::capabilities::controls::input_state::InputState;
3use crate::capabilities::controls::textarea_state::TextareaState;
4use crate::capabilities::controls::validation::ValidationError;
5use crate::capabilities::layout::VStack;
6use gpui::prelude::FluentBuilder as _;
7use gpui::*;
8use std::collections::{HashMap, HashSet};
9
10/// A field registered with a [`Form`] for validation orchestration.
11///
12/// Single-line (`InputState`) and multi-line (`TextareaState`) inputs share
13/// the same validation machinery, so the form validates either kind without
14/// knowing which one it holds.
15#[derive(Clone)]
16pub enum FormField {
17    Input(Entity<InputState>),
18    Textarea(Entity<TextareaState>),
19}
20
21impl From<Entity<InputState>> for FormField {
22    fn from(state: Entity<InputState>) -> Self {
23        Self::Input(state)
24    }
25}
26
27impl From<Entity<TextareaState>> for FormField {
28    fn from(state: Entity<TextareaState>) -> Self {
29        Self::Textarea(state)
30    }
31}
32
33impl FormField {
34    /// Validate the underlying field state, recording its error/success
35    /// message on the state itself.
36    pub fn validate(&self, cx: &mut App) -> Result<(), ValidationError> {
37        match self {
38            Self::Input(entity) => entity.update(cx, |state, cx| state.validate(cx)),
39            Self::Textarea(entity) => entity.update(cx, |state, cx| state.validate(cx)),
40        }
41    }
42
43    fn clear_validation(&self, cx: &mut App) {
44        match self {
45            Self::Input(entity) => entity.update(cx, |state, cx| {
46                state.validation_error = None;
47                state.success_message = None;
48                cx.notify();
49            }),
50            Self::Textarea(entity) => entity.update(cx, |state, cx| {
51                state.validation_error = None;
52                state.success_message = None;
53                cx.notify();
54            }),
55        }
56    }
57}
58
59pub struct FormState {
60    fields: Vec<(SharedString, FormField)>,
61    errors: HashMap<SharedString, Vec<String>>,
62    dirty: HashSet<SharedString>,
63    submitted: bool,
64    field_subscriptions: Vec<Subscription>,
65}
66
67impl FormState {
68    pub fn new(cx: &mut App) -> Entity<Self> {
69        cx.new(|_cx| Self {
70            fields: Vec::new(),
71            errors: HashMap::new(),
72            dirty: HashSet::new(),
73            submitted: false,
74            field_subscriptions: Vec::new(),
75        })
76    }
77
78    /// Register a field for validation and Enter-driven form submission.
79    ///
80    /// Accepts both `Entity<InputState>` and `Entity<TextareaState>`.
81    pub fn register_field(&mut self, name: impl Into<SharedString>, field: impl Into<FormField>) {
82        let name = name.into();
83        self.fields.push((name, field.into()));
84    }
85
86    fn replace_field_subscriptions(&mut self, subscriptions: Vec<Subscription>) {
87        self.field_subscriptions = subscriptions;
88    }
89
90    pub fn validate_all(&mut self, cx: &mut Context<Self>) -> bool {
91        self.errors.clear();
92        self.submitted = true;
93
94        let fields: Vec<_> = self.fields.clone();
95        let mut all_valid = true;
96
97        for (name, field) in fields {
98            let result = field.validate(cx);
99
100            if let Err(error) = result {
101                all_valid = false;
102                self.errors
103                    .entry(name)
104                    .or_default()
105                    .push(error.message.to_string());
106            }
107        }
108
109        cx.notify();
110        all_valid
111    }
112
113    pub fn field_errors(&self, name: &str) -> Option<&Vec<String>> {
114        self.errors.get(name)
115    }
116
117    pub fn is_valid(&self) -> bool {
118        self.errors.is_empty()
119    }
120
121    pub fn is_dirty(&self) -> bool {
122        !self.dirty.is_empty()
123    }
124
125    pub fn mark_dirty(&mut self, name: impl Into<SharedString>) {
126        self.dirty.insert(name.into());
127    }
128
129    pub fn reset(&mut self, cx: &mut Context<Self>) {
130        let fields = self.fields.clone();
131        for (_, field) in fields {
132            field.clear_validation(cx);
133        }
134        self.errors.clear();
135        self.dirty.clear();
136        self.submitted = false;
137        cx.notify();
138    }
139
140    pub fn is_submitted(&self) -> bool {
141        self.submitted
142    }
143}
144
145#[derive(IntoElement)]
146pub struct Form {
147    state: Entity<FormState>,
148    on_submit: Option<Box<dyn Fn(&mut Window, &mut App)>>,
149    children: Vec<AnyElement>,
150    style: StyleRefinement,
151}
152
153impl Form {
154    pub fn new(state: Entity<FormState>) -> Self {
155        Self {
156            state,
157            on_submit: None,
158            children: Vec::new(),
159            style: StyleRefinement::default(),
160        }
161    }
162
163    /// Register the callback invoked when a registered single-line input
164    /// receives Enter and all registered fields validate successfully.
165    pub fn on_submit(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
166        self.on_submit = Some(Box::new(handler));
167        self
168    }
169
170    pub fn child(mut self, child: impl IntoElement) -> Self {
171        self.children.push(child.into_any_element());
172        self
173    }
174
175    pub fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
176        self.children
177            .extend(children.into_iter().map(|c| c.into_any_element()));
178        self
179    }
180}
181
182impl Styled for Form {
183    fn style(&mut self) -> &mut StyleRefinement {
184        &mut self.style
185    }
186}
187
188impl RenderOnce for Form {
189    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
190        let state = self.state.clone();
191        let on_submit = self.on_submit;
192        let user_style = self.style;
193
194        let handler = on_submit.map(std::rc::Rc::new);
195        let subscriptions = if let Some(handler) = handler {
196            // Enter-driven submission only applies to single-line inputs; in a
197            // textarea Enter inserts a newline.
198            let fields: Vec<_> = state
199                .read(cx)
200                .fields
201                .iter()
202                .filter_map(|(_, field)| match field {
203                    FormField::Input(entity) => Some(entity.clone()),
204                    FormField::Textarea(_) => None,
205                })
206                .collect();
207            fields
208                .into_iter()
209                .map(|field| {
210                    let form = state.clone();
211                    let handler = handler.clone();
212                    window.subscribe(&field, cx, move |_, event: &InputEvent, window, cx| {
213                        if !matches!(event, InputEvent::Enter) {
214                            return;
215                        }
216
217                        let is_valid =
218                            form.update(cx, |form_state, cx| form_state.validate_all(cx));
219                        if is_valid {
220                            (handler)(window, cx);
221                        }
222                    })
223                })
224                .collect()
225        } else {
226            Vec::new()
227        };
228        state.update(cx, |form, _| {
229            form.replace_field_subscriptions(subscriptions)
230        });
231
232        VStack::new()
233            .w_full()
234            .gap(px(16.0))
235            .children(self.children)
236            .map(|this| {
237                let mut vstack = this;
238                vstack.style().refine(&user_style);
239                vstack
240            })
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use crate::capabilities::controls::input::Input;
248    use crate::capabilities::foundation::theme::{install_theme, Theme};
249    use std::cell::Cell;
250    use std::rc::Rc;
251
252    struct FormTestView {
253        form: Entity<FormState>,
254        input: Entity<InputState>,
255        submits: Rc<Cell<usize>>,
256        enters: Rc<Cell<usize>>,
257    }
258
259    impl Render for FormTestView {
260        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
261            let submits = self.submits.clone();
262            let enters = self.enters.clone();
263            Form::new(self.form.clone())
264                .child(Input::new(&self.input).on_enter(move |_, _| {
265                    enters.set(enters.get() + 1);
266                }))
267                .on_submit(move |_, _| submits.set(submits.get() + 1))
268        }
269    }
270
271    #[gpui::test]
272    fn enter_from_single_line_input_reaches_form_submit() {
273        let mut app = TestApp::new();
274        app.update(|cx| {
275            install_theme(cx, Theme::light());
276            crate::capabilities::controls::input::init(cx);
277        });
278
279        let submits = Rc::new(Cell::new(0));
280        let submits_for_view = submits.clone();
281        let enters = Rc::new(Cell::new(0));
282        let enters_for_view = enters.clone();
283        let input = app.update(|cx| cx.new(InputState::new));
284        let form = app.update(|cx| {
285            let form = cx.new(|_| FormState {
286                fields: Vec::new(),
287                errors: HashMap::new(),
288                dirty: HashSet::new(),
289                submitted: false,
290                field_subscriptions: Vec::new(),
291            });
292            form.update(cx, |form, _| form.register_field("value", input.clone()));
293            form
294        });
295
296        let mut window = app.open_window(|_, _| FormTestView {
297            form,
298            input: input.clone(),
299            submits: submits_for_view,
300            enters: enters_for_view,
301        });
302        window.draw();
303        window.update(|_, window, cx| input.read(cx).focus_handle(cx).focus(window));
304        window.draw();
305        let handle: AnyWindowHandle = window.handle().into();
306        app.raw_context_mut().simulate_keystrokes(handle, "enter");
307        app.flush();
308
309        assert_eq!(submits.get(), 1);
310        assert_eq!(enters.get(), 1);
311    }
312    #[gpui::test]
313    fn validate_all_covers_textarea_fields() {
314        let mut app = TestApp::new();
315        app.update(|cx| install_theme(cx, Theme::light()));
316
317        let input = app.update(|cx| cx.new(InputState::new));
318        let textarea = app.update(|cx| {
319            cx.new(|cx| {
320                crate::capabilities::controls::textarea_state::TextareaState::new(cx)
321                    .min_length(3)
322                    .value("ab")
323            })
324        });
325        let form = app.update(|cx| {
326            let form = FormState::new(cx);
327            form.update(cx, |form, _| {
328                form.register_field("name", input.clone());
329                form.register_field("bio", textarea.clone());
330            });
331            form
332        });
333
334        app.update(|cx| {
335            let valid = form.update(cx, |form, cx| form.validate_all(cx));
336            assert!(!valid);
337            assert_eq!(
338                form.read(cx).field_errors("bio").unwrap()[0].as_str(),
339                "Must be at least 3 characters"
340            );
341            // The optional empty input skips constraint checks entirely.
342            assert!(form.read(cx).field_errors("name").is_none());
343        });
344
345        app.update(|cx| {
346            textarea.update(cx, |state, _| state.content = "abcd".into());
347            let valid = form.update(cx, |form, cx| form.validate_all(cx));
348            assert!(valid);
349            assert!(form.read(cx).is_valid());
350        });
351    }
352}