Skip to main content

laravel_rust_admin/schema/
table.rs

1//! A resource's table: its columns, filters, tabs, default order, and actions.
2
3use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use laravel::db::{Builder, col};
7use laravel::model::Model;
8use laravel::time::civil::Date;
9
10use crate::protocol::{
11    BadgeColor, ColumnAlign, ColumnKind, ColumnSchemaDto, DefaultSortDto, FilterKindDto, FilterSchemaDto,
12    SelectOptionDto, SortDirection, TableTabSchemaDto,
13};
14use crate::schema::action::{BulkAction, RowAction};
15use crate::schema::form::SelectOption;
16use crate::schema::humanize;
17
18/// A column of a resource's table: which value of a record it shows, and how.
19#[derive(Debug, Clone)]
20pub struct Column {
21    pub(crate) name: String,
22    pub(crate) label: String,
23    pub(crate) kind: ColumnKind,
24    pub(crate) align: ColumnAlign,
25    pub(crate) sortable: bool,
26    pub(crate) searchable: bool,
27    pub(crate) toggleable: bool,
28    pub(crate) hidden_by_default: bool,
29    pub(crate) copyable: bool,
30    pub(crate) mono: bool,
31    pub(crate) prefix: Option<String>,
32    pub(crate) suffix: Option<String>,
33    pub(crate) currency: Option<String>,
34    pub(crate) description_column: Option<String>,
35    pub(crate) limit: Option<usize>,
36    pub(crate) badge_colors: BTreeMap<String, BadgeColor>,
37    pub(crate) badge_dot: bool,
38}
39
40impl Column {
41    fn new(name: impl Into<String>, kind: ColumnKind) -> Self {
42        let name = name.into();
43        let label = humanize(&name);
44        let align = match kind {
45            ColumnKind::Number | ColumnKind::Currency => ColumnAlign::Right,
46            ColumnKind::Boolean => ColumnAlign::Center,
47            _ => ColumnAlign::Left,
48        };
49        Self {
50            name,
51            label,
52            kind,
53            align,
54            sortable: false,
55            searchable: false,
56            toggleable: true,
57            hidden_by_default: false,
58            copyable: false,
59            mono: false,
60            prefix: None,
61            suffix: None,
62            currency: None,
63            description_column: None,
64            limit: None,
65            badge_colors: BTreeMap::new(),
66            badge_dot: false,
67        }
68    }
69
70    /// A column of plain text.
71    ///
72    /// A column's name is a field of the serialized model. To show a value of a related model,
73    /// load the relationship in [`AdminResource::query`](crate::AdminResource::query) and name
74    /// the column with a dotted path, such as `Column::text("customer.name")`. The database
75    /// can't sort or search by such a column.
76    #[must_use]
77    pub fn text(name: impl Into<String>) -> Self {
78        Self::new(name, ColumnKind::Text)
79    }
80
81    /// A column that shows its value as a colored badge, for a status or another small set of
82    /// values. Give each value a color with [`color`](Self::color).
83    #[must_use]
84    pub fn badge(name: impl Into<String>) -> Self {
85        let mut col = Self::new(name, ColumnKind::Badge);
86        col.badge_dot = true;
87        col
88    }
89
90    /// A column that shows a `bool` as a check mark or a dash.
91    #[must_use]
92    pub fn boolean(name: impl Into<String>) -> Self {
93        Self::new(name, ColumnKind::Boolean)
94    }
95
96    /// A right-aligned column for a number, shown with thousands separators.
97    #[must_use]
98    pub fn number(name: impl Into<String>) -> Self {
99        Self::new(name, ColumnKind::Number)
100    }
101
102    /// A right-aligned column for an amount of money in the given currency, such as
103    /// `Column::currency("total", "USD")`.
104    #[must_use]
105    pub fn currency(name: impl Into<String>, currency_code: impl Into<String>) -> Self {
106        let mut col = Self::new(name, ColumnKind::Currency);
107        col.currency = Some(currency_code.into());
108        col
109    }
110
111    /// A column for an instant, shown as a date and a time in the user's time zone.
112    #[must_use]
113    pub fn datetime(name: impl Into<String>) -> Self {
114        Self::new(name, ColumnKind::Datetime)
115    }
116
117    /// A column for a calendar date.
118    #[must_use]
119    pub fn date(name: impl Into<String>) -> Self {
120        Self::new(name, ColumnKind::Date)
121    }
122
123    /// A column for an instant, shown as how long ago it was, such as `3 hours ago`. Hovering
124    /// over it shows the date and time.
125    #[must_use]
126    pub fn relative_time(name: impl Into<String>) -> Self {
127        Self::new(name, ColumnKind::RelativeTime)
128    }
129
130    /// A column that shows a name beside a circle with its initials. Add a second line under the
131    /// name with [`description_column`](Self::description_column).
132    #[must_use]
133    pub fn avatar(name: impl Into<String>) -> Self {
134        Self::new(name, ColumnKind::Avatar)
135    }
136
137    /// A column that shows a list of short values as badges.
138    #[must_use]
139    pub fn tags(name: impl Into<String>) -> Self {
140        Self::new(name, ColumnKind::Tags)
141    }
142
143    /// A column that shows the start of a JSON value in a monospace font.
144    #[must_use]
145    pub fn json(name: impl Into<String>) -> Self {
146        Self::new(name, ColumnKind::Json)
147    }
148
149    /// Sets the column's heading. By default it's the column's name in words.
150    #[must_use]
151    pub fn label(mut self, label: impl Into<String>) -> Self {
152        self.label = label.into();
153        self
154    }
155
156    /// Sets which side of the column its values line up on.
157    #[must_use]
158    pub fn align(mut self, align: ColumnAlign) -> Self {
159        self.align = align;
160        self
161    }
162
163    /// Lets the user sort the table by this column, by clicking its heading.
164    #[must_use]
165    pub fn sortable(mut self) -> Self {
166        self.sortable = true;
167        self
168    }
169
170    /// Looks in this column when the user searches the table, or the whole panel with ⌘K. The
171    /// column must hold text.
172    #[must_use]
173    pub fn searchable(mut self) -> Self {
174        self.searchable = true;
175        self
176    }
177
178    /// Sets whether the user may hide the column from the table's `Columns` menu. They may by
179    /// default.
180    #[must_use]
181    pub fn toggleable(mut self, toggleable: bool) -> Self {
182        self.toggleable = toggleable;
183        self
184    }
185
186    /// Leaves the column out of the table until the user turns it on from the `Columns` menu.
187    #[must_use]
188    pub fn hidden_by_default(mut self) -> Self {
189        self.hidden_by_default = true;
190        self
191    }
192
193    /// Shows a button beside the value, on hover, that copies it to the clipboard.
194    #[must_use]
195    pub fn copyable(mut self) -> Self {
196        self.copyable = true;
197        self
198    }
199
200    /// Shows the value in a monospace font, for an identifier such as a SKU. A number column
201    /// also drops its thousands separators.
202    #[must_use]
203    pub fn mono(mut self) -> Self {
204        self.mono = true;
205        self
206    }
207
208    /// Sets text shown before the value, such as `#`.
209    #[must_use]
210    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
211        self.prefix = Some(prefix.into());
212        self
213    }
214
215    /// Sets text shown after the value, such as `%`.
216    #[must_use]
217    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
218        self.suffix = Some(suffix.into());
219        self
220    }
221
222    /// Shows another field's value in smaller text under this column's value, such as an email
223    /// under a name.
224    #[must_use]
225    pub fn description_column(mut self, column: impl Into<String>) -> Self {
226        self.description_column = Some(column.into());
227        self
228    }
229
230    /// Shortens text longer than this many characters, ending it with an ellipsis.
231    #[must_use]
232    pub fn limit(mut self, chars: usize) -> Self {
233        self.limit = Some(chars);
234        self
235    }
236
237    /// Sets the color of the badge for one value of a [`badge`](Self::badge) column, such as
238    /// green for `published`. A value without a color gets a gray badge.
239    #[must_use]
240    pub fn color(mut self, value: impl Into<String>, color: BadgeColor) -> Self {
241        self.badge_colors.insert(value.into(), color);
242        self
243    }
244
245    /// Sets whether a badge has a small dot before its text. It does by default.
246    #[must_use]
247    pub fn dot(mut self, show_dot: bool) -> Self {
248        self.badge_dot = show_dot;
249        self
250    }
251
252    pub(crate) fn to_dto(&self) -> ColumnSchemaDto {
253        ColumnSchemaDto {
254            name: self.name.clone(),
255            label: self.label.clone(),
256            kind: self.kind,
257            align: self.align,
258            sortable: self.sortable,
259            searchable: self.searchable,
260            toggleable: self.toggleable,
261            hidden_by_default: self.hidden_by_default,
262            copyable: self.copyable,
263            mono: self.mono,
264            prefix: self.prefix.clone(),
265            suffix: self.suffix.clone(),
266            currency: self.currency.clone(),
267            description_column: self.description_column.clone(),
268            limit: self.limit,
269            badge_colors: self.badge_colors.clone(),
270            badge_dot: self.badge_dot,
271        }
272    }
273}
274
275type QueryModifier<M> = Arc<dyn Fn(Builder<M>, &str) -> Builder<M> + Send + Sync>;
276type TabModifier<M> = Arc<dyn Fn(Builder<M>) -> Builder<M> + Send + Sync>;
277
278/// A filter the user can apply to a resource's table, shown as a chip above it.
279pub struct Filter<M: Model> {
280    pub(crate) name: String,
281    pub(crate) label: String,
282    pub(crate) control: FilterKindDto,
283    pub(crate) apply: QueryModifier<M>,
284}
285
286impl<M: Model> Filter<M> {
287    /// A filter that offers a list of choices, and keeps the records whose column equals the
288    /// chosen one.
289    ///
290    /// The filter compares the column with the choice's value as text, which suits a column that
291    /// holds text, such as an enum. For another kind of column, such as an integer key, compare
292    /// it yourself with [`query`](SelectFilterBuilder::query).
293    #[must_use]
294    pub fn select(name: impl Into<String>) -> SelectFilterBuilder<M> {
295        let name = name.into();
296        let label = humanize(&name);
297        SelectFilterBuilder {
298            column: name.clone(),
299            name,
300            label,
301            options: Vec::new(),
302            custom: None,
303            _marker: std::marker::PhantomData,
304        }
305    }
306
307    /// A filter for a `bool` column, with a choice for `true` and one for `false`.
308    #[must_use]
309    pub fn boolean(name: impl Into<String>) -> Self {
310        let name = name.into();
311        let label = humanize(&name);
312        let apply_col = name.clone();
313        Self {
314            name,
315            label,
316            control: FilterKindDto::Boolean {
317                true_label: "Yes".to_owned(),
318                false_label: "No".to_owned(),
319            },
320            apply: Arc::new(move |query, value| match value {
321                "true" | "1" | "yes" => query.filter(col(apply_col.as_str()).eq(true)),
322                "false" | "0" | "no" => query.filter(col(apply_col.as_str()).eq(false)),
323                _ => query,
324            }),
325        }
326    }
327
328    /// A filter for a date or timestamp column that keeps the records from one date through
329    /// another. The user may leave either end open. A timestamp is compared by its date in UTC.
330    #[must_use]
331    pub fn date_range(name: impl Into<String>) -> Self {
332        let name = name.into();
333        let label = humanize(&name);
334        let apply_col = name.clone();
335        Self {
336            name,
337            label,
338            control: FilterKindDto::DateRange,
339            apply: Arc::new(move |mut query, value| {
340                // The value is `from..to`, with either date left out for an open end. A date that
341                // doesn't parse is ignored, as a filter the user never set would be.
342                let Some((from, to)) = value.split_once("..") else {
343                    return query;
344                };
345                if let Ok(from) = from.parse::<Date>() {
346                    query = query.filter(col(apply_col.as_str()).date().ge(from));
347                }
348                if let Ok(to) = to.parse::<Date>() {
349                    query = query.filter(col(apply_col.as_str()).date().le(to));
350                }
351                query
352            }),
353        }
354    }
355
356    /// A filter that keeps the records whose column contains the text the user types.
357    #[must_use]
358    pub fn text(name: impl Into<String>) -> Self {
359        let name = name.into();
360        let label = humanize(&name);
361        let apply_col = name.clone();
362        Self {
363            name,
364            label,
365            control: FilterKindDto::Text { placeholder: None },
366            apply: Arc::new(move |query, value| {
367                if value.trim().is_empty() {
368                    query
369                } else {
370                    query.filter(col(apply_col.as_str()).contains(value.trim()))
371                }
372            }),
373        }
374    }
375
376    /// Sets the filter's label. By default it's the filter's name in words.
377    #[must_use]
378    pub fn label(mut self, label: impl Into<String>) -> Self {
379        self.label = label.into();
380        self
381    }
382
383    /// Sets what a [`boolean`](Self::boolean) filter calls its two choices, instead of `Yes` and
384    /// `No`.
385    #[must_use]
386    pub fn boolean_labels(mut self, true_label: impl Into<String>, false_label: impl Into<String>) -> Self {
387        if let FilterKindDto::Boolean {
388            true_label: t,
389            false_label: f,
390        } = &mut self.control
391        {
392            *t = true_label.into();
393            *f = false_label.into();
394        }
395        self
396    }
397
398    /// Replaces how the filter narrows the query. The closure receives the query and the value
399    /// the user chose or typed.
400    #[must_use]
401    pub fn query<F>(mut self, modifier: F) -> Self
402    where
403        F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
404    {
405        self.apply = Arc::new(modifier);
406        self
407    }
408
409    pub(crate) fn to_dto(&self) -> FilterSchemaDto {
410        FilterSchemaDto {
411            name: self.name.clone(),
412            label: self.label.clone(),
413            control: self.control.clone(),
414        }
415    }
416}
417
418/// A [`Filter::select`] being built. Give it its choices with [`options`](Self::options).
419pub struct SelectFilterBuilder<M: Model> {
420    name: String,
421    label: String,
422    column: String,
423    options: Vec<SelectOptionDto>,
424    custom: Option<QueryModifier<M>>,
425    _marker: std::marker::PhantomData<fn() -> M>,
426}
427
428impl<M: Model> SelectFilterBuilder<M> {
429    /// Sets the filter's label. By default it's the filter's name in words.
430    #[must_use]
431    pub fn label(mut self, label: impl Into<String>) -> Self {
432        self.label = label.into();
433        self
434    }
435
436    /// Sets the database column the filter compares, when it differs from the filter's name.
437    #[must_use]
438    pub fn column(mut self, column: impl Into<String>) -> Self {
439        self.column = column.into();
440        self
441    }
442
443    /// Sets the choices the filter offers.
444    #[must_use]
445    pub fn options<I, O>(mut self, options: I) -> Self
446    where
447        I: IntoIterator<Item = O>,
448        O: Into<SelectOption>,
449    {
450        self.options = options.into_iter().map(|opt| opt.into().to_dto()).collect();
451        self
452    }
453
454    /// Replaces how the filter narrows the query. The closure receives the query and the value
455    /// of the chosen option.
456    #[must_use]
457    pub fn query<F>(mut self, modifier: F) -> Self
458    where
459        F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
460    {
461        self.custom = Some(Arc::new(modifier));
462        self
463    }
464
465    /// Finishes the filter. [`TableBuilder::filter`] does this for you.
466    #[must_use]
467    pub fn build(self) -> Filter<M> {
468        let apply_col = self.column.clone();
469        let apply = self.custom.unwrap_or_else(|| {
470            Arc::new(move |query: Builder<M>, value: &str| {
471                if value.is_empty() {
472                    query
473                } else {
474                    query.filter(col(apply_col.as_str()).eq(value.to_owned()))
475                }
476            })
477        });
478        Filter {
479            name: self.name,
480            label: self.label,
481            control: FilterKindDto::Select { options: self.options },
482            apply,
483        }
484    }
485}
486
487impl<M: Model> From<SelectFilterBuilder<M>> for Filter<M> {
488    fn from(builder: SelectFilterBuilder<M>) -> Self {
489        builder.build()
490    }
491}
492
493/// A view of a resource's table that narrows it to some of its records, such as the orders that
494/// are still pending. Tabs appear above the table as cards, each with a live count of its records.
495pub struct TableTab<M: Model> {
496    pub(crate) key: String,
497    pub(crate) label: String,
498    pub(crate) badge_color: Option<BadgeColor>,
499    pub(crate) apply: TabModifier<M>,
500}
501
502impl<M: Model> TableTab<M> {
503    /// A tab with a key for URLs, a label, and a closure that narrows the query to the tab's
504    /// records.
505    #[must_use]
506    pub fn new<F>(key: impl Into<String>, label: impl Into<String>, modifier: F) -> Self
507    where
508        F: Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
509    {
510        Self {
511            key: key.into(),
512            label: label.into(),
513            badge_color: None,
514            apply: Arc::new(modifier),
515        }
516    }
517
518    /// A tab that shows every record, usually the first one. Its key is `all`.
519    #[must_use]
520    pub fn all(label: impl Into<String>) -> Self {
521        Self::new("all", label, |q| q)
522    }
523
524    /// Shows a dot of this color before the tab's label, to match the badges of its records.
525    #[must_use]
526    pub fn color(mut self, color: BadgeColor) -> Self {
527        self.badge_color = Some(color);
528        self
529    }
530
531    pub(crate) fn to_dto(&self) -> TableTabSchemaDto {
532        TableTabSchemaDto {
533            key: self.key.clone(),
534            label: self.label.clone(),
535            badge_color: self.badge_color,
536        }
537    }
538}
539
540/// Builds a resource's table. [`AdminResource::table`](crate::AdminResource::table) receives an
541/// empty one, and returns it with columns and everything else the table should have.
542pub struct TableBuilder<M: Model> {
543    pub(crate) columns: Vec<Column>,
544    pub(crate) filters: Vec<Filter<M>>,
545    pub(crate) tabs: Vec<TableTab<M>>,
546    pub(crate) row_actions: Vec<RowAction<M>>,
547    pub(crate) bulk_actions: Vec<BulkAction<M>>,
548    pub(crate) default_sort: Option<DefaultSortDto>,
549    pub(crate) exportable: bool,
550    /// Columns of the model's table to search besides the `searchable` columns.
551    pub(crate) search_by: Vec<String>,
552}
553
554impl<M: Model> Default for TableBuilder<M> {
555    fn default() -> Self {
556        Self {
557            columns: Vec::new(),
558            filters: Vec::new(),
559            tabs: Vec::new(),
560            row_actions: Vec::new(),
561            bulk_actions: Vec::new(),
562            default_sort: None,
563            exportable: true,
564            search_by: Vec::new(),
565        }
566    }
567}
568
569impl<M: Model> TableBuilder<M> {
570    /// Adds a column. Columns appear in the order you add them.
571    #[must_use]
572    pub fn column(mut self, column: Column) -> Self {
573        self.columns.push(column);
574        self
575    }
576
577    /// Adds several columns.
578    #[must_use]
579    pub fn columns(mut self, columns: impl IntoIterator<Item = Column>) -> Self {
580        self.columns.extend(columns);
581        self
582    }
583
584    /// Adds a filter, shown as a chip above the table.
585    #[must_use]
586    pub fn filter(mut self, filter: impl Into<Filter<M>>) -> Self {
587        self.filters.push(filter.into());
588        self
589    }
590
591    /// Adds a tab above the table. The first tab you add is the one the table opens on.
592    #[must_use]
593    pub fn tab(mut self, tab: TableTab<M>) -> Self {
594        self.tabs.push(tab);
595        self
596    }
597
598    /// Adds an action on one record, offered in each row's menu and in the record's details.
599    #[must_use]
600    pub fn action(mut self, action: RowAction<M>) -> Self {
601        self.row_actions.push(action);
602        self
603    }
604
605    /// Adds an action on every selected record, offered once the user selects rows.
606    #[must_use]
607    pub fn bulk_action(mut self, action: BulkAction<M>) -> Self {
608        self.bulk_actions.push(action);
609        self
610    }
611
612    /// Sets the order the table opens in. Without one, the newest keys come first.
613    #[must_use]
614    pub fn default_sort(mut self, column: impl Into<String>, direction: SortDirection) -> Self {
615        self.default_sort = Some(DefaultSortDto {
616            column: column.into(),
617            direction,
618        });
619        self
620    }
621
622    /// Every database column a search looks in: the `searchable` columns, then the
623    /// [`search_by`](Self::search_by) columns.
624    pub(crate) fn search_columns(&self) -> Vec<&str> {
625        let mut columns: Vec<&str> = self
626            .columns
627            .iter()
628            .filter(|column| column.searchable)
629            .map(|column| column.name.as_str())
630            .collect();
631        for column in &self.search_by {
632            if !columns.contains(&column.as_str()) {
633                columns.push(column);
634            }
635        }
636        columns
637    }
638
639    /// Also search these columns of the model's table, which the table doesn't have to show.
640    ///
641    /// For example, a customers table that shows the email under the name, instead of in a
642    /// column of its own, can still be searched by email:
643    ///
644    /// ```ignore
645    /// table
646    ///     .column(Column::avatar("name").searchable().description_column("email"))
647    ///     .search_by(["email", "company"])
648    /// ```
649    #[must_use]
650    pub fn search_by(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
651        self.search_by.extend(columns.into_iter().map(Into::into));
652        self
653    }
654
655    /// Sets whether the user may export the table as CSV. They may by default.
656    ///
657    /// An export holds every record that matches the table's search, filters, and tab, with the
658    /// table's columns, and is streamed, so it may be of any size.
659    #[must_use]
660    pub fn exportable(mut self, exportable: bool) -> Self {
661        self.exportable = exportable;
662        self
663    }
664}