tablo-core 0.10.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! [`ResourceDef`]: everything a resource declares, as one value.

use std::sync::Arc;

use toasty::stmt::{Expr, Path};
use topcoat::{context::Cx, icon::IconData};

use super::{Action, Actions, HeaderActions, Relation, Resource, SoftDelete};
use crate::{
    DeclarationErrorKind, Lens,
    detail::Detail,
    form::FormScalar,
    navigation::NavigationItem,
    policy::{Ability, Deny, Policy},
    schema::Schema,
    table::Table,
    tenancy::Tenancy,
    toasty_compat::model::{self, ModelPath},
};

mod header_actions;

/// What a [`Resource`] declares: its names, navigation, policy, tenancy, table, list widgets, form,
/// detail page, record pages, relations and actions.
///
/// [`Resource::declare`] returns one, and [`Panel::resource_with`](crate::Panel::resource_with)
/// adjusts it for one panel. Every setting has a default, so a resource sets only what differs:
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String, featured: bool }
/// # #[derive(Debug, Clone, tablo_core::RecordForm)]
/// # #[form(model = Post)]
/// # struct PostForm { title: String, featured: bool }
/// # struct PostResource;
/// use tablo_core::{ModelColumns, ReadOnly, Resource, ResourceDef, TernaryFilter, lens};
///
/// impl Resource for PostResource {
///     type Model = Post;
///     type Form = PostForm;
///
///     fn declare() -> ResourceDef<Self> {
///         ResourceDef::new()
///             .label("Blog post")
///             .policy(ReadOnly)
///             .table(Post::table().filters(TernaryFilter::new(lens!(Post.featured))))
///     }
/// }
/// ```
///
/// The panel builds the def once when it mounts, binding the paths it names to the database
/// schema, and serves the result to every request.
pub struct ResourceDef<R: Resource> {
    pub(crate) slug: Option<String>,
    pub(crate) label: Option<crate::Text>,
    pub(crate) plural_label: Option<crate::Text>,
    pub(crate) icon: Option<IconData>,
    pub(crate) navigation_order: Option<i32>,
    pub(crate) navigation_group: Option<crate::Text>,
    pub(crate) navigation: Option<NavigationItem>,
    pub(crate) navigation_badge: Option<Expr<bool>>,
    pub(crate) navigation_hidden: bool,
    pub(crate) policy: Arc<dyn Policy<R::Model>>,
    pub(crate) queries: Vec<super::QueryFn<R::Model>>,
    pub(crate) tenancy: Tenancy<R::Model>,
    pub(crate) table: Option<Table<R::Model>>,
    pub(crate) form: Option<Schema<R::Form>>,
    pub(crate) detail: Option<Detail<R::Model>>,
    pub(crate) record_title: Option<super::RecordTitle<R::Model>>,
    /// `None` once [`Self::without_global_search`] leaves the resource out.
    pub(crate) global_search: Option<super::GlobalSearch<R::Model>>,
    pub(crate) public_link: Option<PublicLinkFn<R::Model>>,
    pub(crate) relations: Vec<Relation<R::Model>>,
    pub(crate) record_pages: Vec<super::RecordPageEntry<R>>,
    pub(crate) actions: Actions<R>,
    pub(crate) header_actions: HeaderActions,
    /// The header actions' badges, each action's name with the filter its count matches.
    pub(crate) header_badges: Vec<(&'static str, Expr<bool>)>,
    pub(crate) list_widgets: crate::widget::WidgetGrid,
    /// The columns [`Self::create_column`] names, or why a path names no column.
    pub(crate) create_columns: Vec<Result<String, DeclarationErrorKind>>,
    /// The pages [`Self::without_page`] has not turned off.
    pub(crate) pages: super::Pages,
    /// Whether [`Self::importable`] turned the CSV import on.
    pub(crate) importable: bool,
    pub(crate) soft_delete: Option<SoftDelete<R::Model>>,
    pub(crate) field_rules: Vec<super::FieldRule>,
}

impl<R: Resource> Default for ResourceDef<R> {
    fn default() -> Self {
        Self {
            slug: None,
            label: None,
            plural_label: None,
            icon: None,
            navigation_order: None,
            navigation_group: None,
            navigation: None,
            navigation_badge: None,
            navigation_hidden: false,
            policy: Arc::new(Deny),
            queries: Vec::new(),
            tenancy: Tenancy::undeclared(),
            table: None,
            form: None,
            detail: None,
            record_title: None,
            global_search: Some(super::GlobalSearch::default()),
            public_link: None,
            relations: Vec::new(),
            record_pages: Vec::new(),
            actions: Actions::default(),
            header_actions: HeaderActions::new(),
            header_badges: Vec::new(),
            list_widgets: crate::widget::WidgetGrid::default(),
            create_columns: Vec::new(),
            pages: super::Pages::default(),
            importable: false,
            soft_delete: None,
            field_rules: Vec::new(),
        }
    }
}

impl<R: Resource> ResourceDef<R> {
    /// A def with every default: the policy denies all, rows belong to no tenant, the model's
    /// [`ModelColumns`](crate::ModelColumns) give the table and the detail page, and the record
    /// form gives the form.
    pub fn new() -> Self {
        Self::default()
    }

