Skip to main content

tablo_core/
resource.rs

1//! `Resource` — maps one Toasty [`Model`](toasty::schema::Model) to its admin UI.
2
3use toasty::{
4    Executor,
5    stmt::{List, Query},
6};
7use topcoat::{Result, context::Cx};
8
9use crate::form::{FieldErrors, Posted, RecordForm};
10
11mod action;
12mod check;
13mod commit;
14mod def;
15mod editable;
16mod field_access;
17mod global_search;
18mod header_action;
19mod mounted;
20mod pages;
21mod query;
22mod record_page;
23mod record_title;
24mod relation;
25mod soft_delete;
26mod write;
27mod write_error;
28
29pub use action::{Action, ActionDef, Places, Submits, filter_keys};
30pub(crate) use action::{
31    ActionEntry, Actions, ErasedInput, InputResult, InputSpec, RESERVED_KEYS, Reports, SubmitSpec,
32    parse_validated,
33};
34pub(crate) use check::{ResourceCheck, ServesTenants, check_inputs, check_resource};
35pub(crate) use commit::run_after_commit;
36pub use commit::{Acted, Change};
37pub use def::{PublicLink, ResourceDef};
38pub use field_access::FieldAccess;
39pub(crate) use field_access::{FieldMask, FieldRule};
40pub use global_search::GlobalSearch;
41pub(crate) use global_search::{Opens, SearchHit, search, searchable};
42pub(crate) use header_action::HeaderEntry;
43pub use header_action::{HeaderAction, HeaderActionDef, HeaderActions};
44pub(crate) use mounted::{
45    MountScope, Mounted, Mounts, is_mounted, is_restricted_model, is_tenant_model, model_rules,
46    mounted, require_mounted, restricts_any,
47};
48pub(crate) use pages::Pages;
49pub use pages::ResourcePage;
50pub(crate) use query::QueryFn;
51pub(crate) use record_page::{
52    RESERVED_SEGMENTS as RESERVED_RECORD_SEGMENTS, RecordPageEntry, check as check_record_pages,
53};
54pub use record_page::{RecordPage, RecordPageDef};
55use record_title::RecordTitle;
56pub use relation::{ForeignKey, Relation};
57pub(crate) use relation::{Links, RelationKind};
58pub use soft_delete::Trashed;
59pub(crate) use soft_delete::{SoftDelete, TRASH_FILTER, TrashFilter};
60pub use write::{write_create, write_delete, write_force_delete, write_restore, write_update};
61pub use write_error::WriteError;
62
63/// Maps one Toasty `Model` to its admin UI.
64///
65/// # Contract
66///
67/// Requires [`Model`](Self::Model) and [`Form`](Self::Form); every other item has a default.
68/// [`declare`](Self::declare) returns what the resource declares, as one [`ResourceDef`] value;
69/// the methods scope, validate and write records for a request.
70///
71/// The panel builds the def once when it mounts, binding the paths it names to the database
72/// schema, and serves the result to every request. Record fns run inside the handler transaction
73/// and fail without partial writes.
74pub trait Resource: Sized + Send + Sync + 'static {
75    /// The persisted model this resource administers. Its [`PanelModel`](crate::PanelModel)
76    /// give the table and detail page the resource declares none of.
77    type Model: crate::PanelModel
78        + toasty::stmt::IntoExpr<Self::Model>
79        + Send
80        + Sync
81        + Clone
82        + 'static;
83
84    /// The typed value the create and edit forms parse into.
85    ///
86    /// A resource with create and edit pages names its
87    /// [`#[derive(RecordForm)]`](crate::RecordForm) struct; a list-only resource
88    /// names [`NoForm<Self::Model>`](crate::NoForm), and
89    /// [`Panel::resource`](crate::Panel::resource) registers no form route for
90    /// it ([`RecordForm::HAS_FORM`]).
91    type Form: RecordForm<Model = Self::Model>;
92
93    /// What the resource declares: names, navigation, policy, tenancy, table, form, detail page,
94    /// relations and actions. Defaults to [`ResourceDef::new`], whose policy denies all.
95    ///
96    /// ```rust
97    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
98    /// # struct Post {
99    /// #     #[key] #[auto] id: uuid::Uuid,
100    /// #     title: String,
101    /// #     body: String,
102    /// # }
103    /// # #[derive(Debug, Clone, tablo_core::RecordForm)]
104    /// # #[form(model = Post)]
105    /// # struct PostForm { title: String, body: String }
106    /// # struct PostResource;
107    /// # use tablo_core::{ReadOnly, RecordForm, Resource, ResourceDef, Schema, Section};
108    /// impl Resource for PostResource {
109    ///     type Model = Post;
110    ///     type Form = PostForm;
111    ///
112    ///     fn declare() -> ResourceDef<Self> {
113    ///         let c = PostForm::controls();
114    ///         ResourceDef::new().policy(ReadOnly).form(Schema::new(
115    ///             Section::new("Content").schema((c.title, c.body.multiline(6))),
116    ///         ))
117    ///     }
118    /// }
119    /// ```
120    ///
121    /// The panel builds the def once when it mounts and serves that copy to every request, so
122    /// `declare` takes no user, tenant or query string: a request-dependent decision belongs to
123    /// the policy or to a trait method, which receives `cx`.
124    fn declare() -> ResourceDef<Self> {
125        ResourceDef::new()
126    }
127
128    /// App-level rules on the parsed form. The errors render inline with a
129    /// 200 and nothing is written, so a range or cross-field rule belongs here. A rule that
130    /// reads the database belongs in [`create_record`](Self::create_record) or
131    /// [`update_record`](Self::update_record), which refuse through the transaction they write
132    /// in.
133    ///
134    /// Each error names a field of the record form, `errors.add(|f| f.age, ..)`, and renders
135    /// under its control, or under an embedded value's first control.
136    fn validate_record(_cx: &Cx, _form: &Self::Form) -> FieldErrors<Self::Form> {
137        FieldErrors::new()
138    }
139
140    /// Create a record from the parsed form, inside the handler's transaction.
141    ///
142    /// Defaults to the derived write, [`write_create`]; override to check
143    /// something inside the transaction, then delegate. An override on a
144    /// [`Tenancy::column`](crate::Tenancy::column) resource stamps the tenant
145    /// only by delegating to [`write_create`]: the handler re-reads the returned row through the
146    /// request's tenant scope before it commits, and a row outside it fails the write closed.
147    /// `ex` is the open transaction: run every statement through it. Return the created row; the
148    /// hooks receive it as [`Change::Create`].
149    ///
150    /// A rule that reads the database refuses the submission with [`WriteError::Refused`]: the
151    /// transaction rolls back and the form renders again with the errors under their fields. A
152    /// reason that names no field declines it with [`WriteError::declined`], which the form
153    /// renders above its fields.
154    fn create_record(
155        cx: &Cx,
156        form: Self::Form,
157        ex: &mut dyn Executor,
158    ) -> impl Future<Output = Result<Self::Model, WriteError<Self::Form>>> + Send {
159        write_create::<Self>(cx, form, ex)
160    }
161
162    /// Update the already-authorized `record` from the posted form, inside the
163    /// handler's transaction.
164    ///
165    /// Defaults to the derived write, [`write_update`]. `record` is the
166    /// snapshot the handler loaded and policy-checked inside the transaction:
167    /// use it, never re-query. Return the row as it now stands: a row the request's tenant scope
168    /// no longer holds fails the write closed, as in [`create_record`](Self::create_record).
169    ///
170    /// Refuses or declines the submission as [`create_record`](Self::create_record) does.
171    fn update_record(
172        cx: &Cx,
173        record: Self::Model,
174        posted: Posted<Self::Form>,
175        ex: &mut dyn Executor,
176    ) -> impl Future<Output = Result<Self::Model, WriteError<Self::Form>>> + Send {
177        write_update::<Self>(cx, record, posted, ex)
178    }
179
180    /// Delete the already-authorized `record`.
181    ///
182    /// The handler loads `record` through the tenancy-scoped query inside the
183    /// framework transaction and checks the policy on that snapshot, then
184    /// calls this with the same transaction as `ex`. The hooks receive the
185    /// snapshot as [`Change::Delete`].
186    ///
187    /// The default is [`write_delete`]: it deletes the row through [`scoped_query`], filtered to
188    /// the record's primary key, or stamps its [`soft_delete`](ResourceDef::soft_delete) column
189    /// with the time when the resource declares one. Override to delete another way, or to refuse
190    /// with [`WriteError::declined`] and delegate the rest to [`write_delete`]: the transaction
191    /// rolls back and the message flashes, as it does for the restore, the force delete and the
192    /// bulk delete.
193    fn delete_record(
194        cx: &Cx,
195        record: &Self::Model,
196        ex: &mut dyn toasty::Executor,
197    ) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
198        write_delete::<Self>(cx, record, ex)
199    }
200
201    /// Restore the already-authorized trashed `record` of a resource that
202    /// [soft-deletes](ResourceDef::soft_delete), inside the handler's transaction.
203    ///
204    /// The handler loads `record` through [`scoped_query_in`] with [`Trashed::Only`] and checks
205    /// [`Ability::Restore`](crate::Ability::Restore) on it. The default, [`write_restore`], empties
206    /// the soft-delete column.
207    fn restore_record(
208        cx: &Cx,
209        record: &Self::Model,
210        ex: &mut dyn toasty::Executor,
211    ) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
212        write_restore::<Self>(cx, record, ex)
213    }
214
215    /// Delete the already-authorized trashed `record` for good, inside the handler's
216    /// transaction.
217    ///
218    /// The handler loads `record` through [`scoped_query_in`] with [`Trashed::Only`] and checks
219    /// [`Ability::ForceDelete`](crate::Ability::ForceDelete) on it. The default,
220    /// [`write_force_delete`], removes the row.
221    fn force_delete_record(
222        cx: &Cx,
223        record: &Self::Model,
224        ex: &mut dyn toasty::Executor,
225    ) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
226        write_force_delete::<Self>(cx, record, ex)
227    }
228
229    /// Bulk-delete the already-authorized `records`: the handler
230    /// fetches through the tenancy-scoped `IN` query inside the framework
231    /// transaction, checks `View` on every row, and passes the rows
232    /// [`Ability::Delete`](crate::Ability::Delete) allows, skipping the rest
233    /// as a bulk custom action does. The default deletes each record through
234    /// [`Self::delete_record`] in order, through the same `ex` — any error rolls the whole
235    /// batch back, so mid-loop failures delete zero rows. An override of `delete_record`,
236    /// such as a soft delete, therefore covers bulk delete too. Override this
237    /// for a single-statement batch.
238    fn bulk_delete_records(
239        cx: &Cx,
240        records: &[Self::Model],
241        ex: &mut dyn toasty::Executor,
242    ) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
243        async move {
244            for record in records {
245                Self::delete_record(cx, record, &mut *ex).await?;
246            }
247            Ok(())
248        }
249    }
250
251    /// Work inside the write's transaction, after the record fn or action wrote: an audit row,
252    /// a counter, a row in another table that must commit with the write or not at all.
253    /// Work every resource of a panel does, such as an audit trail, belongs in a
254    /// [`CommitHook`](crate::CommitHook), which the panel runs right after this one.
255    ///
256    /// Called once per write, with the [`Change`] it made, through `ex`, the open transaction:
257    /// run every statement through it, and notify through
258    /// [`Notifications::send_in`](crate::Notifications::send_in), which stores the
259    /// notification only if the write commits. A second connection, through
260    /// [`db`](crate::db::db) or [`Notifications::send`](crate::Notifications::send),
261    /// would write outside the transaction, and on a pool of one wait forever for the connection
262    /// the transaction holds; either refuses instead, and the write rolls back.
263    ///
264    /// Every write this resource's panel routes make comes here: a create, once per row of a CSV
265    /// import, an update, a delete or bulk delete, a restore or force delete, a custom or header
266    /// action, and a many-to-many attach or detach. The profile and tenant-settings pages save
267    /// their user and tenant rows themselves and do not. A validation error, a policy denial or
268    /// a failed or refused record fn returns before it. An `Err` rolls the whole write back and
269    /// fails the request with the write's failure toast.
270    ///
271    /// ```rust
272    /// # use tablo_core::{Change, NoForm, Resource};
273    /// # use topcoat::{Result, context::Cx};
274    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
275    /// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
276    /// # #[derive(Debug, toasty::Model)]
277    /// # struct Audit { #[key] #[auto] id: uuid::Uuid, post_id: uuid::Uuid, change: String }
278    /// # struct PostResource;
279    /// # impl Resource for PostResource {
280    /// #     type Model = Post;
281    /// #     type Form = NoForm<Post>;
282    /// async fn before_commit(
283    ///     _cx: &Cx,
284    ///     change: &Change<Post>,
285    ///     ex: &mut dyn toasty::Executor,
286    /// ) -> Result<()> {
287    ///     let kind = match change {
288    ///         Change::Create(_) => "create",
289    ///         Change::Update { .. } => "update",
290    ///         Change::Delete(_) => "delete",
291    ///         Change::Restore(_) => "restore",
292    ///         Change::ForceDelete(_) => "force delete",
293    ///         Change::Action { name, .. } | Change::HeaderAction { name } => name,
294    ///         Change::Attach { .. } => "attach",
295    ///         Change::Detach { .. } => "detach",
296    ///         Change::Export { .. } => "export",
297    ///     };
298    ///     for post in change.records() {
299    ///         toasty::create!(Audit {
300    ///             post_id: post.id,
301    ///             change: kind.to_string()
302    ///         })
303    ///         .exec(&mut *ex)
304    ///         .await?;
305    ///     }
306    ///     Ok(())
307    /// }
308    /// # }
309    /// ```
310    fn before_commit(
311        _cx: &Cx,
312        _change: &Change<Self::Model>,
313        _ex: &mut dyn Executor,
314    ) -> impl Future<Output = Result<()>> + Send {
315        async move { Ok(()) }
316    }
317
318    /// Work after the write commits, outside the database: an email, a webhook, cache
319    /// invalidation.
320    ///
321    /// Called once per committed write, after `tx.commit()` and before the response, with the
322    /// [`Change`] [`Self::before_commit`] received. It is never called when nothing committed, so
323    /// a rollback cannot produce the effect. Nothing guarantees it runs either: an error it
324    /// returns is logged and ignored, since the write is committed, and a crash between the
325    /// commit and the hook skips it. A row that must exist whenever the write does belongs in
326    /// [`Self::before_commit`]; retries are the app's to build. A panic surfaces as Topcoat's
327    /// panic-isolated 500.
328    ///
329    /// ```rust
330    /// # use tablo_core::{Change, NoForm, Resource};
331    /// # use topcoat::{Result, context::Cx};
332    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
333    /// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
334    /// # async fn notify(_cx: &Cx, _post: &Post) -> Result<()> { Ok(()) }
335    /// # struct PostResource;
336    /// # impl Resource for PostResource {
337    /// #     type Model = Post;
338    /// #     type Form = NoForm<Post>;
339    /// async fn after_commit(cx: &Cx, change: Change<Post>) -> Result<()> {
340    ///     if let Change::Create(post) = &change {
341    ///         notify(cx, post).await?;
342    ///     }
343    ///     Ok(())
344    /// }
345    /// # }
346    /// ```
347    fn after_commit(
348        _cx: &Cx,
349        _change: Change<Self::Model>,
350    ) -> impl Future<Output = Result<()>> + Send {
351        async move { Ok(()) }
352    }
353}
354
355/// The tenant-scoped base query.
356///
357/// The resource's rows as the context's panel narrows them with [`ResourceDef::query`], with the
358/// [`tenancy`](ResourceDef::tenancy) filter ANDed onto them, so no narrowing can drop the tenant
359/// scope, and with the trashed records of a resource that [soft-deletes](ResourceDef::soft_delete)
360/// left out.
361/// Every framework loader and app code start here; [`scoped_query_in`] admits the trashed
362/// records too.
363///
364/// # Errors
365///
366/// A tenant-scoped resource and no tenant in `cx`: 403, the same answer the
367/// panel's handlers give. A declaration error when the context's panel does not mount `R`; a
368/// background job builds its context with [`PanelHandle::context`](crate::PanelHandle::context).
369///
370/// App code that loads rows itself must call this: `Query::all()` reads every tenant's rows and
371/// skips the panel's narrowings.
372pub fn scoped_query<R: Resource>(cx: &Cx) -> Result<Query<List<R::Model>>> {
373    scoped_query_in::<R>(cx, Trashed::Without)
374}
375
376/// [`scoped_query`] admitting the records `trashed` names, as a restore or a trash list loads
377/// them, under the same tenant filter.
378///
379/// On a resource that declares no [`soft_delete`](ResourceDef::soft_delete) column every record
380/// is live: [`Trashed::Only`] admits none, and the other scopes admit all.
381///
382/// # Errors
383///
384/// As [`scoped_query`].
385pub fn scoped_query_in<R: Resource>(cx: &Cx, trashed: Trashed) -> Result<Query<List<R::Model>>> {
386    require_mounted::<R>(cx)?.scoped_query_in(cx, trashed)
387}
388
389impl<R: Resource> Mounted<R> {
390    /// [`scoped_query`] for this mount.
391    pub(crate) fn scoped_query(&self, cx: &Cx) -> Result<Query<List<R::Model>>> {
392        self.scoped_query_in(cx, Trashed::Without)
393    }
394
395    /// [`scoped_query_in`] for this mount.
396    pub(crate) fn scoped_query_in(
397        &self,
398        cx: &Cx,
399        trashed: Trashed,
400    ) -> Result<Query<List<R::Model>>> {
401        self.narrowed(cx, trashed, |_| true)
402    }
403
404    /// Every row the request's tenant holds, trashed records included, with the relations
405    /// [`include_unscoped`](ResourceDef::include_unscoped) names: where a write may leave a row,
406    /// since a [`query`](ResourceDef::query) narrowing may rightly hide what it wrote.
407    pub(crate) fn tenant_query(&self, cx: &Cx) -> Result<Query<List<R::Model>>> {
408        self.narrowed(cx, Trashed::With, |_| false)
409    }
410
411    /// The rows a unique index over the fields `index` names covers, of the ones the request
412    /// reads, trashed records included: the tenant's rows, under each
413    /// [`query`](ResourceDef::query) narrowing that reads a field of the index and so fixes it.
414    /// A narrowing that reads none hides rows the index still covers, so the probe leaves it out;
415    /// one whose reads the walk cannot tell stays.
416    pub(crate) fn unique_probe_query(
417        &self,
418        cx: &Cx,
419        index: &[&str],
420    ) -> Result<Query<List<R::Model>>> {
421        self.narrowed(cx, Trashed::With, |predicate| {
422            let (fields, unresolved) =
423                crate::toasty_compat::predicate::root_fields::<R::Model>(predicate);
424            unresolved || fields.iter().any(|field| index.contains(&field.as_str()))
425        })
426    }
427
428    /// Every row, under the [`query`](ResourceDef::query) narrowings `keep` admits, the tenant
429    /// filter and the `trashed` scope, with the relations
430    /// [`include_unscoped`](ResourceDef::include_unscoped) names.
431    fn narrowed(
432        &self,
433        cx: &Cx,
434        trashed: Trashed,
435        keep: impl Fn(&toasty::stmt::Expr<bool>) -> bool,
436    ) -> Result<Query<List<R::Model>>> {
437        let mut query = Query::<List<R::Model>>::all();
438        for predicate in self.queries.iter().filter_map(|narrow| narrow(cx)) {
439            if keep(&predicate) {
440                query = query.filter(predicate);
441            }
442        }
443        for include in &self.includes {
444            query = query.include(include.clone());
445        }
446        let query = self.tenant_scope(cx, query)?;
447        Ok(match &self.soft_delete {
448            Some(soft_delete) => match soft_delete.filter(trashed) {
449                Some(filter) => query.filter(filter),
450                None => query,
451            },
452            None if trashed == Trashed::Only => query.filter(crate::toasty_compat::never()),
453            None => query,
454        })
455    }
456
457    /// The records a list in `state` admits: the ones its trash control selects, else the live
458    /// ones.
459    pub(crate) fn list_trashed(&self, state: &crate::TableState) -> Trashed {
460        if self.soft_delete.is_none() {
461            return Trashed::Without;
462        }
463        Trashed::from_filter(state.filters.get(TRASH_FILTER)).unwrap_or_default()
464    }
465
466    /// [`scoped_query_in`] for the list in `state`.
467    pub(crate) fn list_query(
468        &self,
469        cx: &Cx,
470        state: &crate::TableState,
471    ) -> Result<Query<List<R::Model>>> {
472        self.scoped_query_in(cx, self.list_trashed(state))
473    }
474
475    /// Whether `record` is trashed: never on a resource that does not soft-delete.
476    pub(crate) fn is_trashed(&self, record: &R::Model) -> bool {
477        self.soft_delete
478            .as_ref()
479            .is_some_and(|soft_delete| soft_delete.is_trashed(record))
480    }
481
482    /// AND the resource's tenant filter onto `query`.
483    fn tenant_scope(&self, cx: &Cx, query: Query<List<R::Model>>) -> Result<Query<List<R::Model>>> {
484        if !self.tenancy.is_scoped() {
485            return Ok(query);
486        }
487        if let Some(Err(error)) = self.tenancy.column_field() {
488            return Err(crate::error::declaration(
489                crate::DeclarationError::of::<R>(crate::Site::Tenancy, error).to_string(),
490            ));
491        }
492        let tenant = crate::tenancy::require_tenant(cx)?;
493        Ok(match self.tenancy.filter(tenant) {
494            Some(filter) => query.filter(filter),
495            None => query,
496        })
497    }
498}
499
500/// Whether the request may do `ability` on `R` as the context's panel mounted it: what the
501/// ability's button and route ask. `false` when the panel does not mount `R`. Does not check
502/// sign-in or tenant scope.
503///
504/// It is the policy's answer and what the ability rests on: [`Run`](crate::Ability::Run) also
505/// takes a record the action's [`can_run`](crate::ActionDef::can_run) admits, and a force delete
506/// the delete it implies. [`RunHeader`](crate::Ability::RunHeader) is the policy's answer alone:
507/// a header action's `can_run` may be what asks it. While someone acts as another user under an
508/// [`Impersonation`](crate::Impersonation) that is not
509/// [`writable`](crate::Impersonation::writable), only the reads are allowed.
510pub fn can<R: Resource>(cx: &Cx, ability: crate::Ability<'_, R::Model>) -> bool {
511    mounted::<R>(cx).is_some_and(|resource| resource.can(cx, ability))
512}
513
514/// Every `Resource` is an [`OptionSource`](crate::extend::OptionSource), answering from its def
515/// as the context's panel mounted it.
516///
517/// [`scoped_query`](crate::extend::OptionSource::scoped_query) forwards to
518/// [`scoped_query`], so an option load inherits the tenant check and filter
519/// exactly as every other loader does. The search expression and default ordering come from the
520/// resource's [`table`](ResourceDef::table), whose searchable columns the option search searches
521/// with the [`record_title`](ResourceDef::record_title) column, and each record's label is its
522/// title.
523impl<R: Resource> crate::schema::OptionSource for R {
524    type Model = R::Model;
525
526    fn scoped_query(cx: &Cx) -> Result<Query<List<R::Model>>> {
527        scoped_query::<R>(cx)
528    }
529
530    fn lists(cx: &Cx) -> bool {
531        can::<R>(cx, crate::Ability::ViewAny)
532    }
533
534    fn requires_tenant(cx: &Cx) -> bool {
535        mounted::<R>(cx).is_some_and(|mounted| mounted.tenancy.is_scoped())
536    }
537
538    fn search_expr(cx: &Cx, term: &str) -> Option<toasty::stmt::Expr<bool>> {
539        mounted::<R>(cx)?.option_search_expr(cx, term)
540    }
541
542    fn order_by(cx: &Cx) -> Option<toasty::stmt::OrderByExpr> {
543        mounted::<R>(cx)?.table_for(cx).first_order_by()
544    }
545
546    /// The record's title, as its detail page shows it.
547    fn label(cx: &Cx, record: &R::Model) -> String {
548        let key = crate::toasty_compat::pk::pk_text(record);
549        match mounted::<R>(cx) {
550            Some(mounted) => mounted.record_title(cx, record, &key),
551            None => key,
552        }
553    }
554
555    fn available(cx: &Cx) -> bool {
556        mounted::<R>(cx).is_some()
557    }
558
559    fn hidden_fields(cx: &Cx) -> Vec<String> {
560        mounted::<R>(cx).map_or_else(Vec::new, |mounted| mounted.field_mask(cx).hidden().to_vec())
561    }
562
563    fn creates() -> bool {
564        true
565    }
566
567    fn create_page(cx: &Cx) -> Option<String> {
568        let mounted = mounted::<R>(cx)?;
569        // The page a save lands on offers the record only to a user who may list the resource.
570        (mounted.pages.create && mounted.can_create(cx) && mounted.can(cx, crate::Ability::ViewAny))
571            .then(|| crate::naming::create_page_url(&mounted.url))
572    }
573}
574
575#[cfg(test)]
576mod tests;