laravel-rust-admin 0.1.0

Admin panel framework for Laravel for Rust: auto-generated CRUD tables, forms, actions, and dashboard widgets from your models.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Fluent builders for resource create/edit forms and action modal forms.

use crate::protocol::{FieldKind, FieldSchemaDto, FormSectionSchemaDto, SelectOptionDto};
use crate::schema::humanize;

/// Option entry for select and radio fields.
#[derive(Debug, Clone)]
pub struct SelectOption {
    /// The value submitted when the option is chosen.
    pub value: String,
    /// The text the user sees.
    pub label: String,
    /// A line of detail under the label, which a radio field shows.
    pub description: Option<String>,
}

impl SelectOption {
    /// An option with a value, and the label to show for it.
    #[must_use]
    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            description: None,
        }
    }

    /// Adds a line of detail under the option's label.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub(crate) fn to_dto(&self) -> SelectOptionDto {
        SelectOptionDto {
            value: self.value.clone(),
            label: self.label.clone(),
            description: self.description.clone(),
        }
    }
}

impl<V: Into<String>, L: Into<String>> From<(V, L)> for SelectOption {
    fn from((value, label): (V, L)) -> Self {
        Self::new(value, label)
    }
}

impl From<&str> for SelectOption {
    fn from(value: &str) -> Self {
        Self::new(value, humanize(value))
    }
}

/// Definition of a single form field.
#[derive(Debug, Clone)]
pub struct Field {
    pub(crate) name: String,
    pub(crate) label: String,
    pub(crate) kind: FieldKind,
    pub(crate) required: bool,
    pub(crate) nullable: bool,
    pub(crate) disabled: bool,
    pub(crate) placeholder: Option<String>,
    pub(crate) helper: Option<String>,
    pub(crate) prefix: Option<String>,
    pub(crate) suffix: Option<String>,
    pub(crate) rows: Option<u8>,
    pub(crate) min: Option<f64>,
    pub(crate) max: Option<f64>,
    pub(crate) max_length: Option<usize>,
    pub(crate) column_span: u8,
    pub(crate) default_value: Option<serde_json::Value>,
    pub(crate) options: Vec<SelectOptionDto>,
    pub(crate) create_only: bool,
    pub(crate) edit_only: bool,
}

impl Field {
    fn new(name: impl Into<String>, kind: FieldKind) -> Self {
        let name = name.into();
        let label = humanize(&name);
        Self {
            name,
            label,
            kind,
            required: false,
            nullable: false,
            disabled: false,
            placeholder: None,
            helper: None,
            prefix: None,
            suffix: None,
            rows: if kind == FieldKind::Textarea { Some(4) } else { None },
            min: None,
            max: None,
            max_length: None,
            column_span: 1,
            default_value: None,
            options: Vec::new(),
            create_only: false,
            edit_only: false,
        }
    }

