Skip to main content

laravel_rust_admin/schema/
form.rs

1//! Fluent builders for resource create/edit forms and action modal forms.
2
3use crate::protocol::{FieldKind, FieldSchemaDto, FormSectionSchemaDto, SelectOptionDto};
4use crate::schema::humanize;
5
6/// Option entry for select and radio fields.
7#[derive(Debug, Clone)]
8pub struct SelectOption {
9    /// The value submitted when the option is chosen.
10    pub value: String,
11    /// The text the user sees.
12    pub label: String,
13    /// A line of detail under the label, which a radio field shows.
14    pub description: Option<String>,
15}
16
17impl SelectOption {
18    /// An option with a value, and the label to show for it.
19    #[must_use]
20    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
21        Self {
22            value: value.into(),
23            label: label.into(),
24            description: None,
25        }
26    }
27
28    /// Adds a line of detail under the option's label.
29    #[must_use]
30    pub fn description(mut self, description: impl Into<String>) -> Self {
31        self.description = Some(description.into());
32        self
33    }
34
35    pub(crate) fn to_dto(&self) -> SelectOptionDto {
36        SelectOptionDto {
37            value: self.value.clone(),
38            label: self.label.clone(),
39            description: self.description.clone(),
40        }
41    }
42}
43
44impl<V: Into<String>, L: Into<String>> From<(V, L)> for SelectOption {
45    fn from((value, label): (V, L)) -> Self {
46        Self::new(value, label)
47    }
48}
49
50impl From<&str> for SelectOption {
51    fn from(value: &str) -> Self {
52        Self::new(value, humanize(value))
53    }
54}
55
56/// Definition of a single form field.
57#[derive(Debug, Clone)]
58pub struct Field {
59    pub(crate) name: String,
60    pub(crate) label: String,
61    pub(crate) kind: FieldKind,
62    pub(crate) required: bool,
63    pub(crate) nullable: bool,
64    pub(crate) disabled: bool,
65    pub(crate) placeholder: Option<String>,
66    pub(crate) helper: Option<String>,
67    pub(crate) prefix: Option<String>,
68    pub(crate) suffix: Option<String>,
69    pub(crate) rows: Option<u8>,
70    pub(crate) min: Option<f64>,
71    pub(crate) max: Option<f64>,
72    pub(crate) max_length: Option<usize>,
73    pub(crate) column_span: u8,
74    pub(crate) default_value: Option<serde_json::Value>,
75    pub(crate) options: Vec<SelectOptionDto>,
76    pub(crate) create_only: bool,
77    pub(crate) edit_only: bool,
78}
79
80impl Field {
81    fn new(name: impl Into<String>, kind: FieldKind) -> Self {
82        let name = name.into();
83        let label = humanize(&name);
84        Self {
85            name,
86            label,
87            kind,
88            required: false,
89            nullable: false,
90            disabled: false,
91            placeholder: None,
92            helper: None,
93            prefix: None,
94            suffix: None,
95            rows: if kind == FieldKind::Textarea { Some(4) } else { None },
96            min: None,
97            max: None,
98            max_length: None,
99            column_span: 1,
100            default_value: None,
101            options: Vec::new(),
102            create_only: false,
103            edit_only: false,
104        }
105    }
106
107    /// A single-line text field.
108    #[must_use]
109    pub fn text(name: impl Into<String>) -> Self {
110        Self::new(name, FieldKind::Text)
111    }
112
113    /// A text field for an email address.
114    #[must_use]
115    pub fn email(name: impl Into<String>) -> Self {
116        Self::new(name, FieldKind::Email)
117    }
118
119    /// A text field for a URL.
120    #[must_use]
121    pub fn url(name: impl Into<String>) -> Self {
122        Self::new(name, FieldKind::Url)
123    }
124
125    /// A password field, with a button to reveal what was typed. On an existing record, leaving it
126    /// empty keeps the current password: the form doesn't submit the field at all.
127    #[must_use]
128    pub fn password(name: impl Into<String>) -> Self {
129        Self::new(name, FieldKind::Password)
130    }
131
132    /// A multi-line text field, four rows tall unless you set [`rows`](Self::rows).
133    #[must_use]
134    pub fn textarea(name: impl Into<String>) -> Self {
135        Self::new(name, FieldKind::Textarea)
136    }
137
138    /// A whole number.
139    #[must_use]
140    pub fn number(name: impl Into<String>) -> Self {
141        Self::new(name, FieldKind::Number)
142    }
143
144    /// A number that may have a fraction, such as a price. The value is submitted as text, so
145    /// it reaches a `Decimal` column exactly as typed.
146    #[must_use]
147    pub fn decimal(name: impl Into<String>) -> Self {
148        Self::new(name, FieldKind::Decimal)
149    }
150
151    /// A dropdown. Set its choices with [`options`](Self::options).
152    #[must_use]
153    pub fn select(name: impl Into<String>) -> Self {
154        Self::new(name, FieldKind::Select)
155    }
156
157    /// A list of choices that are all visible, each with an optional description. Set its choices
158    /// with [`options`](Self::options).
159    #[must_use]
160    pub fn radio(name: impl Into<String>) -> Self {
161        Self::new(name, FieldKind::Radio)
162    }
163
164    /// A switch for a `bool`, off unless you set a [`default_value`](Self::default_value).
165    #[must_use]
166    pub fn toggle(name: impl Into<String>) -> Self {
167        let mut f = Self::new(name, FieldKind::Toggle);
168        f.default_value = Some(serde_json::Value::Bool(false));
169        f
170    }
171
172    /// A checkbox for a `bool`, unchecked unless you set a [`default_value`](Self::default_value).
173    #[must_use]
174    pub fn checkbox(name: impl Into<String>) -> Self {
175        let mut f = Self::new(name, FieldKind::Checkbox);
176        f.default_value = Some(serde_json::Value::Bool(false));
177        f
178    }
179
180    /// A date picker for a calendar date, such as a `civil::Date` column.
181    #[must_use]
182    pub fn date(name: impl Into<String>) -> Self {
183        Self::new(name, FieldKind::Date)
184    }
185
186    /// A date and time picker for an instant, such as a `Timestamp` column. The browser shows
187    /// and edits the instant in the user's time zone, and submits it in UTC.
188    #[must_use]
189    pub fn datetime(name: impl Into<String>) -> Self {
190        Self::new(name, FieldKind::Datetime)
191    }
192
193    /// A date and time picker for a wall-clock value without a time zone, such as a
194    /// `civil::DateTime` column. The value is submitted exactly as picked.
195    #[must_use]
196    pub fn civil_datetime(name: impl Into<String>) -> Self {
197        Self::new(name, FieldKind::CivilDatetime)
198    }
199
200    /// A list of short text values, entered one at a time. It submits a JSON array of strings.
201    #[must_use]
202    pub fn tags(name: impl Into<String>) -> Self {
203        let mut f = Self::new(name, FieldKind::Tags);
204        f.default_value = Some(serde_json::Value::Array(Vec::new()));
205        f
206    }
207
208    /// A text area for JSON. The form checks that the text parses, and submits the parsed value.
209    #[must_use]
210    pub fn json(name: impl Into<String>) -> Self {
211        let mut f = Self::new(name, FieldKind::Json);
212        f.rows = Some(6);
213        f
214    }
215
216    /// Shows a value that the form never submits.
217    #[must_use]
218    pub fn readonly(name: impl Into<String>) -> Self {
219        let mut f = Self::new(name, FieldKind::Readonly);
220        f.disabled = true;
221        f
222    }
223
224    /// Sets the field's label. By default it's the field's name in words, such as `Published at`
225    /// for `published_at`.
226    #[must_use]
227    pub fn label(mut self, label: impl Into<String>) -> Self {
228        self.label = label.into();
229        self
230    }
231
232    /// Marks the field as required, with an asterisk beside its label. Your input struct's rules
233    /// decide what is actually required.
234    #[must_use]
235    pub fn required(mut self) -> Self {
236        self.required = true;
237        self
238    }
239
240    /// Lets the user leave the field empty. A select then offers an empty choice even when it's
241    /// required. An empty field always submits `null`.
242    #[must_use]
243    pub fn nullable(mut self) -> Self {
244        self.nullable = true;
245        self
246    }
247
248    /// Shows the field without letting the user change it. Its value isn't submitted.
249    #[must_use]
250    pub fn disabled(mut self) -> Self {
251        self.disabled = true;
252        self
253    }
254
255    /// Sets the hint shown while the field is empty.
256    #[must_use]
257    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
258        self.placeholder = Some(placeholder.into());
259        self
260    }
261
262    /// Sets a line of help shown under the field.
263    #[must_use]
264    pub fn helper(mut self, helper: impl Into<String>) -> Self {
265        self.helper = Some(helper.into());
266        self
267    }
268
269    /// Sets text shown before the input, such as `$` or `https://`.
270    #[must_use]
271    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
272        self.prefix = Some(prefix.into());
273        self
274    }
275
276    /// Sets text shown after the input, such as `kg`.
277    #[must_use]
278    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
279        self.suffix = Some(suffix.into());
280        self
281    }
282
283    /// Sets how many rows tall a text area is.
284    #[must_use]
285    pub fn rows(mut self, rows: u8) -> Self {
286        self.rows = Some(rows);
287        self
288    }
289
290    /// The smallest number a `number` or `decimal` field accepts. The form checks it before
291    /// submitting. Your input struct's rules remain the authority.
292    #[must_use]
293    pub fn min(mut self, min: f64) -> Self {
294        self.min = Some(min);
295        self
296    }
297
298    /// The largest number a `number` or `decimal` field accepts. The form checks it before
299    /// submitting. Your input struct's rules remain the authority.
300    #[must_use]
301    pub fn max(mut self, max: f64) -> Self {
302        self.max = Some(max);
303        self
304    }
305
306    /// Sets the most characters the field accepts.
307    #[must_use]
308    pub fn max_length(mut self, max_length: usize) -> Self {
309        self.max_length = Some(max_length);
310        self
311    }
312
313    /// Span across all columns of the enclosing form section.
314    #[must_use]
315    pub fn column_span_full(mut self) -> Self {
316        self.column_span = 2;
317        self
318    }
319
320    /// Set the initial value on the create form.
321    #[must_use]
322    pub fn default_value(mut self, value: impl Into<serde_json::Value>) -> Self {
323        self.default_value = Some(value.into());
324        self
325    }
326
327    /// Set options for `select` or `radio` fields.
328    #[must_use]
329    pub fn options<I, O>(mut self, options: I) -> Self
330    where
331        I: IntoIterator<Item = O>,
332        O: Into<SelectOption>,
333    {
334        self.options = options.into_iter().map(|opt| opt.into().to_dto()).collect();
335        self
336    }
337
338    /// Show this field only when creating a new record (e.g. initial password).
339    #[must_use]
340    pub fn create_only(mut self) -> Self {
341        self.create_only = true;
342        self
343    }
344
345    /// Show this field only when editing an existing record.
346    #[must_use]
347    pub fn edit_only(mut self) -> Self {
348        self.edit_only = true;
349        self
350    }
351
352    pub(crate) fn to_dto(&self) -> FieldSchemaDto {
353        FieldSchemaDto {
354            name: self.name.clone(),
355            label: self.label.clone(),
356            kind: self.kind,
357            required: self.required,
358            nullable: self.nullable,
359            disabled: self.disabled,
360            placeholder: self.placeholder.clone(),
361            helper: self.helper.clone(),
362            prefix: self.prefix.clone(),
363            suffix: self.suffix.clone(),
364            rows: self.rows,
365            min: self.min,
366            max: self.max,
367            max_length: self.max_length,
368            column_span: self.column_span,
369            default_value: self.default_value.clone(),
370            options: self.options.clone(),
371            create_only: self.create_only,
372            edit_only: self.edit_only,
373        }
374    }
375}
376
377/// A titled card section grouping related form fields.
378#[derive(Debug, Clone)]
379pub struct FormSection {
380    pub(crate) title: Option<String>,
381    pub(crate) description: Option<String>,
382    pub(crate) columns: u8,
383    pub(crate) fields: Vec<Field>,
384}
385
386impl FormSection {
387    /// A section with a heading. Its fields sit in two columns unless you set
388    /// [`columns`](Self::columns).
389    #[must_use]
390    pub fn new(title: impl Into<String>) -> Self {
391        Self {
392            title: Some(title.into()),
393            description: None,
394            columns: 2,
395            fields: Vec::new(),
396        }
397    }
398
399    /// Adds a line under the section's heading.
400    #[must_use]
401    pub fn description(mut self, description: impl Into<String>) -> Self {
402        self.description = Some(description.into());
403        self
404    }
405
406    /// Sets how many columns the section's fields sit in on a wide screen, from one to three.
407    #[must_use]
408    pub fn columns(mut self, columns: u8) -> Self {
409        self.columns = columns.clamp(1, 3);
410        self
411    }
412
413    /// Adds a field to the section.
414    #[must_use]
415    pub fn field(mut self, field: Field) -> Self {
416        self.fields.push(field);
417        self
418    }
419
420    /// Adds several fields to the section.
421    #[must_use]
422    pub fn fields(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
423        self.fields.extend(fields);
424        self
425    }
426
427    pub(crate) fn to_dto(&self) -> FormSectionSchemaDto {
428        FormSectionSchemaDto {
429            title: self.title.clone(),
430            description: self.description.clone(),
431            columns: self.columns,
432            fields: self.fields.iter().map(Field::to_dto).collect(),
433        }
434    }
435}
436
437/// Fluent builder for a resource's create/edit form.
438#[derive(Debug, Clone, Default)]
439pub struct FormBuilder {
440    pub(crate) sections: Vec<FormSection>,
441    pub(crate) loose_fields: Vec<Field>,
442}
443
444impl FormBuilder {
445    /// Add a field to the default unsectioned card.
446    #[must_use]
447    pub fn field(mut self, field: Field) -> Self {
448        self.loose_fields.push(field);
449        self
450    }
451
452    /// Add multiple fields to the default card.
453    #[must_use]
454    pub fn fields(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
455        self.loose_fields.extend(fields);
456        self
457    }
458
459    /// Add a titled section card to the form.
460    #[must_use]
461    pub fn section(mut self, section: FormSection) -> Self {
462        self.sections.push(section);
463        self
464    }
465
466    pub(crate) fn to_dto(&self) -> Vec<FormSectionSchemaDto> {
467        let mut out = Vec::new();
468        if !self.loose_fields.is_empty() {
469            out.push(FormSectionSchemaDto {
470                title: None,
471                description: None,
472                columns: 2,
473                fields: self.loose_fields.iter().map(Field::to_dto).collect(),
474            });
475        }
476        out.extend(self.sections.iter().map(FormSection::to_dto));
477        out
478    }
479}