fc-ui 0.9.7

A comprehensive, professional UI component library for GPUI inspired by shadcn/ui. 85+ polished components for building beautiful desktop applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::capabilities::controls::input::InputEvent;
use crate::capabilities::controls::input_state::InputState;
use crate::capabilities::controls::textarea_state::TextareaState;
use crate::capabilities::controls::validation::ValidationError;
use crate::capabilities::layout::VStack;
use gpui::prelude::FluentBuilder as _;
use gpui::*;
use std::collections::{HashMap, HashSet};

/// A field registered with a [`Form`] for validation orchestration.
///
/// Single-line (`InputState`) and multi-line (`TextareaState`) inputs share
/// the same validation machinery, so the form validates either kind without
/// knowing which one it holds.
#[derive(Clone)]
pub enum FormField {
    Input(Entity<InputState>),
    Textarea(Entity<TextareaState>),
}

impl From<Entity<InputState>> for FormField {
    fn from(state: Entity<InputState>) -> Self {
        Self::Input(state)
    }
}

impl From<Entity<TextareaState>> for FormField {
    fn from(state: Entity<TextareaState>) -> Self {
        Self::Textarea(state)
    }
}

impl FormField {
    /// Validate the underlying field state, recording its error/success
    /// message on the state itself.
    pub fn validate(&self, cx: &mut App) -> Result<(), ValidationError> {
        match self {
            Self::Input(entity) => entity.update(cx, |state, cx| state.validate(cx)),
            Self::Textarea(entity) => entity.update(cx, |state, cx| state.validate(cx)),
        }
    }

    fn clear_validation(&self, cx: &mut App) {
        match self {
            Self::Input(entity) => entity.update(cx, |state, cx| {
                state.validation_error = None;
                state.success_message = None;
                cx.notify();
            }),
            Self::Textarea(entity) => entity.update(cx, |state, cx| {
                state.validation_error = None;
                state.success_message = None;
                cx.notify();
            }),
        }
    }
}

pub struct FormState {
    fields: Vec<(SharedString, FormField)>,
    errors: HashMap<SharedString, Vec<String>>,
    dirty: HashSet<SharedString>,
    submitted: bool,
    field_subscriptions: Vec<Subscription>,
}

impl FormState {
    pub fn new(cx: &mut App) -> Entity<Self> {
        cx.new(|_cx| Self {
            fields: Vec::new(),
            errors: HashMap::new(),
            dirty: HashSet::new(),
            submitted: false,
            field_subscriptions: Vec::new(),
        })
    }

    /// Register a field for validation and Enter-driven form submission.
    ///
    /// Accepts both `Entity<InputState>` and `Entity<TextareaState>`.
    pub fn register_field(&mut self, name: impl Into<SharedString>, field: impl Into<FormField>) {
        let name = name.into();
        self.fields.push((name, field.into()));
    }

    fn replace_field_subscriptions(&mut self, subscriptions: Vec<Subscription>) {
        self.field_subscriptions = subscriptions;
    }

    pub fn validate_all(&mut self, cx: &mut Context<Self>) -> bool {
        self.errors.clear();
        self.submitted = true;

        let fields: Vec<_> = self.fields.clone();
        let mut all_valid = true;

        for (name, field) in fields {
            let result = field.validate(cx);

            if let Err(error) = result {
                all_valid = false;
                self.errors
                    .entry(name)
                    .or_default()
                    .push(error.message.to_string());
            }
        }

        cx.notify();
        all_valid
    }

    pub fn field_errors(&self, name: &str) -> Option<&Vec<String>> {
        self.errors.get(name)
    }

    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    pub fn is_dirty(&self) -> bool {
        !self.dirty.is_empty()
    }

    pub fn mark_dirty(&mut self, name: impl Into<SharedString>) {
        self.dirty.insert(name.into());
    }

    pub fn reset(&mut self, cx: &mut Context<Self>) {
        let fields = self.fields.clone();
        for (_, field) in fields {
            field.clear_validation(cx);
        }
        self.errors.clear();
        self.dirty.clear();
        self.submitted = false;
        cx.notify();
    }

    pub fn is_submitted(&self) -> bool {
        self.submitted
    }
}

#[derive(IntoElement)]
pub struct Form {
    state: Entity<FormState>,
    on_submit: Option<Box<dyn Fn(&mut Window, &mut App)>>,
    children: Vec<AnyElement>,
    style: StyleRefinement,
}

