Skip to main content

ignite_core/
runtime_resource.rs

1//! Resources defined at run time, from data: their slug, fields, columns and queries are
2//! values, not a Rust type, so an app can add and remove them while the panel serves.
3//!
4//! A static resource implements [`IgniteResource`](crate::IgniteResource) and is added with
5//! `Ignite::resource`. A runtime resource is a [`RuntimeResource`] value, whose rows come from
6//! a [`RuntimeData`] the app implements, and is added with [`register_runtime`]. The panel
7//! serves both through the same list, form and delete flows, at the same `/admin/<slug>`
8//! address, and a slug can belong to only one of them.
9//!
10//! ```ignore
11//! register_runtime(
12//!     RuntimeResource::new("books", "Books", "Book", BookData)
13//!         .field(FieldDef { name: "title".into(), label: "Title".into(),
14//!                           kind: FieldKindDef::Text, required: true })
15//!         .column(ColumnDef { key: "title".into(), label: "Title".into(),
16//!                             sortable: true, searchable: true }),
17//! )?;
18//! ```
19
20use std::collections::{BTreeSet, HashSet};
21use std::fmt;
22use std::future::Future;
23use std::pin::Pin;
24use std::sync::{Arc, PoisonError, RwLock};
25
26use orbit_orm::{Database, Error};
27use serde_json::{Map, Value};
28
29use crate::action::RowAction;
30use crate::condition::{FieldConditions, FormContext, Operation};
31use crate::field::{self as check, Block, Column, Field, FieldKind};
32use crate::form::{FieldErrors, FormInput, ValidationError};
33use crate::layout::FormLayout;
34use crate::list::{BadgeColor, ColumnBadges, ListFilter, Tab};
35use crate::policy::ActingUser;
36use crate::query::{ListQuery, Page};
37
38/// One record of a runtime resource: its values by key, as JSON. A row the panel lists or
39/// edits must have a numeric `id`, and a key for each field and column it shows.
40pub type Row = Map<String, Value>;
41
42/// The future a [`RuntimeData`] method returns: boxed, so the trait can be a trait object.
43/// Write the body as `Box::pin(async move { ... })`.
44pub type RuntimeFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;
45
46/// Where the rows of a runtime resource live. The app implements it, so Ignite assumes no
47/// table layout: a custom post type can keep its rows in a shared `posts` table and its
48/// values in a meta table.
49///
50/// The methods mirror the queries of [`IgniteResource`](crate::IgniteResource), with
51/// [`Row`]s for records and for validated input. The panel calls the `*_for` methods, which
52/// are given the signed-in [`ActingUser`]; by default each calls its method without the user,
53/// so a source that does not depend on the user implements only those.
54pub trait RuntimeData: Send + Sync + 'static {
55    /// Returns one page of rows that match `query`. The sort key, when there is one, is a
56    /// sortable column of the resource. The rows and the total must meet the active tab's
57    /// conditions in [`ListQuery::filter`] (see [`ListFilter`](crate::ListFilter)); a
58    /// `per_page` of 0 asks only for the total, to count a tab's rows.
59    fn list<'a>(&'a self, db: &'a Database, query: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>>;
60    /// Returns the row with `id`, or `None` if there is no such row.
61    fn find<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, Option<Row>>;
62    /// Inserts a row from the validated `input` and returns it. See
63    /// [`RegisteredResource::validate`] for the values `input` holds.
64    ///
65    /// An [`Error::UniqueViolation`] whose index is named `{slug}_{field}_unique` shows on the
66    /// form as `"<label> is already taken."`, as for a static resource. Any other error is a
67    /// server error. A source whose indexes are named otherwise (or that keeps values in a
68    /// meta table without such an index) should return a violation with an index of that
69    /// name, or check the value before it writes.
70    fn create<'a>(&'a self, db: &'a Database, input: Row) -> RuntimeFuture<'a, Row>;
71    /// Updates the row with `id` from the validated `input` and returns it. A key that is
72    /// missing from `input`, such as a password left blank or a field the form did not send,
73    /// keeps its stored value. A key whose value is `null` is an optional field the user cleared: store NULL, so the value
74    /// is cleared, as a static resource does. A unique violation is reported as for
75    /// [`create`](Self::create).
76    fn update<'a>(&'a self, db: &'a Database, id: i64, input: Row) -> RuntimeFuture<'a, Row>;
77    /// Deletes the row with `id` and returns the number of rows deleted.
78    fn delete<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, u64>;
79    /// The choices of the field `field`, as `(value, label)` pairs in display order, for a
80    /// field whose kind [loads its options](FieldKindDef::loads_options): a lookup, post
81    /// object, relationship, taxonomy or user field. The default is no choices.
82    fn options<'a>(
83        &'a self,
84        db: &'a Database,
85        field: &'a str,
86    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
87        let _ = (db, field);
88        Box::pin(async { Ok(Vec::new()) })
89    }
90
91    /// [`list`](Self::list) for the signed-in `user`: the panel's list calls it. Restrict the
92    /// rows to the user here, as a Filament resource does in `getEloquentQuery()`, such as an
93    /// author who sees only their own posts. The total counts the same rows. The default is
94    /// [`list`](Self::list), for every user.
95    fn list_for<'a>(
96        &'a self,
97        db: &'a Database,
98        user: &'a ActingUser,
99        query: &'a ListQuery,
100    ) -> RuntimeFuture<'a, Page<Row>> {
101        let _ = user;
102        self.list(db, query)
103    }
104
105    /// [`find`](Self::find) for the signed-in `user`: the panel finds the record of the edit
106    /// form, of its save and of the delete action with it. Return `None` for a row the user's
107    /// list leaves out, so the panel answers 404, as Filament resolves a record through
108    /// `getEloquentQuery()`. The default is [`find`](Self::find), for every user.
109    fn find_for<'a>(
110        &'a self,
111        db: &'a Database,
112        user: &'a ActingUser,
113        id: i64,
114    ) -> RuntimeFuture<'a, Option<Row>> {
115        let _ = user;
116        self.find(db, id)
117    }
118
119    /// [`create`](Self::create) for the signed-in `user`, such as to make them the author.
120    /// The default is [`create`](Self::create).
121    fn create_for<'a>(
122        &'a self,
123        db: &'a Database,
124        user: &'a ActingUser,
125        input: Row,
126    ) -> RuntimeFuture<'a, Row> {
127        let _ = user;
128        self.create(db, input)
129    }
130
131    /// [`update`](Self::update) for the signed-in `user`, such as to keep a status the user
132    /// may not set. The panel calls it only after [`find_for`](Self::find_for) found the row
133    /// and the [`Policy`](crate::Policy) allowed the update. The default is
134    /// [`update`](Self::update).
135    fn update_for<'a>(
136        &'a self,
137        db: &'a Database,
138        user: &'a ActingUser,
139        id: i64,
140        input: Row,
141    ) -> RuntimeFuture<'a, Row> {
142        let _ = user;
143        self.update(db, id, input)
144    }
145
146    /// [`create_for`](Self::create_for) that may refuse the row with field messages, as
147    /// Laravel's `ValidationException::withMessages()`: answer `Ok(Err(ValidationError))` and
148    /// the panel shows the create form again with 422, each message under its field and the
149    /// typed values kept. The panel calls this method; the default is
150    /// [`create_for`](Self::create_for), which never refuses.
151    ///
152    /// ```ignore
153    /// fn try_create_for<'a>(&'a self, db: &'a Database, user: &'a ActingUser, input: Row)
154    ///     -> RuntimeFuture<'a, Result<Row, ValidationError>> {
155    ///     Box::pin(async move {
156    ///         if name_is_taken(db, &input).await? {
157    ///             return Ok(Err(ValidationError::with_messages([("name", "That name is in use.")])));
158    ///         }
159    ///         Ok(Ok(save(db, input).await?))
160    ///     })
161    /// }
162    /// ```
163    fn try_create_for<'a>(
164        &'a self,
165        db: &'a Database,
166        user: &'a ActingUser,
167        input: Row,
168    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
169        Box::pin(async move { self.create_for(db, user, input).await.map(Ok) })
170    }
171
172    /// [`update_for`](Self::update_for) that may refuse the row with field messages, as
173    /// [`try_create_for`](Self::try_create_for) for the edit form. The panel calls it only
174    /// after [`find_for`](Self::find_for) found the row and the policy allowed the update. The
175    /// default is [`update_for`](Self::update_for), which never refuses.
176    fn try_update_for<'a>(
177        &'a self,
178        db: &'a Database,
179        user: &'a ActingUser,
180        id: i64,
181        input: Row,
182    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
183        Box::pin(async move { self.update_for(db, user, id, input).await.map(Ok) })
184    }
185
186    /// [`delete`](Self::delete) for the signed-in `user`. The panel calls it only after
187    /// [`find_for`](Self::find_for) found the row and the [`Policy`](crate::Policy) allowed
188    /// the delete. The default is [`delete`](Self::delete).
189    fn delete_for<'a>(
190        &'a self,
191        db: &'a Database,
192        user: &'a ActingUser,
193        id: i64,
194    ) -> RuntimeFuture<'a, u64> {
195        let _ = user;
196        self.delete(db, id)
197    }
198
199    /// The dashboard cards of the resource for the signed-in `user`, as
200    /// [`IgniteResource::stats`](crate::IgniteResource::stats). The panel shows them only to a
201    /// user who may view the resource's records. The default is none.
202    fn stats<'a>(
203        &'a self,
204        db: &'a Database,
205        user: &'a ActingUser,
206    ) -> RuntimeFuture<'a, Vec<crate::widget::Stat>> {
207        let _ = (db, user);
208        Box::pin(async { Ok(Vec::new()) })
209    }
210
211    /// [`options`](Self::options) for the signed-in `user`: the panel fills the form's
212    /// selects with these choices and checks a submitted value against them, so a choice left
213    /// out cannot be saved, as a Filament select whose options depend on the user. The default
214    /// is [`options`](Self::options).
215    fn options_for<'a>(
216        &'a self,
217        db: &'a Database,
218        user: &'a ActingUser,
219        field: &'a str,
220    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
221        let _ = user;
222        self.options(db, field)
223    }
224}
225
226/// The kind of a [`FieldDef`]: every [`FieldKind`], with owned values so it can be loaded
227/// from a database.
228#[derive(Debug, Clone, PartialEq, Eq, Hash)]
229pub enum FieldKindDef {
230    /// A single line of text. See [`FieldKind::Text`].
231    Text,
232    /// Several lines of text. See [`FieldKind::Textarea`].
233    Textarea,
234    /// A password, hashed on save. See [`FieldKind::Password`].
235    Password,
236    /// A whole number. See [`FieldKind::Number`].
237    Number,
238    /// A decimal number, with the browser's step, such as `"any"` or `"0.01"`. See
239    /// [`FieldKind::Decimal`].
240    Decimal(String),
241    /// A yes/no value. See [`FieldKind::Checkbox`].
242    Checkbox,
243    /// One choice from a list of `(value, label)` pairs. See [`FieldKind::Select`].
244    Select(Vec<(String, String)>),
245    /// One choice from options that [`RuntimeData::options`] loads. See [`FieldKind::Lookup`].
246    Lookup,
247    /// A calendar date. See [`FieldKind::Date`].
248    Date,
249    /// A date and time. See [`FieldKind::DateTime`].
250    DateTime,
251    /// An email address. See [`FieldKind::Email`].
252    Email,
253    /// A URL. See [`FieldKind::Url`].
254    Url,
255    /// One choice from a list of `(value, label)` pairs, as radio buttons. See
256    /// [`FieldKind::Radio`].
257    Radio(Vec<(String, String)>),
258    /// A color, as `#rrggbb`. See [`FieldKind::Color`].
259    Color,
260    /// An image from the media library. See [`FieldKind::Image`].
261    Image,
262    /// A file from the media library. See [`FieldKind::File`].
263    File,
264    /// A link, as JSON text. See [`FieldKind::Link`].
265    Link,
266    /// Rich text, edited with the app's editor. See [`FieldKind::Wysiwyg`].
267    Wysiwyg,
268    /// One post, from options [`RuntimeData::options`] loads. See [`FieldKind::PostObject`].
269    PostObject,
270    /// Several choices, from options [`RuntimeData::options`] loads. See
271    /// [`FieldKind::Relationship`].
272    Relationship,
273    /// One taxonomy term, from loaded options. See [`FieldKind::Taxonomy`].
274    Taxonomy,
275    /// One user, from loaded options. See [`FieldKind::User`].
276    User,
277    /// Rows of the given sub-fields, as JSON text. See [`FieldKind::Repeater`].
278    Repeater(Vec<FieldDef>),
279    /// The given sub-fields, as one JSON object. See [`FieldKind::Group`].
280    Group(Vec<FieldDef>),
281    /// Rows that each take one of the given blocks, as JSON text. See
282    /// [`FieldKind::FlexibleContent`].
283    FlexibleContent(Vec<BlockDef>),
284    /// Several images from the media library, as a JSON array of ids. See
285    /// [`FieldKind::Gallery`].
286    Gallery,
287    /// The fields of another field group, reused. See [`FieldKind::Clone`].
288    Clone(Vec<FieldDef>),
289}
290
291impl FieldKindDef {
292    /// Whether the field's choices come from [`RuntimeData::options`] each time its form is
293    /// shown. See [`FieldKind::loads_options`].
294    pub fn loads_options(&self) -> bool {
295        matches!(
296            self,
297            FieldKindDef::Lookup
298                | FieldKindDef::PostObject
299                | FieldKindDef::Relationship
300                | FieldKindDef::Taxonomy
301                | FieldKindDef::User
302        )
303    }
304
305    /// Whether the field holds media library ids: an image, a file or a gallery.
306    pub fn uses_media(&self) -> bool {
307        matches!(
308            self,
309            FieldKindDef::Image | FieldKindDef::File | FieldKindDef::Gallery
310        )
311    }
312}
313
314/// One block of a [`FieldKindDef::FlexibleContent`] field: the owned twin of [`Block`].
315#[derive(Debug, Clone, PartialEq, Eq, Hash)]
316pub struct BlockDef {
317    /// The block's name, stored as the `type` of each row that uses it.
318    pub name: String,
319    /// The label shown when choosing the block.
320    pub label: String,
321    /// The block's sub-fields, in display order.
322    pub fields: Vec<FieldDef>,
323}
324
325impl From<Block> for BlockDef {
326    fn from(block: Block) -> Self {
327        BlockDef {
328            name: block.name.to_string(),
329            label: block.label.to_string(),
330            fields: owned_fields(block.fields),
331        }
332    }
333}
334
335/// Owned definitions of static sub-fields.
336fn owned_fields(fields: &[Field]) -> Vec<FieldDef> {
337    fields.iter().copied().map(FieldDef::from).collect()
338}
339
340/// Owned `(value, label)` pairs of static choices.
341fn owned_choices(choices: &[(&str, &str)]) -> Vec<(String, String)> {
342    choices
343        .iter()
344        .map(|(value, label)| (value.to_string(), label.to_string()))
345        .collect()
346}
347
348impl From<FieldKind> for FieldKindDef {
349    fn from(kind: FieldKind) -> Self {
350        match kind {
351            FieldKind::Text => FieldKindDef::Text,
352            FieldKind::Textarea => FieldKindDef::Textarea,
353            FieldKind::Password => FieldKindDef::Password,
354            FieldKind::Number => FieldKindDef::Number,
355            FieldKind::Decimal(step) => FieldKindDef::Decimal(step.to_string()),
356            FieldKind::Checkbox => FieldKindDef::Checkbox,
357            FieldKind::Select(choices) => FieldKindDef::Select(owned_choices(choices)),
358            FieldKind::Lookup => FieldKindDef::Lookup,
359            FieldKind::Date => FieldKindDef::Date,
360            FieldKind::DateTime => FieldKindDef::DateTime,
361            FieldKind::Email => FieldKindDef::Email,
362            FieldKind::Url => FieldKindDef::Url,
363            FieldKind::Radio(choices) => FieldKindDef::Radio(owned_choices(choices)),
364            FieldKind::Color => FieldKindDef::Color,
365            FieldKind::Image => FieldKindDef::Image,
366            FieldKind::File => FieldKindDef::File,
367            FieldKind::Link => FieldKindDef::Link,
368            FieldKind::Wysiwyg => FieldKindDef::Wysiwyg,
369            FieldKind::PostObject => FieldKindDef::PostObject,
370            FieldKind::Relationship => FieldKindDef::Relationship,
371            FieldKind::Taxonomy => FieldKindDef::Taxonomy,
372            FieldKind::User => FieldKindDef::User,
373            FieldKind::Repeater(fields) => FieldKindDef::Repeater(owned_fields(fields)),
374            FieldKind::Group(fields) => FieldKindDef::Group(owned_fields(fields)),
375            FieldKind::FlexibleContent(blocks) => {
376                FieldKindDef::FlexibleContent(blocks.iter().copied().map(BlockDef::from).collect())
377            }
378            FieldKind::Gallery => FieldKindDef::Gallery,
379            FieldKind::Clone(fields) => FieldKindDef::Clone(owned_fields(fields)),
380        }
381    }
382}
383
384/// One input on the form of a runtime resource: the owned twin of [`Field`].
385#[derive(Debug, Clone, PartialEq, Eq, Hash)]
386pub struct FieldDef {
387    /// The form field name. It matches a key of the row.
388    pub name: String,
389    /// The label shown next to the input.
390    pub label: String,
391    /// The input type, and how the value is read.
392    pub kind: FieldKindDef,
393    /// Whether the form rejects a blank value.
394    pub required: bool,
395}
396
397impl From<Field> for FieldDef {
398    fn from(field: Field) -> Self {
399        FieldDef {
400            name: field.name.to_string(),
401            label: field.label.to_string(),
402            kind: field.kind.into(),
403            required: field.required,
404        }
405    }
406}
407
408/// One column of the list of a runtime resource: the owned twin of [`Column`].
409#[derive(Debug, Clone, PartialEq, Eq, Hash)]
410pub struct ColumnDef {
411    /// The row key the column shows. It matches a field name.
412    pub key: String,
413    /// The column heading.
414    pub label: String,
415    /// Whether the heading links to a sort by this column.
416    pub sortable: bool,
417    /// Whether the search box matches this column.
418    pub searchable: bool,
419}
420
421impl From<Column> for ColumnDef {
422    fn from(column: Column) -> Self {
423        ColumnDef {
424            key: column.key.to_string(),
425            label: column.label.to_string(),
426            sortable: column.sortable,
427            searchable: column.searchable,
428        }
429    }
430}
431
432/// A resource defined by data. Build it with [`new`](Self::new) and the
433/// [`field`](Self::field) and [`column`](Self::column) methods, then add it to the panel
434/// with [`register_runtime`].
435#[derive(Clone)]
436pub struct RuntimeResource {
437    /// URL segment: `"books"` serves the resource at `/admin/books`. Lowercase letters,
438    /// digits, `-` and `_` only.
439    pub slug: String,
440    /// Heading and navigation label: `"Books"`.
441    pub title: String,
442    /// The name of one record, for headings such as "New Book".
443    pub singular: String,
444    /// Rows per page on the list view. The default is 20, as for a static resource.
445    pub per_page: i64,
446    /// Form fields, in display order.
447    pub fields: Vec<FieldDef>,
448    /// Table columns, in display order. Each column's `key` is a field name.
449    pub columns: Vec<ColumnDef>,
450    /// Where the rows live.
451    pub data: Arc<dyn RuntimeData>,
452    /// The label of the navigation entry, as Filament's `$navigationLabel`. `None`, the
453    /// default, is the [`title`](Self::title).
454    pub navigation_label: Option<String>,
455    /// The navigation group the resource is listed under, as Filament's `$navigationGroup`.
456    /// See [`IgniteResource::NAVIGATION_GROUP`](crate::IgniteResource::NAVIGATION_GROUP).
457    pub navigation_group: Option<String>,
458    /// The resource's place in the navigation, as Filament's `$navigationSort`: lower first.
459    /// See [`IgniteResource::NAVIGATION_SORT`](crate::IgniteResource::NAVIGATION_SORT).
460    pub navigation_sort: Option<i32>,
461    /// The navigation entry the resource is listed under, as Filament's
462    /// `$navigationParentItem`: the parent's label or slug. See
463    /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
464    pub navigation_parent_item: Option<String>,
465    /// The name of the navigation entry's icon, such as `post`, as Filament's
466    /// `$navigationIcon`. See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
467    pub navigation_icon: Option<String>,
468    /// Whether the navigation entry lists a link to the create page. The default is `true`.
469    /// See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
470    pub navigation_create_item: bool,
471    /// The label of the create link. `None`, the default, is `"Add new"`.
472    pub navigation_create_label: Option<String>,
473    /// The conditions that show or hide the form's fields, and the live fields, as
474    /// Filament's `visible()`, `hidden()` and `live()`. See [`FieldConditions`].
475    pub conditions: FieldConditions,
476    /// The layout of the create and edit forms, as Filament's layout components. See
477    /// [`FormLayout`]. The default has none: the form renders as one card of fields.
478    pub form_layout: FormLayout,
479    /// The tabs of the list page, in display order, as Filament's `getTabs()`. See
480    /// [`IgniteResource::tabs`](crate::IgniteResource::tabs). The default is none.
481    pub tabs: Vec<Tab>,
482    /// The key of the tab shown when the list has no `tab` parameter, as Filament's
483    /// `getDefaultActiveTab()`. `None`, the default, is the first tab.
484    pub default_active_tab: Option<String>,
485    /// The list columns shown as coloured badges, as Filament's `badge()` and `color()`. See
486    /// [`ColumnBadges`]. The default is none.
487    pub column_badges: ColumnBadges,
488    /// Whether each tab's count is for the current search. The default is `false`: a tab
489    /// counts all its rows. See
490    /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
491    pub tab_counts_follow_search: bool,
492    /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
493    /// The default is `true`. See
494    /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
495    pub hide_empty_tabs: bool,
496    /// The actions on each row of the list page, in display order, as Filament's
497    /// `recordActions()`. See [`RowAction`]. The default is none.
498    pub row_actions: Vec<RowAction>,
499    /// The records whose built-in Delete button is hidden (and whose delete the panel
500    /// refuses). See
501    /// [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
502    /// The default is none.
503    pub hide_default_delete_when: Option<ListFilter>,
504}
505
506impl fmt::Debug for RuntimeResource {
507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508        f.debug_struct("RuntimeResource")
509            .field("slug", &self.slug)
510            .field("title", &self.title)
511            .field("singular", &self.singular)
512            .field("per_page", &self.per_page)
513            .field("fields", &self.fields)
514            .field("columns", &self.columns)
515            .field("navigation_label", &self.navigation_label)
516            .field("navigation_group", &self.navigation_group)
517            .field("navigation_sort", &self.navigation_sort)
518            .field("navigation_parent_item", &self.navigation_parent_item)
519            .field("navigation_icon", &self.navigation_icon)
520            .field("navigation_create_item", &self.navigation_create_item)
521            .field("navigation_create_label", &self.navigation_create_label)
522            .field("conditions", &self.conditions)
523            .field("form_layout", &self.form_layout)
524            .field("tabs", &self.tabs)
525            .field("default_active_tab", &self.default_active_tab)
526            .field("column_badges", &self.column_badges)
527            .field("tab_counts_follow_search", &self.tab_counts_follow_search)
528            .field("hide_empty_tabs", &self.hide_empty_tabs)
529            .field("row_actions", &self.row_actions)
530            .field("hide_default_delete_when", &self.hide_default_delete_when)
531            .finish_non_exhaustive()
532    }
533}
534
535impl RuntimeResource {
536    /// A resource at `slug` with no fields or columns yet, whose rows come from `data`.
537    pub fn new(
538        slug: impl Into<String>,
539        title: impl Into<String>,
540        singular: impl Into<String>,
541        data: impl RuntimeData,
542    ) -> Self {
543        RuntimeResource {
544            slug: slug.into(),
545            title: title.into(),
546            singular: singular.into(),
547            per_page: 20,
548            fields: Vec::new(),
549            columns: Vec::new(),
550            data: Arc::new(data),
551            navigation_label: None,
552            navigation_group: None,
553            navigation_sort: None,
554            navigation_parent_item: None,
555            navigation_icon: None,
556            navigation_create_item: true,
557            navigation_create_label: None,
558            conditions: FieldConditions::new(),
559            form_layout: FormLayout::new(),
560            tabs: Vec::new(),
561            default_active_tab: None,
562            column_badges: ColumnBadges::new(),
563            tab_counts_follow_search: false,
564            hide_empty_tabs: true,
565            row_actions: Vec::new(),
566            hide_default_delete_when: None,
567        }
568    }
569
570    /// Adds a form field after the others.
571    pub fn field(mut self, field: FieldDef) -> Self {
572        self.fields.push(field);
573        self
574    }
575
576    /// Adds a list column after the others.
577    pub fn column(mut self, column: ColumnDef) -> Self {
578        self.columns.push(column);
579        self
580    }
581
582    /// Sets the rows per page of the list view.
583    pub fn per_page(mut self, per_page: i64) -> Self {
584        self.per_page = per_page;
585        self
586    }
587
588    /// Sets the label of the navigation entry, as Filament's `navigationLabel`.
589    pub fn navigation_label(mut self, label: impl Into<String>) -> Self {
590        self.navigation_label = Some(label.into());
591        self
592    }
593
594    /// Lists the resource under the navigation group `group`, as Filament's `navigationGroup`.
595    pub fn navigation_group(mut self, group: impl Into<String>) -> Self {
596        self.navigation_group = Some(group.into());
597        self
598    }
599
600    /// Sets the resource's place in the navigation, as Filament's `navigationSort`: lower first.
601    pub fn navigation_sort(mut self, sort: i32) -> Self {
602        self.navigation_sort = Some(sort);
603        self
604    }
605
606    /// Lists the resource under the navigation entry `parent` (its label or slug), as
607    /// Filament's `navigationParentItem`. See
608    /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
609    pub fn navigation_parent_item(mut self, parent: impl Into<String>) -> Self {
610        self.navigation_parent_item = Some(parent.into());
611        self
612    }
613
614    /// Sets the name of the navigation entry's icon, as Filament's `navigationIcon`: a name
615    /// such as `"post"` or a custom post type's own, which the admin theme maps to its icon.
616    /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
617    pub fn navigation_icon(mut self, name: impl Into<String>) -> Self {
618        self.navigation_icon = Some(name.into());
619        self
620    }
621
622    /// Whether the navigation entry lists a link to the create page, under the entry, in its
623    /// group. See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
624    pub fn navigation_create_item(mut self, listed: bool) -> Self {
625        self.navigation_create_item = listed;
626        self
627    }
628
629    /// Sets the label of the create link, such as `"Add New Post"`. See
630    /// [`IgniteResource::NAVIGATION_CREATE_LABEL`](crate::IgniteResource::NAVIGATION_CREATE_LABEL).
631    pub fn navigation_create_label(mut self, label: impl Into<String>) -> Self {
632        self.navigation_create_label = Some(label.into());
633        self
634    }
635
636    /// Shows the field `field` only when `rule` holds, as Filament's `->visible()`. See
637    /// [`FieldConditions::visible`].
638    pub fn visible(
639        mut self,
640        field: impl Into<String>,
641        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
642    ) -> Self {
643        self.conditions = self.conditions.visible(field, rule);
644        self
645    }
646
647    /// Hides the field `field` when `rule` holds, as Filament's `->hidden()`. See
648    /// [`FieldConditions::hidden`].
649    pub fn hidden(
650        mut self,
651        field: impl Into<String>,
652        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
653    ) -> Self {
654        self.conditions = self.conditions.hidden(field, rule);
655        self
656    }
657
658    /// Shows the field `field` only on the forms of `operations`, as Filament's
659    /// `->visibleOn()`.
660    pub fn visible_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
661        self.conditions = self.conditions.visible_on(field, operations);
662        self
663    }
664
665    /// Hides the field `field` on the forms of `operations`, as Filament's `->hiddenOn()`.
666    pub fn hidden_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
667        self.conditions = self.conditions.hidden_on(field, operations);
668        self
669    }
670
671    /// Makes the field `field` live, as Filament's `->live()`: a change to it in the browser
672    /// shows the form's fields again for the new value. See [`FieldConditions::live`].
673    pub fn live(mut self, field: impl Into<String>) -> Self {
674        self.conditions = self.conditions.live(field);
675        self
676    }
677
678    /// Fills the field `field` with the slug of the field `source` until the user edits it, as
679    /// Filament's slug pattern. See [`FieldConditions::slug_from`].
680    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
681        self.conditions = self.conditions.slug_from(field, source);
682        self
683    }
684
685    /// Stops the slug field `field` from following its source on the edit form of a record
686    /// with a stored slug, when `rule` holds, such as once the record is published. See
687    /// [`FieldConditions::slug_locked_when`].
688    pub fn slug_locked_when(
689        mut self,
690        field: impl Into<String>,
691        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
692    ) -> Self {
693        self.conditions = self.conditions.slug_locked_when(field, rule);
694        self
695    }
696
697    /// Sets the layout of the create and edit forms: columns, sections and groups, as
698    /// Filament's layout components. See [`FormLayout`].
699    pub fn form_layout(mut self, layout: FormLayout) -> Self {
700        self.form_layout = layout;
701        self
702    }
703
704    /// Adds a tab to the list page after the others, as a [`Tab`] in Filament's `getTabs()`.
705    /// The [`RuntimeData`] list is given the active tab's conditions in
706    /// [`ListQuery::filter`]: apply them with [`ListFilter::apply`](crate::ListFilter::apply)
707    /// or [`ListFilter::matches`](crate::ListFilter::matches).
708    pub fn tab(mut self, tab: Tab) -> Self {
709        self.tabs.push(tab);
710        self
711    }
712
713    /// Sets the tab shown when the list has no `tab` parameter, by its key, as Filament's
714    /// `getDefaultActiveTab()`. Without it, the first tab is shown.
715    pub fn default_active_tab(mut self, key: impl Into<String>) -> Self {
716        self.default_active_tab = Some(key.into());
717        self
718    }
719
720    /// Whether each tab's count is for the current search. The default, `false`, counts all
721    /// of a tab's rows. See
722    /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
723    pub fn tab_counts_follow_search(mut self, follow: bool) -> Self {
724        self.tab_counts_follow_search = follow;
725        self
726    }
727
728    /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
729    /// The default is `true`; `false` renders every tab. See
730    /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
731    pub fn hide_empty_tabs(mut self, hide: bool) -> Self {
732        self.hide_empty_tabs = hide;
733        self
734    }
735
736    /// Adds an action on each row of the list, after the others, as an action in Filament's
737    /// `recordActions()`. See [`RowAction`].
738    pub fn row_action(mut self, action: RowAction) -> Self {
739        self.row_actions.push(action);
740        self
741    }
742
743    /// Hides the built-in Delete button on the records that meet `filter`, and refuses their
744    /// delete, such as `ListFilter::new().where_eq("status", "trash")` for a post in the trash.
745    /// See [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
746    pub fn hide_default_delete_when(mut self, filter: ListFilter) -> Self {
747        self.hide_default_delete_when = Some(filter);
748        self
749    }
750
751    /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`.
752    /// See [`ColumnBadges::badge`].
753    pub fn badge(mut self, column: impl Into<String>) -> Self {
754        self.column_badges = self.column_badges.badge(column);
755        self
756    }
757
758    /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
759    /// as Filament's `->badge()->color(fn (string $state) => ...)`. See
760    /// [`ColumnBadges::badge_color`].
761    pub fn badge_color(
762        mut self,
763        column: impl Into<String>,
764        color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
765    ) -> Self {
766        self.column_badges = self.column_badges.badge_color(column, color);
767        self
768    }
769
770    /// Shows the badge of the column `column` inside the cell of the column `target`, instead
771    /// of in a column of its own. See [`ColumnBadges::badge_inside`].
772    pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
773        self.column_badges = self.column_badges.badge_inside(column, target);
774        self
775    }
776
777    /// Shows the badge of the column `column` only on the list's tabs `tabs`, by key. See
778    /// [`ColumnBadges::badge_on_tabs`].
779    pub fn badge_on_tabs<S: Into<String>>(
780        mut self,
781        column: impl Into<String>,
782        tabs: impl IntoIterator<Item = S>,
783    ) -> Self {
784        self.column_badges = self.column_badges.badge_on_tabs(column, tabs);
785        self
786    }
787}
788
789/// The checks of [`RegisteredResource::validate`]. Each error is keyed by its field's name.
790/// The fields of `hidden` are skipped: they are not checked and the row has no key for them.
791fn validate_fields(
792    fields: &[FieldDef],
793    form: &FormInput,
794    creating: bool,
795    hidden: &BTreeSet<String>,
796) -> Result<Row, FieldErrors> {
797    let mut errors = FieldErrors::new();
798    let mut row = Row::new();
799    for field in fields.iter().filter(|f| !hidden.contains(&f.name)) {
800        let name = field.name.as_str();
801        let label = field.label.as_str();
802        // A checkbox is never blank: an unticked checkbox is false.
803        if field.kind == FieldKindDef::Checkbox {
804            row.insert(name.to_string(), Value::Bool(form.checkbox(name)));
805            continue;
806        }
807        let is_password = field.kind == FieldKindDef::Password;
808        // A password is required only when creating. On an edit a blank one keeps the hash.
809        let present = if field.required && (creating || !is_password) {
810            check::check_required(name, label, form, &mut errors)
811        } else {
812            form.get(name)
813        };
814        let Some(text) = present else {
815            // On an update, a field the form did not send keeps its stored value, and a blank
816            // password keeps its hash. A field sent blank is cleared to NULL.
817            let keep = !creating && (is_password || !form.has(name));
818            if !keep {
819                row.insert(name.to_string(), Value::Null);
820            }
821            continue;
822        };
823        let value = match &field.kind {
824            FieldKindDef::Password => match crate::hash_password(text) {
825                Ok(hash) => Some(Value::String(hash)),
826                Err(_) => {
827                    errors.insert(
828                        name.to_string(),
829                        "Could not save this password.".to_string(),
830                    );
831                    None
832                }
833            },
834            FieldKindDef::Number => {
835                check::check_whole_number::<i64>(name, label, text, &mut errors).map(Value::from)
836            }
837            FieldKindDef::Decimal(_) => {
838                check::check_decimal::<f64>(name, label, text, &mut errors).map(Value::from)
839            }
840            FieldKindDef::Select(choices) => {
841                let text = text.trim();
842                let choices: Vec<(&str, &str)> = choices
843                    .iter()
844                    .map(|(value, label)| (value.as_str(), label.as_str()))
845                    .collect();
846                check::check_choice(name, text, &choices, &mut errors)
847                    .then(|| Value::String(text.to_string()))
848            }
849            FieldKindDef::Lookup => Some(Value::String(text.trim().to_string())),
850            FieldKindDef::Date => check::check_date(name, label, text, &mut errors)
851                .map(|date| Value::String(date.format("%Y-%m-%d").to_string())),
852            FieldKindDef::DateTime => check::check_datetime(name, label, text, &mut errors)
853                .map(|stamp| Value::String(stamp.format("%Y-%m-%d %H:%M:%S").to_string())),
854            FieldKindDef::Text | FieldKindDef::Textarea | FieldKindDef::Checkbox => {
855                Some(Value::String(text.to_string()))
856            }
857            kind => crate::value::check_value(name, label, field.required, kind, text, &mut errors)
858                .map(Value::String),
859        };
860        if let Some(value) = value {
861            row.insert(name.to_string(), value);
862        }
863    }
864    if errors.is_empty() {
865        Ok(row)
866    } else {
867        Err(errors)
868    }
869}
870
871/// Why the registry refused a change.
872#[derive(Debug, Clone, PartialEq, Eq)]
873pub enum RuntimeError {
874    /// The slug is not one URL segment of lowercase letters, digits, `-` and `_`.
875    InvalidSlug(String),
876    /// Another resource, static or runtime, or one of the panel's own pages, has the slug.
877    SlugTaken(String),
878    /// A field name is not a lowercase identifier: lowercase ASCII letters, digits and `_`,
879    /// starting with a letter, at most 64 bytes ([`MAX_FIELD_NAME`]).
880    InvalidFieldName {
881        /// The slug of the resource.
882        slug: String,
883        /// The name that was refused.
884        field: String,
885    },
886    /// Two fields of the resource have the same name.
887    DuplicateField {
888        /// The slug of the resource.
889        slug: String,
890        /// The name used twice.
891        field: String,
892    },
893    /// No runtime resource has the slug.
894    NotRegistered(String),
895}
896
897impl fmt::Display for RuntimeError {
898    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899        match self {
900            RuntimeError::InvalidSlug(slug) => write!(
901                f,
902                "the slug `{slug}` is not valid: use lowercase letters, digits, `-` and `_`"
903            ),
904            RuntimeError::SlugTaken(slug) => write!(
905                f,
906                "the slug `{slug}` is already used by another Ignite resource"
907            ),
908            RuntimeError::InvalidFieldName { slug, field } => write!(
909                f,
910                "the field `{field}` of the resource `{slug}` is not valid: use lowercase \
911                 letters, digits and `_`, starting with a letter, at most {MAX_FIELD_NAME} bytes"
912            ),
913            RuntimeError::DuplicateField { slug, field } => {
914                write!(f, "the resource `{slug}` has two fields named `{field}`")
915            }
916            RuntimeError::NotRegistered(slug) => {
917                write!(f, "no runtime resource is registered at `{slug}`")
918            }
919        }
920    }
921}
922
923impl std::error::Error for RuntimeError {}
924
925/// A runtime resource as the registry holds it: the definition, ready for the panel.
926pub struct RegisteredResource {
927    resource: RuntimeResource,
928}
929
930impl RegisteredResource {
931    /// The definition that was registered.
932    pub fn resource(&self) -> &RuntimeResource {
933        &self.resource
934    }
935
936    /// The slug, as the panel's routes match it.
937    pub fn slug(&self) -> &str {
938        &self.resource.slug
939    }
940
941    /// The heading and navigation label.
942    pub fn title(&self) -> &str {
943        &self.resource.title
944    }
945
946    /// The name of one record.
947    pub fn singular(&self) -> &str {
948        &self.resource.singular
949    }
950
951    /// The label of the navigation entry: the navigation label, or the title.
952    pub fn navigation_label(&self) -> &str {
953        self.resource
954            .navigation_label
955            .as_deref()
956            .unwrap_or(&self.resource.title)
957    }
958
959    /// The navigation group the resource is listed under, if any.
960    pub fn navigation_group(&self) -> Option<&str> {
961        self.resource.navigation_group.as_deref()
962    }
963
964    /// The resource's place in the navigation, if set.
965    pub fn navigation_sort(&self) -> Option<i32> {
966        self.resource.navigation_sort
967    }
968
969    /// The navigation entry the resource is listed under, if any.
970    pub fn navigation_parent_item(&self) -> Option<&str> {
971        self.resource.navigation_parent_item.as_deref()
972    }
973
974    /// The name of the navigation entry's icon, if set.
975    pub fn navigation_icon(&self) -> Option<&str> {
976        self.resource.navigation_icon.as_deref()
977    }
978
979    /// The label of the navigation entry's create link, or `None` when it lists none.
980    pub fn navigation_create_item(&self) -> Option<&str> {
981        self.resource.navigation_create_item.then(|| {
982            self.resource
983                .navigation_create_label
984                .as_deref()
985                .unwrap_or("Add new")
986        })
987    }
988
989    /// The form fields, in display order.
990    pub fn fields(&self) -> &[FieldDef] {
991        &self.resource.fields
992    }
993
994    /// The list columns, in display order.
995    pub fn columns(&self) -> &[ColumnDef] {
996        &self.resource.columns
997    }
998
999    /// Turns the submitted form into a [`Row`] for a create, or returns one message per
1000    /// field. It runs the same checks as a static resource, with the same messages:
1001    /// required fields ([`Field::check_required`](crate::Field::check_required)), whole
1002    /// numbers, decimals, dates, date-times and select choices. The row holds one key per
1003    /// field:
1004    ///
1005    /// - text, textarea, select, lookup: a string. A required value is trimmed.
1006    /// - email, URL, radio, color, image, file, link, wysiwyg, post object, relationship,
1007    ///   taxonomy, user, repeater, group, flexible content, gallery, clone: the text
1008    ///   [`Field::check_value`](crate::Field::check_value) returns. The structured kinds
1009    ///   hold JSON text.
1010    /// - number: an integer. Decimal: a number.
1011    /// - checkbox: `true` or `false`; a checkbox is never blank.
1012    /// - date: `"YYYY-MM-DD"`. Date-time: `"YYYY-MM-DD HH:MM:SS"`.
1013    /// - password: the hash of the password ([`hash_password`](crate::hash_password)).
1014    /// - a blank field that is not required: `null`.
1015    ///
1016    /// Each error in [`FieldErrors`] is keyed by the field's name, an owned `String`.
1017    ///
1018    /// A lookup, post object, relationship, taxonomy or user value is checked against
1019    /// [`RuntimeData::options`] by the panel, which can read the database, and so is a media
1020    /// id against the registered [`MediaLibrary`](crate::MediaLibrary).
1021    pub fn validate(&self, form: &FormInput) -> Result<Row, FieldErrors> {
1022        validate_fields(&self.resource.fields, form, true, &BTreeSet::new())
1023    }
1024
1025    /// Turns the submitted form into a [`Row`] for an update. It is
1026    /// [`validate`](Self::validate), except that:
1027    ///
1028    /// - a blank password is not an error: the row leaves its key out, so the stored
1029    ///   password is kept;
1030    /// - an optional field the form did not send at all ([`FormInput::has`] is false) is left
1031    ///   out of the row, so its stored value is kept;
1032    /// - an optional field sent blank is `null`, so clearing it on the edit form clears the
1033    ///   stored value, as `#[derive(IgniteResource)]` does since 0.3.0;
1034    /// - a checkbox the form did not send is `false`, because an unticked HTML checkbox sends
1035    ///   nothing.
1036    pub fn validate_update(&self, form: &FormInput) -> Result<Row, FieldErrors> {
1037        validate_fields(&self.resource.fields, form, false, &BTreeSet::new())
1038    }
1039
1040    /// The conditions that show or hide the form's fields.
1041    pub fn conditions(&self) -> &FieldConditions {
1042        &self.resource.conditions
1043    }
1044
1045    /// The layout of the create and edit forms.
1046    pub fn form_layout(&self) -> &FormLayout {
1047        &self.resource.form_layout
1048    }
1049
1050    /// The tabs of the list page, in display order.
1051    pub fn tabs(&self) -> &[Tab] {
1052        &self.resource.tabs
1053    }
1054
1055    /// The key of the tab shown when the list has no `tab` parameter, if set.
1056    pub fn default_active_tab(&self) -> Option<&str> {
1057        self.resource.default_active_tab.as_deref()
1058    }
1059
1060    /// The list columns shown as coloured badges.
1061    pub fn column_badges(&self) -> &ColumnBadges {
1062        &self.resource.column_badges
1063    }
1064
1065    /// Whether each tab's count is for the current search.
1066    pub fn tab_counts_follow_search(&self) -> bool {
1067        self.resource.tab_counts_follow_search
1068    }
1069
1070    /// Whether a tab whose count is 0 is left out.
1071    pub fn hide_empty_tabs(&self) -> bool {
1072        self.resource.hide_empty_tabs
1073    }
1074
1075    /// The actions on each row of the list, in display order.
1076    pub fn row_actions(&self) -> &[RowAction] {
1077        &self.resource.row_actions
1078    }
1079
1080    /// The records whose built-in Delete button is hidden, if set.
1081    pub fn hide_default_delete_when(&self) -> Option<&ListFilter> {
1082        self.resource.hide_default_delete_when.as_ref()
1083    }
1084
1085    /// [`validate`](Self::validate) for a form whose fields `hidden` are hidden (see
1086    /// [`FieldConditions::hidden_fields`]): they are not checked, a required one included, and
1087    /// the row has no key for them, so the source writes nothing for them. The panel calls it.
1088    pub fn validate_shown(
1089        &self,
1090        form: &FormInput,
1091        hidden: &BTreeSet<String>,
1092    ) -> Result<Row, FieldErrors> {
1093        validate_fields(&self.resource.fields, form, true, hidden)
1094    }
1095
1096    /// [`validate_update`](Self::validate_update) for a form whose fields `hidden` are hidden:
1097    /// the row has no key for them, so their stored values are kept, whatever the form sent.
1098    pub fn validate_update_shown(
1099        &self,
1100        form: &FormInput,
1101        hidden: &BTreeSet<String>,
1102    ) -> Result<Row, FieldErrors> {
1103        validate_fields(&self.resource.fields, form, false, hidden)
1104    }
1105}
1106
1107/// The registry: the runtime resources in registration order, and the slugs reserved for
1108/// static resources and for the panel's own pages.
1109#[derive(Default)]
1110struct Registry {
1111    resources: Vec<Arc<RegisteredResource>>,
1112    reserved: HashSet<String>,
1113}
1114
1115static REGISTRY: RwLock<Option<Registry>> = RwLock::new(None);
1116
1117/// Runs `f` on the registry, read-only. The lock is never held across an `.await`: every
1118/// caller is synchronous.
1119fn read<T>(f: impl FnOnce(&Registry) -> T) -> T {
1120    let guard = REGISTRY.read().unwrap_or_else(PoisonError::into_inner);
1121    match guard.as_ref() {
1122        Some(registry) => f(registry),
1123        None => f(&Registry::default()),
1124    }
1125}
1126
1127/// Runs `f` on the registry, to change it.
1128fn write<T>(f: impl FnOnce(&mut Registry) -> T) -> T {
1129    let mut guard = REGISTRY.write().unwrap_or_else(PoisonError::into_inner);
1130    f(guard.get_or_insert_with(Registry::default))
1131}
1132
1133/// The longest field name a runtime resource accepts, in bytes, as for a MySQL or MariaDB
1134/// column name. The limit is a validation rule: names are owned by their resource and freed
1135/// with it.
1136pub const MAX_FIELD_NAME: usize = 64;
1137
1138/// Whether `name` is a field name a runtime resource accepts: lowercase ASCII letters, digits
1139/// and `_`, starting with a letter, at most [`MAX_FIELD_NAME`] bytes, as a column name is.
1140fn valid_field_name(name: &str) -> bool {
1141    name.len() <= MAX_FIELD_NAME
1142        && name.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
1143        && name
1144            .bytes()
1145            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
1146}
1147
1148/// Whether `slug` is one URL segment the panel's `/<slug>` routes match: lowercase ASCII
1149/// letters, digits, `-` and `_`, as Filament's kebab-case slugs are.
1150fn valid_slug(slug: &str) -> bool {
1151    !slug.is_empty()
1152        && slug
1153            .bytes()
1154            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1155}
1156
1157/// Adds a runtime resource to the panel. It shows in the navigation and the dashboard, and
1158/// its list, forms and delete action answer at `/<mount>/<slug>`, from the next request on.
1159/// Create its permissions (`<slug>.viewAny` and the others) in the same request with
1160/// `ignite_panel::register_runtime_permissions`; otherwise the panel creates them on the next
1161/// signed-in request.
1162///
1163/// Refuses a slug that is not valid, a slug that a static resource, another runtime resource
1164/// or one of the panel's own pages (such as `login`) uses, and two fields with one name.
1165pub fn register_runtime(resource: RuntimeResource) -> Result<(), RuntimeError> {
1166    if !valid_slug(&resource.slug) {
1167        return Err(RuntimeError::InvalidSlug(resource.slug));
1168    }
1169    if let Some(field) = resource.fields.iter().find(|f| !valid_field_name(&f.name)) {
1170        return Err(RuntimeError::InvalidFieldName {
1171            slug: resource.slug.clone(),
1172            field: field.name.clone(),
1173        });
1174    }
1175    let mut names = HashSet::new();
1176    if let Some(field) = resource.fields.iter().find(|f| !names.insert(&f.name)) {
1177        return Err(RuntimeError::DuplicateField {
1178            slug: resource.slug.clone(),
1179            field: field.name.clone(),
1180        });
1181    }
1182    write(|registry| {
1183        let slug = resource.slug.as_str();
1184        if registry.reserved.contains(slug) || registry.resources.iter().any(|r| r.slug() == slug) {
1185            return Err(RuntimeError::SlugTaken(resource.slug.clone()));
1186        }
1187        registry
1188            .resources
1189            .push(Arc::new(RegisteredResource { resource }));
1190        Ok(())
1191    })
1192}
1193
1194/// Removes the runtime resource at `slug`. From the next request on, it is gone from the
1195/// navigation and its routes answer 404. Its permission rows stay, so the grants come back
1196/// if the resource is registered again.
1197pub fn unregister_runtime(slug: &str) -> Result<(), RuntimeError> {
1198    write(|registry| {
1199        let before = registry.resources.len();
1200        registry.resources.retain(|r| r.slug() != slug);
1201        if registry.resources.len() == before {
1202            Err(RuntimeError::NotRegistered(slug.to_string()))
1203        } else {
1204            Ok(())
1205        }
1206    })
1207}
1208
1209/// The runtime resource at `slug`, if one is registered.
1210pub fn runtime_resource(slug: &str) -> Option<Arc<RegisteredResource>> {
1211    read(|registry| {
1212        registry
1213            .resources
1214            .iter()
1215            .find(|r| r.slug() == slug)
1216            .cloned()
1217    })
1218}
1219
1220/// Every runtime resource, in registration order.
1221pub fn runtime_resources() -> Vec<Arc<RegisteredResource>> {
1222    read(|registry| registry.resources.clone())
1223}
1224
1225/// Reserves `slugs`, so no runtime resource can take them. The panel reserves the slugs of
1226/// its static resources and of its own pages when it is built. Reserving a slug twice is
1227/// fine. Refuses, and reserves none, when a runtime resource already has one of them.
1228pub fn reserve_slugs(slugs: &[&str]) -> Result<(), RuntimeError> {
1229    write(|registry| {
1230        if let Some(slug) = slugs
1231            .iter()
1232            .find(|slug| registry.resources.iter().any(|r| r.slug() == **slug))
1233        {
1234            return Err(RuntimeError::SlugTaken(slug.to_string()));
1235        }
1236        registry
1237            .reserved
1238            .extend(slugs.iter().map(|slug| slug.to_string()));
1239        Ok(())
1240    })
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245    use super::*;
1246
1247    struct NoData;
1248
1249    impl RuntimeData for NoData {
1250        fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
1251            unreachable!()
1252        }
1253        fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
1254            unreachable!()
1255        }
1256        fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
1257            unreachable!()
1258        }
1259        fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
1260            unreachable!()
1261        }
1262        fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
1263            unreachable!()
1264        }
1265    }
1266
1267    /// A resource with the fields `growth_title` and `growth_status`, whose label and
1268    /// choices change with `n`.
1269    fn edited(slug: &str, n: usize) -> RuntimeResource {
1270        RuntimeResource::new(slug, format!("Title {n}"), format!("One {n}"), NoData)
1271            .field(FieldDef {
1272                name: "growth_title".into(),
1273                label: format!("Title {n}"),
1274                kind: FieldKindDef::Text,
1275                required: n.is_multiple_of(2),
1276            })
1277            .field(FieldDef {
1278                name: "growth_status".into(),
1279                label: format!("Status {n}"),
1280                kind: FieldKindDef::Select(vec![(format!("v{n}"), format!("Value {n}"))]),
1281                required: false,
1282            })
1283            .column(ColumnDef {
1284                key: "growth_title".into(),
1285                label: format!("Column {n}"),
1286                sortable: false,
1287                searchable: false,
1288            })
1289    }
1290
1291    // Field names are owned by their resource: editing a definition a thousand times keeps
1292    // nothing of the old ones, and an error is keyed by the field's own name.
1293    #[test]
1294    fn editing_a_definition_a_thousand_times_keeps_owned_names() {
1295        register_runtime(edited("growth", 0)).expect("register");
1296        for n in 1..=1000 {
1297            unregister_runtime("growth").expect("unregister");
1298            register_runtime(edited("growth", n)).expect("register again");
1299            let registered = runtime_resource("growth").expect("registered");
1300            let mut values = std::collections::HashMap::new();
1301            values.insert("growth_status".to_string(), "not a choice".to_string());
1302            let errors = registered
1303                .validate(&FormInput::new(values.clone()))
1304                .unwrap_err();
1305            assert!(errors.contains_key("growth_status"));
1306            let _ = registered.validate_update(&FormInput::new(values));
1307        }
1308        // The last registration is the only one the registry holds.
1309        let registered = runtime_resource("growth").expect("registered");
1310        assert_eq!(registered.title(), "Title 1000");
1311        assert_eq!(
1312            runtime_resources()
1313                .iter()
1314                .filter(|r| r.slug() == "growth")
1315                .count(),
1316            1
1317        );
1318        unregister_runtime("growth").expect("unregister");
1319    }
1320}