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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! A resource's table: its columns, filters, tabs, default order, and actions.

use std::collections::BTreeMap;
use std::sync::Arc;

use laravel::db::{Builder, col};
use laravel::model::Model;
use laravel::time::civil::Date;

use crate::protocol::{
    BadgeColor, ColumnAlign, ColumnKind, ColumnSchemaDto, DefaultSortDto, FilterKindDto, FilterSchemaDto,
    SelectOptionDto, SortDirection, TableTabSchemaDto,
};
use crate::schema::action::{BulkAction, RowAction};
use crate::schema::form::SelectOption;
use crate::schema::humanize;

/// A column of a resource's table: which value of a record it shows, and how.
#[derive(Debug, Clone)]
pub struct Column {
    pub(crate) name: String,
    pub(crate) label: String,
    pub(crate) kind: ColumnKind,
    pub(crate) align: ColumnAlign,
    pub(crate) sortable: bool,
    pub(crate) searchable: bool,
    pub(crate) toggleable: bool,
    pub(crate) hidden_by_default: bool,
    pub(crate) copyable: bool,
    pub(crate) mono: bool,
    pub(crate) prefix: Option<String>,
    pub(crate) suffix: Option<String>,
    pub(crate) currency: Option<String>,
    pub(crate) description_column: Option<String>,
    pub(crate) limit: Option<usize>,
    pub(crate) badge_colors: BTreeMap<String, BadgeColor>,
    pub(crate) badge_dot: bool,
}

impl Column {
    fn new(name: impl Into<String>, kind: ColumnKind) -> Self {
        let name = name.into();
        let label = humanize(&name);
        let align = match kind {
            ColumnKind::Number | ColumnKind::Currency => ColumnAlign::Right,
            ColumnKind::Boolean => ColumnAlign::Center,
            _ => ColumnAlign::Left,
        };
        Self {
            name,
            label,
            kind,
            align,
            sortable: false,
            searchable: false,
            toggleable: true,
            hidden_by_default: false,
            copyable: false,
            mono: false,
            prefix: None,
            suffix: None,
            currency: None,
            description_column: None,
            limit: None,
            badge_colors: BTreeMap::new(),
            badge_dot: false,
        }
    }

