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 [`Registries::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::{BTreeMap, BTreeSet, HashSet};
21use std::fmt;
22use std::future::Future;
23use std::pin::Pin;
24use std::sync::{Arc, PoisonError};
25
26use orbit_orm::{Database, Error};
27use serde_json::{Map, Value};
28
29use crate::action::{BulkAction, 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, ResourceAction};
36use crate::query::{ListQuery, Page};
37use crate::registries::Registries;
38use crate::structure::{RepeaterSettings, Repeaters};
39
40/// One record of a runtime resource: its values by key, as JSON. A row the panel lists or
41/// edits must have a numeric `id`, and a key for each field and column it shows.
42pub type Row = Map<String, Value>;
43
44/// A rule on a record's form, given its [`FormContext`]: the operation, the record, the user
45/// and the form's values, as a Filament closure is given `$record` and `$operation`.
46pub type FormRule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
47
48/// A line a record's form shows, from its [`FormContext`], or none.
49pub type FormNotice = Arc<dyn Fn(&FormContext<'_>) -> Option<String> + Send + Sync>;
50
51/// The future a [`RuntimeData`] method returns: boxed, so the trait can be a trait object.
52/// Write the body as `Box::pin(async move { ... })`.
53pub type RuntimeFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;
54
55/// Where the rows of a runtime resource live. The app implements it, so Ignite assumes no
56/// table layout: a custom post type can keep its rows in a shared `posts` table and its
57/// values in a meta table.
58///
59/// The methods mirror the queries of [`IgniteResource`](crate::IgniteResource), with
60/// [`Row`]s for records and for validated input. The panel calls the `*_for` methods, which
61/// are given the signed-in [`ActingUser`]; by default each calls its method without the user,
62/// so a source that does not depend on the user implements only those.
63pub trait RuntimeData: Send + Sync + 'static {
64    /// Returns one page of rows that match `query`. The sort key, when there is one, is a
65    /// sortable column of the resource. The rows and the total must meet the active tab's
66    /// conditions in [`ListQuery::filter`] (see [`ListFilter`](crate::ListFilter)); a
67    /// `per_page` of 0 asks only for the total, to count a tab's rows.
68    fn list<'a>(&'a self, db: &'a Database, query: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>>;
69    /// Returns the row with `id`, or `None` if there is no such row.
70    fn find<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, Option<Row>>;
71    /// Inserts a row from the validated `input` and returns it. See
72    /// [`RegisteredResource::validate`] for the values `input` holds.
73    ///
74    /// An [`Error::UniqueViolation`] whose index is named `{slug}_{field}_unique` shows on the
75    /// form as `"<label> is already taken."`, as for a static resource. Any other error is a
76    /// server error. A source whose indexes are named otherwise (or that keeps values in a
77    /// meta table without such an index) should return a violation with an index of that
78    /// name, or check the value before it writes.
79    fn create<'a>(&'a self, db: &'a Database, input: Row) -> RuntimeFuture<'a, Row>;
80    /// Updates the row with `id` from the validated `input` and returns it. A key that is
81    /// missing from `input`, such as a password left blank or a field the form did not send,
82    /// keeps its stored value. A key whose value is `null` is an optional field the user cleared: store NULL, so the value
83    /// is cleared, as a static resource does. A unique violation is reported as for
84    /// [`create`](Self::create).
85    fn update<'a>(&'a self, db: &'a Database, id: i64, input: Row) -> RuntimeFuture<'a, Row>;
86    /// Deletes the row with `id` and returns the number of rows deleted.
87    fn delete<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, u64>;
88    /// The choices of the field `field`, as `(value, label)` pairs in display order, for a
89    /// field whose kind [loads its options](FieldKindDef::loads_options): a lookup, post
90    /// object, relationship, taxonomy or user field. The default is no choices.
91    fn options<'a>(
92        &'a self,
93        db: &'a Database,
94        field: &'a str,
95    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
96        let _ = (db, field);
97        Box::pin(async { Ok(Vec::new()) })
98    }
99
100    /// [`list`](Self::list) for the signed-in `user`: the panel's list calls it. Restrict the
101    /// rows to the user here, as a Filament resource does in `getEloquentQuery()`, such as an
102    /// author who sees only their own posts. The total counts the same rows. The default is
103    /// [`list`](Self::list), for every user.
104    fn list_for<'a>(
105        &'a self,
106        db: &'a Database,
107        user: &'a ActingUser,
108        query: &'a ListQuery,
109    ) -> RuntimeFuture<'a, Page<Row>> {
110        let _ = user;
111        self.list(db, query)
112    }
113
114    /// [`find`](Self::find) for the signed-in `user`: the panel finds the record of the edit
115    /// form, of its save and of the delete action with it. Return `None` for a row the user's
116    /// list leaves out, so the panel answers 404, as Filament resolves a record through
117    /// `getEloquentQuery()`. The default is [`find`](Self::find), for every user.
118    fn find_for<'a>(
119        &'a self,
120        db: &'a Database,
121        user: &'a ActingUser,
122        id: i64,
123    ) -> RuntimeFuture<'a, Option<Row>> {
124        let _ = user;
125        self.find(db, id)
126    }
127
128    /// [`create`](Self::create) for the signed-in `user`, such as to make them the author.
129    /// The default is [`create`](Self::create).
130    fn create_for<'a>(
131        &'a self,
132        db: &'a Database,
133        user: &'a ActingUser,
134        input: Row,
135    ) -> RuntimeFuture<'a, Row> {
136        let _ = user;
137        self.create(db, input)
138    }
139
140    /// [`update`](Self::update) for the signed-in `user`, such as to keep a status the user
141    /// may not set. The panel calls it only after [`find_for`](Self::find_for) found the row
142    /// and the [`Policy`](crate::Policy) allowed the update. The default is
143    /// [`update`](Self::update).
144    fn update_for<'a>(
145        &'a self,
146        db: &'a Database,
147        user: &'a ActingUser,
148        id: i64,
149        input: Row,
150    ) -> RuntimeFuture<'a, Row> {
151        let _ = user;
152        self.update(db, id, input)
153    }
154
155    /// [`create_for`](Self::create_for) that may refuse the row with field messages, as
156    /// Laravel's `ValidationException::withMessages()`: answer `Ok(Err(ValidationError))` and
157    /// the panel shows the create form again with 422, each message under its field and the
158    /// typed values kept. The panel calls this method; the default is
159    /// [`create_for`](Self::create_for), which never refuses.
160    ///
161    /// ```ignore
162    /// fn try_create_for<'a>(&'a self, db: &'a Database, user: &'a ActingUser, input: Row)
163    ///     -> RuntimeFuture<'a, Result<Row, ValidationError>> {
164    ///     Box::pin(async move {
165    ///         if name_is_taken(db, &input).await? {
166    ///             return Ok(Err(ValidationError::with_messages([("name", "That name is in use.")])));
167    ///         }
168    ///         Ok(Ok(save(db, input).await?))
169    ///     })
170    /// }
171    /// ```
172    fn try_create_for<'a>(
173        &'a self,
174        db: &'a Database,
175        user: &'a ActingUser,
176        input: Row,
177    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
178        Box::pin(async move { self.create_for(db, user, input).await.map(Ok) })
179    }
180
181    /// [`find_for`](Self::find_for) by the record's key in the URL, for a resource whose
182    /// records are addressed by a key other than the numeric `id`
183    /// ([`RuntimeResource::record_route_key_name`], as Filament's `$recordRouteKeyName`), such
184    /// as a post type's key. The default parses `key` as an id and calls
185    /// [`find_for`](Self::find_for); a key that is not a whole number finds nothing.
186    fn find_by_key_for<'a>(
187        &'a self,
188        db: &'a Database,
189        user: &'a ActingUser,
190        key: &'a str,
191    ) -> RuntimeFuture<'a, Option<Row>> {
192        match key.parse::<i64>() {
193            Ok(id) => self.find_for(db, user, id),
194            Err(_) => Box::pin(async { Ok(None) }),
195        }
196    }
197
198    /// [`try_update_for`](Self::try_update_for) by the record's key, as
199    /// [`find_by_key_for`](Self::find_by_key_for). The default parses `key` as an id.
200    fn try_update_by_key_for<'a>(
201        &'a self,
202        db: &'a Database,
203        user: &'a ActingUser,
204        key: &'a str,
205        input: Row,
206    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
207        match key.parse::<i64>() {
208            Ok(id) => self.try_update_for(db, user, id, input),
209            Err(_) => Box::pin(async { Err(Error::NotFound { table: "records" }) }),
210        }
211    }
212
213    /// [`delete_for`](Self::delete_for) by the record's key, as
214    /// [`find_by_key_for`](Self::find_by_key_for). The default parses `key` as an id; a key
215    /// that is not a whole number deletes nothing.
216    fn delete_by_key_for<'a>(
217        &'a self,
218        db: &'a Database,
219        user: &'a ActingUser,
220        key: &'a str,
221    ) -> RuntimeFuture<'a, u64> {
222        match key.parse::<i64>() {
223            Ok(id) => self.delete_for(db, user, id),
224            Err(_) => Box::pin(async { Ok(0) }),
225        }
226    }
227
228    /// [`update_for`](Self::update_for) that may refuse the row with field messages, as
229    /// [`try_create_for`](Self::try_create_for) for the edit form. The panel calls it only
230    /// after [`find_for`](Self::find_for) found the row and the policy allowed the update. The
231    /// default is [`update_for`](Self::update_for), which never refuses.
232    fn try_update_for<'a>(
233        &'a self,
234        db: &'a Database,
235        user: &'a ActingUser,
236        id: i64,
237        input: Row,
238    ) -> RuntimeFuture<'a, Result<Row, ValidationError>> {
239        Box::pin(async move { self.update_for(db, user, id, input).await.map(Ok) })
240    }
241
242    /// [`delete`](Self::delete) for the signed-in `user`. The panel calls it only after
243    /// [`find_for`](Self::find_for) found the row and the [`Policy`](crate::Policy) allowed
244    /// the delete. The default is [`delete`](Self::delete).
245    fn delete_for<'a>(
246        &'a self,
247        db: &'a Database,
248        user: &'a ActingUser,
249        id: i64,
250    ) -> RuntimeFuture<'a, u64> {
251        let _ = user;
252        self.delete(db, id)
253    }
254
255    /// The dashboard cards of the resource for the signed-in `user`, as
256    /// [`IgniteResource::stats`](crate::IgniteResource::stats). The panel shows them only to a
257    /// user who may view the resource's records. The default is none.
258    fn stats<'a>(
259        &'a self,
260        db: &'a Database,
261        user: &'a ActingUser,
262    ) -> RuntimeFuture<'a, Vec<crate::widget::Stat>> {
263        let _ = (db, user);
264        Box::pin(async { Ok(Vec::new()) })
265    }
266
267    /// [`options`](Self::options) for the signed-in `user`: the panel fills the form's
268    /// selects with these choices and checks a submitted value against them, so a choice left
269    /// out cannot be saved, as a Filament select whose options depend on the user. The default
270    /// is [`options`](Self::options).
271    fn options_for<'a>(
272        &'a self,
273        db: &'a Database,
274        user: &'a ActingUser,
275        field: &'a str,
276    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
277        let _ = user;
278        self.options(db, field)
279    }
280
281    /// The choices of the field at `field` for the form's current values, as Filament's
282    /// dependent select, `options(fn (Get $get) => ...)` on a field whose controlling field is
283    /// `live()`: such as a location rule's values, which depend on the rule's parameter. The
284    /// panel calls it each time it shows the form, again when a live field changes (see
285    /// [`FieldConditions::live`]), and when it checks a submitted value, so a choice the
286    /// current values leave out cannot be saved.
287    ///
288    /// `field` is the field's path of names, without row numbers: `"city"` for a field of the
289    /// form, `"rules.value"` for the sub-field `value` of each row of the repeater `rules`,
290    /// `"content.hero.style"` for a sub-field of a flexible content block. `state` holds the
291    /// current values around the field, as Filament's `$get` reads its siblings: the form's
292    /// fields for a field of the form (a structured field's value as JSON), and the row's (or
293    /// group's) values for a sub-field. A blank value is missing or `null`. The default is
294    /// [`options_for`](Self::options_for), which does not depend on the values.
295    ///
296    /// A value no longer among the choices after the controlling field changed shows as not
297    /// chosen, and is refused if saved, which is Filament's `afterStateUpdated` reset of the
298    /// dependent field, done by the server.
299    fn options_with<'a>(
300        &'a self,
301        db: &'a Database,
302        user: &'a ActingUser,
303        field: &'a str,
304        state: &'a Row,
305    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
306        let _ = state;
307        self.options_for(db, user, field)
308    }
309
310    /// The tabs of the list page for the signed-in `user`, computed on each list request, as
311    /// Filament's `getTabs()` is a method of the List page: such as one tab per role on a users
312    /// list, which changes when a role is added. `None`, the default, keeps the resource's
313    /// [`tabs`](RuntimeResource::tabs). The `tab` query parameter, the default tab and the
314    /// counts work as for the declared tabs.
315    fn tabs_for<'a>(
316        &'a self,
317        db: &'a Database,
318        user: &'a ActingUser,
319    ) -> RuntimeFuture<'a, Option<Vec<Tab>>> {
320        let _ = (db, user);
321        Box::pin(async { Ok(None) })
322    }
323
324    /// Rules on the submitted form, checked beside the fields' own checks before the row is
325    /// built, as the rules of a Laravel form request: such as a password's minimum length,
326    /// which the row cannot show because a password is hashed in it. `operation` is
327    /// [`Operation::Create`] or [`Operation::Edit`]. Each error is keyed by the field's name and
328    /// shows under it, with 422, as a field's own error. The default is none.
329    fn validate_form(&self, form: &FormInput, operation: Operation) -> FieldErrors {
330        let _ = (form, operation);
331        FieldErrors::new()
332    }
333}
334
335/// The kind of a [`FieldDef`]: every [`FieldKind`], with owned values so it can be loaded
336/// from a database.
337#[derive(Debug, Clone, PartialEq, Eq, Hash)]
338pub enum FieldKindDef {
339    /// A single line of text. See [`FieldKind::Text`].
340    Text,
341    /// Several lines of text. See [`FieldKind::Textarea`].
342    Textarea,
343    /// A password, hashed on save. See [`FieldKind::Password`].
344    Password,
345    /// A whole number. See [`FieldKind::Number`].
346    Number,
347    /// A decimal number, with the browser's step, such as `"any"` or `"0.01"`. See
348    /// [`FieldKind::Decimal`].
349    Decimal(String),
350    /// A yes/no value. See [`FieldKind::Checkbox`].
351    Checkbox,
352    /// One choice from a list of `(value, label)` pairs. See [`FieldKind::Select`].
353    Select(Vec<(String, String)>),
354    /// One choice from options that [`RuntimeData::options`] loads. See [`FieldKind::Lookup`].
355    Lookup,
356    /// A calendar date. See [`FieldKind::Date`].
357    Date,
358    /// A date and time. See [`FieldKind::DateTime`].
359    DateTime,
360    /// An email address. See [`FieldKind::Email`].
361    Email,
362    /// A URL. See [`FieldKind::Url`].
363    Url,
364    /// One choice from a list of `(value, label)` pairs, as radio buttons. See
365    /// [`FieldKind::Radio`].
366    Radio(Vec<(String, String)>),
367    /// A color, as `#rrggbb`. See [`FieldKind::Color`].
368    Color,
369    /// An image from the media library. See [`FieldKind::Image`].
370    Image,
371    /// A file from the media library. See [`FieldKind::File`].
372    File,
373    /// A link, as JSON text. See [`FieldKind::Link`].
374    Link,
375    /// Rich text, edited with the app's editor. See [`FieldKind::Wysiwyg`].
376    Wysiwyg,
377    /// One post, from options [`RuntimeData::options`] loads. See [`FieldKind::PostObject`].
378    PostObject,
379    /// Several choices from a list of `(value, label)` pairs, as checkboxes; with no pairs,
380    /// from options [`RuntimeData::options`] loads. See [`FieldKind::CheckboxList`].
381    CheckboxList(Vec<(String, String)>),
382    /// Several choices, from options [`RuntimeData::options`] loads. See
383    /// [`FieldKind::Relationship`].
384    Relationship,
385    /// One taxonomy term, from loaded options. See [`FieldKind::Taxonomy`].
386    Taxonomy,
387    /// One user, from loaded options. See [`FieldKind::User`].
388    User,
389    /// Rows of the given sub-fields, as JSON text. See [`FieldKind::Repeater`].
390    Repeater(Vec<FieldDef>),
391    /// The given sub-fields, as one JSON object. See [`FieldKind::Group`].
392    Group(Vec<FieldDef>),
393    /// Rows that each take one of the given blocks, as JSON text. See
394    /// [`FieldKind::FlexibleContent`].
395    FlexibleContent(Vec<BlockDef>),
396    /// Several images from the media library, as a JSON array of ids. See
397    /// [`FieldKind::Gallery`].
398    Gallery,
399    /// The fields of another field group, reused. See [`FieldKind::Clone`].
400    Clone(Vec<FieldDef>),
401}
402
403impl FieldKindDef {
404    /// Whether the field's choices come from [`RuntimeData::options`] each time its form is
405    /// shown. See [`FieldKind::loads_options`].
406    pub fn loads_options(&self) -> bool {
407        match self {
408            FieldKindDef::CheckboxList(choices) => choices.is_empty(),
409            _ => matches!(
410                self,
411                FieldKindDef::Lookup
412                    | FieldKindDef::PostObject
413                    | FieldKindDef::Relationship
414                    | FieldKindDef::Taxonomy
415                    | FieldKindDef::User
416            ),
417        }
418    }
419
420    /// Whether the field holds media library ids: an image, a file or a gallery.
421    pub fn uses_media(&self) -> bool {
422        matches!(
423            self,
424            FieldKindDef::Image | FieldKindDef::File | FieldKindDef::Gallery
425        )
426    }
427}
428
429/// One block of a [`FieldKindDef::FlexibleContent`] field: the owned twin of [`Block`].
430#[derive(Debug, Clone, PartialEq, Eq, Hash)]
431pub struct BlockDef {
432    /// The block's name, stored as the `type` of each row that uses it.
433    pub name: String,
434    /// The label shown when choosing the block.
435    pub label: String,
436    /// The block's sub-fields, in display order.
437    pub fields: Vec<FieldDef>,
438}
439
440impl From<Block> for BlockDef {
441    fn from(block: Block) -> Self {
442        BlockDef {
443            name: block.name.to_string(),
444            label: block.label.to_string(),
445            fields: owned_fields(block.fields),
446        }
447    }
448}
449
450/// Owned definitions of static sub-fields.
451fn owned_fields(fields: &[Field]) -> Vec<FieldDef> {
452    fields.iter().copied().map(FieldDef::from).collect()
453}
454
455/// Owned `(value, label)` pairs of static choices.
456fn owned_choices(choices: &[(&str, &str)]) -> Vec<(String, String)> {
457    choices
458        .iter()
459        .map(|(value, label)| (value.to_string(), label.to_string()))
460        .collect()
461}
462
463impl From<FieldKind> for FieldKindDef {
464    fn from(kind: FieldKind) -> Self {
465        match kind {
466            FieldKind::Text => FieldKindDef::Text,
467            FieldKind::Textarea => FieldKindDef::Textarea,
468            FieldKind::Password => FieldKindDef::Password,
469            FieldKind::Number => FieldKindDef::Number,
470            FieldKind::Decimal(step) => FieldKindDef::Decimal(step.to_string()),
471            FieldKind::Checkbox => FieldKindDef::Checkbox,
472            FieldKind::Select(choices) => FieldKindDef::Select(owned_choices(choices)),
473            FieldKind::Lookup => FieldKindDef::Lookup,
474            FieldKind::Date => FieldKindDef::Date,
475            FieldKind::DateTime => FieldKindDef::DateTime,
476            FieldKind::Email => FieldKindDef::Email,
477            FieldKind::Url => FieldKindDef::Url,
478            FieldKind::Radio(choices) => FieldKindDef::Radio(owned_choices(choices)),
479            FieldKind::Color => FieldKindDef::Color,
480            FieldKind::Image => FieldKindDef::Image,
481            FieldKind::File => FieldKindDef::File,
482            FieldKind::Link => FieldKindDef::Link,
483            FieldKind::Wysiwyg => FieldKindDef::Wysiwyg,
484            FieldKind::PostObject => FieldKindDef::PostObject,
485            FieldKind::CheckboxList(choices) => FieldKindDef::CheckboxList(owned_choices(choices)),
486            FieldKind::Relationship => FieldKindDef::Relationship,
487            FieldKind::Taxonomy => FieldKindDef::Taxonomy,
488            FieldKind::User => FieldKindDef::User,
489            FieldKind::Repeater(fields) => FieldKindDef::Repeater(owned_fields(fields)),
490            FieldKind::Group(fields) => FieldKindDef::Group(owned_fields(fields)),
491            FieldKind::FlexibleContent(blocks) => {
492                FieldKindDef::FlexibleContent(blocks.iter().copied().map(BlockDef::from).collect())
493            }
494            FieldKind::Gallery => FieldKindDef::Gallery,
495            FieldKind::Clone(fields) => FieldKindDef::Clone(owned_fields(fields)),
496        }
497    }
498}
499
500/// One input on the form of a runtime resource: the owned twin of [`Field`].
501#[derive(Debug, Clone, PartialEq, Eq, Hash)]
502pub struct FieldDef {
503    /// The form field name. It matches a key of the row.
504    pub name: String,
505    /// The label shown next to the input.
506    pub label: String,
507    /// The input type, and how the value is read.
508    pub kind: FieldKindDef,
509    /// Whether the form rejects a blank value.
510    pub required: bool,
511}
512
513impl From<Field> for FieldDef {
514    fn from(field: Field) -> Self {
515        FieldDef {
516            name: field.name.to_string(),
517            label: field.label.to_string(),
518            kind: field.kind.into(),
519            required: field.required,
520        }
521    }
522}
523
524/// One column of the list of a runtime resource: the owned twin of [`Column`].
525#[derive(Debug, Clone, PartialEq, Eq, Hash)]
526pub struct ColumnDef {
527    /// The row key the column shows. It matches a field name.
528    pub key: String,
529    /// The column heading.
530    pub label: String,
531    /// Whether the heading links to a sort by this column.
532    pub sortable: bool,
533    /// Whether the search box matches this column.
534    pub searchable: bool,
535}
536
537impl From<Column> for ColumnDef {
538    fn from(column: Column) -> Self {
539        ColumnDef {
540            key: column.key.to_string(),
541            label: column.label.to_string(),
542            sortable: column.sortable,
543            searchable: column.searchable,
544        }
545    }
546}
547
548/// Where the panel goes after a successful save of a runtime resource's form, as Filament's
549/// `getRedirectUrl()` and the panel's `resourceCreatePageRedirect()` and
550/// `resourceEditPageRedirect()`. See [`RuntimeResource::redirect_after_create`] and
551/// [`RuntimeResource::redirect_after_update`].
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553pub enum RedirectAfter {
554    /// The record's edit page, with the flash message: after a create, the new record's (or
555    /// the list, for a user who may not edit it), as Filament's default after creating; after
556    /// an update, the same page again, as Filament's default after saving (it stays on the
557    /// page and shows the notification).
558    Edit,
559    /// The resource's list page, with the flash message: Ignite's default before 0.6.8, as
560    /// Filament's `getUrl('index')`.
561    List,
562}
563
564/// A resource defined by data. Build it with [`new`](Self::new) and the
565/// [`field`](Self::field) and [`column`](Self::column) methods, then add it to the panel
566/// with [`Registries::register_runtime`].
567#[derive(Clone)]
568pub struct RuntimeResource {
569    /// URL segment: `"books"` serves the resource at `/admin/books`. Lowercase letters,
570    /// digits, `-` and `_` only.
571    pub slug: String,
572    /// Heading and navigation label: `"Books"`.
573    pub title: String,
574    /// The name of one record, for headings such as "New Book".
575    pub singular: String,
576    /// Rows per page on the list view. The default is 20, as for a static resource.
577    pub per_page: i64,
578    /// Form fields, in display order.
579    pub fields: Vec<FieldDef>,
580    /// Table columns, in display order. Each column's `key` is a field name.
581    pub columns: Vec<ColumnDef>,
582    /// Where the rows live.
583    pub data: Arc<dyn RuntimeData>,
584    /// The label of the navigation entry, as Filament's `$navigationLabel`. `None`, the
585    /// default, is the [`title`](Self::title).
586    pub navigation_label: Option<String>,
587    /// The navigation group the resource is listed under, as Filament's `$navigationGroup`.
588    /// See [`IgniteResource::NAVIGATION_GROUP`](crate::IgniteResource::NAVIGATION_GROUP).
589    pub navigation_group: Option<String>,
590    /// The resource's place in the navigation, as Filament's `$navigationSort`: lower first.
591    /// See [`IgniteResource::NAVIGATION_SORT`](crate::IgniteResource::NAVIGATION_SORT).
592    pub navigation_sort: Option<i32>,
593    /// The navigation entry the resource is listed under, as Filament's
594    /// `$navigationParentItem`: the parent's label or slug. See
595    /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
596    pub navigation_parent_item: Option<String>,
597    /// More navigation entries the resource is listed under, by label or slug. See
598    /// [`IgniteResource::NAVIGATION_PARENT_ITEMS`](crate::IgniteResource::NAVIGATION_PARENT_ITEMS).
599    pub navigation_parent_items: Vec<String>,
600    /// Whether the resource has a navigation entry, as Filament's `$shouldRegisterNavigation`.
601    /// The default is `true`. See
602    /// [`IgniteResource::SHOULD_REGISTER_NAVIGATION`](crate::IgniteResource::SHOULD_REGISTER_NAVIGATION).
603    pub should_register_navigation: bool,
604    /// The name of the navigation entry's icon, such as `post`, as Filament's
605    /// `$navigationIcon`. See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
606    pub navigation_icon: Option<String>,
607    /// Whether the navigation entry lists a link to the create page. The default is `true`.
608    /// See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
609    pub navigation_create_item: bool,
610    /// The label of the create link. `None`, the default, is `"Add new"`.
611    pub navigation_create_label: Option<String>,
612    /// The conditions that show or hide the form's fields, and the live fields, as
613    /// Filament's `visible()`, `hidden()` and `live()`. See [`FieldConditions`].
614    pub conditions: FieldConditions,
615    /// The layout of the create and edit forms, as Filament's layout components. See
616    /// [`FormLayout`]. The default has none: the form renders as one card of fields.
617    pub form_layout: FormLayout,
618    /// The tabs of the list page, in display order, as Filament's `getTabs()`. See
619    /// [`IgniteResource::tabs`](crate::IgniteResource::tabs). The default is none.
620    pub tabs: Vec<Tab>,
621    /// The key of the tab shown when the list has no `tab` parameter, as Filament's
622    /// `getDefaultActiveTab()`. `None`, the default, is the first tab.
623    pub default_active_tab: Option<String>,
624    /// The list columns shown as coloured badges, as Filament's `badge()` and `color()`. See
625    /// [`ColumnBadges`]. The default is none.
626    pub column_badges: ColumnBadges,
627    /// Whether each tab's count is for the current search. The default is `false`: a tab
628    /// counts all its rows. See
629    /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
630    pub tab_counts_follow_search: bool,
631    /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
632    /// The default is `true`. See
633    /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
634    pub hide_empty_tabs: bool,
635    /// The actions on each row of the list page, in display order, as Filament's
636    /// `recordActions()`. See [`RowAction`]. The default is none.
637    pub row_actions: Vec<RowAction>,
638    /// The actions on the records ticked in the list, as Filament's `toolbarActions()`. See
639    /// [`BulkAction`]. The default is none: the list has no checkboxes.
640    pub bulk_actions: Vec<BulkAction>,
641    /// The records whose built-in Delete button is hidden (and whose delete the panel
642    /// refuses). See
643    /// [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
644    /// The default is none.
645    pub hide_default_delete_when: Option<ListFilter>,
646    /// The settings of the form's repeaters and flexible content fields, by path, as
647    /// Filament's `minItems()`, `maxItems()` and `itemLabel()`. See [`Repeaters`]. The default
648    /// has none: every repeater has the default settings.
649    pub repeaters: Repeaters,
650    /// The records the signed-in user may only view. See
651    /// [`read_only_when`](Self::read_only_when). The default is none.
652    pub read_only: Option<FormRule>,
653    /// The line the form of a read-only record shows. See
654    /// [`read_only_notice`](Self::read_only_notice).
655    pub read_only_notice: Option<FormNotice>,
656    /// The row key that addresses a record in the panel's URLs, as Filament's
657    /// `$recordRouteKeyName`. `None`, the default, is the numeric `id`. See
658    /// [`record_route_key_name`](Self::record_route_key_name).
659    pub record_route_key_name: Option<String>,
660    /// Where a successful create goes. `None`, the default, is the list page, as before 0.6.8.
661    /// See [`redirect_after_create`](Self::redirect_after_create).
662    pub redirect_after_create: Option<RedirectAfter>,
663    /// Where a successful update goes. `None`, the default, is the list page, as before 0.6.8.
664    /// See [`redirect_after_update`](Self::redirect_after_update).
665    pub redirect_after_update: Option<RedirectAfter>,
666    /// The ability each action on the resource needs, when it is not `<slug>.<action>`. See
667    /// [`ability`](Self::ability). The default is none: every action needs its default.
668    pub abilities: BTreeMap<ResourceAction, String>,
669    /// The ability every action on the resource needs besides its own, if any. See
670    /// [`access_ability`](Self::access_ability).
671    pub access_ability: Option<String>,
672}
673
674impl fmt::Debug for RuntimeResource {
675    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676        f.debug_struct("RuntimeResource")
677            .field("slug", &self.slug)
678            .field("title", &self.title)
679            .field("singular", &self.singular)
680            .field("per_page", &self.per_page)
681            .field("fields", &self.fields)
682            .field("columns", &self.columns)
683            .field("navigation_label", &self.navigation_label)
684            .field("navigation_group", &self.navigation_group)
685            .field("navigation_sort", &self.navigation_sort)
686            .field("navigation_parent_item", &self.navigation_parent_item)
687            .field("navigation_parent_items", &self.navigation_parent_items)
688            .field(
689                "should_register_navigation",
690                &self.should_register_navigation,
691            )
692            .field("navigation_icon", &self.navigation_icon)
693            .field("navigation_create_item", &self.navigation_create_item)
694            .field("navigation_create_label", &self.navigation_create_label)
695            .field("conditions", &self.conditions)
696            .field("form_layout", &self.form_layout)
697            .field("tabs", &self.tabs)
698            .field("default_active_tab", &self.default_active_tab)
699            .field("column_badges", &self.column_badges)
700            .field("tab_counts_follow_search", &self.tab_counts_follow_search)
701            .field("hide_empty_tabs", &self.hide_empty_tabs)
702            .field("row_actions", &self.row_actions)
703            .field("bulk_actions", &self.bulk_actions)
704            .field("hide_default_delete_when", &self.hide_default_delete_when)
705            .field("repeaters", &self.repeaters)
706            .field("read_only", &self.read_only.is_some())
707            .field("record_route_key_name", &self.record_route_key_name)
708            .field("redirect_after_create", &self.redirect_after_create)
709            .field("redirect_after_update", &self.redirect_after_update)
710            .field("abilities", &self.abilities)
711            .field("access_ability", &self.access_ability)
712            .finish_non_exhaustive()
713    }
714}
715
716impl RuntimeResource {
717    /// A resource at `slug` with no fields or columns yet, whose rows come from `data`.
718    pub fn new(
719        slug: impl Into<String>,
720        title: impl Into<String>,
721        singular: impl Into<String>,
722        data: impl RuntimeData,
723    ) -> Self {
724        RuntimeResource {
725            slug: slug.into(),
726            title: title.into(),
727            singular: singular.into(),
728            per_page: 20,
729            fields: Vec::new(),
730            columns: Vec::new(),
731            data: Arc::new(data),
732            navigation_label: None,
733            navigation_group: None,
734            navigation_sort: None,
735            navigation_parent_item: None,
736            navigation_parent_items: Vec::new(),
737            should_register_navigation: true,
738            navigation_icon: None,
739            navigation_create_item: true,
740            navigation_create_label: None,
741            conditions: FieldConditions::new(),
742            form_layout: FormLayout::new(),
743            tabs: Vec::new(),
744            default_active_tab: None,
745            column_badges: ColumnBadges::new(),
746            tab_counts_follow_search: false,
747            hide_empty_tabs: true,
748            row_actions: Vec::new(),
749            bulk_actions: Vec::new(),
750            hide_default_delete_when: None,
751            repeaters: Repeaters::new(),
752            read_only: None,
753            read_only_notice: None,
754            record_route_key_name: None,
755            redirect_after_create: None,
756            redirect_after_update: None,
757            abilities: BTreeMap::new(),
758            access_ability: None,
759        }
760    }
761
762    /// Adds a form field after the others.
763    pub fn field(mut self, field: FieldDef) -> Self {
764        self.fields.push(field);
765        self
766    }
767
768    /// Adds a list column after the others.
769    pub fn column(mut self, column: ColumnDef) -> Self {
770        self.columns.push(column);
771        self
772    }
773
774    /// Sets the rows per page of the list view.
775    pub fn per_page(mut self, per_page: i64) -> Self {
776        self.per_page = per_page;
777        self
778    }
779
780    /// Sets the label of the navigation entry, as Filament's `navigationLabel`.
781    pub fn navigation_label(mut self, label: impl Into<String>) -> Self {
782        self.navigation_label = Some(label.into());
783        self
784    }
785
786    /// Lists the resource under the navigation group `group`, as Filament's `navigationGroup`.
787    pub fn navigation_group(mut self, group: impl Into<String>) -> Self {
788        self.navigation_group = Some(group.into());
789        self
790    }
791
792    /// Sets the resource's place in the navigation, as Filament's `navigationSort`: lower first.
793    pub fn navigation_sort(mut self, sort: i32) -> Self {
794        self.navigation_sort = Some(sort);
795        self
796    }
797
798    /// Lists the resource under the navigation entry `parent` (its label or slug), as
799    /// Filament's `navigationParentItem`. See
800    /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
801    pub fn navigation_parent_item(mut self, parent: impl Into<String>) -> Self {
802        self.navigation_parent_item = Some(parent.into());
803        self
804    }
805
806    /// Lists the resource under each of the navigation entries `parents` (labels or slugs)
807    /// that the sidebar shows, as a taxonomy's screen under every post type it is attached
808    /// to. See
809    /// [`IgniteResource::NAVIGATION_PARENT_ITEMS`](crate::IgniteResource::NAVIGATION_PARENT_ITEMS).
810    pub fn navigation_parent_items<I>(mut self, parents: I) -> Self
811    where
812        I: IntoIterator,
813        I::Item: Into<String>,
814    {
815        self.navigation_parent_items
816            .extend(parents.into_iter().map(Into::into));
817        self
818    }
819
820    /// Whether the resource has a navigation entry, as Filament's `shouldRegisterNavigation`.
821    /// See [`IgniteResource::SHOULD_REGISTER_NAVIGATION`](crate::IgniteResource::SHOULD_REGISTER_NAVIGATION).
822    pub fn should_register_navigation(mut self, listed: bool) -> Self {
823        self.should_register_navigation = listed;
824        self
825    }
826
827    /// Sets the name of the navigation entry's icon, as Filament's `navigationIcon`: a name
828    /// such as `"post"` or a custom post type's own, which the admin theme maps to its icon.
829    /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
830    pub fn navigation_icon(mut self, name: impl Into<String>) -> Self {
831        self.navigation_icon = Some(name.into());
832        self
833    }
834
835    /// Whether the navigation entry lists a link to the create page, under the entry, in its
836    /// group. See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
837    pub fn navigation_create_item(mut self, listed: bool) -> Self {
838        self.navigation_create_item = listed;
839        self
840    }
841
842    /// Sets the label of the create link, such as `"Add New Post"`. See
843    /// [`IgniteResource::NAVIGATION_CREATE_LABEL`](crate::IgniteResource::NAVIGATION_CREATE_LABEL).
844    pub fn navigation_create_label(mut self, label: impl Into<String>) -> Self {
845        self.navigation_create_label = Some(label.into());
846        self
847    }
848
849    /// Shows the field `field` only when `rule` holds, as Filament's `->visible()`. See
850    /// [`FieldConditions::visible`].
851    pub fn visible(
852        mut self,
853        field: impl Into<String>,
854        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
855    ) -> Self {
856        self.conditions = self.conditions.visible(field, rule);
857        self
858    }
859
860    /// Hides the field `field` when `rule` holds, as Filament's `->hidden()`. See
861    /// [`FieldConditions::hidden`].
862    pub fn hidden(
863        mut self,
864        field: impl Into<String>,
865        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
866    ) -> Self {
867        self.conditions = self.conditions.hidden(field, rule);
868        self
869    }
870
871    /// Shows the field `field` only on the forms of `operations`, as Filament's
872    /// `->visibleOn()`.
873    pub fn visible_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
874        self.conditions = self.conditions.visible_on(field, operations);
875        self
876    }
877
878    /// Hides the field `field` on the forms of `operations`, as Filament's `->hiddenOn()`.
879    pub fn hidden_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
880        self.conditions = self.conditions.hidden_on(field, operations);
881        self
882    }
883
884    /// Makes the field `field` live, as Filament's `->live()`: a change to it in the browser
885    /// shows the form's fields again for the new value. See [`FieldConditions::live`].
886    pub fn live(mut self, field: impl Into<String>) -> Self {
887        self.conditions = self.conditions.live(field);
888        self
889    }
890
891    /// Gives the field `field` the default value `value` on the create form, as Filament's
892    /// `->default(...)`; the edit form shows the stored value. See
893    /// [`FieldConditions::default_value`].
894    pub fn default_value(mut self, field: impl Into<String>, value: impl Into<Value>) -> Self {
895        self.conditions = self.conditions.default_value(field, value);
896        self
897    }
898
899    /// Gives the field `field` a default computed from the create form's state, as Filament's
900    /// `->default(fn (Get $get) => ...)`. See [`FieldConditions::default_with`].
901    pub fn default_with(
902        mut self,
903        field: impl Into<String>,
904        rule: impl Fn(&FormContext<'_>) -> Value + Send + Sync + 'static,
905    ) -> Self {
906        self.conditions = self.conditions.default_with(field, rule);
907        self
908    }
909
910    /// Fills the field `field` with the slug of the field `source` until the user edits it, as
911    /// Filament's slug pattern. See [`FieldConditions::slug_from`].
912    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
913        self.conditions = self.conditions.slug_from(field, source);
914        self
915    }
916
917    /// Stops the slug field `field` from following its source on the edit form of a record
918    /// with a stored slug, when `rule` holds, such as once the record is published. See
919    /// [`FieldConditions::slug_locked_when`].
920    pub fn slug_locked_when(
921        mut self,
922        field: impl Into<String>,
923        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
924    ) -> Self {
925        self.conditions = self.conditions.slug_locked_when(field, rule);
926        self
927    }
928
929    /// Sets the layout of the create and edit forms: columns, sections and groups, as
930    /// Filament's layout components. See [`FormLayout`].
931    pub fn form_layout(mut self, layout: FormLayout) -> Self {
932        self.form_layout = layout;
933        self
934    }
935
936    /// Adds a tab to the list page after the others, as a [`Tab`] in Filament's `getTabs()`.
937    /// The [`RuntimeData`] list is given the active tab's conditions in
938    /// [`ListQuery::filter`]: apply them with [`ListFilter::apply`](crate::ListFilter::apply)
939    /// or [`ListFilter::matches`](crate::ListFilter::matches).
940    pub fn tab(mut self, tab: Tab) -> Self {
941        self.tabs.push(tab);
942        self
943    }
944
945    /// Sets the tab shown when the list has no `tab` parameter, by its key, as Filament's
946    /// `getDefaultActiveTab()`. Without it, the first tab is shown.
947    pub fn default_active_tab(mut self, key: impl Into<String>) -> Self {
948        self.default_active_tab = Some(key.into());
949        self
950    }
951
952    /// Whether each tab's count is for the current search. The default, `false`, counts all
953    /// of a tab's rows. See
954    /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
955    pub fn tab_counts_follow_search(mut self, follow: bool) -> Self {
956        self.tab_counts_follow_search = follow;
957        self
958    }
959
960    /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
961    /// The default is `true`; `false` renders every tab. See
962    /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
963    pub fn hide_empty_tabs(mut self, hide: bool) -> Self {
964        self.hide_empty_tabs = hide;
965        self
966    }
967
968    /// Adds an action on each row of the list, after the others, as an action in Filament's
969    /// `recordActions()`. See [`RowAction`].
970    pub fn row_action(mut self, action: RowAction) -> Self {
971        self.row_actions.push(action);
972        self
973    }
974
975    /// Adds an action on the records ticked in the list, as Filament's `BulkAction::make()` in
976    /// `toolbarActions()`. See [`BulkAction`].
977    pub fn bulk_action(mut self, action: BulkAction) -> Self {
978        self.bulk_actions.push(action);
979        self
980    }
981
982    /// Hides the built-in Delete button on the records that meet `filter`, and refuses their
983    /// delete, such as `ListFilter::new().where_eq("status", "trash")` for a post in the trash.
984    /// See [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
985    pub fn hide_default_delete_when(mut self, filter: ListFilter) -> Self {
986        self.hide_default_delete_when = Some(filter);
987        self
988    }
989
990    /// Sets the settings of the repeater or flexible content field at `path`, such as
991    /// `"members"`, or `"groups.rules"` for the repeater `rules` inside each row of `groups`:
992    /// its fewest and most rows, its row label and its buttons, as Filament's `Repeater`
993    /// methods. See [`RepeaterSettings`].
994    pub fn repeater(mut self, path: impl Into<String>, settings: RepeaterSettings) -> Self {
995        self.repeaters = self.repeaters.repeater(path, settings);
996        self
997    }
998
999    /// Names the ability that allows `action` on the resource, in place of `<slug>.<action>`,
1000    /// as a Filament resource policy's method checks the permission it chooses: such as
1001    /// `ability(ResourceAction::Update, "edit_books")` for a post type whose capability type
1002    /// is `book`, as WordPress maps `edit_post` to `edit_books`. The ability gates the
1003    /// resource as a whole (its list and navigation entry for `ViewAny`, its forms and saves
1004    /// for `Create` and `Update`, its delete for `Delete`); a [`Policy`](crate::Policy) still
1005    /// decides each record. The panel registers the ability as a permission on the next
1006    /// signed-in request after the resource is registered (or at once with
1007    /// `ignite_panel::register_runtime_permissions`), so the Roles screen lists it without a
1008    /// restart. Several actions may share one ability.
1009    pub fn ability(mut self, action: ResourceAction, name: impl Into<String>) -> Self {
1010        self.abilities.insert(action, name.into());
1011        self
1012    }
1013
1014    /// Requires the ability `name` for every action on the resource, besides each action's
1015    /// own, as Filament's `canAccess()` and WordPress's `manage_options` for the settings
1016    /// screens: a user without it does not see the navigation entry and gets 403 on every
1017    /// route of the resource.
1018    pub fn access_ability(mut self, name: impl Into<String>) -> Self {
1019        self.access_ability = Some(name.into());
1020        self
1021    }
1022
1023    /// Addresses each record in the panel's URLs by the row key `key` instead of the numeric
1024    /// `id`, as Filament's `$recordRouteKeyName`: such as `"key"`, so a post type's edit form
1025    /// is at `/admin/post-types/book/edit`. The rows the list gives must have the key, as text
1026    /// or a number, and the data finds, updates and deletes them by it
1027    /// ([`RuntimeData::find_by_key_for`], [`try_update_by_key_for`](RuntimeData::try_update_by_key_for)
1028    /// and [`delete_by_key_for`](RuntimeData::delete_by_key_for)). A key that the form sets is
1029    /// usually locked after the first save with [`disabled_on`](Self::disabled_on), as
1030    /// WordPress keeps a post type's key.
1031    pub fn record_route_key_name(mut self, key: impl Into<String>) -> Self {
1032        self.record_route_key_name = Some(key.into());
1033        self
1034    }
1035
1036    /// Where a successful create goes, as Filament's `getRedirectUrl()` on the Create page and
1037    /// the panel's `resourceCreatePageRedirect()`: [`RedirectAfter::Edit`], Filament's default,
1038    /// opens the new record's edit page (the list, for a user who may not edit it), and
1039    /// [`RedirectAfter::List`] the list page. Without this call a create goes to the list, as
1040    /// in 0.6.7. A dashboard form widget comes back to the dashboard either way.
1041    pub fn redirect_after_create(mut self, redirect: RedirectAfter) -> Self {
1042        self.redirect_after_create = Some(redirect);
1043        self
1044    }
1045
1046    /// Where a successful update goes, as Filament's `getRedirectUrl()` on the Edit page and
1047    /// the panel's `resourceEditPageRedirect()`: [`RedirectAfter::Edit`], Filament's default,
1048    /// stays on the record's edit page with the flash message, and [`RedirectAfter::List`]
1049    /// goes to the list page. Without this call an update goes to the list, as in 0.6.7.
1050    pub fn redirect_after_update(mut self, redirect: RedirectAfter) -> Self {
1051        self.redirect_after_update = Some(redirect);
1052        self
1053    }
1054
1055    /// Shows the field `field` but does not let the user change it when `rule` holds, as
1056    /// Filament's `->disabled()`. A disabled field is not saved. See
1057    /// [`FieldConditions::disabled`].
1058    pub fn disabled(
1059        mut self,
1060        field: impl Into<String>,
1061        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
1062    ) -> Self {
1063        self.conditions = self.conditions.disabled(field, rule);
1064        self
1065    }
1066
1067    /// Disables the field `field` on the forms of `operations`, as Filament's
1068    /// `->disabledOn('edit')`. See [`FieldConditions::disabled_on`].
1069    pub fn disabled_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
1070        self.conditions = self.conditions.disabled_on(field, operations);
1071        self
1072    }
1073
1074    /// Makes the records for which `rule` holds read-only for the signed-in user, as Filament's
1075    /// View page, a disabled form with the record's data: their edit form shows the values
1076    /// with every input disabled and no Save, its heading says "View", the list's button says
1077    /// "View", and their save (and the form's live URL) answers 403 Forbidden. `rule` is given
1078    /// the edit form's [`FormContext`]: the record, the user and the stored values. Such as a
1079    /// post type defined in code, which the admin screens may show but not change:
1080    ///
1081    /// ```ignore
1082    /// .read_only_when(|form| form.record().and_then(|r| r.get("origin")) != Some(&json!("admin")))
1083    /// ```
1084    pub fn read_only_when(
1085        mut self,
1086        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
1087    ) -> Self {
1088        self.read_only = Some(Arc::new(rule));
1089        self
1090    }
1091
1092    /// The line the form of a read-only record shows above its fields, such as "This post type
1093    /// is defined in code by the theme. Change it there.", or none.
1094    pub fn read_only_notice(
1095        mut self,
1096        notice: impl Fn(&FormContext<'_>) -> Option<String> + Send + Sync + 'static,
1097    ) -> Self {
1098        self.read_only_notice = Some(Arc::new(notice));
1099        self
1100    }
1101
1102    /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`.
1103    /// See [`ColumnBadges::badge`].
1104    pub fn badge(mut self, column: impl Into<String>) -> Self {
1105        self.column_badges = self.column_badges.badge(column);
1106        self
1107    }
1108
1109    /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
1110    /// as Filament's `->badge()->color(fn (string $state) => ...)`. See
1111    /// [`ColumnBadges::badge_color`].
1112    pub fn badge_color(
1113        mut self,
1114        column: impl Into<String>,
1115        color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
1116    ) -> Self {
1117        self.column_badges = self.column_badges.badge_color(column, color);
1118        self
1119    }
1120
1121    /// Shows the badge of the column `column` inside the cell of the column `target`, instead
1122    /// of in a column of its own. See [`ColumnBadges::badge_inside`].
1123    pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
1124        self.column_badges = self.column_badges.badge_inside(column, target);
1125        self
1126    }
1127
1128    /// Shows the badge of the column `column` only on the list's tabs `tabs`, by key. See
1129    /// [`ColumnBadges::badge_on_tabs`].
1130    pub fn badge_on_tabs<S: Into<String>>(
1131        mut self,
1132        column: impl Into<String>,
1133        tabs: impl IntoIterator<Item = S>,
1134    ) -> Self {
1135        self.column_badges = self.column_badges.badge_on_tabs(column, tabs);
1136        self
1137    }
1138}
1139
1140/// Turns a submitted form into a [`Row`] for the fields `fields` that are not a resource's,
1141/// such as the fields an app adds to the panel's profile page, with the checks and the values of
1142/// [`RegisteredResource::validate_update`]: a blank password and a field the form did not send
1143/// are left out of the row, an optional field sent blank is `null`, and a checkbox the form did
1144/// not send is `false`. Each error is keyed by its field's name. A lookup's value is not checked
1145/// against its choices here: the panel checks it, as for a resource.
1146pub fn validate_fields_for_update(
1147    fields: &[FieldDef],
1148    form: &FormInput,
1149) -> Result<Row, FieldErrors> {
1150    validate_fields(fields, form, false, &BTreeSet::new(), &Repeaters::default())
1151}
1152
1153/// The checks of [`RegisteredResource::validate`]. Each error is keyed by its field's name.
1154/// The fields of `hidden` are skipped: they are not checked and the row has no key for them.
1155fn validate_fields(
1156    fields: &[FieldDef],
1157    form: &FormInput,
1158    creating: bool,
1159    hidden: &BTreeSet<String>,
1160    repeaters: &Repeaters,
1161) -> Result<Row, FieldErrors> {
1162    let mut errors = FieldErrors::new();
1163    let mut row = Row::new();
1164    for field in fields.iter().filter(|f| !hidden.contains(&f.name)) {
1165        let name = field.name.as_str();
1166        let label = field.label.as_str();
1167        // A checkbox is never blank: an unticked checkbox is false.
1168        if field.kind == FieldKindDef::Checkbox {
1169            row.insert(name.to_string(), Value::Bool(form.checkbox(name)));
1170            continue;
1171        }
1172        let is_password = field.kind == FieldKindDef::Password;
1173        // A password is required only when creating. On an edit a blank one keeps the hash.
1174        let present = if field.required && (creating || !is_password) {
1175            check::check_required(name, label, form, &mut errors)
1176        } else {
1177            form.get(name)
1178        };
1179        let Some(text) = present else {
1180            // On an update, a field the form did not send keeps its stored value, and a blank
1181            // password keeps its hash. A field sent blank is cleared to NULL.
1182            let keep = !creating && (is_password || !form.has(name));
1183            // A repeater sent with no rows has none, which its fewest rows may refuse.
1184            let min = match field.kind {
1185                FieldKindDef::Repeater(_) | FieldKindDef::FlexibleContent(_) if !keep => {
1186                    repeaters.get(name).get_min_items().filter(|min| *min > 0)
1187                }
1188                _ => None,
1189            };
1190            if let (Some(min), false) = (min, errors.contains_key(name)) {
1191                errors.insert(
1192                    name.to_string(),
1193                    format!("{label} must have at least {min} items."),
1194                );
1195            }
1196            if !keep {
1197                row.insert(name.to_string(), Value::Null);
1198            }
1199            continue;
1200        };
1201        let value = match &field.kind {
1202            FieldKindDef::Password => match crate::hash_password(text) {
1203                Ok(hash) => Some(Value::String(hash)),
1204                Err(_) => {
1205                    errors.insert(
1206                        name.to_string(),
1207                        "Could not save this password.".to_string(),
1208                    );
1209                    None
1210                }
1211            },
1212            FieldKindDef::Number => {
1213                check::check_whole_number::<i64>(name, label, text, &mut errors).map(Value::from)
1214            }
1215            FieldKindDef::Decimal(_) => {
1216                check::check_decimal::<f64>(name, label, text, &mut errors).map(Value::from)
1217            }
1218            FieldKindDef::Select(choices) => {
1219                let text = text.trim();
1220                let choices: Vec<(&str, &str)> = choices
1221                    .iter()
1222                    .map(|(value, label)| (value.as_str(), label.as_str()))
1223                    .collect();
1224                check::check_choice(name, text, &choices, &mut errors)
1225                    .then(|| Value::String(text.to_string()))
1226            }
1227            FieldKindDef::Lookup => Some(Value::String(text.trim().to_string())),
1228            FieldKindDef::Date => check::check_date(name, label, text, &mut errors)
1229                .map(|date| Value::String(date.format("%Y-%m-%d").to_string())),
1230            FieldKindDef::DateTime => check::check_datetime(name, label, text, &mut errors)
1231                .map(|stamp| Value::String(stamp.format("%Y-%m-%d %H:%M:%S").to_string())),
1232            FieldKindDef::Text | FieldKindDef::Textarea | FieldKindDef::Checkbox => {
1233                Some(Value::String(text.to_string()))
1234            }
1235            kind => crate::value::check_value_in(
1236                name,
1237                label,
1238                field.required,
1239                kind,
1240                text,
1241                &mut errors,
1242                repeaters,
1243            )
1244            .map(Value::String),
1245        };
1246        if let Some(value) = value {
1247            row.insert(name.to_string(), value);
1248        }
1249    }
1250    if errors.is_empty() {
1251        Ok(row)
1252    } else {
1253        Err(errors)
1254    }
1255}
1256
1257/// Why the registry refused a change.
1258#[derive(Debug, Clone, PartialEq, Eq)]
1259pub enum RuntimeError {
1260    /// The slug is not one URL segment of lowercase letters, digits, `-` and `_`.
1261    InvalidSlug(String),
1262    /// Another resource, static or runtime, or one of the panel's own pages, has the slug.
1263    SlugTaken(String),
1264    /// A field name is not a lowercase identifier: lowercase ASCII letters, digits and `_`,
1265    /// starting with a letter, at most 64 bytes ([`MAX_FIELD_NAME`]).
1266    InvalidFieldName {
1267        /// The slug of the resource.
1268        slug: String,
1269        /// The name that was refused.
1270        field: String,
1271    },
1272    /// Two fields of the resource have the same name.
1273    DuplicateField {
1274        /// The slug of the resource.
1275        slug: String,
1276        /// The name used twice.
1277        field: String,
1278    },
1279    /// No runtime resource has the slug.
1280    NotRegistered(String),
1281}
1282
1283impl fmt::Display for RuntimeError {
1284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1285        match self {
1286            RuntimeError::InvalidSlug(slug) => write!(
1287                f,
1288                "the slug `{slug}` is not valid: use lowercase letters, digits, `-` and `_`"
1289            ),
1290            RuntimeError::SlugTaken(slug) => write!(
1291                f,
1292                "the slug `{slug}` is already used by another Ignite resource"
1293            ),
1294            RuntimeError::InvalidFieldName { slug, field } => write!(
1295                f,
1296                "the field `{field}` of the resource `{slug}` is not valid: use lowercase \
1297                 letters, digits and `_`, starting with a letter, at most {MAX_FIELD_NAME} bytes"
1298            ),
1299            RuntimeError::DuplicateField { slug, field } => {
1300                write!(f, "the resource `{slug}` has two fields named `{field}`")
1301            }
1302            RuntimeError::NotRegistered(slug) => {
1303                write!(f, "no runtime resource is registered at `{slug}`")
1304            }
1305        }
1306    }
1307}
1308
1309impl std::error::Error for RuntimeError {}
1310
1311/// A runtime resource as the registry holds it: the definition, ready for the panel.
1312pub struct RegisteredResource {
1313    resource: RuntimeResource,
1314}
1315
1316impl RegisteredResource {
1317    /// Checks `resource` as [`Registries::register_runtime`] does, without adding it to the registry: its
1318    /// slug and its field names. The panel uses it for a resource defined by data that is part
1319    /// of the panel from its start (`Ignite::runtime_resource`), such as the Users screen.
1320    pub fn new(resource: RuntimeResource) -> Result<Self, RuntimeError> {
1321        check_definition(&resource)?;
1322        Ok(RegisteredResource { resource })
1323    }
1324
1325    /// The definition that was registered.
1326    pub fn resource(&self) -> &RuntimeResource {
1327        &self.resource
1328    }
1329
1330    /// The slug, as the panel's routes match it.
1331    pub fn slug(&self) -> &str {
1332        &self.resource.slug
1333    }
1334
1335    /// The heading and navigation label.
1336    pub fn title(&self) -> &str {
1337        &self.resource.title
1338    }
1339
1340    /// The name of one record.
1341    pub fn singular(&self) -> &str {
1342        &self.resource.singular
1343    }
1344
1345    /// The label of the navigation entry: the navigation label, or the title.
1346    pub fn navigation_label(&self) -> &str {
1347        self.resource
1348            .navigation_label
1349            .as_deref()
1350            .unwrap_or(&self.resource.title)
1351    }
1352
1353    /// The navigation group the resource is listed under, if any.
1354    pub fn navigation_group(&self) -> Option<&str> {
1355        self.resource.navigation_group.as_deref()
1356    }
1357
1358    /// The resource's place in the navigation, if set.
1359    pub fn navigation_sort(&self) -> Option<i32> {
1360        self.resource.navigation_sort
1361    }
1362
1363    /// The navigation entry the resource is listed under, if any.
1364    pub fn navigation_parent_item(&self) -> Option<&str> {
1365        self.resource.navigation_parent_item.as_deref()
1366    }
1367
1368    /// Every navigation entry the resource is listed under: its parent item, then its parent
1369    /// items, each once, without blank names.
1370    pub fn navigation_parent_items(&self) -> Vec<&str> {
1371        crate::navigation_parents(
1372            self.resource.navigation_parent_item.as_deref(),
1373            self.resource
1374                .navigation_parent_items
1375                .iter()
1376                .map(String::as_str),
1377        )
1378    }
1379
1380    /// Whether the resource has a navigation entry.
1381    pub fn should_register_navigation(&self) -> bool {
1382        self.resource.should_register_navigation
1383    }
1384
1385    /// The name of the navigation entry's icon, if set.
1386    pub fn navigation_icon(&self) -> Option<&str> {
1387        self.resource.navigation_icon.as_deref()
1388    }
1389
1390    /// The label of the navigation entry's create link, or `None` when it lists none.
1391    pub fn navigation_create_item(&self) -> Option<&str> {
1392        self.resource.navigation_create_item.then(|| {
1393            self.resource
1394                .navigation_create_label
1395                .as_deref()
1396                .unwrap_or("Add new")
1397        })
1398    }
1399
1400    /// The form fields, in display order.
1401    pub fn fields(&self) -> &[FieldDef] {
1402        &self.resource.fields
1403    }
1404
1405    /// The list columns, in display order.
1406    pub fn columns(&self) -> &[ColumnDef] {
1407        &self.resource.columns
1408    }
1409
1410    /// Turns the submitted form into a [`Row`] for a create, or returns one message per
1411    /// field. It runs the same checks as a static resource, with the same messages:
1412    /// required fields ([`Field::check_required`](crate::Field::check_required)), whole
1413    /// numbers, decimals, dates, date-times and select choices. The row holds one key per
1414    /// field:
1415    ///
1416    /// - text, textarea, select, lookup: a string. A required value is trimmed.
1417    /// - email, URL, radio, color, image, file, link, wysiwyg, post object, checkbox list,
1418    ///   relationship,
1419    ///   taxonomy, user, repeater, group, flexible content, gallery, clone: the text
1420    ///   [`Field::check_value`](crate::Field::check_value) returns. The structured kinds
1421    ///   hold JSON text.
1422    /// - number: an integer. Decimal: a number.
1423    /// - checkbox: `true` or `false`; a checkbox is never blank.
1424    /// - date: `"YYYY-MM-DD"`. Date-time: `"YYYY-MM-DD HH:MM:SS"`.
1425    /// - password: the hash of the password ([`hash_password`](crate::hash_password)).
1426    /// - a blank field that is not required: `null`.
1427    ///
1428    /// Each error in [`FieldErrors`] is keyed by the field's name, an owned `String`.
1429    ///
1430    /// A lookup, post object, relationship, taxonomy or user value is checked against
1431    /// [`RuntimeData::options`] by the panel, which can read the database, and so is a media
1432    /// id against the registered [`MediaLibrary`](crate::MediaLibrary).
1433    pub fn validate(&self, form: &FormInput) -> Result<Row, FieldErrors> {
1434        validate_fields(
1435            &self.resource.fields,
1436            form,
1437            true,
1438            &BTreeSet::new(),
1439            &self.resource.repeaters,
1440        )
1441    }
1442
1443    /// Turns the submitted form into a [`Row`] for an update. It is
1444    /// [`validate`](Self::validate), except that:
1445    ///
1446    /// - a blank password is not an error: the row leaves its key out, so the stored
1447    ///   password is kept;
1448    /// - an optional field the form did not send at all ([`FormInput::has`] is false) is left
1449    ///   out of the row, so its stored value is kept;
1450    /// - an optional field sent blank is `null`, so clearing it on the edit form clears the
1451    ///   stored value, as `#[derive(IgniteResource)]` does since 0.3.0;
1452    /// - a checkbox the form did not send is `false`, because an unticked HTML checkbox sends
1453    ///   nothing.
1454    pub fn validate_update(&self, form: &FormInput) -> Result<Row, FieldErrors> {
1455        validate_fields(
1456            &self.resource.fields,
1457            form,
1458            false,
1459            &BTreeSet::new(),
1460            &self.resource.repeaters,
1461        )
1462    }
1463
1464    /// The conditions that show or hide the form's fields.
1465    pub fn conditions(&self) -> &FieldConditions {
1466        &self.resource.conditions
1467    }
1468
1469    /// The layout of the create and edit forms.
1470    pub fn form_layout(&self) -> &FormLayout {
1471        &self.resource.form_layout
1472    }
1473
1474    /// The tabs of the list page, in display order.
1475    pub fn tabs(&self) -> &[Tab] {
1476        &self.resource.tabs
1477    }
1478
1479    /// The key of the tab shown when the list has no `tab` parameter, if set.
1480    pub fn default_active_tab(&self) -> Option<&str> {
1481        self.resource.default_active_tab.as_deref()
1482    }
1483
1484    /// The list columns shown as coloured badges.
1485    pub fn column_badges(&self) -> &ColumnBadges {
1486        &self.resource.column_badges
1487    }
1488
1489    /// Whether each tab's count is for the current search.
1490    pub fn tab_counts_follow_search(&self) -> bool {
1491        self.resource.tab_counts_follow_search
1492    }
1493
1494    /// Whether a tab whose count is 0 is left out.
1495    pub fn hide_empty_tabs(&self) -> bool {
1496        self.resource.hide_empty_tabs
1497    }
1498
1499    /// The actions on each row of the list, in display order.
1500    pub fn row_actions(&self) -> &[RowAction] {
1501        &self.resource.row_actions
1502    }
1503
1504    /// The actions on the ticked records, in display order.
1505    pub fn bulk_actions(&self) -> &[BulkAction] {
1506        &self.resource.bulk_actions
1507    }
1508
1509    /// The records whose built-in Delete button is hidden, if set.
1510    pub fn hide_default_delete_when(&self) -> Option<&ListFilter> {
1511        self.resource.hide_default_delete_when.as_ref()
1512    }
1513
1514    /// The settings of the form's repeaters and flexible content fields.
1515    pub fn repeaters(&self) -> &Repeaters {
1516        &self.resource.repeaters
1517    }
1518
1519    /// The ability `action` on the resource needs: the one [`RuntimeResource::ability`]
1520    /// names, or `<slug>.<action>`, such as `books.update`.
1521    pub fn ability_for(&self, action: ResourceAction) -> String {
1522        self.resource
1523            .abilities
1524            .get(&action)
1525            .cloned()
1526            .unwrap_or_else(|| format!("{}.{}", self.resource.slug, action.as_str()))
1527    }
1528
1529    /// The ability every action needs besides its own, if any
1530    /// ([`RuntimeResource::access_ability`]).
1531    pub fn access_ability(&self) -> Option<&str> {
1532        self.resource.access_ability.as_deref()
1533    }
1534
1535    /// Every ability `action` needs: the access ability, if any, and the action's own.
1536    pub fn required_abilities(&self, action: ResourceAction) -> Vec<String> {
1537        self.access_ability()
1538            .map(str::to_string)
1539            .into_iter()
1540            .chain(std::iter::once(self.ability_for(action)))
1541            .collect()
1542    }
1543
1544    /// Every ability the resource's actions need, without repeats, in action order: the
1545    /// permissions the panel registers for it.
1546    pub fn ability_names(&self) -> Vec<String> {
1547        let mut names: Vec<String> = Vec::new();
1548        for action in ResourceAction::ALL {
1549            for name in self.required_abilities(action) {
1550                if !names.contains(&name) {
1551                    names.push(name);
1552                }
1553            }
1554        }
1555        names
1556    }
1557
1558    /// Where a successful create goes: the
1559    /// [`redirect_after_create`](RuntimeResource::redirect_after_create), or the list.
1560    pub fn redirect_after_create(&self) -> RedirectAfter {
1561        self.resource
1562            .redirect_after_create
1563            .unwrap_or(RedirectAfter::List)
1564    }
1565
1566    /// Where a successful update goes: the
1567    /// [`redirect_after_update`](RuntimeResource::redirect_after_update), or the list.
1568    pub fn redirect_after_update(&self) -> RedirectAfter {
1569        self.resource
1570            .redirect_after_update
1571            .unwrap_or(RedirectAfter::List)
1572    }
1573
1574    /// The row key that addresses a record in the panel's URLs: the
1575    /// [`record_route_key_name`](RuntimeResource::record_route_key_name), or `id`.
1576    pub fn record_route_key_name(&self) -> &str {
1577        self.resource
1578            .record_route_key_name
1579            .as_deref()
1580            .unwrap_or("id")
1581    }
1582
1583    /// Whether the record of the edit form `form` is read-only for its user
1584    /// ([`RuntimeResource::read_only_when`]).
1585    pub fn is_read_only(&self, form: &FormContext<'_>) -> bool {
1586        self.resource
1587            .read_only
1588            .as_ref()
1589            .is_some_and(|rule| rule(form))
1590    }
1591
1592    /// The line the form of a read-only record shows, if any.
1593    pub fn read_only_notice(&self, form: &FormContext<'_>) -> Option<String> {
1594        self.resource
1595            .read_only_notice
1596            .as_ref()
1597            .and_then(|notice| notice(form))
1598    }
1599
1600    /// [`validate`](Self::validate) for a form whose fields `hidden` are hidden (see
1601    /// [`FieldConditions::hidden_fields`]): they are not checked, a required one included, and
1602    /// the row has no key for them, so the source writes nothing for them. The panel calls it.
1603    pub fn validate_shown(
1604        &self,
1605        form: &FormInput,
1606        hidden: &BTreeSet<String>,
1607    ) -> Result<Row, FieldErrors> {
1608        validate_fields(
1609            &self.resource.fields,
1610            form,
1611            true,
1612            hidden,
1613            &self.resource.repeaters,
1614        )
1615    }
1616
1617    /// [`validate_update`](Self::validate_update) for a form whose fields `hidden` are hidden:
1618    /// the row has no key for them, so their stored values are kept, whatever the form sent.
1619    pub fn validate_update_shown(
1620        &self,
1621        form: &FormInput,
1622        hidden: &BTreeSet<String>,
1623    ) -> Result<Row, FieldErrors> {
1624        validate_fields(
1625            &self.resource.fields,
1626            form,
1627            false,
1628            hidden,
1629            &self.resource.repeaters,
1630        )
1631    }
1632}
1633
1634/// The runtime resources of one app, in registration order, and the slugs reserved for static
1635/// resources and for the panel's own pages. It lives in the app's
1636/// [`Registries`](crate::Registries).
1637#[derive(Default)]
1638pub(crate) struct RuntimeRegistry {
1639    resources: Vec<Arc<RegisteredResource>>,
1640    reserved: HashSet<String>,
1641}
1642
1643impl Registries {
1644    /// Runs `f` on the registry, read-only. The lock is never held across an `.await`: every
1645    /// caller is synchronous.
1646    fn read_runtime<T>(&self, f: impl FnOnce(&RuntimeRegistry) -> T) -> T {
1647        f(&self
1648            .inner
1649            .runtime
1650            .read()
1651            .unwrap_or_else(PoisonError::into_inner))
1652    }
1653
1654    /// Runs `f` on the registry, to change it.
1655    fn write_runtime<T>(&self, f: impl FnOnce(&mut RuntimeRegistry) -> T) -> T {
1656        f(&mut self
1657            .inner
1658            .runtime
1659            .write()
1660            .unwrap_or_else(PoisonError::into_inner))
1661    }
1662}
1663
1664/// The longest field name a runtime resource accepts, in bytes, as for a MySQL or MariaDB
1665/// column name. The limit is a validation rule: names are owned by their resource and freed
1666/// with it.
1667pub const MAX_FIELD_NAME: usize = 64;
1668
1669/// Whether `name` is a field name a runtime resource accepts: lowercase ASCII letters, digits
1670/// and `_`, starting with a letter, at most [`MAX_FIELD_NAME`] bytes, as a column name is.
1671fn valid_field_name(name: &str) -> bool {
1672    name.len() <= MAX_FIELD_NAME
1673        && name.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
1674        && name
1675            .bytes()
1676            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
1677}
1678
1679/// Whether `slug` is one URL segment the panel's `/<slug>` routes match: lowercase ASCII
1680/// letters, digits, `-` and `_`, as Filament's kebab-case slugs are.
1681fn valid_slug(slug: &str) -> bool {
1682    !slug.is_empty()
1683        && slug
1684            .bytes()
1685            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1686}
1687
1688impl Registries {
1689    /// Adds a runtime resource to this app. It shows in the navigation and the dashboard, and
1690    /// its list, forms and delete action answer at `/<mount>/<slug>`, from the next request on.
1691    /// Create its permissions (`<slug>.viewAny` and the others) in the same request with
1692    /// `ignite_panel::register_runtime_permissions`; otherwise the panel creates them on the
1693    /// next signed-in request.
1694    ///
1695    /// Refuses a slug that is not valid, a slug that a static resource, another runtime resource
1696    /// of this app or one of the panel's own pages (such as `login`) uses, and two fields with
1697    /// one name. Another app's resources are not consulted: each app has its own registry.
1698    pub fn register_runtime(&self, resource: RuntimeResource) -> Result<(), RuntimeError> {
1699        check_definition(&resource)?;
1700        self.write_runtime(|registry| {
1701            let slug = resource.slug.as_str();
1702            if registry.reserved.contains(slug)
1703                || registry.resources.iter().any(|r| r.slug() == slug)
1704            {
1705                return Err(RuntimeError::SlugTaken(resource.slug.clone()));
1706            }
1707            registry
1708                .resources
1709                .push(Arc::new(RegisteredResource { resource }));
1710            Ok(())
1711        })
1712    }
1713}
1714
1715/// Checks a definition's slug and field names.
1716fn check_definition(resource: &RuntimeResource) -> Result<(), RuntimeError> {
1717    if !valid_slug(&resource.slug) {
1718        return Err(RuntimeError::InvalidSlug(resource.slug.clone()));
1719    }
1720    if let Some(field) = resource.fields.iter().find(|f| !valid_field_name(&f.name)) {
1721        return Err(RuntimeError::InvalidFieldName {
1722            slug: resource.slug.clone(),
1723            field: field.name.clone(),
1724        });
1725    }
1726    let mut names = HashSet::new();
1727    if let Some(field) = resource.fields.iter().find(|f| !names.insert(&f.name)) {
1728        return Err(RuntimeError::DuplicateField {
1729            slug: resource.slug.clone(),
1730            field: field.name.clone(),
1731        });
1732    }
1733    Ok(())
1734}
1735
1736impl Registries {
1737    /// Removes the runtime resource at `slug`. From the next request on, it is gone from the
1738    /// navigation and its routes answer 404. Its permission rows stay, so the grants come back
1739    /// if the resource is registered again.
1740    pub fn unregister_runtime(&self, slug: &str) -> Result<(), RuntimeError> {
1741        self.write_runtime(|registry| {
1742            let before = registry.resources.len();
1743            registry.resources.retain(|r| r.slug() != slug);
1744            if registry.resources.len() == before {
1745                Err(RuntimeError::NotRegistered(slug.to_string()))
1746            } else {
1747                Ok(())
1748            }
1749        })
1750    }
1751
1752    /// The runtime resource at `slug`, if one is registered.
1753    pub fn runtime_resource(&self, slug: &str) -> Option<Arc<RegisteredResource>> {
1754        self.read_runtime(|registry| {
1755            registry
1756                .resources
1757                .iter()
1758                .find(|r| r.slug() == slug)
1759                .cloned()
1760        })
1761    }
1762
1763    /// Every runtime resource, in registration order.
1764    pub fn runtime_resources(&self) -> Vec<Arc<RegisteredResource>> {
1765        self.read_runtime(|registry| registry.resources.clone())
1766    }
1767
1768    /// Reserves `slugs`, so no runtime resource can take them. The panel reserves the slugs of
1769    /// its static resources and of its own pages when it is built. Reserving a slug twice is
1770    /// fine. Refuses, and reserves none, when a runtime resource already has one of them.
1771    pub fn reserve_slugs(&self, slugs: &[&str]) -> Result<(), RuntimeError> {
1772        self.write_runtime(|registry| {
1773            if let Some(slug) = slugs
1774                .iter()
1775                .find(|slug| registry.resources.iter().any(|r| r.slug() == **slug))
1776            {
1777                return Err(RuntimeError::SlugTaken(slug.to_string()));
1778            }
1779            registry
1780                .reserved
1781                .extend(slugs.iter().map(|slug| slug.to_string()));
1782            Ok(())
1783        })
1784    }
1785}
1786
1787/// Registers `resource` on the default app, as 0.7.1 did. See
1788/// [`Registries::register_runtime`](crate::Registries::register_runtime).
1789pub fn register_runtime(resource: RuntimeResource) -> Result<(), RuntimeError> {
1790    crate::Registries::default_app().register_runtime(resource)
1791}
1792
1793/// Removes the runtime resource at `slug` from the default app. See
1794/// [`Registries::unregister_runtime`](crate::Registries::unregister_runtime).
1795pub fn unregister_runtime(slug: &str) -> Result<(), RuntimeError> {
1796    crate::Registries::default_app().unregister_runtime(slug)
1797}
1798
1799/// The runtime resource at `slug` on the default app. See
1800/// [`Registries::runtime_resource`](crate::Registries::runtime_resource).
1801pub fn runtime_resource(slug: &str) -> Option<Arc<RegisteredResource>> {
1802    crate::Registries::default_app().runtime_resource(slug)
1803}
1804
1805/// The runtime resources of the default app. See
1806/// [`Registries::runtime_resources`](crate::Registries::runtime_resources).
1807pub fn runtime_resources() -> Vec<Arc<RegisteredResource>> {
1808    crate::Registries::default_app().runtime_resources()
1809}
1810
1811/// Reserves `slugs` on the default app, as 0.7.1 did. See
1812/// [`Registries::reserve_slugs`](crate::Registries::reserve_slugs).
1813pub fn reserve_slugs(slugs: &[&str]) -> Result<(), RuntimeError> {
1814    crate::Registries::default_app().reserve_slugs(slugs)
1815}
1816
1817#[cfg(test)]
1818mod tests {
1819    use super::*;
1820
1821    struct NoData;
1822
1823    impl RuntimeData for NoData {
1824        fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
1825            unreachable!()
1826        }
1827        fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
1828            unreachable!()
1829        }
1830        fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
1831            unreachable!()
1832        }
1833        fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
1834            unreachable!()
1835        }
1836        fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
1837            unreachable!()
1838        }
1839    }
1840
1841    /// A resource with the fields `growth_title` and `growth_status`, whose label and
1842    /// choices change with `n`.
1843    fn edited(slug: &str, n: usize) -> RuntimeResource {
1844        RuntimeResource::new(slug, format!("Title {n}"), format!("One {n}"), NoData)
1845            .field(FieldDef {
1846                name: "growth_title".into(),
1847                label: format!("Title {n}"),
1848                kind: FieldKindDef::Text,
1849                required: n.is_multiple_of(2),
1850            })
1851            .field(FieldDef {
1852                name: "growth_status".into(),
1853                label: format!("Status {n}"),
1854                kind: FieldKindDef::Select(vec![(format!("v{n}"), format!("Value {n}"))]),
1855                required: false,
1856            })
1857            .column(ColumnDef {
1858                key: "growth_title".into(),
1859                label: format!("Column {n}"),
1860                sortable: false,
1861                searchable: false,
1862            })
1863    }
1864
1865    // Field names are owned by their resource: editing a definition a thousand times keeps
1866    // nothing of the old ones, and an error is keyed by the field's own name.
1867    #[test]
1868    fn editing_a_definition_a_thousand_times_keeps_owned_names() {
1869        let registries = Registries::new();
1870        registries
1871            .register_runtime(edited("growth", 0))
1872            .expect("register");
1873        for n in 1..=1000 {
1874            registries.unregister_runtime("growth").expect("unregister");
1875            registries
1876                .register_runtime(edited("growth", n))
1877                .expect("register again");
1878            let registered = registries.runtime_resource("growth").expect("registered");
1879            let mut values = std::collections::HashMap::new();
1880            values.insert("growth_status".to_string(), "not a choice".to_string());
1881            let errors = registered
1882                .validate(&FormInput::new(values.clone()))
1883                .unwrap_err();
1884            assert!(errors.contains_key("growth_status"));
1885            let _ = registered.validate_update(&FormInput::new(values));
1886        }
1887        // The last registration is the only one the registry holds.
1888        let registered = registries.runtime_resource("growth").expect("registered");
1889        assert_eq!(registered.title(), "Title 1000");
1890        assert_eq!(
1891            registries
1892                .runtime_resources()
1893                .iter()
1894                .filter(|r| r.slug() == "growth")
1895                .count(),
1896            1
1897        );
1898        registries.unregister_runtime("growth").expect("unregister");
1899    }
1900
1901    // Each app has its own registry: the same slug registers in two apps, and one app's
1902    // reserved slugs and resources are not seen by the other.
1903    #[test]
1904    fn two_registries_do_not_share_resources_or_reserved_slugs() {
1905        let (a, b) = (Registries::new(), Registries::new());
1906        a.reserve_slugs(&["taken"]).unwrap();
1907        a.register_runtime(edited("shared", 1)).unwrap();
1908        b.register_runtime(edited("shared", 2)).unwrap();
1909        b.register_runtime(edited("taken", 3)).unwrap();
1910        assert_eq!(a.runtime_resource("shared").unwrap().title(), "Title 1");
1911        assert_eq!(b.runtime_resource("shared").unwrap().title(), "Title 2");
1912        assert!(a.runtime_resource("taken").is_none());
1913        assert!(a.register_runtime(edited("taken", 4)).is_err());
1914        let clone = a.clone();
1915        clone.unregister_runtime("shared").unwrap();
1916        assert!(
1917            a.runtime_resource("shared").is_none(),
1918            "a clone is the same app"
1919        );
1920        assert!(b.runtime_resource("shared").is_some());
1921    }
1922}