Skip to main content

gpui_component/form/
form.rs

1use gpui::{
2    AnyElement, App, Axis, IntoElement, ParentElement, Pixels, Rems, RenderOnce, StyleRefinement,
3    Styled, Window, prelude::FluentBuilder as _, px,
4};
5use gpui_base::LogicalStyledExt as _;
6
7use crate::{
8    Sizable, Size, StyledExt,
9    form::{Field, FieldProps},
10    h_flex, v_flex,
11};
12
13/// A form element that contains multiple form fields.
14#[derive(IntoElement)]
15pub struct Form {
16    style: StyleRefinement,
17    fields: Vec<Field>,
18    footer: Option<AnyElement>,
19    props: FieldProps,
20}
21
22impl Default for Form {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl Form {
29    /// Creates a single-column form with labels above their controls.
30    pub fn new() -> Self {
31        Self {
32            style: StyleRefinement::default(),
33            props: FieldProps::default(),
34            fields: Vec::new(),
35            footer: None,
36        }
37    }
38
39    /// Creates a new form with labels beside their controls.
40    pub fn horizontal() -> Self {
41        Self::new().layout(Axis::Horizontal)
42    }
43
44    /// Creates a new form with labels above their controls.
45    pub fn vertical() -> Self {
46        Self::new().layout(Axis::Vertical)
47    }
48
49    /// Sets label/control orientation within each field, default is `Axis::Vertical`.
50    ///
51    /// This is an alias for [`Self::label_layout`]. Use [`Self::columns`] to arrange fields.
52    pub fn layout(self, layout: Axis) -> Self {
53        self.label_layout(layout)
54    }
55
56    /// Sets label/control orientation within each field.
57    ///
58    /// `Axis::Vertical` (default) places labels above controls; `Axis::Horizontal`
59    /// places labels beside controls. This does not change the field grid columns.
60    pub fn label_layout(mut self, layout: Axis) -> Self {
61        self.props.layout = layout;
62        self
63    }
64
65    /// Set the width of the labels in the form. Default is `px(140.)`.
66    pub fn label_width(mut self, width: Pixels) -> Self {
67        self.props.label_width = Some(width);
68        self
69    }
70
71    /// Set the text size of the labels in the form. Default is `None`.
72    pub fn label_text_size(mut self, size: Rems) -> Self {
73        self.props.label_text_size = Some(size);
74        self
75    }
76
77    /// Add a child to the form.
78    pub fn child(mut self, field: impl Into<Field>) -> Self {
79        self.fields.push(field.into());
80        self
81    }
82
83    /// Add multiple children to the form.
84    pub fn children(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
85        self.fields.extend(fields);
86        self
87    }
88
89    /// Sets content in a full-width footer after all fields, aligned to the trailing edge.
90    ///
91    /// The caller owns action composition, state, and callbacks. Calling this again
92    /// replaces the footer. No footer row is rendered unless content is supplied.
93    pub fn footer(mut self, footer: impl IntoElement) -> Self {
94        self.footer = Some(footer.into_any_element());
95        self
96    }
97
98    /// Set the column count for the field grid, independently of label orientation.
99    ///
100    /// Default is 1.
101    pub fn columns(mut self, columns: usize) -> Self {
102        self.props.columns = columns;
103        self
104    }
105}
106
107impl Styled for Form {
108    fn style(&mut self) -> &mut StyleRefinement {
109        &mut self.style
110    }
111}
112
113impl Sizable for Form {
114    fn with_size(mut self, size: impl Into<Size>) -> Self {
115        self.props.size = size.into();
116        self
117    }
118}
119
120impl RenderOnce for Form {
121    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
122        let props = self.props;
123
124        let gap = match props.size {
125            Size::XSmall | Size::Small => px(6.),
126            Size::Large => px(12.),
127            _ => px(8.),
128        };
129
130        v_flex()
131            .w_full()
132            .gap_x(gap * 3.)
133            .gap_y(gap)
134            .grid()
135            .grid_cols(props.columns as u16)
136            .children(
137                self.fields
138                    .into_iter()
139                    .enumerate()
140                    .filter(|(_, field)| field.is_visible())
141                    .map(|(ix, field)| field.props(ix, props)),
142            )
143            .when_some(self.footer, |this, footer| {
144                this.child(
145                    h_flex()
146                        .flex_row_dir(cx)
147                        .col_span_full()
148                        .min_w_0()
149                        .justify_flex_end()
150                        .child(footer),
151                )
152            })
153            .refine_style(&self.style)
154    }
155}
156
157#[cfg(test)]
158#[path = "tests.rs"]
159mod tests;