Skip to main content

tablo_core/resource/
def.rs

1//! [`ResourceDef`]: everything a resource declares, as one value.
2
3use std::sync::Arc;
4
5use toasty::stmt::{Expr, Path};
6use topcoat::{context::Cx, icon::IconData};
7
8use super::{Action, Actions, HeaderActions, Relation, Resource, SoftDelete};
9use crate::{
10    DeclarationErrorKind, Lens,
11    detail::Detail,
12    form::FormScalar,
13    navigation::NavigationItem,
14    policy::{Ability, Deny, Policy},
15    schema::Schema,
16    table::Table,
17    tenancy::Tenancy,
18    toasty_compat::model::{self, ModelPath},
19};
20
21mod header_actions;
22
23/// What a [`Resource`] declares, from its names, policy and tenancy to its pages and actions.
24///
25/// [`Resource::declare`] returns one, and [`Panel::resource_with`](crate::Panel::resource_with)
26/// adjusts it for one panel. Every setting has a default, so a resource sets only what differs:
27///
28/// ```rust
29/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
30/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String, featured: bool }
31/// # #[derive(Debug, Clone, tablo_core::RecordForm)]
32/// # #[form(model = Post)]
33/// # struct PostForm { title: String, featured: bool }
34/// # struct PostResource;
35/// use tablo_core::{PanelModel, ReadOnly, Resource, ResourceDef, TernaryFilter, lens};
36///
37/// impl Resource for PostResource {
38///     type Model = Post;
39///     type Form = PostForm;
40///
41///     fn declare() -> ResourceDef<Self> {
42///         ResourceDef::new()
43///             .label("Blog post")
44///             .policy(ReadOnly)
45///             .table(Post::table().filters(TernaryFilter::new(lens!(Post.featured))))
46///     }
47/// }
48/// ```
49///
50/// The panel builds the def once when it mounts, binding the paths it names to the database
51/// schema, and serves the result to every request.
52pub struct ResourceDef<R: Resource> {
53    pub(crate) slug: Option<String>,
54    pub(crate) label: Option<crate::Text>,
55    pub(crate) plural_label: Option<crate::Text>,
56    pub(crate) icon: Option<IconData>,
57    pub(crate) navigation_order: Option<i32>,
58    pub(crate) navigation_group: Option<crate::Text>,
59    pub(crate) navigation: Option<NavigationItem>,
60    pub(crate) navigation_badge: Option<Expr<bool>>,
61    pub(crate) navigation_hidden: bool,
62    pub(crate) policy: Arc<dyn Policy<R::Model>>,
63    /// The policies [`Self::restrict`] adds, which every later [`Self::policy`] must pass too.
64    restrictions: Vec<Arc<dyn Policy<R::Model>>>,
65    pub(crate) required_hooks: Vec<(std::any::TypeId, &'static str)>,
66    pub(crate) queries: Vec<super::QueryFn>,
67    /// The relations [`Self::include_unscoped`] loads with every row.
68    pub(crate) includes: crate::column::Includes<R::Model>,
69    pub(crate) tenancy: Tenancy<R::Model>,
70    pub(crate) table: Option<Table<R::Model>>,
71    pub(crate) form: Option<Schema<R::Form>>,
72    pub(crate) detail: Option<Detail<R::Model>>,
73    pub(crate) record_title: Option<super::RecordTitle<R::Model>>,
74    /// `None` once [`Self::without_global_search`] leaves the resource out.
75    pub(crate) global_search: Option<super::GlobalSearch<R::Model>>,
76    pub(crate) public_link: Option<PublicLinkFn<R::Model>>,
77    pub(crate) relations: Vec<Relation<R::Model>>,
78    pub(crate) record_pages: Vec<super::RecordPageEntry<R>>,
79    pub(crate) actions: Actions<R>,
80    pub(crate) header_actions: HeaderActions,
81    /// The header actions' badges, each action's name with the filter its count matches.
82    pub(crate) header_badges: Vec<(&'static str, Expr<bool>)>,
83    pub(crate) list_widgets: crate::widget::WidgetGrid,
84    /// The columns [`Self::create_column`] names, or why a path names no column.
85    pub(crate) create_columns: Vec<Result<String, DeclarationErrorKind>>,
86    /// The pages [`Self::without_page`] has not turned off.
87    pub(crate) pages: super::Pages,
88    /// Whether [`Self::importable`] turned the CSV import on.
89    pub(crate) importable: bool,
90    pub(crate) soft_delete: Option<SoftDelete<R::Model>>,
91    pub(crate) field_rules: Vec<super::FieldRule>,
92}
93
94impl<R: Resource> Default for ResourceDef<R> {
95    fn default() -> Self {
96        Self {
97            slug: None,
98            label: None,
99            plural_label: None,
100            icon: None,
101            navigation_order: None,
102            navigation_group: None,
103            navigation: None,
104            navigation_badge: None,
105            navigation_hidden: false,
106            policy: Arc::new(Deny),
107            restrictions: Vec::new(),
108            required_hooks: Vec::new(),
109            queries: Vec::new(),
110            includes: crate::column::Includes::new(),
111            tenancy: Tenancy::undeclared(),
112            table: None,
113            form: None,
114            detail: None,
115            record_title: None,
116            global_search: Some(super::GlobalSearch::default()),
117            public_link: None,
118            relations: Vec::new(),
119            record_pages: Vec::new(),
120            actions: Actions::default(),
121            header_actions: HeaderActions::new(),
122            header_badges: Vec::new(),
123            list_widgets: crate::widget::WidgetGrid::default(),
124            create_columns: Vec::new(),
125            pages: super::Pages::default(),
126            importable: false,
127            soft_delete: None,
128            field_rules: Vec::new(),
129        }
130    }
131}
132
133impl<R: Resource> ResourceDef<R> {
134    /// A def with every default: the policy denies all, rows belong to no tenant, the model's
135    /// [`PanelModel`](crate::PanelModel) give the table and the detail page, and the record
136    /// form gives the form.
137    pub fn new() -> Self {
138        Self::default()
139    }
140
141    /// The URL slug for the resource's pages: `"users"` mounts the list at `{panel prefix}/users`.
142    ///
143    /// Defaults to the resource type's name without a trailing `Resource`, pluralized and
144    /// kebab-cased: `UserResource` → `users`, `BlogPostResource` → `blog-posts`. Renaming the type
145    /// then moves the resource's URLs and drops the column choices its users saved, which are
146    /// stored under the slug; set it to keep both.
147    #[must_use]
148    pub fn slug(mut self, slug: impl Into<String>) -> Self {
149        self.slug = Some(slug.into());
150        self
151    }
152
153    /// One record's name, the noun in the "Create {label}" and "Edit {label}" titles.
154    ///
155    /// Defaults to the message `resource-{model}` of the panel's catalogs, else the model's type
156    /// name in sentence case: `BlogPost` reads `resource-blog-post`, else `Blog post`, and
157    /// `APIKey` reads `resource-api-key`, else `API key`.
158    #[must_use]
159    pub fn label(mut self, label: impl Into<crate::Text>) -> Self {
160        self.label = Some(label.into());
161        self
162    }
163
164    /// The list title and sidebar label.
165    ///
166    /// Defaults to the plural of the [`label`](Self::label): a plain label pluralized in English,
167    /// `Category` reading `Categories` and `Person` `People`, and a message's attribute `plural`.
168    /// The default label's message is `resource-{model}`, so its plural is
169    /// `resource-{model}.plural`, else the derived English noun pluralized.
170    ///
171    /// ```ftl
172    /// resource-blog-post = Article
173    ///     .plural = Articles
174    /// ```
175    #[must_use]
176    pub fn plural_label(mut self, label: impl Into<crate::Text>) -> Self {
177        self.plural_label = Some(label.into());
178        self
179    }
180
181    /// The icon of the resource's sidebar entry, replacing the icon of a
182    /// [`navigation`](Self::navigation) item.
183    #[must_use]
184    pub fn icon(mut self, icon: IconData) -> Self {
185        self.icon = Some(icon);
186        self
187    }
188
189    /// Where the sidebar entry sorts among the panel's entries, lowest first; defaults to `0`, and
190    /// entries of equal order keep their registration order. It replaces the order of a
191    /// [`navigation`](Self::navigation) item.
192    #[must_use]
193    pub fn navigation_order(mut self, order: i32) -> Self {
194        self.navigation_order = Some(order);
195        self
196    }
197
198    /// The labelled sidebar group the entry renders in, such as `"Content"`; defaults to none,
199    /// above every group. It replaces the group of a [`navigation`](Self::navigation) item.
200    #[must_use]
201    pub fn navigation_group(mut self, group: impl Into<crate::Text>) -> Self {
202        self.navigation_group = Some(group.into());
203        self
204    }
205
206    /// Replaces the sidebar entry, for one that links somewhere other than the list page:
207    /// `NavigationItem::at("Drafts", "/admin/posts?f.status=draft")`. [`icon`](Self::icon),
208    /// [`navigation_order`](Self::navigation_order), [`navigation_group`](Self::navigation_group)
209    /// and [`navigation_badge`](Self::navigation_badge) still apply to it.
210    #[must_use]
211    pub fn navigation(mut self, item: NavigationItem) -> Self {
212        self.navigation = Some(item);
213        self
214    }
215
216    /// Badge the sidebar entry with the number of rows of [`scoped_query`](crate::scoped_query)
217    /// that `filter` matches, so a tenant counts its own rows. The panel counts them each time its
218    /// sidebar renders, on a page load and on each runtime rerun such as a sort or a page step,
219    /// one query per badge run together, and shows no badge for zero. It replaces the
220    /// badge of a [`navigation`](Self::navigation) item.
221    ///
222    /// ```rust
223    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
224    /// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String, draft: bool }
225    /// # struct PostResource;
226    /// # impl tablo_core::Resource for PostResource {
227    /// #     type Model = Post;
228    /// #     type Form = tablo_core::NoForm<Post>;
229    /// fn declare() -> tablo_core::ResourceDef<Self> {
230    ///     // "Posts 3" while three drafts wait.
231    ///     tablo_core::ResourceDef::new().navigation_badge(Post::fields().draft().eq(true))
232    /// }
233    /// # }
234    /// ```
235    #[must_use]
236    pub fn navigation_badge(mut self, filter: Expr<bool>) -> Self {
237        self.navigation_badge = Some(filter);
238        self
239    }
240
241    /// Keeps the resource out of the sidebar and the root's redirect: hiding every resource needs
242    /// a [`Panel::home`](crate::Panel::home) ([`NoRoot`](crate::DeclarationErrorKind::NoRoot)).
243    /// Its pages stay mounted at their URLs, and its policy still decides who may open them.
244    #[must_use]
245    pub fn without_navigation(mut self) -> Self {
246        self.navigation_hidden = true;
247        self
248    }
249
250    /// Authorizes every handler; defaults to [`Deny`]. Row scoping belongs in
251    /// [`query`](Self::query), not the policy. Each policy [`restrict`](Self::restrict) added
252    /// must allow an ability too.
253    #[must_use]
254    pub fn policy(mut self, policy: impl Policy<R::Model>) -> Self {
255        self.policy = self
256            .restrictions
257            .iter()
258            .fold(Arc::new(policy), |policy, restriction| {
259                Arc::new(Restricted(policy, Arc::clone(restriction)))
260            });
261        self
262    }
263
264    /// Requires `restriction` to allow every ability too, whatever policy the def holds now or
265    /// [`policy`](Self::policy) sets later: a resource's own [`declare`](Resource::declare)
266    /// keeps a rule through the def a [`Panel::resource_with`](crate::Panel::resource_with)
267    /// customization returns.
268    ///
269    /// ```rust
270    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
271    /// # struct Entry { #[key] #[auto] id: uuid::Uuid }
272    /// # struct EntryResource;
273    /// use tablo_core::{Allow, NoForm, Panel, ReadOnly, Resource, ResourceDef};
274    ///
275    /// impl Resource for EntryResource {
276    ///     type Model = Entry;
277    ///     type Form = NoForm<Entry>;
278    ///
279    ///     fn declare() -> ResourceDef<Self> {
280    ///         ResourceDef::new().restrict(ReadOnly)
281    ///     }
282    /// }
283    ///
284    /// // Reads only: `ReadOnly` still refuses every write `Allow` would let through.
285    /// Panel::new("admin").resource_with::<EntryResource>(|def| def.policy(Allow));
286    /// ```
287    #[must_use]
288    pub fn restrict(mut self, restriction: impl Policy<R::Model>) -> Self {
289        let restriction: Arc<dyn Policy<R::Model>> = Arc::new(restriction);
290        self.policy = Arc::new(Restricted(self.policy, Arc::clone(&restriction)));
291        self.restrictions.push(restriction);
292        self
293    }
294
295    /// Authorizes every handler with a closure, as [`policy`](Self::policy) does, inferring the
296    /// closure's argument types from the def's model:
297    ///
298    /// ```rust
299    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
300    /// # struct Post { #[key] #[auto] id: uuid::Uuid, locked: bool }
301    /// # struct PostResource;
302    /// # impl tablo_core::Resource for PostResource {
303    /// #     type Model = Post;
304    /// #     type Form = tablo_core::NoForm<Post>;
305    /// # }
306    /// use tablo_core::{Ability, Panel};
307    ///
308    /// Panel::new("portal").resource_with::<PostResource>(|def| {
309    ///     // No update, delete, restore or record action on a locked post.
310    ///     def.policy_fn(|_cx, ability| ability.written_record().is_none_or(|post| !post.locked))
311    /// });
312    /// ```
313    ///
314    /// In [`Resource::declare`], the chain on `ResourceDef::new()` learns its resource from the
315    /// return type, after the closure is checked, so a closure that reads the record names the
316    /// ability's type, `|_cx, ability: Ability<'_, Post>|`, or the chain starts from
317    /// `ResourceDef::<Self>::new()`.
318    ///
319    /// [`policy`](Self::policy) takes a closure too, but infers neither argument type: Rust infers
320    /// a closure's signature from an `Fn` bound, not from [`Policy`]'s blanket impl.
321    #[must_use]
322    pub fn policy_fn(
323        self,
324        policy: impl Fn(&Cx, Ability<'_, R::Model>) -> bool + Send + Sync + 'static,
325    ) -> Self {
326        self.policy(policy)
327    }
328
329    /// Restricts who views and who changes the field `path` names, as in
330    /// `.field_access(lens!(Employee.salary), FieldAccess::new().view(is_hr))`: see
331    /// [`FieldAccess`](super::FieldAccess).
332    ///
333    /// The rule restricts the field of its model within the panel: every resource the panel mounts
334    /// over the model drops what reads a field the request may not view, the table's and the detail
335    /// page's columns, the filters and the grouping, the export's columns, the searches of the list
336    /// and of the relationship choices over those resources, and the relation columns showing it.
337    /// Each form renders nothing for the field, or a disabled control for one it may view but not
338    /// change, and refuses a submission posting either with 400. A create the field needs a value
339    /// for, with no default, is refused.
340    ///
341    /// Hiding a `belongs_to` relation hides its foreign keys, and hiding a key hides the relation.
342    /// Mounting the panel refuses a path that is not one field of the model, a second declaration
343    /// over one field, a primary key with a `view` rule, a record title or a form condition reading
344    /// a restricted field, and a column or a filter that does not say which fields it
345    /// [`reads`](crate::Reads), and the declarations [`FieldAccessFault`](crate::FieldAccessFault)
346    /// lists that would show a restricted record no panel can mask.
347    ///
348    /// A validation error on a field the request may not view shows as an alert that a hidden
349    /// field refuses the save, without its message.
350    #[must_use]
351    pub fn field_access<T>(
352        mut self,
353        path: impl Into<toasty::stmt::Path<R::Model, T>>,
354        access: super::FieldAccess,
355    ) -> Self {
356        self.field_rules
357            .push(super::FieldRule::new(&path.into(), access));
358        self
359    }
360
361    /// How rows belong to a tenant. A resource that declares none is served to every tenant;
362    /// [`Tenancy::none`] says when mounting the panel refuses it instead.
363    #[must_use]
364    pub fn tenancy(mut self, tenancy: Tenancy<R::Model>) -> Self {
365        self.tenancy = tenancy;
366        self
367    }
368
369    /// The list table; defaults to the model's ([`PanelModel::table`]). Its columns are also
370    /// the [`detail`](Self::detail) page's, unless the resource declares one.
371    ///
372    /// [`PanelModel::table`]: crate::PanelModel::table
373    #[must_use]
374    pub fn table(mut self, table: Table<R::Model>) -> Self {
375        self.table = Some(table);
376        self
377    }
378
379    /// Arranges the create and edit forms: the record form's own controls, from its
380    /// `controls()`, in layout blocks.
381    ///
382    /// A control the schema does not place follows the ones it does, in the record form's
383    /// declaration order and outside every layout block, so the default form renders one control
384    /// per field, and a form that adjusts one control places only that one:
385    ///
386    /// ```rust
387    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
388    /// # struct User { #[key] #[auto] id: uuid::Uuid, name: String, email: String }
389    /// # #[derive(Debug, Clone, tablo_core::RecordForm)]
390    /// # #[form(model = User)]
391    /// # struct UserForm { name: String, email: String }
392    /// # struct UserResource;
393    /// use tablo_core::{Resource, ResourceDef, Schema};
394    ///
395    /// impl Resource for UserResource {
396    ///     type Model = User;
397    ///     type Form = UserForm;
398    ///
399    ///     fn declare() -> ResourceDef<Self> {
400    ///         // `email`, then `name`.
401    ///         ResourceDef::new().form(Schema::new(UserForm::controls().email.email()))
402    ///     }
403    /// }
404    /// ```
405    #[must_use]
406    pub fn form(mut self, form: Schema<R::Form>) -> Self {
407        self.form = Some(form);
408        self
409    }
410
411    /// The detail page: columns in layout blocks; defaults to the [`table`](Self::table)'s columns,
412    /// else to the model's ([`PanelModel::detail`]). The page adds a View action to each
413    /// row; [`without_page(ResourcePage::View)`](Self::without_page) turns it off, and mounting
414    /// refuses a detail listing no column on a resource that serves it.
415    ///
416    /// The page, at `{list}/{key}`, carries in its header the record's title, a link back to the
417    /// list, the actions placed on [`Places::DETAIL`](crate::Places::DETAIL) and Delete as the
418    /// policy allows them on the record, and Edit when the resource has a form and the policy
419    /// allows `Update`. The [related tables](Self::relation) follow its columns.
420    ///
421    /// The record loads through the resource's tenant-scoped [`query`](Self::query) with every
422    /// relation the columns declare, once each, wherever its block sits; no other relation
423    /// loads. An unknown key and a key outside the request's tenant are the same 404, and a
424    /// record the policy refuses `View` is a 403. The [`form`](Self::form) does not shape the
425    /// page: a resource that arranges its form declares a detail to show the same arrangement.
426    ///
427    /// [`PanelModel::detail`]: crate::PanelModel::detail
428    #[must_use]
429    pub fn detail(mut self, detail: Detail<R::Model>) -> Self {
430        self.detail = Some(detail);
431        self
432    }
433
434    /// Titles each record with the text column `lens` reads, as in
435    /// `.record_title(lens!(Post.title))`: the detail page's heading, each option of a
436    /// [`relationship`](crate::ChoiceField::relationship) choice over this resource, and each cell
437    /// of a [`RelationColumn::of`](crate::RelationColumn::of) it.
438    ///
439    /// A record whose column is empty, and every record by default, is titled with the
440    /// [`label`](Self::label) and its key, as in `Blog Post 3f2a…`. A relationship choice over this
441    /// resource also searches the column, besides the table's searchable columns.
442    ///
443    /// A title is display text, not a key: two records can share one, so it never replaces the
444    /// primary key that keys the table's rows and the action routes. A lens names one of the
445    /// model's own columns, never a relation, so the title reads on every record however it was
446    /// loaded; a title built from several columns is a column the model stores.
447    #[must_use]
448    pub fn record_title<T>(mut self, lens: Lens<R::Model, T>) -> Self
449    where
450        T: FormScalar + toasty::schema::Field<Inner = String> + Send + Sync + 'static,
451    {
452        self.record_title = Some(super::RecordTitle::new(lens));
453        self
454    }
455
456    /// Links a record's public page from its detail and edit pages, for each record `link` returns
457    /// one for; defaults to no link.
458    ///
459    /// The edit page loads the record without relations, so a link that reads one renders on the
460    /// detail page only when its relation is loaded there.
461    #[must_use]
462    pub fn public_link(
463        mut self,
464        link: impl Fn(&Cx, &R::Model) -> Option<PublicLink> + Send + Sync + 'static,
465    ) -> Self {
466        self.public_link = Some(Arc::new(link));
467        self
468    }
469
470    /// Adds a related resource: its table, narrowed to the record, on the detail and edit pages.
471    #[must_use]
472    pub fn relation(mut self, relation: Relation<R::Model>) -> Self {
473        self.relations.push(relation);
474        self
475    }
476
477    /// Adds the custom [`Action`] `A` after the ones already declared.
478    ///
479    /// The policy decides who may run it, through
480    /// [`Ability::RunAny`](crate::Ability::RunAny) and [`Ability::Run`](crate::Ability::Run). An
481    /// `A::NAME` that is not a single URL path segment does not compile.
482    #[must_use]
483    pub fn action<A: Action<R>>(mut self) -> Self {
484        self.actions = self.actions.add::<A>();
485        self
486    }
487
488    /// Adds the [`Widget`](crate::Widget) `W` to the grid above the list page's table, after the
489    /// ones already declared: a banner, a row of [`Stat`](crate::Stat)s, a chart.
490    ///
491    /// The grid renders with the list, behind its sign-in and
492    /// [`Ability::ViewAny`](crate::Ability::ViewAny), and leaves out each widget whose
493    /// [`WidgetDef::access`](crate::WidgetDef::access) refuses the request. Its widgets render
494    /// before the rows load, and an error from one fails the list's response. A sort, filter or
495    /// page change reruns the list and its widgets with it. Mounting refuses two widgets sharing a
496    /// name.
497    #[must_use]
498    pub fn list_widget<W: crate::Widget>(mut self) -> Self {
499        self.list_widgets.push::<W>();
500        self
501    }
502
503    /// How many columns the list page's widget grid has on a wide screen, from 1 to 4; defaults
504    /// to 2, as a page's does.
505    #[must_use]
506    pub fn list_widget_columns(mut self, columns: u8) -> Self {
507        self.list_widgets.set_columns(columns);
508        self
509    }
510
511    /// Declares a column an overriding [`Resource::create_record`] sets itself, beyond the form's
512    /// fields: `.create_column(lens!(Post.slug))`. Call it once per column.
513    ///
514    /// Mounting the panel refuses a path that names no one field of the model, and the tenant
515    /// column, which the framework stamps.
516    #[must_use]
517    pub fn create_column<T>(mut self, path: impl Into<Path<R::Model, T>>) -> Self {
518        let path = ModelPath::of(&path.into());
519        self.create_columns
520            .push(model::field::<R::Model>(&path).map(|field| field.name));
521        self
522    }
523
524    /// Serves a CSV import beside the create page: the list links **Import CSV** to a page that
525    /// takes a file whose header names the form's keys, and creates one record per row through
526    /// the create form, all in one transaction or none.
527    ///
528    /// Each row is checked as a create submission is, under the same policy, field access and
529    /// tenant. Mounting refuses an importable resource that serves no create page.
530    ///
531    /// - The first row names the columns, each by its form key or its field's label in any case:
532    ///   the controls the request may change, but file fields, repeaters and controls disabled on
533    ///   the create page. A header naming any other column, or a label two fields carry, refuses
534    ///   the file. **Download template** at `{list}/-/import/template` returns the header row.
535    /// - Each cell posts what the create form's control would: an option's value, `true` or `false`
536    ///   for a checkbox, a date and time in the request's time zone. A blank cell posts a blank
537    ///   value, and a column the header leaves out takes the field's `default`. A multiple choice
538    ///   takes one column per value, its key repeated; no other column may repeat.
539    /// - The file is UTF-8 text with commas or semicolons between cells, of at most
540    ///   [`Limits::import_rows`](crate::Limits::import_rows) rows, 500 cells a row and
541    ///   [`Limits::body_bytes`](crate::Limits::body_bytes). A row whose every cell is blank is
542    ///   skipped.
543    /// - [`Resource::before_commit`] receives each row's [`Change::Create`](crate::Change::Create)
544    ///   inside the transaction. A row [`Resource::create_record`] refuses rolls back to a
545    ///   savepoint taken before it, so the rows after it are checked without its writes. When any
546    ///   row is refused nothing is written, and the page lists each refusal by row number, as a
547    ///   spreadsheet numbers it, and column. Once every row passes, the import lands on the list
548    ///   and [`Resource::after_commit`] receives each row's change, in file order.
549    ///
550    /// The transaction lasts the whole file: on SQLite it holds the write lock that long. The
551    /// import reads what the form posts, not what the export writes: an exported `$1,234.50`,
552    /// `Yes` or option label does not import back.
553    #[must_use]
554    pub fn importable(mut self) -> Self {
555        self.importable = true;
556        self
557    }
558}
559
560/// A record's public page, linked from its detail and edit pages.
561#[derive(Debug, Clone)]
562pub struct PublicLink {
563    pub(crate) url: String,
564    pub(crate) label: crate::Text,
565}
566
567impl PublicLink {
568    /// A link to `url` that reads `label`.
569    pub fn new(url: impl Into<String>, label: impl Into<crate::Text>) -> Self {
570        Self {
571            url: url.into(),
572            label: label.into(),
573        }
574    }
575}
576
577/// A record's public page, as [`ResourceDef::public_link`] declares it.
578pub(crate) type PublicLinkFn<M> = Arc<dyn Fn(&Cx, &M) -> Option<PublicLink> + Send + Sync>;
579
580impl<R: Resource> std::fmt::Debug for ResourceDef<R> {
581    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
582        f.debug_struct("ResourceDef")
583            .field("slug", &self.slug)
584            .field("label", &self.label)
585            .field("plural_label", &self.plural_label)
586            .field("relations", &self.relations)
587            .field("actions", &self.actions)
588            .field("header_actions", &self.header_actions)
589            .finish_non_exhaustive()
590    }
591}
592
593/// A policy and a [`ResourceDef::restrict`] restriction, both of which must allow an ability.
594struct Restricted<M>(Arc<dyn Policy<M>>, Arc<dyn Policy<M>>);
595
596impl<M: 'static> Policy<M> for Restricted<M> {
597    fn allows(&self, cx: &Cx, ability: Ability<'_, M>) -> bool {
598        self.0.allows(cx, ability) && self.1.allows(cx, ability)
599    }
600}