gpui-component 0.2.0

UI components for building fantastic desktop application by using GPUI.
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::rc::{Rc, Weak};

use gpui::{
    div, prelude::FluentBuilder as _, px, AlignItems, AnyElement, AnyView, App, Axis, Div, Element,
    ElementId, FocusHandle, InteractiveElement as _, IntoElement, ParentElement, Pixels, Rems,
    RenderOnce, SharedString, Styled, Window,
};

use crate::{h_flex, v_flex, ActiveTheme as _, AxisExt, Sizable, Size, StyledExt};

/// Create a new form with a vertical layout.
pub fn v_form() -> Form {
    Form::vertical()
}

/// Create a new form with a horizontal layout.
pub fn h_form() -> Form {
    Form::horizontal()
}

/// Create a new form field.
pub fn form_field() -> FormField {
    FormField::new()
}

#[derive(IntoElement)]
pub struct Form {
    fields: Vec<FormField>,
    props: FieldProps,
}

#[derive(Clone, Copy)]
struct FieldProps {
    size: Size,
    label_width: Option<Pixels>,
    label_text_size: Option<Rems>,
    layout: Axis,
    /// Field gap
    gap: Option<Pixels>,
    column: u16,
}

impl Default for FieldProps {
    fn default() -> Self {
        Self {
            label_width: Some(px(140.)),
            label_text_size: None,
            layout: Axis::Vertical,
            size: Size::default(),
            gap: None,
            column: 1,
        }
    }
}

impl Form {
    fn new() -> Self {
        Self {
            props: FieldProps::default(),
            fields: Vec::new(),
        }
    }

    /// Creates a new form with a horizontal layout.
    pub fn horizontal() -> Self {
        Self::new().layout(Axis::Horizontal)
    }

    /// Creates a new form with a vertical layout.
    pub fn vertical() -> Self {
        Self::new().layout(Axis::Vertical)
    }

    /// Set the layout for the form, default is `Axis::Vertical`.
    pub fn layout(mut self, layout: Axis) -> Self {
        self.props.layout = layout;
        self
    }

    /// Set the width of the labels in the form. Default is `px(100.)`.
    pub fn label_width(mut self, width: Pixels) -> Self {
        self.props.label_width = Some(width);
        self
    }

    /// Set the text size of the labels in the form. Default is `None`.
    pub fn label_text_size(mut self, size: Rems) -> Self {
        self.props.label_text_size = Some(size);
        self
    }

    /// Set the gap between the form fields.
    pub fn gap(mut self, gap: Pixels) -> Self {
        self.props.gap = Some(gap);
        self
    }

    /// Add a child to the form.
    pub fn child(mut self, field: impl Into<FormField>) -> Self {
        self.fields.push(field.into());
        self
    }

    /// Add multiple children to the form.
    pub fn children(mut self, fields: impl IntoIterator<Item = FormField>) -> Self {
        self.fields.extend(fields);
        self
    }

    /// Set the column count for the form.
    ///
    /// Default is 1.
    pub fn column(mut self, column: u16) -> Self {
        self.props.column = column;
        self
    }
}

impl Sizable for Form {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.props.size = size.into();
        self
    }
}

pub enum FieldBuilder {
    String(SharedString),
    Element(Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>),
    View(AnyView),
}

impl Default for FieldBuilder {
    fn default() -> Self {
        Self::String(SharedString::default())
    }
}

impl From<AnyView> for FieldBuilder {
    fn from(view: AnyView) -> Self {
        Self::View(view)
    }
}

impl RenderOnce for FieldBuilder {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        match self {
            FieldBuilder::String(value) => value.into_any_element(),
            FieldBuilder::Element(builder) => builder(window, cx),
            FieldBuilder::View(view) => view.into_any(),
        }
    }
}

impl From<&'static str> for FieldBuilder {
    fn from(value: &'static str) -> Self {
        Self::String(value.into())
    }
}

impl From<String> for FieldBuilder {
    fn from(value: String) -> Self {
        Self::String(value.into())
    }
}

impl From<SharedString> for FieldBuilder {
    fn from(value: SharedString) -> Self {
        Self::String(value)
    }
}

#[derive(IntoElement)]
pub struct FormField {
    id: ElementId,
    form: Weak<Form>,
    label: Option<FieldBuilder>,
    no_label_indent: bool,
    focus_handle: Option<FocusHandle>,
    description: Option<FieldBuilder>,
    /// Used to render the actual form field, e.g.: TextInput, Switch...
    child: Div,
    visible: bool,
    required: bool,
    /// Alignment of the form field.
    align_items: Option<AlignItems>,
    props: FieldProps,
    col_span: u16,
    col_start: Option<i16>,
    col_end: Option<i16>,
}

impl FormField {
    pub fn new() -> Self {
        Self {
            id: 0.into(),
            form: Weak::new(),
            label: None,
            description: None,
            child: div(),
            visible: true,
            required: false,
            no_label_indent: false,
            focus_handle: None,
            align_items: None,
            props: FieldProps::default(),
            col_span: 1,
            col_start: None,
            col_end: None,
        }
    }