    /// A single-line text field.
    #[must_use]
    pub fn text(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Text)
    }

    /// A text field for an email address.
    #[must_use]
    pub fn email(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Email)
    }

    /// A text field for a URL.
    #[must_use]
    pub fn url(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Url)
    }

    /// A password field, with a button to reveal what was typed. On an existing record, leaving it
    /// empty keeps the current password: the form doesn't submit the field at all.
    #[must_use]
    pub fn password(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Password)
    }

    /// A multi-line text field, four rows tall unless you set [`rows`](Self::rows).
    #[must_use]
    pub fn textarea(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Textarea)
    }

    /// A whole number.
    #[must_use]
    pub fn number(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Number)
    }

    /// A number that may have a fraction, such as a price. The value is submitted as text, so
    /// it reaches a `Decimal` column exactly as typed.
    #[must_use]
    pub fn decimal(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Decimal)
    }

    /// A dropdown. Set its choices with [`options`](Self::options).
    #[must_use]
    pub fn select(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Select)
    }

    /// A list of choices that are all visible, each with an optional description. Set its choices
    /// with [`options`](Self::options).
    #[must_use]
    pub fn radio(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Radio)
    }

    /// A switch for a `bool`, off unless you set a [`default_value`](Self::default_value).
    #[must_use]
    pub fn toggle(name: impl Into<String>) -> Self {
        let mut f = Self::new(name, FieldKind::Toggle);
        f.default_value = Some(serde_json::Value::Bool(false));
        f
    }

    /// A checkbox for a `bool`, unchecked unless you set a [`default_value`](Self::default_value).
    #[must_use]
    pub fn checkbox(name: impl Into<String>) -> Self {
        let mut f = Self::new(name, FieldKind::Checkbox);
        f.default_value = Some(serde_json::Value::Bool(false));
        f
    }

    /// A date picker for a calendar date, such as a `civil::Date` column.
    #[must_use]
    pub fn date(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Date)
    }

    /// A date and time picker for an instant, such as a `Timestamp` column. The browser shows
    /// and edits the instant in the user's time zone, and submits it in UTC.
    #[must_use]
    pub fn datetime(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::Datetime)
    }

    /// A date and time picker for a wall-clock value without a time zone, such as a
    /// `civil::DateTime` column. The value is submitted exactly as picked.
    #[must_use]
    pub fn civil_datetime(name: impl Into<String>) -> Self {
        Self::new(name, FieldKind::CivilDatetime)
    }

    /// A list of short text values, entered one at a time. It submits a JSON array of strings.
    #[must_use]
    pub fn tags(name: impl Into<String>) -> Self {
        let mut f = Self::new(name, FieldKind::Tags);
        f.default_value = Some(serde_json::Value::Array(Vec::new()));
        f
    }

    /// A text area for JSON. The form checks that the text parses, and submits the parsed value.
    #[must_use]
    pub fn json(name: impl Into<String>) -> Self {
        let mut f = Self::new(name, FieldKind::Json);
        f.rows = Some(6);
        f
    }

    /// Shows a value that the form never submits.
    #[must_use]
    pub fn readonly(name: impl Into<String>) -> Self {
        let mut f = Self::new(name, FieldKind::Readonly);
        f.disabled = true;
        f
    }

    /// Sets the field's label. By default it's the field's name in words, such as `Published at`
    /// for `published_at`.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Marks the field as required, with an asterisk beside its label. Your input struct's rules
    /// decide what is actually required.
    #[must_use]
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Lets the user leave the field empty. A select then offers an empty choice even when it's
    /// required. An empty field always submits `null`.
    #[must_use]
    pub fn nullable(mut self) -> Self {
        self.nullable = true;
        self
    }

    /// Shows the field without letting the user change it. Its value isn't submitted.
    #[must_use]
    pub fn disabled(mut self) -> Self {
        self.disabled = true;
        self
    }

    /// Sets the hint shown while the field is empty.
    #[must_use]
    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Sets a line of help shown under the field.
    #[must_use]
    pub fn helper(mut self, helper: impl Into<String>) -> Self {
        self.helper = Some(helper.into());
        self
    }

    /// Sets text shown before the input, such as `$` or `https://`.
    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = Some(prefix.into());
        self
    }

    /// Sets text shown after the input, such as `kg`.
    #[must_use]
    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
        self.suffix = Some(suffix.into());
        self
    }

    /// Sets how many rows tall a text area is.
    #[must_use]
    pub fn rows(mut self, rows: u8) -> Self {
        self.rows = Some(rows);
        self
    }

    /// The smallest number a `number` or `decimal` field accepts. The form checks it before
    /// submitting. Your input struct's rules remain the authority.
    #[must_use]
    pub fn min(mut self, min: f64) -> Self {
        self.min = Some(min);
        self
    }

    /// The largest number a `number` or `decimal` field accepts. The form checks it before
    /// submitting. Your input struct's rules remain the authority.
    #[must_use]
    pub fn max(mut self, max: f64) -> Self {
        self.max = Some(max);
        self
    }

    /// Sets the most characters the field accepts.
    #[must_use]
    pub fn max_length(mut self, max_length: usize) -> Self {
        self.max_length = Some(max_length);
        self
    }

    /// Span across all columns of the enclosing form section.
    #[must_use]
    pub fn column_span_full(mut self) -> Self {
        self.column_span = 2;
        self
    }

    /// Set the initial value on the create form.
    #[must_use]
    pub fn default_value(mut self, value: impl Into<serde_json::Value>) -> Self {
        self.default_value = Some(value.into());
        self
    }

    /// Set options for `select` or `radio` fields.
    #[must_use]
    pub fn options<I, O>(mut self, options: I) -> Self
    where
        I: IntoIterator<Item = O>,
        O: Into<SelectOption>,
    {
        self.options = options.into_iter().map(|opt| opt.into().to_dto()).collect();
        self
    }

    /// Show this field only when creating a new record (e.g. initial password).
    #[must_use]
    pub fn create_only(mut self) -> Self {
        self.create_only = true;
        self
    }

    /// Show this field only when editing an existing record.
    #[must_use]
    pub fn edit_only(mut self) -> Self {
        self.edit_only = true;
        self
    }

    pub(crate) fn to_dto(&self) -> FieldSchemaDto {
        FieldSchemaDto {
            name: self.name.clone(),
            label: self.label.clone(),
            kind: self.kind,
            required: self.required,
            nullable: self.nullable,
            disabled: self.disabled,
            placeholder: self.placeholder.clone(),
            helper: self.helper.clone(),
            prefix: self.prefix.clone(),
            suffix: self.suffix.clone(),
            rows: self.rows,
            min: self.min,
            max: self.max,
            max_length: self.max_length,
            column_span: self.column_span,
            default_value: self.default_value.clone(),
            options: self.options.clone(),
            create_only: self.create_only,
            edit_only: self.edit_only,
        }
    }
}

