tablo_core/resource/record_page.rs
1//! [`RecordPage`]: a page of the app's own about one record of a resource, served under the
2//! record's URL, and the [`RecordPageDef`] it declares.
3
4use std::{any::TypeId, future::Future, sync::Arc};
5
6use topcoat::{
7 Result,
8 context::Cx,
9 icon::IconData,
10 view::{BoxView, View, ViewExt},
11};
12
13use super::{Resource, ResourceDef};
14use crate::{
15 DeclarationError, DeclarationErrorKind, Site, Text,
16 naming::{derived_id, kebab_case, sentence_case, slug_case, type_stem},
17};
18
19/// A page about one record of the resource `R`, served at `{list}/{key}/{slug}` and linked from
20/// the record's navigation: the tab bar its detail page, edit page, record pages and relation tabs
21/// share. The panel loads the record and checks the request may open the page;
22/// the page renders its body.
23///
24/// ```rust
25/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
26/// # struct Order { #[key] #[auto] id: uuid::Uuid, number: String }
27/// # struct OrderResource;
28/// # impl tablo_core::Resource for OrderResource {
29/// # type Model = Order;
30/// # type Form = tablo_core::NoForm<Order>;
31/// # fn declare() -> tablo_core::ResourceDef<Self> {
32/// # tablo_core::ResourceDef::new().record_page::<OrderHistoryPage>()
33/// # }
34/// # }
35/// use tablo_core::RecordPage;
36/// use topcoat::{
37/// Result,
38/// context::Cx,
39/// view::{View, view},
40/// };
41///
42/// struct OrderHistoryPage; // GET /admin/orders/{key}/order-history
43///
44/// impl RecordPage<OrderResource> for OrderHistoryPage {
45/// async fn render(cx: &Cx, order: Order) -> Result<impl View> {
46/// Ok(view! { <p>"Order " (order.number)</p> })
47/// }
48/// }
49/// ```
50///
51/// A request reaches [`render`](Self::render) only through the checks the detail page makes:
52/// sign-in, the request's tenant, the resource's [`query`](crate::ResourceDef::query), and
53/// [`Ability::View`](crate::Ability::View) of the record; then [`RecordPageDef::access`]. A
54/// trashed record opens too, as it does on its detail page.
55///
56/// A form the page renders posts to an app route, which none of those checks cover: the route
57/// loads the record through [`scoped_query`](crate::scoped_query) and asks the policy itself.
58pub trait RecordPage<R: Resource>: Sized + Send + Sync + 'static {
59 /// The page's slug, label, icon and access. Defaults to [`RecordPageDef::new`]: every
60 /// default.
61 fn declare() -> RecordPageDef<R::Model> {
62 RecordPageDef::new()
63 }
64
65 /// Renders the page's body under the record's header, from the record as the resource's
66 /// [`query`](crate::ResourceDef::query) loads it, with the relations its
67 /// [`include_unscoped`](crate::ResourceDef::include_unscoped) names and no other.
68 ///
69 /// The record arrives whole: a field a [`ResourceDef::field_access`] rule hides from the
70 /// request is still on it, so a page that shows such a field asks
71 /// [`can_view_field`](crate::can_view_field) first.
72 fn render(cx: &Cx, record: R::Model) -> impl Future<Output = Result<impl View>> + Send;
73}
74
75/// Whether the request's user may open a record page for one record.
76type AccessFn<M> = dyn Fn(&Cx, &M) -> bool + Send + Sync;
77
78/// What a [`RecordPage`] declares: its slug, label, icon and access. Every setting has a default.
79pub struct RecordPageDef<M> {
80 slug: Option<String>,
81 label: Option<Text>,
82 icon: Option<IconData>,
83 access: Arc<AccessFn<M>>,
84}
85
86impl<M> RecordPageDef<M> {
87 /// A def with every default: the slug and label from the page's type name, and access for
88 /// whoever may view the record.
89 pub fn new() -> Self {
90 Self::default()
91 }
92
93 /// The URL segment after the record's key: `"history"` serves the page at
94 /// `{list}/{key}/history`.
95 ///
96 /// Defaults to the page type's name without a trailing `Page`, kebab-cased:
97 /// `OrderHistoryPage` → `order-history`. Mounting refuses a slug that is not one URL path
98 /// segment, `edit`, `delete`, `-`, or one another record page of the resource takes.
99 #[must_use]
100 pub fn slug(mut self, slug: impl Into<String>) -> Self {
101 self.slug = Some(slug.into());
102 self
103 }
104
105 /// The label of the page's tab in the record's navigation, and of its breadcrumb.
106 ///
107 /// Defaults to the message `page-{name}` of the panel's catalogs, else the page type's name
108 /// without a trailing `Page`, in sentence case: `OrderHistoryPage` reads `page-order-history`,
109 /// else `Order history`.
110 #[must_use]
111 pub fn label(mut self, label: impl Into<Text>) -> Self {
112 self.label = Some(label.into());
113 self
114 }
115
116 /// The icon of the page's tab in the record's navigation.
117 #[must_use]
118 pub fn icon(mut self, icon: IconData) -> Self {
119 self.icon = Some(icon);
120 self
121 }
122
123 /// Whether the request's user may open the page for `record`, asked once the policy allows
124 /// [`Ability::View`](crate::Ability::View) of it. The panel answers 403 and links no page it
125 /// answers `false` for. Defaults to `true`.
126 ///
127 /// Read no relation of `record`: each page asking loads the record with relations of its own,
128 /// the record page with none.
129 #[must_use]
130 pub fn access(mut self, access: impl Fn(&Cx, &M) -> bool + Send + Sync + 'static) -> Self {
131 self.access = Arc::new(access);
132 self
133 }
134}
135
136impl<M> Default for RecordPageDef<M> {
137 fn default() -> Self {
138 Self {
139 slug: None,
140 label: None,
141 icon: None,
142 access: Arc::new(|_, _| true),
143 }
144 }
145}
146
147impl<M> std::fmt::Debug for RecordPageDef<M> {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.debug_struct("RecordPageDef")
150 .field("slug", &self.slug)
151 .field("label", &self.label)
152 .finish_non_exhaustive()
153 }
154}
155
156impl<R: Resource> ResourceDef<R> {
157 /// Adds the [`RecordPage`] `P` after the ones already declared, served at
158 /// `{list}/{key}/{slug}` for each record and linked from the record's navigation.
159 #[must_use]
160 pub fn record_page<P: RecordPage<R>>(mut self) -> Self {
161 self.record_pages.push(RecordPageEntry::new::<P>());
162 self
163 }
164}
165
166/// Renders a record page's body.
167type RenderFn<M> = for<'a> fn(&'a Cx, M) -> crate::BoxFuture<'a, Result<BoxView<'a>>>;
168
169/// A [`RecordPageDef`] with its defaults filled in for the page `P`, its type erased.
170pub(crate) struct RecordPageEntry<R: Resource> {
171 pub(crate) page: TypeId,
172 pub(crate) name: &'static str,
173 pub(crate) slug: String,
174 pub(crate) label: Text,
175 pub(crate) icon: Option<IconData>,
176 access: Arc<AccessFn<R::Model>>,
177 pub(crate) render: RenderFn<R::Model>,
178}
179
180impl<R: Resource> RecordPageEntry<R> {
181 fn new<P: RecordPage<R>>() -> Self {
182 let def = P::declare();
183 let stem = type_stem::<P>("Page");
184 let label = def.label.unwrap_or_else(|| {
185 let noun = sentence_case(stem);
186 Text::derived(derived_id("page", &slug_case(&noun)), noun)
187 });
188 Self {
189 page: TypeId::of::<P>(),
190 name: std::any::type_name::<P>(),
191 slug: def.slug.unwrap_or_else(|| kebab_case(stem)),
192 label,
193 icon: def.icon,
194 access: def.access,
195 render: render::<R, P>,
196 }
197 }
198
199 /// Whether the request's user may open the page for `record`, once `View` allows it.
200 pub(crate) fn admits(&self, cx: &Cx, record: &R::Model) -> bool {
201 (self.access)(cx, record)
202 }
203}
204
205impl<R: Resource> std::fmt::Debug for RecordPageEntry<R> {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 f.debug_struct("RecordPageEntry")
208 .field("name", &self.name)
209 .field("slug", &self.slug)
210 .finish_non_exhaustive()
211 }
212}
213
214fn render<R: Resource, P: RecordPage<R>>(
215 cx: &Cx,
216 record: R::Model,
217) -> crate::BoxFuture<'_, Result<BoxView<'_>>> {
218 Box::pin(async move { Ok(P::render(cx, record).await?.boxed()) })
219}
220
221/// The segments a record's own routes take after its key, which no record page may.
222pub(crate) const RESERVED_SEGMENTS: &[&str] = &["edit", "delete", "-"];
223
224/// Refuses a record page of `R` whose slug `validate` refuses as a URL path segment, is one of
225/// the record's own routes, or is another record page's. Answers whether it refused none.
226pub(crate) fn check<R: Resource>(
227 pages: &[RecordPageEntry<R>],
228 validate: impl Fn(&str) -> Option<DeclarationErrorKind>,
229 errors: &mut Vec<DeclarationError>,
230) -> bool {
231 let before = errors.len();
232 for (index, page) in pages.iter().enumerate() {
233 let slug = page.slug.clone();
234 let kind = if let Some(kind) = validate(&slug) {
235 kind
236 } else if RESERVED_SEGMENTS.contains(&slug.as_str()) {
237 DeclarationErrorKind::ReservedSlug { slug: slug.clone() }
238 } else if pages[..index].iter().any(|earlier| earlier.slug == slug) {
239 DeclarationErrorKind::DuplicateSlug { slug: slug.clone() }
240 } else {
241 continue;
242 };
243 errors.push(DeclarationError::of::<R>(Site::RecordPage(slug), kind));
244 }
245 errors.len() == before
246}