ignite_core/layout.rs
1//! The layout of a resource's form, as Filament's layout components: a grid of
2//! [`columns`](FormLayout::columns), [`Section`]s that group fields under a heading, and
3//! [`Group`]s that stack sections in one column, each with a
4//! [`column_span`](Section::column_span).
5//!
6//! A WordPress-like post editor puts the content in a main column two thirds wide and the
7//! publishing settings in a sidebar column one third wide, as a Filament form does with
8//! `->columns(3)` and a `Group` of sections with `->columnSpan(2)` beside one with
9//! `->columnSpan(1)`:
10//!
11//! ```
12//! use ignite_core::{FormLayout, Group, Section};
13//!
14//! let layout = FormLayout::new().columns(3).schema([
15//! Group::make([Section::make("Content").schema(["title", "slug", "body"])]).column_span(2),
16//! Group::make([
17//! Section::make("Publish").schema(["status", "published_at"]),
18//! Section::make("Category").schema(["category"]),
19//! ])
20//! .column_span(1),
21//! ]);
22//! assert_eq!(layout.column_count(), Some(3));
23//! ```
24//!
25//! As in Filament, `columns` and `column_span` apply from the `lg` breakpoint; on a smaller
26//! screen every component takes the full width, one under the other. A form without a layout
27//! (the default, [`FormLayout::new`]) renders as before: one card of fields. A field the
28//! layout does not place is shown after the others, in the first column, so a form never
29//! loses a field it saves.
30
31/// The widest the page's content may be, as Filament's `getMaxContentWidth()` and its `Width`
32/// enum. The panel's default is [`ScreenTwoExtraLarge`](Self::ScreenTwoExtraLarge).
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum Width {
36 /// 1536px, Tailwind's `max-w-screen-2xl`: the panel's default.
37 ScreenTwoExtraLarge,
38 /// The whole width of the page beside the sidebar, as Filament's `Width::Full`.
39 Full,
40}
41
42/// How many grid columns a component takes, as Filament's `columnSpan()`.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ColumnSpan {
45 /// This many columns, from the `lg` breakpoint, as `->columnSpan(2)`.
46 Columns(u8),
47 /// Every column, on every screen, as `->columnSpanFull()`.
48 Full,
49}
50
51/// One part of a form layout: a field by name, a [`Section`] or a [`Group`].
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Component {
54 /// The field of this name, on its own.
55 Field(String),
56 /// Fields under a heading.
57 Section(Section),
58 /// Sections and fields stacked in one column.
59 Group(Group),
60}
61
62impl From<&str> for Component {
63 fn from(name: &str) -> Self {
64 Component::Field(name.to_string())
65 }
66}
67
68impl From<String> for Component {
69 fn from(name: String) -> Self {
70 Component::Field(name)
71 }
72}
73
74impl From<Section> for Component {
75 fn from(section: Section) -> Self {
76 Component::Section(section)
77 }
78}
79
80impl From<Group> for Component {
81 fn from(group: Group) -> Self {
82 Component::Group(group)
83 }
84}
85
86/// Fields under a heading, shown as one card, as Filament's `Section`.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Section {
89 heading: String,
90 description: Option<String>,
91 fields: Vec<String>,
92 column_span: ColumnSpan,
93}
94
95impl Section {
96 /// A section with the heading `heading`, as `Section::make('Content')`. An empty heading
97 /// shows none. It has no fields until [`schema`](Self::schema).
98 pub fn make(heading: impl Into<String>) -> Self {
99 Section {
100 heading: heading.into(),
101 description: None,
102 fields: Vec::new(),
103 column_span: ColumnSpan::Columns(1),
104 }
105 }
106
107 /// A line under the heading, as `->description()`.
108 pub fn description(mut self, text: impl Into<String>) -> Self {
109 self.description = Some(text.into());
110 self
111 }
112
113 /// The section's fields by name, in display order, as `->schema([...])`. Each call adds
114 /// after the fields already given.
115 pub fn schema<I, S>(mut self, fields: I) -> Self
116 where
117 I: IntoIterator<Item = S>,
118 S: Into<String>,
119 {
120 self.fields.extend(fields.into_iter().map(Into::into));
121 self
122 }
123
124 /// The columns the section takes in the form's grid, as `->columnSpan(2)`.
125 pub fn column_span(mut self, columns: u8) -> Self {
126 self.column_span = ColumnSpan::Columns(columns.clamp(1, 12));
127 self
128 }
129
130 /// Takes every column, as `->columnSpanFull()`.
131 pub fn column_span_full(mut self) -> Self {
132 self.column_span = ColumnSpan::Full;
133 self
134 }
135
136 /// The heading, empty when the section has none.
137 pub fn heading(&self) -> &str {
138 &self.heading
139 }
140
141 /// The line under the heading, if any.
142 pub fn get_description(&self) -> Option<&str> {
143 self.description.as_deref()
144 }
145
146 /// The names of the section's fields, in display order.
147 pub fn fields(&self) -> &[String] {
148 &self.fields
149 }
150
151 /// The columns the section takes.
152 pub fn get_column_span(&self) -> ColumnSpan {
153 self.column_span
154 }
155}
156
157/// Sections and fields stacked one under the other in one column of the form, as Filament's
158/// `Group`: a sidebar is a group of sections.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct Group {
161 components: Vec<Component>,
162 column_span: ColumnSpan,
163}
164
165impl Group {
166 /// A group of `components`, sections or field names, as `Group::make([...])`. A group in
167 /// a group adds its components in its place.
168 pub fn make<I, C>(components: I) -> Self
169 where
170 I: IntoIterator<Item = C>,
171 C: Into<Component>,
172 {
173 Group {
174 components: components.into_iter().map(Into::into).collect(),
175 column_span: ColumnSpan::Columns(1),
176 }
177 }
178
179 /// The columns the group takes in the form's grid, as `->columnSpan(2)`.
180 pub fn column_span(mut self, columns: u8) -> Self {
181 self.column_span = ColumnSpan::Columns(columns.clamp(1, 12));
182 self
183 }
184
185 /// Takes every column, as `->columnSpanFull()`.
186 pub fn column_span_full(mut self) -> Self {
187 self.column_span = ColumnSpan::Full;
188 self
189 }
190
191 /// The group's components, in display order.
192 pub fn components(&self) -> &[Component] {
193 &self.components
194 }
195
196 /// The columns the group takes.
197 pub fn get_column_span(&self) -> ColumnSpan {
198 self.column_span
199 }
200}
201
202/// The layout of a resource's create and edit forms: the grid's columns, the components in
203/// it, and the page's content width. See the [module documentation](self).
204#[derive(Debug, Clone, Default, PartialEq, Eq)]
205pub struct FormLayout {
206 columns: Option<u8>,
207 components: Vec<Component>,
208 max_content_width: Option<Width>,
209}
210
211impl FormLayout {
212 /// No layout: the form renders as one card of fields, as before.
213 pub fn new() -> Self {
214 FormLayout::default()
215 }
216
217 /// The number of columns of the form's grid, from the `lg` breakpoint, as Filament's
218 /// `->columns(3)`. Between 1 and 12. Without it, the grid has one column.
219 pub fn columns(mut self, columns: u8) -> Self {
220 self.columns = Some(columns.clamp(1, 12));
221 self
222 }
223
224 /// The form's components, in display order, as Filament's `->schema([...])`: sections,
225 /// groups and field names. Each call adds after the components already given.
226 pub fn schema<I, C>(mut self, components: I) -> Self
227 where
228 I: IntoIterator<Item = C>,
229 C: Into<Component>,
230 {
231 self.components
232 .extend(components.into_iter().map(Into::into));
233 self
234 }
235
236 /// The widest the form's page may be, as a Filament page's `getMaxContentWidth()`.
237 /// [`Width::Full`] lets a settings form use the whole width beside the sidebar.
238 pub fn max_content_width(mut self, width: Width) -> Self {
239 self.max_content_width = Some(width);
240 self
241 }
242
243 /// Whether the form has no layout, and renders as before.
244 pub fn is_empty(&self) -> bool {
245 self.columns.is_none() && self.components.is_empty() && self.max_content_width.is_none()
246 }
247
248 /// The number of columns, if set.
249 pub fn column_count(&self) -> Option<u8> {
250 self.columns
251 }
252
253 /// The form's components, in display order.
254 pub fn components(&self) -> &[Component] {
255 &self.components
256 }
257
258 /// The page's content width, if set.
259 pub fn content_width(&self) -> Option<Width> {
260 self.max_content_width
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn a_new_layout_is_empty() {
270 assert!(FormLayout::new().is_empty());
271 assert!(!FormLayout::new().columns(2).is_empty());
272 assert!(!FormLayout::new().max_content_width(Width::Full).is_empty());
273 }
274
275 #[test]
276 fn columns_and_spans_stay_between_1_and_12() {
277 assert_eq!(FormLayout::new().columns(0).column_count(), Some(1));
278 assert_eq!(FormLayout::new().columns(20).column_count(), Some(12));
279 assert_eq!(
280 Section::make("A").column_span(0).get_column_span(),
281 ColumnSpan::Columns(1)
282 );
283 assert_eq!(
284 Group::make(["a"]).column_span_full().get_column_span(),
285 ColumnSpan::Full
286 );
287 }
288
289 #[test]
290 fn schema_adds_in_order() {
291 let section = Section::make("Content").schema(["title"]).schema(["body"]);
292 assert_eq!(section.fields(), ["title", "body"]);
293 let layout = FormLayout::new().schema(["a"]).schema([section.clone()]);
294 assert_eq!(
295 layout.components(),
296 [Component::Field("a".into()), Component::Section(section)]
297 );
298 }
299}