    /// A column of plain text.
    ///
    /// A column's name is a field of the serialized model. To show a value of a related model,
    /// load the relationship in [`AdminResource::query`](crate::AdminResource::query) and name
    /// the column with a dotted path, such as `Column::text("customer.name")`. The database
    /// can't sort or search by such a column.
    #[must_use]
    pub fn text(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Text)
    }

    /// A column that shows its value as a colored badge, for a status or another small set of
    /// values. Give each value a color with [`color`](Self::color).
    #[must_use]
    pub fn badge(name: impl Into<String>) -> Self {
        let mut col = Self::new(name, ColumnKind::Badge);
        col.badge_dot = true;
        col
    }

    /// A column that shows a `bool` as a check mark or a dash.
    #[must_use]
    pub fn boolean(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Boolean)
    }

    /// A right-aligned column for a number, shown with thousands separators.
    #[must_use]
    pub fn number(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Number)
    }

    /// A right-aligned column for an amount of money in the given currency, such as
    /// `Column::currency("total", "USD")`.
    #[must_use]
    pub fn currency(name: impl Into<String>, currency_code: impl Into<String>) -> Self {
        let mut col = Self::new(name, ColumnKind::Currency);
        col.currency = Some(currency_code.into());
        col
    }

    /// A column for an instant, shown as a date and a time in the user's time zone.
    #[must_use]
    pub fn datetime(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Datetime)
    }

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

    /// A column for an instant, shown as how long ago it was, such as `3 hours ago`. Hovering
    /// over it shows the date and time.
    #[must_use]
    pub fn relative_time(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::RelativeTime)
    }

    /// A column that shows a name beside a circle with its initials. Add a second line under the
    /// name with [`description_column`](Self::description_column).
    #[must_use]
    pub fn avatar(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Avatar)
    }

    /// A column that shows a list of short values as badges.
    #[must_use]
    pub fn tags(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Tags)
    }

    /// A column that shows the start of a JSON value in a monospace font.
    #[must_use]
    pub fn json(name: impl Into<String>) -> Self {
        Self::new(name, ColumnKind::Json)
    }

    /// Sets the column's heading. By default it's the column's name in words.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Sets which side of the column its values line up on.
    #[must_use]
    pub fn align(mut self, align: ColumnAlign) -> Self {
        self.align = align;
        self
    }

    /// Lets the user sort the table by this column, by clicking its heading.
    #[must_use]
    pub fn sortable(mut self) -> Self {
        self.sortable = true;
        self
    }

    /// Looks in this column when the user searches the table, or the whole panel with ⌘K. The
    /// column must hold text.
    #[must_use]
    pub fn searchable(mut self) -> Self {
        self.searchable = true;
        self
    }

    /// Sets whether the user may hide the column from the table's `Columns` menu. They may by
    /// default.
    #[must_use]
    pub fn toggleable(mut self, toggleable: bool) -> Self {
        self.toggleable = toggleable;
        self
    }

    /// Leaves the column out of the table until the user turns it on from the `Columns` menu.
    #[must_use]
    pub fn hidden_by_default(mut self) -> Self {
        self.hidden_by_default = true;
        self
    }

    /// Shows a button beside the value, on hover, that copies it to the clipboard.
    #[must_use]
    pub fn copyable(mut self) -> Self {
        self.copyable = true;
        self
    }

    /// Shows the value in a monospace font, for an identifier such as a SKU. A number column
    /// also drops its thousands separators.
    #[must_use]
    pub fn mono(mut self) -> Self {
        self.mono = true;
        self
    }

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

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

    /// Shows another field's value in smaller text under this column's value, such as an email
    /// under a name.
    #[must_use]
    pub fn description_column(mut self, column: impl Into<String>) -> Self {
        self.description_column = Some(column.into());
        self
    }

    /// Shortens text longer than this many characters, ending it with an ellipsis.
    #[must_use]
    pub fn limit(mut self, chars: usize) -> Self {
        self.limit = Some(chars);
        self
    }

    /// Sets the color of the badge for one value of a [`badge`](Self::badge) column, such as
    /// green for `published`. A value without a color gets a gray badge.
    #[must_use]
    pub fn color(mut self, value: impl Into<String>, color: BadgeColor) -> Self {
        self.badge_colors.insert(value.into(), color);
        self
    }

    /// Sets whether a badge has a small dot before its text. It does by default.
    #[must_use]
    pub fn dot(mut self, show_dot: bool) -> Self {
        self.badge_dot = show_dot;
        self
    }

    pub(crate) fn to_dto(&self) -> ColumnSchemaDto {
        ColumnSchemaDto {
            name: self.name.clone(),
            label: self.label.clone(),
            kind: self.kind,
            align: self.align,
            sortable: self.sortable,
            searchable: self.searchable,
            toggleable: self.toggleable,
            hidden_by_default: self.hidden_by_default,
            copyable: self.copyable,
            mono: self.mono,
            prefix: self.prefix.clone(),
            suffix: self.suffix.clone(),
            currency: self.currency.clone(),
            description_column: self.description_column.clone(),
            limit: self.limit,
            badge_colors: self.badge_colors.clone(),
            badge_dot: self.badge_dot,
        }
    }
}

type QueryModifier<M> = Arc<dyn Fn(Builder<M>, &str) -> Builder<M> + Send + Sync>;
type TabModifier<M> = Arc<dyn Fn(Builder<M>) -> Builder<M> + Send + Sync>;

/// A filter the user can apply to a resource's table, shown as a chip above it.
pub struct Filter<M: Model> {
    pub(crate) name: String,
    pub(crate) label: String,
    pub(crate) control: FilterKindDto,
    pub(crate) apply: QueryModifier<M>,
}

impl<M: Model> Filter<M> {
    /// A filter that offers a list of choices, and keeps the records whose column equals the
    /// chosen one.
    ///
    /// The filter compares the column with the choice's value as text, which suits a column that
    /// holds text, such as an enum. For another kind of column, such as an integer key, compare
    /// it yourself with [`query`](SelectFilterBuilder::query).
    #[must_use]
    pub fn select(name: impl Into<String>) -> SelectFilterBuilder<M> {
        let name = name.into();
        let label = humanize(&name);
        SelectFilterBuilder {
            column: name.clone(),
            name,
            label,
            options: Vec::new(),
            custom: None,
            _marker: std::marker::PhantomData,
        }
    }

    /// A filter for a `bool` column, with a choice for `true` and one for `false`.
    #[must_use]
    pub fn boolean(name: impl Into<String>) -> Self {
        let name = name.into();
        let label = humanize(&name);
        let apply_col = name.clone();
        Self {
            name,
            label,
            control: FilterKindDto::Boolean {
                true_label: "Yes".to_owned(),
                false_label: "No".to_owned(),
            },
            apply: Arc::new(move |query, value| match value {
                "true" | "1" | "yes" => query.filter(col(apply_col.as_str()).eq(true)),
                "false" | "0" | "no" => query.filter(col(apply_col.as_str()).eq(false)),
                _ => query,
            }),
        }
    }

