Skip to main content

ignite_core/
runtime_resource.rs

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