Skip to main content

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,
3//! [`Group`]s that stack sections in one column, each with a
4//! [`column_span`](Section::column_span), and [`Tabs`] that show one [`Tab`] of fields at a
5//! time.
6//!
7//! A WordPress-like post editor puts the content in a main column two thirds wide and the
8//! publishing settings in a sidebar column one third wide, as a Filament form does with
9//! `->columns(3)` and a `Group` of sections with `->columnSpan(2)` beside one with
10//! `->columnSpan(1)`:
11//!
12//! ```
13//! use ignite_core::{FormLayout, Group, Section};
14//!
15//! let layout = FormLayout::new().columns(3).schema([
16//!     Group::make([Section::make("Content").schema(["title", "slug", "body"])]).column_span(2),
17//!     Group::make([
18//!         Section::make("Publish").schema(["status", "published_at"]),
19//!         Section::make("Category").schema(["category"]),
20//!     ])
21//!     .column_span(1),
22//! ]);
23//! assert_eq!(layout.column_count(), Some(3));
24//! ```
25//!
26//! As in Filament, `columns` and `column_span` apply from the `lg` breakpoint; on a smaller
27//! screen every component takes the full width, one under the other. A form without a layout
28//! (the default, [`FormLayout::new`]) renders as before: one card of fields. A field the
29//! layout does not place is shown after the others, in the first column, so a form never
30//! loses a field it saves.
31
32/// The widest the page's content may be, as Filament's `getMaxContentWidth()` and its `Width`
33/// enum. The panel's default is [`ScreenTwoExtraLarge`](Self::ScreenTwoExtraLarge).
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum Width {
37    /// 1536px, Tailwind's `max-w-screen-2xl`: the panel's default.
38    ScreenTwoExtraLarge,
39    /// The whole width of the page beside the sidebar, as Filament's `Width::Full`.
40    Full,
41}
42
43/// How many grid columns a component takes, as Filament's `columnSpan()`.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ColumnSpan {
46    /// This many columns, from the `lg` breakpoint, as `->columnSpan(2)`.
47    Columns(u8),
48    /// Every column, on every screen, as `->columnSpanFull()`.
49    Full,
50}
51
52/// One part of a form layout: a field by name, a [`Section`], a [`Group`] or [`Tabs`].
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum Component {
55    /// The field of this name, on its own.
56    Field(String),
57    /// Fields under a heading.
58    Section(Section),
59    /// Sections and fields stacked in one column.
60    Group(Group),
61    /// Tabs, each with its own fields and sections, one shown at a time.
62    Tabs(Tabs),
63}
64
65impl From<Tabs> for Component {
66    fn from(tabs: Tabs) -> Self {
67        Component::Tabs(tabs)
68    }
69}
70
71impl From<&str> for Component {
72    fn from(name: &str) -> Self {
73        Component::Field(name.to_string())
74    }
75}
76
77impl From<String> for Component {
78    fn from(name: String) -> Self {
79        Component::Field(name)
80    }
81}
82
83impl From<Section> for Component {
84    fn from(section: Section) -> Self {
85        Component::Section(section)
86    }
87}
88
89impl From<Group> for Component {
90    fn from(group: Group) -> Self {
91        Component::Group(group)
92    }
93}
94
95/// Fields under a heading, shown as one card, as Filament's `Section`.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct Section {
98    heading: String,
99    description: Option<String>,
100    fields: Vec<String>,
101    column_span: ColumnSpan,
102}
103
104impl Section {
105    /// A section with the heading `heading`, as `Section::make('Content')`. An empty heading
106    /// shows none. It has no fields until [`schema`](Self::schema).
107    pub fn make(heading: impl Into<String>) -> Self {
108        Section {
109            heading: heading.into(),
110            description: None,
111            fields: Vec::new(),
112            column_span: ColumnSpan::Columns(1),
113        }
114    }
115
116    /// A line under the heading, as `->description()`.
117    pub fn description(mut self, text: impl Into<String>) -> Self {
118        self.description = Some(text.into());
119        self
120    }
121
122    /// The section's fields by name, in display order, as `->schema([...])`. Each call adds
123    /// after the fields already given.
124    pub fn schema<I, S>(mut self, fields: I) -> Self
125    where
126        I: IntoIterator<Item = S>,
127        S: Into<String>,
128    {
129        self.fields.extend(fields.into_iter().map(Into::into));
130        self
131    }
132
133    /// The columns the section takes in the form's grid, as `->columnSpan(2)`.
134    pub fn column_span(mut self, columns: u8) -> Self {
135        self.column_span = ColumnSpan::Columns(columns.clamp(1, 12));
136        self
137    }
138
139    /// Takes every column, as `->columnSpanFull()`.
140    pub fn column_span_full(mut self) -> Self {
141        self.column_span = ColumnSpan::Full;
142        self
143    }
144
145    /// The heading, empty when the section has none.
146    pub fn heading(&self) -> &str {
147        &self.heading
148    }
149
150    /// The line under the heading, if any.
151    pub fn get_description(&self) -> Option<&str> {
152        self.description.as_deref()
153    }
154
155    /// The names of the section's fields, in display order.
156    pub fn fields(&self) -> &[String] {
157        &self.fields
158    }
159
160    /// The columns the section takes.
161    pub fn get_column_span(&self) -> ColumnSpan {
162        self.column_span
163    }
164}
165
166/// Sections and fields stacked one under the other in one column of the form, as Filament's
167/// `Group`: a sidebar is a group of sections.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct Group {
170    components: Vec<Component>,
171    column_span: ColumnSpan,
172}
173
174impl Group {
175    /// A group of `components`, sections or field names, as `Group::make([...])`. A group in
176    /// a group adds its components in its place.
177    pub fn make<I, C>(components: I) -> Self
178    where
179        I: IntoIterator<Item = C>,
180        C: Into<Component>,
181    {
182        Group {
183            components: components.into_iter().map(Into::into).collect(),
184            column_span: ColumnSpan::Columns(1),
185        }
186    }
187
188    /// The columns the group takes in the form's grid, as `->columnSpan(2)`.
189    pub fn column_span(mut self, columns: u8) -> Self {
190        self.column_span = ColumnSpan::Columns(columns.clamp(1, 12));
191        self
192    }
193
194    /// Takes every column, as `->columnSpanFull()`.
195    pub fn column_span_full(mut self) -> Self {
196        self.column_span = ColumnSpan::Full;
197        self
198    }
199
200    /// The group's components, in display order.
201    pub fn components(&self) -> &[Component] {
202        &self.components
203    }
204
205    /// The columns the group takes.
206    pub fn get_column_span(&self) -> ColumnSpan {
207        self.column_span
208    }
209}
210
211/// Tabs, as Filament's `Tabs` schema component: one card whose tab list shows one [`Tab`] of
212/// fields at a time. The first tab is open when the form shows, as in Filament, unless
213/// [`active_tab`](Self::active_tab) names another. Every tab's fields are in the form, so a
214/// save sends them all, whichever tab is open.
215///
216/// ```
217/// use ignite_core::layout::{Tab, Tabs};
218/// use ignite_core::{FormLayout, Section};
219///
220/// let layout = FormLayout::new().schema([Tabs::make("Settings").tabs([
221///     Tab::make("General").schema(["description", "active"]),
222///     Tab::make("Labels").schema([Section::make("Menu").schema(["menu_name"])]),
223/// ])]);
224/// ```
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct Tabs {
227    label: String,
228    tabs: Vec<Tab>,
229    active_tab: usize,
230    column_span: ColumnSpan,
231}
232
233impl Tabs {
234    /// Tabs with the label `label`, which names the tab list for a screen reader, as
235    /// `Tabs::make('Settings')`. They have no tabs until [`tabs`](Self::tabs).
236    pub fn make(label: impl Into<String>) -> Self {
237        Tabs {
238            label: label.into(),
239            tabs: Vec::new(),
240            active_tab: 1,
241            column_span: ColumnSpan::Columns(1),
242        }
243    }
244
245    /// The tabs, in display order, as `->tabs([...])`. Each call adds after the tabs given.
246    pub fn tabs(mut self, tabs: impl IntoIterator<Item = Tab>) -> Self {
247        self.tabs.extend(tabs);
248        self
249    }
250
251    /// The tab open when the form shows, counted from 1, as Filament's `->activeTab(2)`. A
252    /// number past the last tab opens the first.
253    pub fn active_tab(mut self, tab: usize) -> Self {
254        self.active_tab = tab;
255        self
256    }
257
258    /// The columns the tabs take in the form's grid, as `->columnSpan(2)`.
259    pub fn column_span(mut self, columns: u8) -> Self {
260        self.column_span = ColumnSpan::Columns(columns.clamp(1, 12));
261        self
262    }
263
264    /// Takes every column, as `->columnSpanFull()`.
265    pub fn column_span_full(mut self) -> Self {
266        self.column_span = ColumnSpan::Full;
267        self
268    }
269
270    /// The label of the tab list.
271    pub fn label(&self) -> &str {
272        &self.label
273    }
274
275    /// The tabs, in display order.
276    pub fn get_tabs(&self) -> &[Tab] {
277        &self.tabs
278    }
279
280    /// The index (from 0) of the tab open when the form shows.
281    pub fn active_index(&self) -> usize {
282        match self.active_tab {
283            n if n >= 1 && n <= self.tabs.len() => n - 1,
284            _ => 0,
285        }
286    }
287
288    /// The columns the tabs take.
289    pub fn get_column_span(&self) -> ColumnSpan {
290        self.column_span
291    }
292}
293
294/// One tab of [`Tabs`], as Filament's `Tabs\Tab`: a label and its fields and sections. It is
295/// not re-exported at the crate root, where [`Tab`](crate::Tab) is a list page's tab; write
296/// `ignite_core::layout::Tab`.
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct Tab {
299    label: String,
300    components: Vec<Component>,
301}
302
303impl Tab {
304    /// A tab labelled `label`, as `Tab::make('General')`, the label as the app gives it. It
305    /// has no fields until [`schema`](Self::schema).
306    pub fn make(label: impl Into<String>) -> Self {
307        Tab {
308            label: label.into(),
309            components: Vec::new(),
310        }
311    }
312
313    /// The tab's fields and sections, in display order, as `->schema([...])`. A group in a tab
314    /// adds its components in its place. Each call adds after the components given.
315    pub fn schema<I, C>(mut self, components: I) -> Self
316    where
317        I: IntoIterator<Item = C>,
318        C: Into<Component>,
319    {
320        self.components
321            .extend(components.into_iter().map(Into::into));
322        self
323    }
324
325    /// The tab's label.
326    pub fn label(&self) -> &str {
327        &self.label
328    }
329
330    /// The tab's components, in display order.
331    pub fn components(&self) -> &[Component] {
332        &self.components
333    }
334}
335
336/// The layout of a resource's create and edit forms: the grid's columns, the components in
337/// it, and the page's content width. See the [module documentation](self).
338#[derive(Debug, Clone, Default, PartialEq, Eq)]
339pub struct FormLayout {
340    columns: Option<u8>,
341    components: Vec<Component>,
342    max_content_width: Option<Width>,
343}
344
345impl FormLayout {
346    /// No layout: the form renders as one card of fields, as before.
347    pub fn new() -> Self {
348        FormLayout::default()
349    }
350
351    /// The number of columns of the form's grid, from the `lg` breakpoint, as Filament's
352    /// `->columns(3)`. Between 1 and 12. Without it, the grid has one column.
353    pub fn columns(mut self, columns: u8) -> Self {
354        self.columns = Some(columns.clamp(1, 12));
355        self
356    }
357
358    /// The form's components, in display order, as Filament's `->schema([...])`: sections,
359    /// groups and field names. Each call adds after the components already given.
360    pub fn schema<I, C>(mut self, components: I) -> Self
361    where
362        I: IntoIterator<Item = C>,
363        C: Into<Component>,
364    {
365        self.components
366            .extend(components.into_iter().map(Into::into));
367        self
368    }
369
370    /// The widest the form's page may be, as a Filament page's `getMaxContentWidth()`.
371    /// [`Width::Full`] lets a settings form use the whole width beside the sidebar.
372    pub fn max_content_width(mut self, width: Width) -> Self {
373        self.max_content_width = Some(width);
374        self
375    }
376
377    /// Whether the form has no layout, and renders as before.
378    pub fn is_empty(&self) -> bool {
379        self.columns.is_none() && self.components.is_empty() && self.max_content_width.is_none()
380    }
381
382    /// The number of columns, if set.
383    pub fn column_count(&self) -> Option<u8> {
384        self.columns
385    }
386
387    /// The form's components, in display order.
388    pub fn components(&self) -> &[Component] {
389        &self.components
390    }
391
392    /// The page's content width, if set.
393    pub fn content_width(&self) -> Option<Width> {
394        self.max_content_width
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn a_new_layout_is_empty() {
404        assert!(FormLayout::new().is_empty());
405        assert!(!FormLayout::new().columns(2).is_empty());
406        assert!(!FormLayout::new().max_content_width(Width::Full).is_empty());
407    }
408
409    #[test]
410    fn columns_and_spans_stay_between_1_and_12() {
411        assert_eq!(FormLayout::new().columns(0).column_count(), Some(1));
412        assert_eq!(FormLayout::new().columns(20).column_count(), Some(12));
413        assert_eq!(
414            Section::make("A").column_span(0).get_column_span(),
415            ColumnSpan::Columns(1)
416        );
417        assert_eq!(
418            Group::make(["a"]).column_span_full().get_column_span(),
419            ColumnSpan::Full
420        );
421    }
422
423    #[test]
424    fn the_first_tab_is_active_unless_another_is_named() {
425        let tabs = Tabs::make("Settings").tabs([Tab::make("A"), Tab::make("B")]);
426        assert_eq!(tabs.active_index(), 0);
427        assert_eq!(tabs.clone().active_tab(2).active_index(), 1);
428        assert_eq!(tabs.active_tab(9).active_index(), 0);
429    }
430
431    #[test]
432    fn schema_adds_in_order() {
433        let section = Section::make("Content").schema(["title"]).schema(["body"]);
434        assert_eq!(section.fields(), ["title", "body"]);
435        let layout = FormLayout::new().schema(["a"]).schema([section.clone()]);
436        assert_eq!(
437            layout.components(),
438            [Component::Field("a".into()), Component::Section(section)]
439        );
440    }
441}