    /// The URL slug for the resource's pages: `"users"` mounts the list at `{panel prefix}/users`.
    ///
    /// Defaults to the resource type's name without a trailing `Resource`, pluralized and
    /// kebab-cased: `UserResource` → `users`, `BlogPostResource` → `blog-posts`. Renaming the type
    /// then moves the resource's URLs and drops the column choices its users saved, which are
    /// stored under the slug; set it to keep both.
    #[must_use]
    pub fn slug(mut self, slug: impl Into<String>) -> Self {
        self.slug = Some(slug.into());
        self
    }

    /// One record's name, the noun in the "Create {label}" and "Edit {label}" titles.
    ///
    /// Defaults to the message `resource-{model}` of the panel's catalogs, else the model's type
    /// name in sentence case: `BlogPost` reads `resource-blog-post`, else `Blog post`, and
    /// `APIKey` reads `resource-api-key`, else `API key`.
    #[must_use]
    pub fn label(mut self, label: impl Into<crate::Text>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// The list title and sidebar label.
    ///
    /// Defaults to the plural of the [`label`](Self::label): a plain label pluralized in English,
    /// `Category` reading `Categories` and `Person` `People`, and a message's attribute `plural`.
    /// The default label's message is `resource-{model}`, so its plural is
    /// `resource-{model}.plural`, else the derived English noun pluralized.
    ///
    /// ```ftl
    /// resource-blog-post = Article
    ///     .plural = Articles
    /// ```
    #[must_use]
    pub fn plural_label(mut self, label: impl Into<crate::Text>) -> Self {
        self.plural_label = Some(label.into());
        self
    }

    /// The icon of the resource's sidebar entry, replacing the icon of a
    /// [`navigation`](Self::navigation) item.
    #[must_use]
    pub fn icon(mut self, icon: IconData) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Where the sidebar entry sorts among the panel's entries, lowest first; defaults to `0`, and
    /// entries of equal order keep their registration order. It replaces the order of a
    /// [`navigation`](Self::navigation) item.
    #[must_use]
    pub fn navigation_order(mut self, order: i32) -> Self {
        self.navigation_order = Some(order);
        self
    }

    /// The labelled sidebar group the entry renders in, such as `"Content"`; defaults to none,
    /// above every group. It replaces the group of a [`navigation`](Self::navigation) item.
    #[must_use]
    pub fn navigation_group(mut self, group: impl Into<crate::Text>) -> Self {
        self.navigation_group = Some(group.into());
        self
    }

    /// Replaces the sidebar entry, for one that links somewhere other than the list page:
    /// `NavigationItem::at("Drafts", "/admin/posts?f.status=draft")`. [`icon`](Self::icon),
    /// [`navigation_order`](Self::navigation_order), [`navigation_group`](Self::navigation_group)
    /// and [`navigation_badge`](Self::navigation_badge) still apply to it.
    #[must_use]
    pub fn navigation(mut self, item: NavigationItem) -> Self {
        self.navigation = Some(item);
        self
    }

    /// Badge the sidebar entry with the number of rows of [`scoped_query`](crate::scoped_query)
    /// that `filter` matches, so a tenant counts its own rows. The panel counts them each time its
    /// sidebar renders, on a page load and on each runtime rerun such as a sort or a page step,
    /// one query per badge run together, and shows no badge for zero. It replaces the
    /// badge of a [`navigation`](Self::navigation) item.
    ///
    /// ```rust
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String, draft: bool }
    /// # struct PostResource;
    /// # impl tablo_core::Resource for PostResource {
    /// #     type Model = Post;
    /// #     type Form = tablo_core::NoForm<Post>;
    /// fn declare() -> tablo_core::ResourceDef<Self> {
    ///     // "Posts 3" while three drafts wait.
    ///     tablo_core::ResourceDef::new().navigation_badge(Post::fields().draft().eq(true))
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn navigation_badge(mut self, filter: Expr<bool>) -> Self {
        self.navigation_badge = Some(filter);
        self
    }