    /// Sets the label for the form field.
    pub fn label(mut self, label: impl Into<FieldBuilder>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets not indent with the label width (in Horizontal layout).
    ///
    /// Sometimes you want to align the input form left (Default is align after the label width in Horizontal layout).
    ///
    /// This is only work when the `label` is not set.
    pub fn no_label_indent(mut self) -> Self {
        self.no_label_indent = true;
        self
    }

    /// Sets the label for the form field using a function.
    pub fn label_fn<F, E>(mut self, label: F) -> Self
    where
        E: IntoElement,
        F: Fn(&mut Window, &mut App) -> E + 'static,
    {
        self.label = Some(FieldBuilder::Element(Rc::new(move |window, cx| {
            label(window, cx).into_any_element()
        })));
        self
    }

    /// Sets the description for the form field.
    pub fn description(mut self, description: impl Into<FieldBuilder>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets the description for the form field using a function.
    pub fn description_fn<F, E>(mut self, description: F) -> Self
    where
        E: IntoElement,
        F: Fn(&mut Window, &mut App) -> E + 'static,
    {
        self.description = Some(FieldBuilder::Element(Rc::new(move |window, cx| {
            description(window, cx).into_any_element()
        })));
        self
    }

    /// Set the visibility of the form field, default is `true`.
    pub fn visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Set the required status of the form field, default is `false`.
    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// Set the focus handle for the form field.
    ///
    /// If not set, the form field will not be focusable.
    pub fn track_focus(mut self, focus_handle: &FocusHandle) -> Self {
        self.focus_handle = Some(focus_handle.clone());
        self
    }

    pub fn parent(mut self, form: &Rc<Form>) -> Self {
        self.form = Rc::downgrade(form);
        self
    }

    /// Set the properties for the form field.
    ///
    /// This is internal API for sync props from From.
    fn props(mut self, ix: usize, props: FieldProps) -> Self {
        self.id = ix.into();
        self.props = props;
        self
    }

    /// Align the form field items to the start, this is the default.
    pub fn items_start(mut self) -> Self {
        self.align_items = Some(AlignItems::Start);
        self
    }

    /// Align the form field items to the end.
    pub fn items_end(mut self) -> Self {
        self.align_items = Some(AlignItems::End);
        self
    }

    /// Align the form field items to the center.
    pub fn items_center(mut self) -> Self {
        self.align_items = Some(AlignItems::Center);
        self
    }

    /// Sets the column span for the form field.
    ///
    /// Default is 1.
    pub fn col_span(mut self, col_span: u16) -> Self {
        self.col_span = col_span;
        self
    }

    /// Sets the column start of this form field.
    pub fn col_start(mut self, col_start: i16) -> Self {
        self.col_start = Some(col_start);
        self
    }

    /// Sets the column end of this form field.
    pub fn col_end(mut self, col_end: i16) -> Self {
        self.col_end = Some(col_end);
        self
    }
}
impl ParentElement for FormField {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.child.extend(elements);
    }
}

impl RenderOnce for FormField {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let layout = self.props.layout;

        let label_width = if layout.is_vertical() {
            None
        } else {
            self.props.label_width
        };
        let has_label = !self.no_label_indent;

        #[inline]
        fn wrap_div(layout: Axis) -> Div {
            if layout.is_vertical() {
                v_flex()
            } else {
                h_flex()
            }
        }

        #[inline]
        fn wrap_label(label_width: Option<Pixels>) -> Div {
            div().when_some(label_width, |this, width| this.w(width).flex_shrink_0())
        }

        let gap = match self.props.gap {
            Some(v) => v,
            None => match self.props.size {
                Size::Large => px(8.),
                Size::XSmall | Size::Small => px(4.),
                _ => px(4.),
            },
        };
        let inner_gap = if layout.is_horizontal() {
            gap
        } else {
            gap / 2.
        };

        v_flex()
            .flex_1()
            .gap(gap / 2.)
            .col_span(self.col_span)
            .when_some(self.col_start, |this, start| this.col_start(start))
            .when_some(self.col_end, |this, end| this.col_end(end))
            .child(
                // This warp for aligning the Label + Input
                wrap_div(layout)
                    .id(self.id)
                    .gap(inner_gap)
                    .when_some(self.align_items, |this, align| {
                        this.map(|this| match align {
                            AlignItems::Start => this.items_start(),
                            AlignItems::End => this.items_end(),
                            AlignItems::Center => this.items_center(),
                            AlignItems::Baseline => this.items_baseline(),
                            _ => this,
                        })
                    })
                    .when(has_label, |this| {
                        // Label
                        this.child(
                            wrap_label(label_width)
                                .text_sm()
                                .when_some(self.props.label_text_size, |this, size| {
                                    this.text_size(size)
                                })
                                .font_medium()
                                .flex()
                                .flex_row()
                                .gap_1()
                                .items_center()
                                .when_some(self.label, |this, builder| {
                                    this.child(
                                        h_flex()
                                            .gap_1()
                                            .child(
                                                div()
                                                    .overflow_x_hidden()
                                                    .child(builder.render(window, cx)),
                                            )
                                            .when(self.required, |this| {
                                                this.child(
                                                    div().text_color(cx.theme().danger).child("*"),
                                                )
                                            }),
                                    )
                                }),
                        )
                    })
                    .child(
                        div()
                            .w_full()
                            .flex_1()
                            .overflow_x_hidden()
                            .child(self.child),
                    ),
            )
            .child(
                // Other
                wrap_div(layout)
                    .gap(inner_gap)
                    .when(has_label && layout.is_horizontal(), |this| {
                        this.child(
                            // Empty for spacing to align with the input
                            wrap_label(label_width),
                        )
                    })
                    .when_some(self.description, |this, builder| {
                        this.child(
                            div()
                                .text_xs()
                                .text_color(cx.theme().muted_foreground)
                                .child(builder.render(window, cx)),
                        )
                    }),
            )
    }
}
impl RenderOnce for Form {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        let props = self.props;

        let gap = match props.size {
            Size::XSmall | Size::Small => px(6.),
            Size::Large => px(12.),
            _ => px(8.),
        };

        v_flex()
            .w_full()
            .gap_x(gap * 3.)
            .gap_y(gap)
            .grid()
            .grid_cols(props.column)
            .children(
                self.fields
                    .into_iter()
                    .enumerate()
                    .map(|(ix, field)| field.props(ix, props)),
            )
    }
}