impl Form {
    pub fn new(state: Entity<FormState>) -> Self {
        Self {
            state,
            on_submit: None,
            children: Vec::new(),
            style: StyleRefinement::default(),
        }
    }

    /// Register the callback invoked when a registered single-line input
    /// receives Enter and all registered fields validate successfully.
    pub fn on_submit(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_submit = Some(Box::new(handler));
        self
    }

    pub fn child(mut self, child: impl IntoElement) -> Self {
        self.children.push(child.into_any_element());
        self
    }

    pub fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
        self.children
            .extend(children.into_iter().map(|c| c.into_any_element()));
        self
    }
}

impl Styled for Form {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for Form {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = self.state.clone();
        let on_submit = self.on_submit;
        let user_style = self.style;

        let handler = on_submit.map(std::rc::Rc::new);
        let subscriptions = if let Some(handler) = handler {
            // Enter-driven submission only applies to single-line inputs; in a
            // textarea Enter inserts a newline.
            let fields: Vec<_> = state
                .read(cx)
                .fields
                .iter()
                .filter_map(|(_, field)| match field {
                    FormField::Input(entity) => Some(entity.clone()),
                    FormField::Textarea(_) => None,
                })
                .collect();
            fields
                .into_iter()
                .map(|field| {
                    let form = state.clone();
                    let handler = handler.clone();
                    window.subscribe(&field, cx, move |_, event: &InputEvent, window, cx| {
                        if !matches!(event, InputEvent::Enter) {
                            return;
                        }

                        let is_valid =
                            form.update(cx, |form_state, cx| form_state.validate_all(cx));
                        if is_valid {
                            (handler)(window, cx);
                        }
                    })
                })
                .collect()
        } else {
            Vec::new()
        };
        state.update(cx, |form, _| {
            form.replace_field_subscriptions(subscriptions)
        });

