Skip to main content

gpui_component/form/
field.rs

1use gpui_base::LogicalStyledExt as _;
2use std::rc::Rc;
3
4use gpui::{
5    AlignItems, AnyElement, AnyView, App, Axis, Div, ElementId, InteractiveElement as _,
6    IntoElement, ParentElement, Pixels, Rems, RenderOnce, SharedString, StyleRefinement, Styled,
7    Window, div, prelude::FluentBuilder as _, px,
8};
9
10use crate::{ActiveTheme as _, AxisExt, Size, StyledExt, h_flex, v_flex};
11
12#[derive(Clone, Copy)]
13pub(super) struct FieldProps {
14    pub(super) size: Size,
15    pub(super) layout: Axis,
16    pub(super) columns: usize,
17
18    pub(super) label_width: Option<Pixels>,
19    pub(super) label_text_size: Option<Rems>,
20}
21
22impl Default for FieldProps {
23    fn default() -> Self {
24        Self {
25            layout: Axis::Vertical,
26            size: Size::default(),
27            columns: 1,
28            label_width: Some(px(140.)),
29            label_text_size: None,
30        }
31    }
32}
33
34pub enum FieldBuilder {
35    String(SharedString),
36    Element(Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>),
37    View(AnyView),
38}
39
40impl Default for FieldBuilder {
41    fn default() -> Self {
42        Self::String(SharedString::default())
43    }
44}
45
46impl From<AnyView> for FieldBuilder {
47    fn from(view: AnyView) -> Self {
48        Self::View(view)
49    }
50}
51
52impl RenderOnce for FieldBuilder {
53    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
54        match self {
55            FieldBuilder::String(value) => value.into_any_element(),
56            FieldBuilder::Element(builder) => builder(window, cx),
57            FieldBuilder::View(view) => view.into_any_element(),
58        }
59    }
60}
61
62impl From<&'static str> for FieldBuilder {
63    fn from(value: &'static str) -> Self {
64        Self::String(value.into())
65    }
66}
67
68impl From<String> for FieldBuilder {
69    fn from(value: String) -> Self {
70        Self::String(value.into())
71    }
72}
73
74impl From<SharedString> for FieldBuilder {
75    fn from(value: SharedString) -> Self {
76        Self::String(value)
77    }
78}
79
80/// Form field element.
81#[derive(IntoElement)]
82pub struct Field {
83    id: ElementId,
84    props: FieldProps,
85    style: StyleRefinement,
86    label: Option<FieldBuilder>,
87    label_indent: bool,
88    description: Option<FieldBuilder>,
89    /// Used to render the actual form field, e.g.: Input, Switch...
90    children: Vec<AnyElement>,
91    visible: bool,
92    required: bool,
93    /// Alignment of the form field.
94    align_items: Option<AlignItems>,
95    col_span: u16,
96    col_start: Option<i16>,
97    col_end: Option<i16>,
98}
99
100impl Field {
101    pub fn new() -> Self {
102        Self {
103            id: 0.into(),
104            props: FieldProps::default(),
105            style: StyleRefinement::default(),
106            label: None,
107            description: None,
108            children: Vec::new(),
109            visible: true,
110            required: false,
111            label_indent: true,
112            align_items: None,
113            col_span: 1,
114            col_start: None,
115            col_end: None,
116        }
117    }
118
119    /// Sets the label for the form field.
120    pub fn label(mut self, label: impl Into<FieldBuilder>) -> Self {
121        self.label = Some(label.into());
122        self
123    }
124
125    /// Sets indent with the label width (in Horizontal layout), default is `true`.
126    ///
127    /// Sometimes you want to align the input form left (Default is align after the label width in Horizontal layout).
128    ///
129    /// This is only work when the `label` is not set.
130    pub fn label_indent(mut self, indent: bool) -> Self {
131        self.label_indent = indent;
132        self
133    }
134
135    /// Sets the label for the form field using a function.
136    pub fn label_fn<F, E>(mut self, label: F) -> Self
137    where
138        E: IntoElement,
139        F: Fn(&mut Window, &mut App) -> E + 'static,
140    {
141        self.label = Some(FieldBuilder::Element(Rc::new(move |window, cx| {
142            label(window, cx).into_any_element()
143        })));
144        self
145    }
146
147    /// Sets the description for the form field.
148    pub fn description(mut self, description: impl Into<FieldBuilder>) -> Self {
149        self.description = Some(description.into());
150        self
151    }
152
153    /// Sets the description for the form field using a function.
154    pub fn description_fn<F, E>(mut self, description: F) -> Self
155    where
156        E: IntoElement,
157        F: Fn(&mut Window, &mut App) -> E + 'static,
158    {
159        self.description = Some(FieldBuilder::Element(Rc::new(move |window, cx| {
160            description(window, cx).into_any_element()
161        })));
162        self
163    }
164
165    /// Set the visibility of the form field, default is `true`.
166    pub fn visible(mut self, visible: bool) -> Self {
167        self.visible = visible;
168        self
169    }
170
171    /// Returns whether the form field is visible.
172    pub(super) fn is_visible(&self) -> bool {
173        self.visible
174    }
175
176    /// Set the required status of the form field, default is `false`.
177    pub fn required(mut self, required: bool) -> Self {
178        self.required = required;
179        self
180    }
181
182    /// Set the properties for the form field.
183    ///
184    /// This is internal API for sync props from From.
185    pub(super) fn props(mut self, ix: usize, props: FieldProps) -> Self {
186        self.id = ix.into();
187        self.props = props;
188        self
189    }
190
191    /// Align the form field items to the start, this is the default.
192    pub fn items_start(mut self) -> Self {
193        self.align_items = Some(AlignItems::Start);
194        self
195    }
196
197    /// Align the form field items to the end.
198    pub fn items_end(mut self) -> Self {
199        self.align_items = Some(AlignItems::End);
200        self
201    }
202
203    /// Align the form field items to the center.
204    pub fn items_center(mut self) -> Self {
205        self.align_items = Some(AlignItems::Center);
206        self
207    }
208
209    /// Sets the column span for the form field.
210    ///
211    /// Default is 1.
212    pub fn col_span(mut self, col_span: u16) -> Self {
213        self.col_span = col_span;
214        self
215    }
216
217    /// Sets the column start of this form field.
218    pub fn col_start(mut self, col_start: i16) -> Self {
219        self.col_start = Some(col_start);
220        self
221    }
222
223    /// Sets the column end of this form field.
224    pub fn col_end(mut self, col_end: i16) -> Self {
225        self.col_end = Some(col_end);
226        self
227    }
228}
229
230impl ParentElement for Field {
231    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
232        self.children.extend(elements);
233    }
234}
235
236impl Styled for Field {
237    fn style(&mut self) -> &mut StyleRefinement {
238        &mut self.style
239    }
240}
241
242impl RenderOnce for Field {
243    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
244        let layout = self.props.layout;
245
246        let label_width = if layout.is_vertical() {
247            None
248        } else {
249            self.props.label_width
250        };
251        let has_label = self.label_indent;
252
253        #[inline]
254        fn wrap_div(layout: Axis, cx: &App) -> Div {
255            if layout.is_vertical() {
256                v_flex()
257            } else {
258                h_flex().flex_row_dir(cx)
259            }
260        }
261
262        #[inline]
263        fn wrap_label(label_width: Option<Pixels>) -> Div {
264            div().when_some(label_width, |this, width| this.w(width).flex_shrink_0())
265        }
266
267        let gap = match self.props.size {
268            Size::Large => px(8.),
269            Size::XSmall | Size::Small => px(4.),
270            _ => px(4.),
271        };
272        let inner_gap = if layout.is_horizontal() {
273            gap
274        } else {
275            gap / 2.
276        };
277
278        v_flex()
279            .flex_1()
280            .gap(gap / 2.)
281            .col_span(self.col_span)
282            .when_some(self.col_start, |this, start| this.col_start(start))
283            .when_some(self.col_end, |this, end| this.col_end(end))
284            .refine_style(&self.style)
285            .when(!self.visible, |this| this.hidden())
286            .child(
287                // This warp for aligning the Label + Input
288                wrap_div(layout, cx)
289                    .id(self.id)
290                    .gap(inner_gap)
291                    .when_some(self.align_items, |this, align| {
292                        this.map(|this| match align {
293                            AlignItems::Start => this.items_start(),
294                            AlignItems::End => this.items_end(),
295                            AlignItems::Center => this.items_center(),
296                            AlignItems::Baseline => this.items_baseline(),
297                            _ => this,
298                        })
299                    })
300                    .when(has_label, |this| {
301                        // Label
302                        this.child(
303                            wrap_label(label_width)
304                                .text_sm()
305                                .when_some(self.props.label_text_size, |this, size| {
306                                    this.text_size(size)
307                                })
308                                .font_medium()
309                                .gap_1()
310                                .items_center()
311                                .when_some(self.label, |this, builder| {
312                                    this.child(
313                                        h_flex()
314                                            .flex_row_dir(cx)
315                                            .gap_1()
316                                            .child(
317                                                div()
318                                                    .overflow_x_hidden()
319                                                    .child(builder.render(window, cx)),
320                                            )
321                                            .when(self.required, |this| {
322                                                this.child(
323                                                    div().text_color(cx.theme().danger).child("*"),
324                                                )
325                                            }),
326                                    )
327                                }),
328                        )
329                    })
330                    .child(div().w_full().flex_1().children(self.children)),
331            )
332            .child(
333                // Other
334                wrap_div(layout, cx)
335                    .gap(inner_gap)
336                    .when(has_label && layout.is_horizontal(), |this| {
337                        this.child(
338                            // Empty for spacing to align with the input
339                            wrap_label(label_width),
340                        )
341                    })
342                    .when_some(self.description, |this, builder| {
343                        this.child(
344                            div()
345                                .text_xs()
346                                .text_color(cx.theme().muted_foreground)
347                                .child(builder.render(window, cx)),
348                        )
349                    }),
350            )
351    }
352}