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