    /// A filter for a date or timestamp column that keeps the records from one date through
    /// another. The user may leave either end open. A timestamp is compared by its date in UTC.
    #[must_use]
    pub fn date_range(name: impl Into<String>) -> Self {
        let name = name.into();
        let label = humanize(&name);
        let apply_col = name.clone();
        Self {
            name,
            label,
            control: FilterKindDto::DateRange,
            apply: Arc::new(move |mut query, value| {
                // The value is `from..to`, with either date left out for an open end. A date that
                // doesn't parse is ignored, as a filter the user never set would be.
                let Some((from, to)) = value.split_once("..") else {
                    return query;
                };
                if let Ok(from) = from.parse::<Date>() {
                    query = query.filter(col(apply_col.as_str()).date().ge(from));
                }
                if let Ok(to) = to.parse::<Date>() {
                    query = query.filter(col(apply_col.as_str()).date().le(to));
                }
                query
            }),
        }
    }

    /// A filter that keeps the records whose column contains the text the user types.
    #[must_use]
    pub fn text(name: impl Into<String>) -> Self {
        let name = name.into();
        let label = humanize(&name);
        let apply_col = name.clone();
        Self {
            name,
            label,
            control: FilterKindDto::Text { placeholder: None },
            apply: Arc::new(move |query, value| {
                if value.trim().is_empty() {
                    query
                } else {
                    query.filter(col(apply_col.as_str()).contains(value.trim()))
                }
            }),
        }
    }

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

    /// Sets what a [`boolean`](Self::boolean) filter calls its two choices, instead of `Yes` and
    /// `No`.
    #[must_use]
    pub fn boolean_labels(mut self, true_label: impl Into<String>, false_label: impl Into<String>) -> Self {
        if let FilterKindDto::Boolean {
            true_label: t,
            false_label: f,
        } = &mut self.control
        {
            *t = true_label.into();
            *f = false_label.into();
        }
        self
    }

    /// Replaces how the filter narrows the query. The closure receives the query and the value
    /// the user chose or typed.
    #[must_use]
    pub fn query<F>(mut self, modifier: F) -> Self
    where
        F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
    {
        self.apply = Arc::new(modifier);
        self
    }

    pub(crate) fn to_dto(&self) -> FilterSchemaDto {
        FilterSchemaDto {
            name: self.name.clone(),
            label: self.label.clone(),
            control: self.control.clone(),
        }
    }
}

/// A [`Filter::select`] being built. Give it its choices with [`options`](Self::options).
pub struct SelectFilterBuilder<M: Model> {
    name: String,
    label: String,
    column: String,
    options: Vec<SelectOptionDto>,
    custom: Option<QueryModifier<M>>,
    _marker: std::marker::PhantomData<fn() -> M>,
}

impl<M: Model> SelectFilterBuilder<M> {
    /// Sets the filter's label. By default it's the filter's name in words.
    #[must_use]
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Sets the database column the filter compares, when it differs from the filter's name.
    #[must_use]
    pub fn column(mut self, column: impl Into<String>) -> Self {
        self.column = column.into();
        self
    }

    /// Sets the choices the filter offers.
    #[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
    }

    /// Replaces how the filter narrows the query. The closure receives the query and the value
    /// of the chosen option.
    #[must_use]
    pub fn query<F>(mut self, modifier: F) -> Self
    where
        F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
    {
        self.custom = Some(Arc::new(modifier));
        self
    }

    /// Finishes the filter. [`TableBuilder::filter`] does this for you.
    #[must_use]
    pub fn build(self) -> Filter<M> {
        let apply_col = self.column.clone();
        let apply = self.custom.unwrap_or_else(|| {
            Arc::new(move |query: Builder<M>, value: &str| {
                if value.is_empty() {
                    query
                } else {
                    query.filter(col(apply_col.as_str()).eq(value.to_owned()))
                }
            })
        });
        Filter {
            name: self.name,
            label: self.label,
            control: FilterKindDto::Select { options: self.options },
            apply,
        }
    }
}

impl<M: Model> From<SelectFilterBuilder<M>> for Filter<M> {
    fn from(builder: SelectFilterBuilder<M>) -> Self {
        builder.build()
    }
}

/// A view of a resource's table that narrows it to some of its records, such as the orders that
/// are still pending. Tabs appear above the table as cards, each with a live count of its records.
pub struct TableTab<M: Model> {
    pub(crate) key: String,
    pub(crate) label: String,
    pub(crate) badge_color: Option<BadgeColor>,
    pub(crate) apply: TabModifier<M>,
}

