Skip to main content

tablo_core/
column.rs

1//! Columns, which a [`Table`](crate::Table) lists and a [`Detail`](crate::Detail) shows: the
2//! [`Column`] trait, the built-in [`TextColumn`], [`DateColumn`], [`ComputedColumn`],
3//! [`RelationColumn`], [`CountColumn`], [`BooleanColumn`], [`FileColumn`], [`ColorColumn`],
4//! [`ImageColumn`], [`IconColumn`], [`EmbeddedColumn`], [`ListColumn`], [`RepeaterColumn`] and
5//! [`RichTextColumn`], the [`ToggleColumn`], [`SelectColumn`] and [`TextInputColumn`] that edit
6//! their field in a table's cell, and the [`IntoColumns`] seam.
7//!
8//! The module sits below both: `table` re-exports it, and `detail` implements
9//! [`IntoDetail`](crate::IntoDetail) for each built-in column.
10
11use std::sync::Arc;
12
13use derive_where::derive_where;
14use toasty::stmt::{Expr, List, OrderByExpr, Path, Query};
15use topcoat::{context::Cx, view::*};
16
17use crate::{display::Alignment, schema::Binding};
18
19/// The `label` and `width` builders of a column over a [`ColumnBase`], inside its inherent impl.
20macro_rules! base_builders {
21    () => {
22        /// Replace the label the field's name gives it.
23        pub fn label(mut self, label: impl Into<$crate::Text>) -> Self {
24            self.base.label = Some(label.into());
25            self
26        }
27
28        /// Declare this column's width.
29        pub fn width(mut self, width: $crate::column::ColumnWidth) -> Self {
30            self.base.width = width;
31            self
32        }
33
34        toggle_builders!(base.toggle);
35    };
36    (sortable) => {
37        base_builders!();
38
39        /// Make the header a sort link.
40        pub fn sortable(mut self) -> Self {
41            self.sortable = true;
42            self
43        }
44    };
45}
46
47/// The `toggleable` and `hidden_by_default` builders of a column holding its [`ColumnToggle`] at
48/// the field path given, inside its inherent impl.
49macro_rules! toggle_builders {
50    ($($field:ident).+) => {
51        /// Let each reader hide this column from their list; it starts shown.
52        pub fn toggleable(mut self) -> Self {
53            self.$($field).+ = $crate::column::ColumnToggle::ShownByDefault;
54            self
55        }
56
57        /// Let each reader show this column in their list; it starts hidden.
58        pub fn hidden_by_default(mut self) -> Self {
59            self.$($field).+ = $crate::column::ColumnToggle::HiddenByDefault;
60            self
61        }
62    };
63}
64
65/// The [`Column`] methods a column over a [`ColumnBase`] answers from it, inside its `Column`
66/// impl, and the accessor to its [`ColumnInternals`] impl; `reads` leaves `reads` to the column.
67macro_rules! base_column_methods {
68    () => {
69        base_column_methods!(reads);
70
71        fn reads(&self) -> Option<$crate::lens::Reads<M>> {
72            Some(self.base.reads())
73        }
74    };
75    (reads) => {
76        fn name(&self) -> &str {
77            self.base.name()
78        }
79
80        fn label(&self) -> $crate::Text {
81            self.base.label()
82        }
83
84        fn column_width(&self) -> $crate::column::ColumnWidth {
85            self.base.width
86        }
87
88        fn toggle(&self) -> $crate::column::ColumnToggle {
89            self.base.toggle
90        }
91
92        fn internals(&self) -> &dyn $crate::column::ColumnInternals<M> {
93            self
94        }
95    };
96}
97
98/// The [`ColumnInternals`] methods a column over a [`ColumnBase`] answers from it, inside its
99/// `ColumnInternals` impl: it reads no related record; `binding` adds the binding's
100/// `misdeclared`, and `binding, related` leaves `related` to the column.
101macro_rules! base_internals {
102    () => {
103        fn related(&self) -> $crate::column::Related {
104            $crate::column::Related::None
105        }
106    };
107    (binding) => {
108        base_internals!();
109        base_internals!(binding, related);
110    };
111    (binding, related) => {
112        fn misdeclared(&self) -> Option<$crate::DeclarationErrorKind> {
113            self.base.binding.misdeclared()
114        }
115    };
116}
117
118/// A closure reading a value off a row or a field for a request: a cell's color, icon, link or
119/// tooltip, which may read the request's locale or user.
120pub(crate) type ReadFn<T, V> = Arc<dyn Fn(&Cx, &T) -> V + Send + Sync>;
121
122fn sort_order<M, T>(path: &Path<M, T>, descending: bool) -> OrderByExpr {
123    if descending {
124        path.clone().desc()
125    } else {
126        path.clone().asc()
127    }
128}
129
130mod related;
131pub use related::Related;
132mod bare;
133mod boolean;
134mod cell;
135mod color;
136mod computed;
137mod date;
138mod editable;
139mod embedded;
140mod file;
141mod icon;
142mod image;
143mod into_columns;
144mod list;
145mod relation;
146mod repeater;
147#[cfg(feature = "rich-text")]
148mod rich_text;
149mod text;
150
151pub(crate) use bare::{bare_column, reads_own_fields};
152pub use boolean::BooleanColumn;
153pub(crate) use cell::link_href;
154pub use color::ColorColumn;
155pub(crate) use color::is_css_color;
156pub use computed::ComputedColumn;
157pub use date::{DateColumn, DateValue};
158pub(crate) use editable::Editor;
159pub use editable::{SelectColumn, TextInputColumn, ToggleColumn};
160pub use embedded::EmbeddedColumn;
161pub use file::FileColumn;
162pub use icon::IconColumn;
163pub use image::ImageColumn;
164pub use into_columns::IntoColumns;
165pub use list::ListColumn;
166pub use relation::{CountColumn, RelationColumn, RelationLens, ToOneRelation};
167pub use repeater::RepeaterColumn;
168#[cfg(feature = "rich-text")]
169pub use rich_text::RichTextColumn;
170pub(crate) use sealed::ColumnInternals;
171#[cfg(test)]
172use text::escape_like_pattern;
173pub(crate) use text::{LIKE_ESCAPE, escape_like};
174pub use text::{TextColumn, contains_expr};
175
176mod sealed {
177    use topcoat::{context::Cx, view::BoxView};
178
179    use super::{Editor, Related};
180
181    /// The [`Column`](super::Column) methods only the framework answers, through
182    /// [`Column::internals`](super::Column::internals). It lives in a private module, so a column
183    /// outside tablo cannot implement it and answers the [`Defaults`].
184    pub trait ColumnInternals<M>: Send + Sync {
185        /// Check which related records the column's includes loaded into `rows` the related
186        /// resource shows the user, before any cell renders: a cell shows only those. Every
187        /// loader that applies the includes runs it through `ex`, the executor that loaded the
188        /// rows.
189        fn restrict<'a>(
190            &'a self,
191            _cx: &'a Cx,
192            _rows: &'a [M],
193            _ex: &'a mut dyn toasty::Executor,
194        ) -> crate::BoxFuture<'a, topcoat::Result<()>> {
195            Box::pin(async { Ok(()) })
196        }
197
198        /// Whether the column shows a field of a related record that the related resource's
199        /// [`field_access`](crate::ResourceDef::field_access) hides from `cx`: a panel drops it
200        /// then, as it drops one reading a hidden field of the row.
201        fn masked(&self, _cx: &Cx) -> bool {
202            false
203        }
204
205        /// What the column reads of the related records it loads: see [`Related`]. A column
206        /// answers [`Related::Row`] unless it says otherwise, since a closure reading its row may
207        /// reach any relation the page loads.
208        fn related(&self) -> Related {
209            Related::Row
210        }
211
212        /// What is wrong with this column's declaration.
213        fn misdeclared(&self) -> Option<crate::DeclarationErrorKind> {
214            None
215        }
216
217        /// The source the column labels its records by, when the context's panel cannot load
218        /// from it.
219        fn unavailable_source(&self, _cx: &Cx) -> Option<&'static str> {
220            None
221        }
222
223        /// The control the column edits its field with in a table's cell, if it does: the mount
224        /// checks the resource's form edits the field the column names with it.
225        fn edits(&self) -> Option<Editor> {
226            None
227        }
228
229        /// The options a [`Editor::Select`] offers, each a value and its label: the mount checks
230        /// the form's choice offers the same.
231        fn edit_options(&self) -> Vec<(String, crate::Text)> {
232            Vec::new()
233        }
234
235        /// The control editing `row`'s field, posting the field's form key, which a table renders
236        /// in place of the cell where the user may change the field. `None` renders the cell.
237        fn editor<'a>(&self, _cx: &'a Cx, _row: &M) -> Option<BoxView<'a>> {
238            None
239        }
240    }
241
242    /// What a column outside tablo answers.
243    pub struct Defaults;
244
245    impl<M> ColumnInternals<M> for Defaults {}
246}
247
248/// One column of a table or a [`Detail`](crate::Detail) declares its label, its value read off
249/// the record, and its query predicates.
250///
251/// ```rust
252/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
253/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String }
254/// # use tablo_core::{Text, extend::Column};
255/// # use topcoat::context::Cx;
256/// struct Initials;
257///
258/// impl Column<User> for Initials {
259///     fn name(&self) -> &str {
260///         "initials"
261///     }
262///     fn label(&self) -> Text {
263///         "Initials".into()
264///     }
265///     fn text(&self, _cx: &Cx, row: &User) -> String {
266///         row.name
267///             .split_whitespace()
268///             .filter_map(|w| w.chars().next())
269///             .collect()
270///     }
271/// }
272/// ```
273///
274/// Only [`name`](Self::name), [`label`](Self::label) and
275/// [`text`](Self::text) are required.
276pub trait Column<M>: Send + Sync {
277    /// The column's identifier, distinct within its table.
278    fn name(&self) -> &str;
279
280    /// The header text.
281    fn label(&self) -> crate::Text;
282
283    /// The row's value as plain text.
284    fn text(&self, cx: &Cx, row: &M) -> String;
285
286    /// The row's table cell.
287    fn cell<'a>(&self, cx: &'a Cx, row: &M) -> BoxView<'a> {
288        crate::schema::value_cell(cx, &self.text(cx, row))
289    }
290
291    /// The record's entry on a detail page: the [`label`](Self::label) over the
292    /// [`cell`](Self::cell).
293    fn entry<'a>(&self, cx: &'a Cx, row: &M) -> BoxView<'a> {
294        crate::schema::read_only(cx, &self.label(), self.cell(cx, row))
295    }
296
297    /// The width the column claims.
298    fn column_width(&self) -> ColumnWidth {
299        ColumnWidth::Auto
300    }
301
302    /// Whether each reader may hide or show the column in their list, and how it starts. A
303    /// detail page shows every column.
304    fn toggle(&self) -> ColumnToggle {
305        ColumnToggle::Fixed
306    }
307
308    /// Where the header and the cells align their content.
309    fn alignment(&self) -> Alignment {
310        Alignment::Start
311    }
312
313    /// The predicate a search for `term` adds, or `None` when the column does not join the table's
314    /// search. A column that joins it answers `Some` for every non-empty, trimmed `term`.
315    fn search_expr(&self, _term: &str) -> Option<Expr<bool>> {
316        None
317    }
318
319    /// The ordering a sort on this column applies, or `None` when the header does not link to a
320    /// sort on it. A sortable column answers `Some` either way.
321    fn order_by(&self, _descending: bool) -> Option<OrderByExpr> {
322        None
323    }
324
325    /// The relations [`text`](Self::text), [`cell`](Self::cell) and [`entry`](Self::entry) read.
326    fn includes(&self) -> Includes<M> {
327        Includes::new()
328    }
329
330    /// The fields of the row [`text`](Self::text), [`cell`](Self::cell),
331    /// [`entry`](Self::entry), [`search_expr`](Self::search_expr) and
332    /// [`order_by`](Self::order_by) read, or `None` when the column does not say.
333    ///
334    /// A panel drops a column reading a field
335    /// [`field_access`](crate::ResourceDef::field_access) hides from the user, and refuses to
336    /// mount a panel restricting a field whose columns answer `None`. The built-in columns
337    /// answer their own field.
338    fn reads(&self) -> Option<crate::lens::Reads<M>> {
339        None
340    }
341
342    /// The framework's own column methods. The trait is sealed: a column outside tablo answers
343    /// their defaults.
344    #[doc(hidden)]
345    fn internals(&self) -> &dyn ColumnInternals<M> {
346        &sealed::Defaults
347    }
348}
349
350/// The relations a [`Column`] reads off its row.
351#[derive_where(Clone, Debug, Default)]
352pub struct Includes<M>(
353    Vec<crate::toasty_compat::UntypedInclude>,
354    #[derive_where(skip(Debug))] std::marker::PhantomData<fn() -> M>,
355);
356
357impl<M> Includes<M> {
358    /// No relation.
359    pub fn new() -> Self {
360        Self::default()
361    }
362
363    /// Add `relation`.
364    pub fn with<T>(mut self, relation: impl Into<toasty::stmt::Include<M, T>>) -> Self {
365        let include: crate::toasty_compat::UntypedInclude = relation.into().into();
366        if !self.0.contains(&include) {
367            self.0.push(include);
368        }
369        self
370    }
371
372    /// The relations, in the order they were added.
373    pub(crate) fn into_vec(self) -> Vec<crate::toasty_compat::UntypedInclude> {
374        self.0
375    }
376}
377
378/// One [`UnregisteredLabelSource`](DeclarationErrorKind::UnregisteredLabelSource) per column
379/// labelling its records by a source `cx`'s panel cannot load from.
380pub(crate) fn unavailable_sources<'c, M: 'c>(
381    cx: &Cx,
382    columns: impl IntoIterator<Item = &'c dyn Column<M>>,
383) -> Vec<crate::DeclarationErrorKind> {
384    columns
385        .into_iter()
386        .filter_map(|column| {
387            column.internals().unavailable_source(cx).map(|source| {
388                crate::DeclarationErrorKind::UnregisteredLabelSource {
389                    column: column.name().to_string(),
390                    source,
391                }
392            })
393        })
394        .collect()
395}
396
397pub(crate) fn include_relations<'c, M>(
398    mut query: Query<List<M>>,
399    columns: impl IntoIterator<Item = &'c BoxColumn<M>>,
400) -> Query<List<M>>
401where
402    M: toasty::schema::Model + 'c,
403{
404    let mut seen: Vec<crate::toasty_compat::UntypedInclude> = Vec::new();
405    for include in columns.into_iter().flat_map(|c| c.includes().into_vec()) {
406        if !seen.contains(&include) {
407            query = query.include(include.clone());
408            seen.push(include);
409        }
410    }
411    query
412}
413
414/// Run each column's [`restrict`](ColumnInternals::restrict) over `rows`, which a query through
415/// [`include_relations`] loaded.
416pub(crate) async fn restrict_relations<'c, M>(
417    cx: &Cx,
418    columns: impl IntoIterator<Item = &'c BoxColumn<M>>,
419    rows: &[M],
420    ex: &mut dyn toasty::Executor,
421) -> topcoat::Result<()>
422where
423    M: 'c,
424{
425    for column in columns {
426        column.internals().restrict(cx, rows, &mut *ex).await?;
427    }
428    Ok(())
429}
430
431/// What a column over one field declares beside its lens: the field's binding, the declared label
432/// and the width.
433#[derive(Clone, Debug)]
434struct ColumnBase {
435    binding: Binding,
436    /// The declared label, over the binding's.
437    label: Option<crate::Text>,
438    width: ColumnWidth,
439    toggle: ColumnToggle,
440}
441
442impl ColumnBase {
443    /// Bind `path`, with no declared label.
444    fn new<M, T>(path: &Path<M, T>, width: ColumnWidth) -> Self
445    where
446        M: toasty::schema::Model,
447    {
448        Self {
449            binding: Binding::of(path),
450            label: None,
451            width,
452            toggle: ColumnToggle::Fixed,
453        }
454    }
455
456    fn name(&self) -> &str {
457        self.binding.name()
458    }
459
460    fn label(&self) -> crate::Text {
461        self.label.clone().unwrap_or_else(|| self.binding.label())
462    }
463
464    /// The field the column reads.
465    fn reads<M>(&self) -> crate::lens::Reads<M> {
466        self.binding.reads()
467    }
468}
469
470/// How a [`Column`] takes the table's width.
471///
472/// The table lays out automatically: each column is as wide as its content, and the first column
473/// that [`Grow`](Self::Grow)s takes the width left over. A table wider than its card scrolls
474/// sideways.
475#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
476#[non_exhaustive]
477pub enum ColumnWidth {
478    /// As wide as its content, on one line: a status, date, number or boolean.
479    #[default]
480    Auto,
481    /// As wide as its content up to 20rem, past which a value truncates; the first growing column
482    /// also takes the table's spare width. The default for text and relation columns.
483    Grow,
484    /// Wrap the content onto several lines, between 12rem and 28rem wide.
485    Wrap,
486    /// Exactly this many rem; a value past that truncates.
487    Rem(u8),
488}
489
490/// Whether each reader may hide a [`Column`] from their list, and whether it starts shown.
491///
492/// A list with a toggleable column renders a Columns menu in its toolbar, whose Apply keeps the
493/// checked columns and Reset restores the defaults. A panel keeps each signed-in user's choice per
494/// resource, in the [`ColumnPreference`](crate::auth::ColumnPreference) model, so the relation
495/// tables over a resource show what its list shows; a column added later, or whose default changes,
496/// takes its default until the reader picks otherwise. Search, sort and export still read every
497/// column. A panel without auth, and a table a page renders with
498/// [`wired_table`](crate::wired_table), render no menu and show the defaults.
499///
500/// ```rust
501/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
502/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String, slug: String }
503/// use tablo_core::{TextColumn, lens};
504///
505/// TextColumn::new(lens!(Post.title)).toggleable();
506/// TextColumn::new(lens!(Post.slug)).hidden_by_default();
507/// ```
508#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
509pub enum ColumnToggle {
510    /// Always shown.
511    #[default]
512    Fixed,
513    /// Shown until the reader hides it: `toggleable()`.
514    ShownByDefault,
515    /// Hidden until the reader shows it: `hidden_by_default()`.
516    HiddenByDefault,
517}
518
519impl ColumnToggle {
520    /// Whether the reader may hide or show the column.
521    pub(crate) fn is_toggleable(self) -> bool {
522        self != Self::Fixed
523    }
524}
525
526impl ColumnWidth {
527    /// The classes of the box a body cell wraps its content in, if any.
528    pub(crate) fn content_class(self) -> Option<&'static str> {
529        match self {
530            Self::Auto => None,
531            Self::Grow => Some("max-w-xs truncate"),
532            Self::Wrap => Some("min-w-48 max-w-md whitespace-normal"),
533            Self::Rem(_) => Some("truncate"),
534        }
535    }
536
537    /// The `style` of a cell of this width, header and body alike.
538    pub(crate) fn style(self) -> Option<String> {
539        match self {
540            Self::Rem(rem) => Some(format!("width: {rem}rem; max-width: {rem}rem")),
541            Self::Auto | Self::Grow | Self::Wrap => None,
542        }
543    }
544}
545
546/// Whether `column` joins a table's search: it answers a term, as it answers every one then.
547pub(crate) fn searches<M>(column: &dyn Column<M>) -> bool {
548    column.search_expr("a").is_some()
549}
550
551/// Whether a table's header links to a sort on `column`.
552pub(crate) fn sorts<M>(column: &dyn Column<M>) -> bool {
553    column.order_by(false).is_some()
554}
555
556/// A table's columns, as the table stores them.
557pub(crate) type BoxColumn<M> = Arc<dyn Column<M>>;
558
559/// Whether `column` shows to `cx`, which may not view the row's `hidden` fields: it reads none of
560/// them, and no field of a related record its resource hides from `cx`.
561pub(crate) fn shows<M>(cx: &Cx, column: &dyn Column<M>, hidden: &[String]) -> bool {
562    crate::lens::shows(column.reads(), hidden) && !column.internals().masked(cx)
563}
564
565#[cfg(test)]
566mod tests;