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::layout::VStack;
4use gpui::prelude::FluentBuilder as _;
5use gpui::*;
6use std::collections::{HashMap, HashSet};
7
8pub struct FormState {
9    fields: Vec<(SharedString, Entity<InputState>)>,
10    errors: HashMap<SharedString, Vec<String>>,
11    dirty: HashSet<SharedString>,
12    submitted: bool,
13    field_subscriptions: Vec<Subscription>,
14}
15
16impl FormState {
17    pub fn new(cx: &mut App) -> Entity<Self> {
18        cx.new(|_cx| Self {
19            fields: Vec::new(),
20            errors: HashMap::new(),
21            dirty: HashSet::new(),
22            submitted: false,
23            field_subscriptions: Vec::new(),
24        })
25    }
26
27    /// Register an input for validation and Enter-driven form submission.
28    pub fn register_field(&mut self, name: impl Into<SharedString>, state: Entity<InputState>) {
29        let name = name.into();
30        self.fields.push((name, state));
31    }
32
33    fn replace_field_subscriptions(&mut self, subscriptions: Vec<Subscription>) {
34        self.field_subscriptions = subscriptions;
35    }
36
37    pub fn validate_all(&mut self, cx: &mut Context<Self>) -> bool {
38        self.errors.clear();
39        self.submitted = true;
40
41        let fields: Vec<_> = self.fields.clone();
42        let mut all_valid = true;
43
44        for (name, field_entity) in fields {
45            let result = field_entity.update(cx, |state, cx| state.validate(cx));
46
47            if let Err(error) = result {
48                all_valid = false;
49                self.errors
50                    .entry(name)
51                    .or_default()
52                    .push(error.message.to_string());
53            }
54        }
55
56        cx.notify();
57        all_valid
58    }
59
60    pub fn field_errors(&self, name: &str) -> Option<&Vec<String>> {
61        self.errors.get(name)
62    }
63
64    pub fn is_valid(&self) -> bool {
65        self.errors.is_empty()
66    }
67
68    pub fn is_dirty(&self) -> bool {
69        !self.dirty.is_empty()
70    }
71
72    pub fn mark_dirty(&mut self, name: impl Into<SharedString>) {
73        self.dirty.insert(name.into());
74    }
75
76    pub fn reset(&mut self, cx: &mut Context<Self>) {
77        self.errors.clear();
78        self.dirty.clear();
79        self.submitted = false;
80        cx.notify();
81    }
82
83    pub fn is_submitted(&self) -> bool {
84        self.submitted
85    }
86}
87
88#[derive(IntoElement)]
89pub struct Form {
90    state: Entity<FormState>,
91    on_submit: Option<Box<dyn Fn(&mut Window, &mut App)>>,
92    children: Vec<AnyElement>,
93    style: StyleRefinement,
94}
95
96impl Form {
97    pub fn new(state: Entity<FormState>) -> Self {
98        Self {
99            state,
100            on_submit: None,
101            children: Vec::new(),
102            style: StyleRefinement::default(),
103        }
104    }
105
106    /// Register the callback invoked when a registered single-line input
107    /// receives Enter and all registered fields validate successfully.
108    pub fn on_submit(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
109        self.on_submit = Some(Box::new(handler));
110        self
111    }
112
113    pub fn child(mut self, child: impl IntoElement) -> Self {
114        self.children.push(child.into_any_element());
115        self
116    }
117
118    pub fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
119        self.children
120            .extend(children.into_iter().map(|c| c.into_any_element()));
121        self
122    }
123}
124
125impl Styled for Form {
126    fn style(&mut self) -> &mut StyleRefinement {
127        &mut self.style
128    }
129}
130
131impl RenderOnce for Form {
132    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
133        let state = self.state.clone();
134        let on_submit = self.on_submit;
135        let user_style = self.style;
136
137        let handler = on_submit.map(std::rc::Rc::new);
138        let subscriptions = if let Some(handler) = handler {
139            let fields: Vec<_> = state
140                .read(cx)
141                .fields
142                .iter()
143                .map(|(_, field)| field.clone())
144                .collect();
145            fields
146                .into_iter()
147                .map(|field| {
148                    let form = state.clone();
149                    let handler = handler.clone();
150                    window.subscribe(&field, cx, move |_, event: &InputEvent, window, cx| {
151                        if !matches!(event, InputEvent::Enter) {
152                            return;
153                        }
154
155                        let is_valid =
156                            form.update(cx, |form_state, cx| form_state.validate_all(cx));
157                        if is_valid {
158                            (handler)(window, cx);
159                        }
160                    })
161                })
162                .collect()
163        } else {
164            Vec::new()
165        };
166        state.update(cx, |form, _| {
167            form.replace_field_subscriptions(subscriptions)
168        });
169
170        VStack::new()
171            .w_full()
172            .gap(px(16.0))
173            .children(self.children)
174            .map(|this| {
175                let mut vstack = this;
176                vstack.style().refine(&user_style);
177                vstack
178            })
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::capabilities::controls::input::Input;
186    use crate::capabilities::foundation::theme::{install_theme, Theme};
187    use std::cell::Cell;
188    use std::rc::Rc;
189
190    struct FormTestView {
191        form: Entity<FormState>,
192        input: Entity<InputState>,
193        submits: Rc<Cell<usize>>,
194        enters: Rc<Cell<usize>>,
195    }
196
197    impl Render for FormTestView {
198        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
199            let submits = self.submits.clone();
200            let enters = self.enters.clone();
201            Form::new(self.form.clone())
202                .child(Input::new(&self.input).on_enter(move |_, _| {
203                    enters.set(enters.get() + 1);
204                }))
205                .on_submit(move |_, _| submits.set(submits.get() + 1))
206        }
207    }
208
209    #[gpui::test]
210    fn enter_from_single_line_input_reaches_form_submit() {
211        let mut app = TestApp::new();
212        app.update(|cx| {
213            install_theme(cx, Theme::light());
214            crate::capabilities::controls::input::init(cx);
215        });
216
217        let submits = Rc::new(Cell::new(0));
218        let submits_for_view = submits.clone();
219        let enters = Rc::new(Cell::new(0));
220        let enters_for_view = enters.clone();
221        let input = app.update(|cx| cx.new(InputState::new));
222        let form = app.update(|cx| {
223            let form = cx.new(|_| FormState {
224                fields: Vec::new(),
225                errors: HashMap::new(),
226                dirty: HashSet::new(),
227                submitted: false,
228                field_subscriptions: Vec::new(),
229            });
230            form.update(cx, |form, _| form.register_field("value", input.clone()));
231            form
232        });
233
234        let mut window = app.open_window(|_, _| FormTestView {
235            form,
236            input: input.clone(),
237            submits: submits_for_view,
238            enters: enters_for_view,
239        });
240        window.draw();
241        window.update(|_, window, cx| input.read(cx).focus_handle(cx).focus(window));
242        window.draw();
243        let handle: AnyWindowHandle = window.handle().into();
244        app.raw_context_mut().simulate_keystrokes(handle, "enter");
245        app.flush();
246
247        assert_eq!(submits.get(), 1);
248        assert_eq!(enters.get(), 1);
249    }
250}