    /// Keeps the resource out of the sidebar and the root's redirect: hiding every resource needs
    /// a [`Panel::home`](crate::Panel::home) ([`NoRoot`](crate::DeclarationErrorKind::NoRoot)).
    /// Its pages stay mounted at their URLs, and its policy still decides who may open them.
    #[must_use]
    pub fn without_navigation(mut self) -> Self {
        self.navigation_hidden = true;
        self
    }

    /// Authorizes every handler; defaults to [`Deny`]. Row scoping belongs in
    /// [`query`](Self::query), not the policy.
    #[must_use]
    pub fn policy(mut self, policy: impl Policy<R::Model>) -> Self {
        self.policy = Arc::new(policy);
        self
    }

    /// Authorizes every handler with a closure, as [`policy`](Self::policy) does, inferring the
    /// closure's argument types from the def's model:
    ///
    /// ```rust
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct Post { #[key] #[auto] id: uuid::Uuid, locked: bool }
    /// # struct PostResource;
    /// # impl tablo_core::Resource for PostResource {
    /// #     type Model = Post;
    /// #     type Form = tablo_core::NoForm<Post>;
    /// # }
    /// use tablo_core::{Ability, Panel};
    ///
    /// Panel::new("portal").resource_with::<PostResource>(|def| {
    ///     // No update, delete, restore or record action on a locked post.
    ///     def.policy_fn(|_cx, ability| ability.written_record().is_none_or(|post| !post.locked))
    /// });
    /// ```
    ///
    /// In [`Resource::declare`], the chain on `ResourceDef::new()` learns its resource from the
    /// return type, after the closure is checked, so a closure that reads the record names the
    /// ability's type, `|_cx, ability: Ability<'_, Post>|`, or the chain starts from
    /// `ResourceDef::<Self>::new()`.
    ///
    /// [`policy`](Self::policy) takes a closure too, but infers neither argument type: Rust infers
    /// a closure's signature from an `Fn` bound, not from [`Policy`]'s blanket impl.
    #[must_use]
    pub fn policy_fn(
        self,
        policy: impl Fn(&Cx, Ability<'_, R::Model>) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.policy(policy)
    }

    /// Restricts who views and who changes the field `path` names, as in
    /// `.field_access(lens!(Employee.salary), FieldAccess::new().view(is_hr))`: see
    /// [`FieldAccess`](super::FieldAccess).
    ///
    /// The rule restricts the field of its model within the panel: every resource the panel mounts
    /// over the model drops what reads a field the request may not view, the table's and the detail
    /// page's columns, the filters and the grouping, the export's columns, the searches of the list
    /// and of the relationship choices over those resources, and the relation columns showing it.
    /// Each form renders nothing for the field, or a disabled control for one it may view but not
    /// change, and refuses a submission posting either with 400. A create the field needs a value
    /// for, with no default, is refused.
    ///
    /// Hiding a `belongs_to` relation hides its foreign keys, and hiding a key hides the relation.
    /// Mounting the panel refuses a path that is not one field of the model, a second declaration
    /// over one field, a primary key with a `view` rule, a record title or a form condition reading
    /// a restricted field, and a column or a filter that does not say which fields it
    /// [`reads`](crate::Reads), and the declarations [`FieldAccessFault`](crate::FieldAccessFault)
    /// lists that would show a restricted record no panel can mask.
    ///
    /// A validation error on a field the request may not view shows as an alert that a hidden
    /// field refuses the save, without its message.
    #[must_use]
    pub fn field_access<T>(
        mut self,
        path: impl Into<toasty::stmt::Path<R::Model, T>>,
        access: super::FieldAccess,
    ) -> Self {
        self.field_rules
            .push(super::FieldRule::new(&path.into(), access));
        self
    }

    /// How rows belong to a tenant. A resource that declares none is served to every tenant;
    /// [`Tenancy::none`] says when mounting the panel refuses it instead.
    #[must_use]
    pub fn tenancy(mut self, tenancy: Tenancy<R::Model>) -> Self {
        self.tenancy = tenancy;
        self
    }

    /// The list table; defaults to the model's ([`ModelColumns::table`]). Its columns are also
    /// the [`detail`](Self::detail) page's, unless the resource declares one.
    ///
    /// [`ModelColumns::table`]: crate::ModelColumns::table
    #[must_use]
    pub fn table(mut self, table: Table<R::Model>) -> Self {
        self.table = Some(table);
        self
    }

    /// Arranges the create and edit forms: the record form's own controls, from its
    /// `controls()`, in layout blocks.
    ///
    /// A control the schema does not place follows the ones it does, in the record form's
    /// declaration order and outside every layout block, so the default form renders one control
    /// per field, and a form that adjusts one control places only that one:
    ///
    /// ```rust
    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
    /// # struct User { #[key] #[auto] id: uuid::Uuid, name: String, email: String }
    /// # #[derive(Debug, Clone, tablo_core::RecordForm)]
    /// # #[form(model = User)]
    /// # struct UserForm { name: String, email: String }
    /// # struct UserResource;
    /// use tablo_core::{Resource, ResourceDef, Schema};
    ///
    /// impl Resource for UserResource {
    ///     type Model = User;
    ///     type Form = UserForm;
    ///
    ///     fn declare() -> ResourceDef<Self> {
    ///         // `email`, then `name`.
    ///         ResourceDef::new().form(Schema::new(UserForm::controls().email.email()))
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn form(mut self, form: Schema<R::Form>) -> Self {
        self.form = Some(form);
        self
    }

    /// The detail page: columns in layout blocks; defaults to the [`table`](Self::table)'s columns,
    /// else to the model's ([`ModelColumns::detail`]). The page adds a View action to each
    /// row; [`without_page(ResourcePage::View)`](Self::without_page) turns it off, and mounting
    /// refuses a detail listing no column on a resource that serves it.
    ///
    /// The page, at `{list}/{key}`, carries in its header the record's title, a link back to the
    /// list, the actions placed on [`Places::DETAIL`](crate::Places::DETAIL) and Delete as the
    /// policy allows them on the record, and Edit when the resource has a form and the policy
    /// allows `Update`. The [related tables](Self::relation) follow its columns.
    ///
    /// The record loads through the resource's tenant-scoped [`query`](Self::query) with every
    /// relation the columns declare, once each, wherever its block sits; no other relation
    /// loads. An unknown key and a key outside the request's tenant are the same 404, and a
    /// record the policy refuses `View` is a 403. The [`form`](Self::form) does not shape the
    /// page: a resource that arranges its form declares a detail to show the same arrangement.
    ///
    /// [`ModelColumns::detail`]: crate::ModelColumns::detail
    #[must_use]
    pub fn detail(mut self, detail: Detail<R::Model>) -> Self {
        self.detail = Some(detail);
        self
    }

    /// Titles each record with the text column `lens` reads, as in
    /// `.record_title(lens!(Post.title))`: the detail page's heading, each option of a
    /// [`relationship`](crate::ChoiceField::relationship) choice over this resource, and each cell
    /// of a [`RelationColumn::of`](crate::RelationColumn::of) it.
    ///
    /// A record whose column is empty, and every record by default, is titled with the
    /// [`label`](Self::label) and its key, as in `Blog Post 3f2a…`. A relationship choice over this
    /// resource also searches the column, besides the table's searchable columns.
    ///
    /// A title is display text, not a key: two records can share one, so it never replaces the
    /// primary key that keys the table's rows and the action routes. A lens names one of the
    /// model's own columns, never a relation, so the title reads on every record however it was
    /// loaded; a title built from several columns is a column the model stores.
    #[must_use]
    pub fn record_title<T>(mut self, lens: Lens<R::Model, T>) -> Self
    where
        T: FormScalar + toasty::schema::Field<Inner = String> + Send + Sync + 'static,
    {
        self.record_title = Some(super::RecordTitle::new(lens));
        self
    }

    /// Links a record's public page from its detail and edit pages, for each record `link` returns
    /// one for; defaults to no link.
    ///
    /// The edit page loads the record without relations, so a link that reads one renders on the
    /// detail page only when its relation is loaded there.
    #[must_use]
    pub fn public_link(
        mut self,
        link: impl Fn(&Cx, &R::Model) -> Option<PublicLink> + Send + Sync + 'static,
    ) -> Self {
        self.public_link = Some(Arc::new(link));
        self
    }

    /// Adds a related resource: its table, narrowed to the record, on the detail and edit pages.
    #[must_use]
    pub fn relation(mut self, relation: Relation<R::Model>) -> Self {
        self.relations.push(relation);
        self
    }

    /// Adds the custom [`Action`] `A` after the ones already declared.
    ///
    /// The policy decides who may run it, through
    /// [`Ability::RunAny`](crate::Ability::RunAny) and [`Ability::Run`](crate::Ability::Run). An
    /// `A::NAME` that is not a single URL path segment does not compile.
    #[must_use]
    pub fn action<A: Action<R>>(mut self) -> Self {
        self.actions = self.actions.add::<A>();
        self
    }

    /// Adds the [`Widget`](crate::Widget) `W` to the grid above the list page's table, after the
    /// ones already declared: a banner, a row of [`Stat`](crate::Stat)s, a chart.
    ///
    /// The grid renders with the list, behind its sign-in and
    /// [`Ability::ViewAny`](crate::Ability::ViewAny), and leaves out each widget whose
    /// [`WidgetDef::access`](crate::WidgetDef::access) refuses the request. Its widgets render
    /// before the rows load, and an error from one fails the list's response. A sort, filter or
    /// page change reruns the list and its widgets with it. Mounting refuses two widgets sharing a
    /// name.
    #[must_use]
    pub fn list_widget<W: crate::Widget>(mut self) -> Self {
        self.list_widgets.push::<W>();
        self
    }

    /// How many columns the list page's widget grid has on a wide screen, from 1 to 4; defaults
    /// to 2, as a page's does.
    #[must_use]
    pub fn list_widget_columns(mut self, columns: u8) -> Self {
        self.list_widgets.set_columns(columns);
        self
    }

    /// Declares a column an overriding [`Resource::create_record`] sets itself, beyond the form's
    /// fields: `.create_column(lens!(Post.slug))`. Call it once per column.
    ///
    /// Mounting the panel refuses a path that names no one field of the model, and the tenant
    /// column, which the framework stamps.
    #[must_use]
    pub fn create_column<T>(mut self, path: impl Into<Path<R::Model, T>>) -> Self {
        let path = ModelPath::of(&path.into());
        self.create_columns
            .push(model::field::<R::Model>(&path).map(|field| field.name));
        self
    }

    /// Serves a CSV import beside the create page: the list links **Import CSV** to a page that
    /// takes a file whose header names the form's keys, and creates one record per row through
    /// the create form, all in one transaction or none.
    ///
    /// Each row is checked as a create submission is, under the same policy, field access and
    /// tenant. Mounting refuses an importable resource that serves no create page.
    ///
    /// - The first row names the columns, each by its form key or its field's label in any case:
    ///   the controls the request may change, but file fields, repeaters and controls disabled on
    ///   the create page. A header naming any other column, or a label two fields carry, refuses
    ///   the file. **Download template** at `{list}/-/import/template` returns the header row.
    /// - Each cell posts what the create form's control would: an option's value, `true` or `false`
    ///   for a checkbox, a date and time in the request's time zone. A blank cell posts a blank
    ///   value, and a column the header leaves out takes the field's `default`. A multiple choice
    ///   takes one column per value, its key repeated; no other column may repeat.
    /// - The file is UTF-8 text with commas or semicolons between cells, of at most
    ///   [`Limits::import_rows`](crate::Limits::import_rows) rows, 500 cells a row and
    ///   [`Limits::body_bytes`](crate::Limits::body_bytes). A row whose every cell is blank is
    ///   skipped.
    /// - [`Resource::before_commit`] receives each row's [`Change::Create`](crate::Change::Create)
    ///   inside the transaction. A row [`Resource::create_record`] refuses rolls back to a
    ///   savepoint taken before it, so the rows after it are checked without its writes. When any
    ///   row is refused nothing is written, and the page lists each refusal by row number, as a
    ///   spreadsheet numbers it, and column. Once every row passes, the import lands on the list
    ///   and [`Resource::after_commit`] receives each row's change, in file order.
    ///
    /// The transaction lasts the whole file: on SQLite it holds the write lock that long. The
    /// import reads what the form posts, not what the export writes: an exported `$1,234.50`,
    /// `Yes` or option label does not import back.
    #[must_use]
    pub fn importable(mut self) -> Self {
        self.importable = true;
        self
    }
}

/// A record's public page, linked from its detail and edit pages.
#[derive(Debug, Clone)]
pub struct PublicLink {
    pub(crate) url: String,
    pub(crate) label: crate::Text,
}

impl PublicLink {
    /// A link to `url` that reads `label`.
    pub fn new(url: impl Into<String>, label: impl Into<crate::Text>) -> Self {
        Self {
            url: url.into(),
            label: label.into(),
        }
    }
}

/// A record's public page, as [`ResourceDef::public_link`] declares it.
pub(crate) type PublicLinkFn<M> = Arc<dyn Fn(&Cx, &M) -> Option<PublicLink> + Send + Sync>;

impl<R: Resource> std::fmt::Debug for ResourceDef<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResourceDef")
            .field("slug", &self.slug)
            .field("label", &self.label)
            .field("plural_label", &self.plural_label)
            .field("relations", &self.relations)
            .field("actions", &self.actions)
            .field("header_actions", &self.header_actions)
            .finish_non_exhaustive()
    }
}