fc_ui/capabilities/controls/
form.rs1use 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#[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 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 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 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 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, textarea::Textarea};
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 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
353 #[gpui::test]
354 fn reset_clears_form_and_field_validation_state() {
355 let mut app = TestApp::new();
356 app.update(|cx| install_theme(cx, Theme::light()));
357
358 let input = app.update(|cx| cx.new(|cx| InputState::new(cx).required(true)));
359 let textarea = app.update(|cx| cx.new(|cx| TextareaState::new(cx).required(true)));
360 let form = app.update(|cx| {
361 let form = FormState::new(cx);
362 form.update(cx, |form, _| {
363 form.register_field("name", input.clone());
364 form.register_field("bio", textarea.clone());
365 form.mark_dirty("name");
366 });
367 form
368 });
369
370 app.update(|cx| {
371 let valid = form.update(cx, |form, cx| form.validate_all(cx));
372 assert!(!valid);
373 assert!(input.read(cx).validation_error.is_some());
374 assert!(textarea.read(cx).validation_error.is_some());
375 assert!(form.read(cx).is_submitted());
376 assert!(form.read(cx).is_dirty());
377 });
378
379 app.update(|cx| form.update(cx, |form, cx| form.reset(cx)));
380
381 app.update(|cx| {
382 assert!(form.read(cx).is_valid());
383 assert!(!form.read(cx).is_submitted());
384 assert!(!form.read(cx).is_dirty());
385 assert!(input.read(cx).validation_error.is_none());
386 assert!(input.read(cx).success_message.is_none());
387 assert!(textarea.read(cx).validation_error.is_none());
388 assert!(textarea.read(cx).success_message.is_none());
389 });
390 }
391
392 struct TextareaFormTestView {
393 form: Entity<FormState>,
394 textarea: Entity<TextareaState>,
395 submits: Rc<Cell<usize>>,
396 enters: Rc<Cell<usize>>,
397 }
398
399 impl Render for TextareaFormTestView {
400 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
401 let submits = self.submits.clone();
402 let enters = self.enters.clone();
403 Form::new(self.form.clone())
404 .child(Textarea::new(&self.textarea).on_enter(move |_, _| {
405 enters.set(enters.get() + 1);
406 }))
407 .on_submit(move |_, _| submits.set(submits.get() + 1))
408 }
409 }
410
411 #[gpui::test]
412 fn enter_in_textarea_inserts_newline_without_submitting_form() {
413 let mut app = TestApp::new();
414 app.update(|cx| {
415 install_theme(cx, Theme::light());
416 crate::capabilities::controls::textarea::init(cx);
417 });
418
419 let textarea = app.update(|cx| cx.new(TextareaState::new));
420 let form = app.update(|cx| {
421 let form = FormState::new(cx);
422 form.update(cx, |form, _| form.register_field("bio", textarea.clone()));
423 form
424 });
425 let submits = Rc::new(Cell::new(0));
426 let enters = Rc::new(Cell::new(0));
427 let mut window = app.open_window(|_, _| TextareaFormTestView {
428 form,
429 textarea: textarea.clone(),
430 submits: submits.clone(),
431 enters: enters.clone(),
432 });
433
434 window.draw();
435 window.update(|_, window, cx| textarea.read(cx).focus_handle(cx).focus(window));
436 window.draw();
437 let handle: AnyWindowHandle = window.handle().into();
438 app.raw_context_mut().simulate_keystrokes(handle, "enter");
439 app.flush();
440
441 app.update(|cx| assert_eq!(textarea.read(cx).content(), "\n"));
442 assert_eq!(enters.get(), 1);
443 assert_eq!(submits.get(), 0);
444 }
445}