        VStack::new()
            .w_full()
            .gap(px(16.0))
            .children(self.children)
            .map(|this| {
                let mut vstack = this;
                vstack.style().refine(&user_style);
                vstack
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capabilities::controls::{input::Input, textarea::Textarea};
    use crate::capabilities::foundation::theme::{install_theme, Theme};
    use std::cell::Cell;
    use std::rc::Rc;

    struct FormTestView {
        form: Entity<FormState>,
        input: Entity<InputState>,
        submits: Rc<Cell<usize>>,
        enters: Rc<Cell<usize>>,
    }

    impl Render for FormTestView {
        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
            let submits = self.submits.clone();
            let enters = self.enters.clone();
            Form::new(self.form.clone())
                .child(Input::new(&self.input).on_enter(move |_, _| {
                    enters.set(enters.get() + 1);
                }))
                .on_submit(move |_, _| submits.set(submits.get() + 1))
        }
    }

    #[gpui::test]
    fn enter_from_single_line_input_reaches_form_submit() {
        let mut app = TestApp::new();
        app.update(|cx| {
            install_theme(cx, Theme::light());
            crate::capabilities::controls::input::init(cx);
        });

        let submits = Rc::new(Cell::new(0));
        let submits_for_view = submits.clone();
        let enters = Rc::new(Cell::new(0));
        let enters_for_view = enters.clone();
        let input = app.update(|cx| cx.new(InputState::new));
        let form = app.update(|cx| {
            let form = cx.new(|_| FormState {
                fields: Vec::new(),
                errors: HashMap::new(),
                dirty: HashSet::new(),
                submitted: false,
                field_subscriptions: Vec::new(),
            });
            form.update(cx, |form, _| form.register_field("value", input.clone()));
            form
        });

        let mut window = app.open_window(|_, _| FormTestView {
            form,
            input: input.clone(),
            submits: submits_for_view,
            enters: enters_for_view,
        });
        window.draw();
        window.update(|_, window, cx| input.read(cx).focus_handle(cx).focus(window));
        window.draw();
        let handle: AnyWindowHandle = window.handle().into();
        app.raw_context_mut().simulate_keystrokes(handle, "enter");
        app.flush();

        assert_eq!(submits.get(), 1);
        assert_eq!(enters.get(), 1);
    }
    #[gpui::test]
    fn validate_all_covers_textarea_fields() {
        let mut app = TestApp::new();
        app.update(|cx| install_theme(cx, Theme::light()));

        let input = app.update(|cx| cx.new(InputState::new));
        let textarea = app.update(|cx| {
            cx.new(|cx| {
                crate::capabilities::controls::textarea_state::TextareaState::new(cx)
                    .min_length(3)
                    .value("ab")
            })
        });
        let form = app.update(|cx| {
            let form = FormState::new(cx);
            form.update(cx, |form, _| {
                form.register_field("name", input.clone());
                form.register_field("bio", textarea.clone());
            });
            form
        });

        app.update(|cx| {
            let valid = form.update(cx, |form, cx| form.validate_all(cx));
            assert!(!valid);
            assert_eq!(
                form.read(cx).field_errors("bio").unwrap()[0].as_str(),
                "Must be at least 3 characters"
            );
            // The optional empty input skips constraint checks entirely.
            assert!(form.read(cx).field_errors("name").is_none());
        });

        app.update(|cx| {
            textarea.update(cx, |state, _| state.content = "abcd".into());
            let valid = form.update(cx, |form, cx| form.validate_all(cx));
            assert!(valid);
            assert!(form.read(cx).is_valid());
        });
    }

    #[gpui::test]
    fn reset_clears_form_and_field_validation_state() {
        let mut app = TestApp::new();
        app.update(|cx| install_theme(cx, Theme::light()));

        let input = app.update(|cx| cx.new(|cx| InputState::new(cx).required(true)));
        let textarea = app.update(|cx| cx.new(|cx| TextareaState::new(cx).required(true)));
        let form = app.update(|cx| {
            let form = FormState::new(cx);
            form.update(cx, |form, _| {
                form.register_field("name", input.clone());
                form.register_field("bio", textarea.clone());
                form.mark_dirty("name");
            });
            form
        });

        app.update(|cx| {
            let valid = form.update(cx, |form, cx| form.validate_all(cx));
            assert!(!valid);
            assert!(input.read(cx).validation_error.is_some());
            assert!(textarea.read(cx).validation_error.is_some());
            assert!(form.read(cx).is_submitted());
            assert!(form.read(cx).is_dirty());
        });

        app.update(|cx| form.update(cx, |form, cx| form.reset(cx)));

        app.update(|cx| {
            assert!(form.read(cx).is_valid());
            assert!(!form.read(cx).is_submitted());
            assert!(!form.read(cx).is_dirty());
            assert!(input.read(cx).validation_error.is_none());
            assert!(input.read(cx).success_message.is_none());
            assert!(textarea.read(cx).validation_error.is_none());
            assert!(textarea.read(cx).success_message.is_none());
        });
    }

    struct TextareaFormTestView {
        form: Entity<FormState>,
        textarea: Entity<TextareaState>,
        submits: Rc<Cell<usize>>,
        enters: Rc<Cell<usize>>,
    }

    impl Render for TextareaFormTestView {
        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
            let submits = self.submits.clone();
            let enters = self.enters.clone();
            Form::new(self.form.clone())
                .child(Textarea::new(&self.textarea).on_enter(move |_, _| {
                    enters.set(enters.get() + 1);
                }))
                .on_submit(move |_, _| submits.set(submits.get() + 1))
        }
    }

    #[gpui::test]
    fn enter_in_textarea_inserts_newline_without_submitting_form() {
        let mut app = TestApp::new();
        app.update(|cx| {
            install_theme(cx, Theme::light());
            crate::capabilities::controls::textarea::init(cx);
        });

        let textarea = app.update(|cx| cx.new(TextareaState::new));
        let form = app.update(|cx| {
            let form = FormState::new(cx);
            form.update(cx, |form, _| form.register_field("bio", textarea.clone()));
            form
        });
        let submits = Rc::new(Cell::new(0));
        let enters = Rc::new(Cell::new(0));
        let mut window = app.open_window(|_, _| TextareaFormTestView {
            form,
            textarea: textarea.clone(),
            submits: submits.clone(),
            enters: enters.clone(),
        });

        window.draw();
        window.update(|_, window, cx| textarea.read(cx).focus_handle(cx).focus(window));
        window.draw();
        let handle: AnyWindowHandle = window.handle().into();
        app.raw_context_mut().simulate_keystrokes(handle, "enter");
        app.flush();

        app.update(|cx| assert_eq!(textarea.read(cx).content(), "\n"));
        assert_eq!(enters.get(), 1);
        assert_eq!(submits.get(), 0);
    }
}