Skip to main content

tablo_core/
detail.rs

1//! A resource's detail page: the [`Detail`] declaration, its columns arranged in layout blocks.
2
3use std::sync::Arc;
4
5use toasty::stmt::{List, Query};
6use topcoat::{context::Cx, view::*};
7
8#[cfg(feature = "rich-text")]
9use crate::column::RichTextColumn;
10use crate::{
11    DeclarationErrorKind,
12    column::{
13        BooleanColumn, BoxColumn, ColorColumn, Column, ComputedColumn, CountColumn, DateColumn,
14        EmbeddedColumn, FileColumn, IconColumn, ImageColumn, ListColumn, RelationColumn,
15        RepeaterColumn, SelectColumn, TextColumn, TextInputColumn, ToggleColumn, include_relations,
16        restrict_relations, shows, unavailable_sources,
17    },
18    schema::{Grid, Group, HoldsTabs, Section, Tab, TabView, Tabs, tab_id, tab_view},
19};
20
21/// The declaration of a detail page: [`Column`]s, the same ones a [`Table`](crate::Table) lists,
22/// arranged in [`Section`], [`Group`], [`Grid`] and [`Tabs`] blocks.
23///
24/// ```rust
25/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
26/// # struct Author { #[key] #[auto] id: uuid::Uuid, name: String }
27/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
28/// # struct Post {
29/// #     #[key] #[auto] id: uuid::Uuid,
30/// #     title: String,
31/// #     featured: bool,
32/// #     author_id: uuid::Uuid,
33/// #     #[belongs_to(key = author_id, references = id)]
34/// #     author: toasty::Deferred<Author>,
35/// # }
36/// use tablo_core::{BooleanColumn, Detail, RelationColumn, Section, TextColumn, lens, relation};
37///
38/// Detail::new(Section::new("Post").columns((
39///     TextColumn::new(lens!(Post.title)),
40///     BooleanColumn::new(lens!(Post.featured)),
41///     RelationColumn::unscoped(relation!(Post.author), |_, a: &Author| a.name.clone()),
42/// )));
43/// ```
44///
45/// The detail page loads the relations its columns declare ([`Column::includes`]) and renders each
46/// column's [`entry`](Column::entry) for the record.
47pub struct Detail<M> {
48    nodes: Vec<Node<M>>,
49}
50
51/// A column's `entry` under the `data-entry` hook naming the column, which lays out nothing.
52fn entry<'a>(cx: &'a Cx, name: &str, entry: BoxView<'a>) -> BoxView<'a> {
53    let name = name.to_string();
54    view! { <div class="contents" data-entry=(name)>(entry)</div> }.boxed()
55}
56
57/// One block or column of a [`Detail`].
58enum Node<M> {
59    Column(BoxColumn<M>),
60    Section(Box<Section<Detail<M>>>),
61    Group(Box<Group<Detail<M>>>),
62    Grid(Box<Grid<Detail<M>>>),
63    /// A `Tabs` block, whose children are its `Tab` nodes.
64    Tabs(Box<Tabs<Detail<M>>>),
65    /// One tab, placed only in a `Tabs` block's children.
66    Tab(Box<Tab<Detail<M>>>),
67}
68
69impl<M> Detail<M> {
70    /// Declare a detail page of `children`: columns and blocks of them.
71    pub fn new(children: impl IntoDetail<M>) -> Self {
72        children.into_detail()
73    }
74
75    /// A detail page showing nothing, for a resource that serves no view page: mounting refuses
76    /// it while the view page is served, which
77    /// [`without_page(ResourcePage::View)`](crate::ResourceDef::without_page) turns off.
78    pub fn empty() -> Self {
79        Self { nodes: Vec::new() }
80    }
81
82    /// A detail page showing `columns`, in order, outside any block.
83    pub(crate) fn of_columns(columns: &[BoxColumn<M>]) -> Self {
84        Self {
85            nodes: columns.iter().cloned().map(Node::Column).collect(),
86        }
87    }
88
89    /// Whether the declaration shows nothing.
90    pub fn is_empty(&self) -> bool {
91        self.nodes.is_empty()
92    }
93
94    /// Append `column` after the declared columns and blocks.
95    pub fn column(mut self, column: impl Column<M> + 'static) -> Self {
96        self.nodes.push(Node::Column(Arc::new(column)));
97        self
98    }
99
100    /// Appends `other`'s columns and blocks after this one's.
101    fn append(&mut self, other: Self) {
102        self.nodes.extend(other.nodes);
103    }
104
105    /// Have each column reading its row that declares it reads none of the row's relations read
106    /// `bare(row)`, a copy of the row without them, when a column loads one.
107    pub(crate) fn read_bare(&mut self, bare: fn(&M) -> M)
108    where
109        M: toasty::schema::Model + 'static,
110    {
111        fn walk<M: toasty::schema::Model + 'static>(nodes: &mut [Node<M>], bare: fn(&M) -> M) {
112            for node in nodes {
113                match node {
114                    Node::Column(column) => {
115                        *column = crate::column::bare_column(column.clone(), bare);
116                    }
117                    Node::Section(section) => walk(&mut section.children.nodes, bare),
118                    Node::Group(group) => walk(&mut group.children.nodes, bare),
119                    Node::Grid(grid) => walk(&mut grid.children.nodes, bare),
120                    Node::Tabs(tabs) => walk(&mut tabs.children.nodes, bare),
121                    Node::Tab(tab) => walk(&mut tab.children.nodes, bare),
122                }
123            }
124        }
125        let loads = self
126            .columns()
127            .iter()
128            .any(|column| !column.includes().into_vec().is_empty());
129        if loads {
130            walk(&mut self.nodes, bare);
131        }
132    }
133
134    /// Every column, in the order the page renders them.
135    pub(crate) fn columns(&self) -> Vec<&BoxColumn<M>> {
136        fn walk<'d, M>(nodes: &'d [Node<M>], out: &mut Vec<&'d BoxColumn<M>>) {
137            for node in nodes {
138                match node {
139                    Node::Column(column) => out.push(column),
140                    Node::Section(section) => walk(&section.children.nodes, out),
141                    Node::Group(group) => walk(&group.children.nodes, out),
142                    Node::Grid(grid) => walk(&grid.children.nodes, out),
143                    Node::Tabs(tabs) => walk(&tabs.children.nodes, out),
144                    Node::Tab(tab) => walk(&tab.children.nodes, out),
145                }
146            }
147        }
148        let mut out = Vec::new();
149        walk(&self.nodes, &mut out);
150        out
151    }
152
153    /// Load the records `query` names as a page rendering this declaration reads them: with every
154    /// relation the columns declare, once each, and the related records the columns' sources show
155    /// the user checked, so [`render`](Self::render) shows only those. Pass the resource's scope,
156    /// as in `detail.load(cx, scoped_query::<R>(cx)?)`.
157    ///
158    /// # Errors
159    ///
160    /// A source's scope refusing the request, or a database failure.
161    pub async fn load(&self, cx: &Cx, query: Query<List<M>>) -> topcoat::Result<Vec<M>>
162    where
163        M: toasty::schema::Model + Send + Sync + 'static,
164    {
165        let mut db = crate::db::db(cx)?;
166        let records = self
167            .include_relations(query)
168            .exec(&mut db)
169            .await
170            .map_err(crate::error::unavailable)?;
171        self.restrict_relations(cx, &records, &mut db).await?;
172        Ok(records)
173    }
174
175    /// Include in `query` every relation the columns declare, once each.
176    pub(crate) fn include_relations(&self, query: Query<List<M>>) -> Query<List<M>>
177    where
178        M: toasty::schema::Model,
179    {
180        include_relations(query, self.columns())
181    }
182
183    /// Check which related records `records`, loaded through [`Self::include_relations`], hold
184    /// that the columns' sources show the user.
185    pub(crate) async fn restrict_relations(
186        &self,
187        cx: &Cx,
188        records: &[M],
189        ex: &mut dyn toasty::Executor,
190    ) -> topcoat::Result<()> {
191        restrict_relations(cx, self.columns(), records, ex).await
192    }
193
194    /// The columns labelling their records by a source the context's panel cannot load from.
195    pub(crate) fn unavailable_sources(&self, cx: &Cx) -> Vec<DeclarationErrorKind> {
196        unavailable_sources(cx, self.columns().into_iter().map(|c| &**c))
197    }
198
199    /// What is wrong with this declaration: each column whose path binds no single field.
200    pub fn declaration_errors(&self) -> Vec<DeclarationErrorKind> {
201        self.columns()
202            .into_iter()
203            .filter_map(|column| column.internals().misdeclared())
204            .collect()
205    }
206
207    /// Renders `record`'s entries in their blocks: each column's [`entry`](Column::entry),
208    /// read-only.
209    ///
210    /// The panel's detail page renders its view this way. A page of the app's own renders one for
211    /// a record it loaded through [`load`](Self::load): a scoped relation column over a record
212    /// loaded otherwise shows no related record.
213    pub fn render<'a>(&self, cx: &'a Cx, record: &M) -> BoxView<'a> {
214        self.render_without(cx, record, &[])
215    }
216
217    /// Renders as [`render`](Self::render) does, without the columns reading one of the `hidden`
218    /// fields, and without a block left with no column.
219    pub(crate) fn render_without<'a>(
220        &self,
221        cx: &'a Cx,
222        record: &M,
223        hidden: &[String],
224    ) -> BoxView<'a> {
225        self.render_in(cx, record, hidden, Inside::default())
226    }
227
228    /// Renders as [`render_without`](Self::render_without) does, `inside` the blocks around it.
229    fn render_in<'a>(
230        &self,
231        cx: &'a Cx,
232        record: &M,
233        hidden: &[String],
234        inside: Inside,
235    ) -> BoxView<'a> {
236        let framed = Inside {
237            panel: true,
238            ..inside
239        };
240        let views: Vec<BoxView<'a>> = self
241            .nodes
242            .iter()
243            .filter(|node| match node {
244                Node::Column(column) => shows(cx, &**column, hidden),
245                Node::Section(section) => {
246                    section.children.is_empty() || section.children.shows_any(cx, hidden)
247                }
248                Node::Group(group) => group.children.shows_any(cx, hidden),
249                Node::Grid(grid) => grid.children.shows_any(cx, hidden),
250                Node::Tabs(tabs) => tabs.children.shows_any(cx, hidden),
251                Node::Tab(tab) => tab.children.shows_any(cx, hidden),
252            })
253            .map(|node| match node {
254                Node::Column(column) => entry(cx, column.name(), column.entry(cx, record)),
255                Node::Section(section) => {
256                    let body = (!section.children.is_empty())
257                        .then(|| section.children.render_in(cx, record, hidden, framed));
258                    section.chrome_in(cx, body, inside.panel)
259                }
260                Node::Group(group) => {
261                    group.chrome(cx, group.children.render_in(cx, record, hidden, inside))
262                }
263                Node::Grid(grid) => {
264                    grid.chrome(cx, grid.children.render_in(cx, record, hidden, inside))
265                }
266                Node::Tabs(tabs) => {
267                    tabs.chrome(cx, tabs.children.render_tabs(cx, record, hidden, framed))
268                }
269                // A tab renders through its block, which lays out its trigger and its panel.
270                Node::Tab(tab) => tab.children.render_in(cx, record, hidden, inside),
271            })
272            .collect();
273        stack(cx, views)
274    }
275
276    /// Renders the tabs this `Tabs` block's children hold, `inside` the blocks around it, the
277    /// first shown one active, without those whose every column reads a `hidden` field.
278    fn render_tabs<'a>(
279        &self,
280        cx: &'a Cx,
281        record: &M,
282        hidden: &[String],
283        inside: Inside,
284    ) -> Vec<TabView<'a>> {
285        let depth = inside.tabs;
286        self.nodes
287            .iter()
288            .filter_map(|node| match node {
289                Node::Tab(tab) if tab.children.shows_any(cx, hidden) => Some(tab),
290                _ => None,
291            })
292            .enumerate()
293            .map(|(index, tab)| {
294                let id = tab
295                    .children
296                    .columns()
297                    .first()
298                    .map(|column| tab_id(&format!("detail-{}", column.name()), depth))
299                    .unwrap_or_default();
300                let body = tab.children.render_in(
301                    cx,
302                    record,
303                    hidden,
304                    Inside {
305                        tabs: depth + 1,
306                        ..inside
307                    },
308                );
309                tab_view(cx, &id, tab.face(), index == 0, false, body)
310            })
311            .collect()
312    }
313
314    /// Whether any column shows to `cx`, which may not view the `hidden` fields.
315    fn shows_any(&self, cx: &Cx, hidden: &[String]) -> bool {
316        self.columns()
317            .into_iter()
318            .any(|column| shows(cx, &**column, hidden))
319    }
320
321    /// The names of the columns that do not say what they read.
322    pub(crate) fn undeclared_reads(&self) -> Vec<&str> {
323        self.columns()
324            .into_iter()
325            .filter(|column| column.reads().is_none())
326            .map(|column| column.name())
327            .collect()
328    }
329}
330
331/// Where a block renders: how many tabs hold it, which tells a nested block's DOM ids from its
332/// outer tab's, and whether a panel holds it, which makes a section a heading.
333#[derive(Debug, Clone, Copy, Default)]
334struct Inside {
335    tabs: usize,
336    panel: bool,
337}
338
339/// `views` one after another. A free function, so tablo-core compiles the view once rather than
340/// once for each model with a detail page.
341fn stack<'a>(cx: &'a Cx, views: Vec<BoxView<'a>>) -> BoxView<'a> {
342    view! {
343        for v in views {
344            (v)
345        }
346    }
347    .boxed()
348}
349
350impl<M> Default for Detail<M> {
351    fn default() -> Self {
352        Self::empty()
353    }
354}
355
356impl<M> std::fmt::Debug for Detail<M> {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        f.debug_struct("Detail")
359            .field(
360                "columns",
361                &self
362                    .columns()
363                    .into_iter()
364                    .map(|column| column.name())
365                    .collect::<Vec<_>>(),
366            )
367            .finish()
368    }
369}
370
371/// Converts a column, a layout block of columns, a tuple of either, or a [`Detail`] into a
372/// [`Detail`].
373///
374/// Every built-in column converts, as does a boxed `Arc<dyn Column<M>>`;
375/// [`Detail::column`] appends any other [`Column`]. An app's column type joins a block as the
376/// built-in ones do by implementing this trait:
377///
378/// ```rust
379/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
380/// # struct User { #[key] #[auto] id: uuid::Uuid, name: String }
381/// # struct Initials;
382/// # use topcoat::context::Cx;
383/// # impl tablo_core::extend::Column<User> for Initials {
384/// #     fn name(&self) -> &str { "initials" }
385/// #     fn label(&self) -> tablo_core::Text { "Initials".into() }
386/// #     fn text(&self, _cx: &Cx, row: &User) -> String { row.name.clone() }
387/// # }
388/// use tablo_core::{Detail, IntoDetail, Section};
389///
390/// impl IntoDetail<User> for Initials {
391///     fn into_detail(self) -> Detail<User> {
392///         Detail::empty().column(self)
393///     }
394/// }
395///
396/// Detail::new(Section::new("User").columns(Initials));
397/// ```
398pub trait IntoDetail<M> {
399    fn into_detail(self) -> Detail<M>;
400}
401
402impl<M> IntoDetail<M> for Detail<M> {
403    fn into_detail(self) -> Detail<M> {
404        self
405    }
406}
407
408impl<M> IntoDetail<M> for () {
409    fn into_detail(self) -> Detail<M> {
410        Detail::empty()
411    }
412}
413
414impl<M> IntoDetail<M> for BoxColumn<M> {
415    fn into_detail(self) -> Detail<M> {
416        Detail {
417            nodes: vec![Node::Column(self)],
418        }
419    }
420}
421
422/// The [`IntoDetail`] impls of the built-in columns: each is one column.
423macro_rules! column_details {
424    ($($ty:ident<$($g:ident),+>),+ $(,)?) => {
425        $(
426            impl<$($g),+> IntoDetail<M> for $ty<$($g),+>
427            where
428                Self: Column<M> + 'static,
429            {
430                fn into_detail(self) -> Detail<M> {
431                    Detail::empty().column(self)
432                }
433            }
434        )+
435    };
436}
437
438column_details!(
439    TextColumn<M, T>,
440    DateColumn<M, T>,
441    ComputedColumn<M>,
442    RelationColumn<M>,
443    CountColumn<M>,
444    BooleanColumn<M>,
445    FileColumn<M>,
446    ColorColumn<M, T>,
447    IconColumn<M, T>,
448    ImageColumn<M, T>,
449    ToggleColumn<M>,
450    SelectColumn<M, T>,
451    TextInputColumn<M, T>,
452    EmbeddedColumn<M, T>,
453    ListColumn<M, T>,
454    RepeaterColumn<M, T>,
455);
456#[cfg(feature = "rich-text")]
457column_details!(RichTextColumn<M, T>);
458
459/// The `columns` builders of the layout blocks: each holds a detail page's columns and blocks.
460macro_rules! block_columns {
461    ($($ty:ident),+ $(,)?) => {
462        $(
463            impl $ty<()> {
464                /// Holds a detail page's columns and blocks.
465                pub fn columns<M>(self, children: impl IntoDetail<M>) -> $ty<Detail<M>> {
466                    self.holding(children.into_detail())
467                }
468            }
469        )+
470    };
471}
472
473block_columns!(Section, Group, Grid, Tab);
474
475impl<M> HoldsTabs for Detail<M> {
476    fn push_tab(&mut self, tab: Tab<Self>) {
477        self.nodes.push(Node::Tab(Box::new(tab)));
478    }
479}
480
481impl<M> IntoDetail<M> for Tabs<Detail<M>> {
482    fn into_detail(self) -> Detail<M> {
483        Detail {
484            nodes: vec![Node::Tabs(Box::new(self))],
485        }
486    }
487}
488
489/// The single-node [`IntoDetail`] impls of every layout block, holding columns or nothing.
490macro_rules! block_details {
491    ($($ty:ident),+ $(,)?) => {
492        $(
493            impl<M> IntoDetail<M> for $ty<Detail<M>> {
494                fn into_detail(self) -> Detail<M> {
495                    Detail {
496                        nodes: vec![Node::$ty(Box::new(self))],
497                    }
498                }
499            }
500
501            impl<M> IntoDetail<M> for $ty<()> {
502                fn into_detail(self) -> Detail<M> {
503                    self.holding(Detail::empty()).into_detail()
504                }
505            }
506        )+
507    };
508}
509
510block_details!(Section, Group, Grid);
511
512/// The tuple impls of [`IntoDetail`], one arity per invocation.
513macro_rules! into_detail_tuples {
514    ($($T:ident => $v:ident),+ $(,)?) => {
515        impl<M, $($T),+> IntoDetail<M> for ($($T,)+)
516        where
517            $($T: IntoDetail<M>,)+
518        {
519            fn into_detail(self) -> Detail<M> {
520                let ($($v,)+) = self;
521                let mut detail = Detail::empty();
522                $( detail.append($v.into_detail()); )+
523                detail
524            }
525        }
526    };
527}
528
529into_detail_tuples!(A => a);
530into_detail_tuples!(A => a, B => b);
531into_detail_tuples!(A => a, B => b, C => c);
532into_detail_tuples!(A => a, B => b, C => c, D => d);
533into_detail_tuples!(A => a, B => b, C => c, D => d, E => e);
534into_detail_tuples!(A => a, B => b, C => c, D => d, E => e, F => f);
535into_detail_tuples!(A => a, B => b, C => c, D => d, E => e, F => f, G => g);
536into_detail_tuples!(
537    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h
538);
539into_detail_tuples!(
540    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i
541);
542into_detail_tuples!(
543    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j
544);
545into_detail_tuples!(
546    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k
547);
548into_detail_tuples!(
549    A => a, B => b, C => c, D => d, E => e, F => f, G => g, H => h, I => i, J => j, K => k, L => l
550);
551
552#[cfg(test)]
553mod tests;