gpui_component/form/
form.rs1use 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#[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 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 pub fn horizontal() -> Self {
41 Self::new().layout(Axis::Horizontal)
42 }
43
44 pub fn vertical() -> Self {
46 Self::new().layout(Axis::Vertical)
47 }
48
49 pub fn layout(self, layout: Axis) -> Self {
53 self.label_layout(layout)
54 }
55
56 pub fn label_layout(mut self, layout: Axis) -> Self {
61 self.props.layout = layout;
62 self
63 }
64
65 pub fn label_width(mut self, width: Pixels) -> Self {
67 self.props.label_width = Some(width);
68 self
69 }
70
71 pub fn label_text_size(mut self, size: Rems) -> Self {
73 self.props.label_text_size = Some(size);
74 self
75 }
76
77 pub fn child(mut self, field: impl Into<Field>) -> Self {
79 self.fields.push(field.into());
80 self
81 }
82
83 pub fn children(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
85 self.fields.extend(fields);
86 self
87 }
88
89 pub fn footer(mut self, footer: impl IntoElement) -> Self {
94 self.footer = Some(footer.into_any_element());
95 self
96 }
97
98 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;