/// A titled card section grouping related form fields.
#[derive(Debug, Clone)]
pub struct FormSection {
    pub(crate) title: Option<String>,
    pub(crate) description: Option<String>,
    pub(crate) columns: u8,
    pub(crate) fields: Vec<Field>,
}

impl FormSection {
    /// A section with a heading. Its fields sit in two columns unless you set
    /// [`columns`](Self::columns).
    #[must_use]
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: Some(title.into()),
            description: None,
            columns: 2,
            fields: Vec::new(),
        }
    }

    /// Adds a line under the section's heading.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets how many columns the section's fields sit in on a wide screen, from one to three.
    #[must_use]
    pub fn columns(mut self, columns: u8) -> Self {
        self.columns = columns.clamp(1, 3);
        self
    }

    /// Adds a field to the section.
    #[must_use]
    pub fn field(mut self, field: Field) -> Self {
        self.fields.push(field);
        self
    }

    /// Adds several fields to the section.
    #[must_use]
    pub fn fields(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
        self.fields.extend(fields);
        self
    }

    pub(crate) fn to_dto(&self) -> FormSectionSchemaDto {
        FormSectionSchemaDto {
            title: self.title.clone(),
            description: self.description.clone(),
            columns: self.columns,
            fields: self.fields.iter().map(Field::to_dto).collect(),
        }
    }
}

/// Fluent builder for a resource's create/edit form.
#[derive(Debug, Clone, Default)]
pub struct FormBuilder {
    pub(crate) sections: Vec<FormSection>,
    pub(crate) loose_fields: Vec<Field>,
}

impl FormBuilder {
    /// Add a field to the default unsectioned card.
    #[must_use]
    pub fn field(mut self, field: Field) -> Self {
        self.loose_fields.push(field);
        self
    }

    /// Add multiple fields to the default card.
    #[must_use]
    pub fn fields(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
        self.loose_fields.extend(fields);
        self
    }

    /// Add a titled section card to the form.
    #[must_use]
    pub fn section(mut self, section: FormSection) -> Self {
        self.sections.push(section);
        self
    }

    pub(crate) fn to_dto(&self) -> Vec<FormSectionSchemaDto> {
        let mut out = Vec::new();
        if !self.loose_fields.is_empty() {
            out.push(FormSectionSchemaDto {
                title: None,
                description: None,
                columns: 2,
                fields: self.loose_fields.iter().map(Field::to_dto).collect(),
            });
        }
        out.extend(self.sections.iter().map(FormSection::to_dto));
        out
    }
}