impl<M: Model> TableTab<M> {
    /// A tab with a key for URLs, a label, and a closure that narrows the query to the tab's
    /// records.
    #[must_use]
    pub fn new<F>(key: impl Into<String>, label: impl Into<String>, modifier: F) -> Self
    where
        F: Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
    {
        Self {
            key: key.into(),
            label: label.into(),
            badge_color: None,
            apply: Arc::new(modifier),
        }
    }

    /// A tab that shows every record, usually the first one. Its key is `all`.
    #[must_use]
    pub fn all(label: impl Into<String>) -> Self {
        Self::new("all", label, |q| q)
    }

    /// Shows a dot of this color before the tab's label, to match the badges of its records.
    #[must_use]
    pub fn color(mut self, color: BadgeColor) -> Self {
        self.badge_color = Some(color);
        self
    }

    pub(crate) fn to_dto(&self) -> TableTabSchemaDto {
        TableTabSchemaDto {
            key: self.key.clone(),
            label: self.label.clone(),
            badge_color: self.badge_color,
        }
    }
}

/// Builds a resource's table. [`AdminResource::table`](crate::AdminResource::table) receives an
/// empty one, and returns it with columns and everything else the table should have.
pub struct TableBuilder<M: Model> {
    pub(crate) columns: Vec<Column>,
    pub(crate) filters: Vec<Filter<M>>,
    pub(crate) tabs: Vec<TableTab<M>>,
    pub(crate) row_actions: Vec<RowAction<M>>,
    pub(crate) bulk_actions: Vec<BulkAction<M>>,
    pub(crate) default_sort: Option<DefaultSortDto>,
    pub(crate) exportable: bool,
    /// Columns of the model's table to search besides the `searchable` columns.
    pub(crate) search_by: Vec<String>,
}

impl<M: Model> Default for TableBuilder<M> {
    fn default() -> Self {
        Self {
            columns: Vec::new(),
            filters: Vec::new(),
            tabs: Vec::new(),
            row_actions: Vec::new(),
            bulk_actions: Vec::new(),
            default_sort: None,
            exportable: true,
            search_by: Vec::new(),
        }
    }
}

impl<M: Model> TableBuilder<M> {
    /// Adds a column. Columns appear in the order you add them.
    #[must_use]
    pub fn column(mut self, column: Column) -> Self {
        self.columns.push(column);
        self
    }

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

    /// Adds a filter, shown as a chip above the table.
    #[must_use]
    pub fn filter(mut self, filter: impl Into<Filter<M>>) -> Self {
        self.filters.push(filter.into());
        self
    }

    /// Adds a tab above the table. The first tab you add is the one the table opens on.
    #[must_use]
    pub fn tab(mut self, tab: TableTab<M>) -> Self {
        self.tabs.push(tab);
        self
    }

    /// Adds an action on one record, offered in each row's menu and in the record's details.
    #[must_use]
    pub fn action(mut self, action: RowAction<M>) -> Self {
        self.row_actions.push(action);
        self
    }

    /// Adds an action on every selected record, offered once the user selects rows.
    #[must_use]
    pub fn bulk_action(mut self, action: BulkAction<M>) -> Self {
        self.bulk_actions.push(action);
        self
    }

    /// Sets the order the table opens in. Without one, the newest keys come first.
    #[must_use]
    pub fn default_sort(mut self, column: impl Into<String>, direction: SortDirection) -> Self {
        self.default_sort = Some(DefaultSortDto {
            column: column.into(),
            direction,
        });
        self
    }

    /// Every database column a search looks in: the `searchable` columns, then the
    /// [`search_by`](Self::search_by) columns.
    pub(crate) fn search_columns(&self) -> Vec<&str> {
        let mut columns: Vec<&str> = self
            .columns
            .iter()
            .filter(|column| column.searchable)
            .map(|column| column.name.as_str())
            .collect();
        for column in &self.search_by {
            if !columns.contains(&column.as_str()) {
                columns.push(column);
            }
        }
        columns
    }

    /// Also search these columns of the model's table, which the table doesn't have to show.
    ///
    /// For example, a customers table that shows the email under the name, instead of in a
    /// column of its own, can still be searched by email:
    ///
    /// ```ignore
    /// table
    ///     .column(Column::avatar("name").searchable().description_column("email"))
    ///     .search_by(["email", "company"])
    /// ```
    #[must_use]
    pub fn search_by(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.search_by.extend(columns.into_iter().map(Into::into));
        self
    }

    /// Sets whether the user may export the table as CSV. They may by default.
    ///
    /// An export holds every record that matches the table's search, filters, and tab, with the
    /// table's columns, and is streamed, so it may be of any size.
    #[must_use]
    pub fn exportable(mut self, exportable: bool) -> Self {
        self.exportable = exportable;
        self
    }
}