Skip to main content

tablo_core/panel/list/
shown.rs

1//! The list state a request's list page shows, which [`list_query`] reads for its widgets.
2
3use std::{
4    any::TypeId,
5    sync::{Arc, OnceLock},
6};
7
8use toasty::stmt::{List, Query};
9use topcoat::{
10    Result,
11    context::{Cx, try_context},
12    router::error::forbidden,
13};
14
15use crate::{panel::gate::gate, policy::Ability, resource::Resource, table::TableState};
16
17/// The resource whose list page the request renders, and the state that page shows. The panel
18/// puts an empty one on each request, and the list page fills it before its widgets render.
19#[derive(Clone, Default)]
20pub(crate) struct ShownList(Arc<OnceLock<(TypeId, TableState)>>);
21
22impl ShownList {
23    /// Record that the request renders `R`'s list in `state`. A request renders one list page,
24    /// so a second record changes nothing.
25    pub(crate) fn record<R: Resource>(cx: &Cx, state: &TableState) {
26        if let Some(Self(shown)) = try_context::<Self>(cx) {
27            let _ = shown.set((TypeId::of::<R>(), state.clone()));
28        }
29    }
30
31    /// The state `R`'s list page shows in this request; `None` outside it.
32    fn of<R: Resource>(cx: &Cx) -> Option<&TableState> {
33        let Self(shown) = try_context::<Self>(cx)?;
34        let (resource, state) = shown.get()?;
35        (*resource == TypeId::of::<R>()).then_some(state)
36    }
37}
38
39/// `R`'s records as its list shows them in this request: the [`scoped_query`](crate::scoped_query)
40/// the list reads, narrowed by its tab, search and filters, unordered. A
41/// [`list_widget`](crate::ResourceDef::list_widget) reading it shows figures that follow the list,
42/// and reruns with it as the reader searches, filters or switches tabs.
43///
44/// Outside `R`'s list page, as on a dashboard, it reads the list's first tab with no search or
45/// filter. Like the list, it leaves out a filter it cannot apply, and the trashed records unless
46/// the list's trash control asks for them. Count what it selects with
47/// [`db::count`](crate::db::count).
48///
49/// ```rust,no_run
50/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
51/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String, published: bool }
52/// # struct PostResource;
53/// # impl tablo_core::Resource for PostResource {
54/// #     type Model = Post;
55/// #     type Form = tablo_core::NoForm<Post>;
56/// #     fn declare() -> tablo_core::ResourceDef<Self> { tablo_core::ResourceDef::new() }
57/// # }
58/// use tablo_core::{Stat, Widget, db, list_query};
59/// use topcoat::{Result, context::Cx, view::View};
60///
61/// struct Published;
62///
63/// impl Widget for Published {
64///     async fn render(cx: &Cx) -> Result<impl View> {
65///         let published = list_query::<PostResource>(cx)
66///             .await?
67///             .filter(Post::fields().published().eq(true));
68///         let count = db::count(cx, published).await?;
69///         Ok(tablo_core::stats(
70///             cx,
71///             vec![Stat::new("Published", count.to_string())],
72///         ))
73///     }
74/// }
75/// ```
76///
77/// A tab and a filter can ask one column for two values. Toasty then folds the query's filter to
78/// `false`, and panics planning an `include` over it: count the query, or ask it for a row, before
79/// loading its rows with their relations.
80///
81/// # Errors
82///
83/// 403 when the request may not open `R`'s list, the check [`can_list`](crate::can_list) makes,
84/// which fails the whole page the widget is on: a widget on another page asks `can_list` first.
85/// The database failing a filter's check.
86pub async fn list_query<R: Resource>(cx: &Cx) -> Result<Query<List<R::Model>>> {
87    let resource = gate::<R>(cx)?;
88    if !resource.can(cx, Ability::ViewAny) {
89        return Err(forbidden().into());
90    }
91    let table = resource.table_for(cx);
92    let state = table.normalize_state(&ShownList::of::<R>(cx).cloned().unwrap_or_default());
93    let refused = table.refused_filters(cx, &state).await?;
94    let query = resource.list_query(cx, &state)?;
95    Ok(table.narrow(cx, &crate::db::db(cx)?, query, &state, &refused))
96}