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::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/// A resource defined by data. Build it with [`new`](Self::new) and the
548/// [`field`](Self::field) and [`column`](Self::column) methods, then add it to the panel
549/// with [`register_runtime`].
550#[derive(Clone)]
551pub struct RuntimeResource {
552 /// URL segment: `"books"` serves the resource at `/admin/books`. Lowercase letters,
553 /// digits, `-` and `_` only.
554 pub slug: String,
555 /// Heading and navigation label: `"Books"`.
556 pub title: String,
557 /// The name of one record, for headings such as "New Book".
558 pub singular: String,
559 /// Rows per page on the list view. The default is 20, as for a static resource.
560 pub per_page: i64,
561 /// Form fields, in display order.
562 pub fields: Vec<FieldDef>,
563 /// Table columns, in display order. Each column's `key` is a field name.
564 pub columns: Vec<ColumnDef>,
565 /// Where the rows live.
566 pub data: Arc<dyn RuntimeData>,
567 /// The label of the navigation entry, as Filament's `$navigationLabel`. `None`, the
568 /// default, is the [`title`](Self::title).
569 pub navigation_label: Option<String>,
570 /// The navigation group the resource is listed under, as Filament's `$navigationGroup`.
571 /// See [`IgniteResource::NAVIGATION_GROUP`](crate::IgniteResource::NAVIGATION_GROUP).
572 pub navigation_group: Option<String>,
573 /// The resource's place in the navigation, as Filament's `$navigationSort`: lower first.
574 /// See [`IgniteResource::NAVIGATION_SORT`](crate::IgniteResource::NAVIGATION_SORT).
575 pub navigation_sort: Option<i32>,
576 /// The navigation entry the resource is listed under, as Filament's
577 /// `$navigationParentItem`: the parent's label or slug. See
578 /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
579 pub navigation_parent_item: Option<String>,
580 /// The name of the navigation entry's icon, such as `post`, as Filament's
581 /// `$navigationIcon`. See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
582 pub navigation_icon: Option<String>,
583 /// Whether the navigation entry lists a link to the create page. The default is `true`.
584 /// See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
585 pub navigation_create_item: bool,
586 /// The label of the create link. `None`, the default, is `"Add new"`.
587 pub navigation_create_label: Option<String>,
588 /// The conditions that show or hide the form's fields, and the live fields, as
589 /// Filament's `visible()`, `hidden()` and `live()`. See [`FieldConditions`].
590 pub conditions: FieldConditions,
591 /// The layout of the create and edit forms, as Filament's layout components. See
592 /// [`FormLayout`]. The default has none: the form renders as one card of fields.
593 pub form_layout: FormLayout,
594 /// The tabs of the list page, in display order, as Filament's `getTabs()`. See
595 /// [`IgniteResource::tabs`](crate::IgniteResource::tabs). The default is none.
596 pub tabs: Vec<Tab>,
597 /// The key of the tab shown when the list has no `tab` parameter, as Filament's
598 /// `getDefaultActiveTab()`. `None`, the default, is the first tab.
599 pub default_active_tab: Option<String>,
600 /// The list columns shown as coloured badges, as Filament's `badge()` and `color()`. See
601 /// [`ColumnBadges`]. The default is none.
602 pub column_badges: ColumnBadges,
603 /// Whether each tab's count is for the current search. The default is `false`: a tab
604 /// counts all its rows. See
605 /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
606 pub tab_counts_follow_search: bool,
607 /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
608 /// The default is `true`. See
609 /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
610 pub hide_empty_tabs: bool,
611 /// The actions on each row of the list page, in display order, as Filament's
612 /// `recordActions()`. See [`RowAction`]. The default is none.
613 pub row_actions: Vec<RowAction>,
614 /// The records whose built-in Delete button is hidden (and whose delete the panel
615 /// refuses). See
616 /// [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
617 /// The default is none.
618 pub hide_default_delete_when: Option<ListFilter>,
619 /// The settings of the form's repeaters and flexible content fields, by path, as
620 /// Filament's `minItems()`, `maxItems()` and `itemLabel()`. See [`Repeaters`]. The default
621 /// has none: every repeater has the default settings.
622 pub repeaters: Repeaters,
623 /// The records the signed-in user may only view. See
624 /// [`read_only_when`](Self::read_only_when). The default is none.
625 pub read_only: Option<FormRule>,
626 /// The line the form of a read-only record shows. See
627 /// [`read_only_notice`](Self::read_only_notice).
628 pub read_only_notice: Option<FormNotice>,
629 /// The row key that addresses a record in the panel's URLs, as Filament's
630 /// `$recordRouteKeyName`. `None`, the default, is the numeric `id`. See
631 /// [`record_route_key_name`](Self::record_route_key_name).
632 pub record_route_key_name: Option<String>,
633 /// The ability each action on the resource needs, when it is not `<slug>.<action>`. See
634 /// [`ability`](Self::ability). The default is none: every action needs its default.
635 pub abilities: BTreeMap<ResourceAction, String>,
636 /// The ability every action on the resource needs besides its own, if any. See
637 /// [`access_ability`](Self::access_ability).
638 pub access_ability: Option<String>,
639}
640
641impl fmt::Debug for RuntimeResource {
642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 f.debug_struct("RuntimeResource")
644 .field("slug", &self.slug)
645 .field("title", &self.title)
646 .field("singular", &self.singular)
647 .field("per_page", &self.per_page)
648 .field("fields", &self.fields)
649 .field("columns", &self.columns)
650 .field("navigation_label", &self.navigation_label)
651 .field("navigation_group", &self.navigation_group)
652 .field("navigation_sort", &self.navigation_sort)
653 .field("navigation_parent_item", &self.navigation_parent_item)
654 .field("navigation_icon", &self.navigation_icon)
655 .field("navigation_create_item", &self.navigation_create_item)
656 .field("navigation_create_label", &self.navigation_create_label)
657 .field("conditions", &self.conditions)
658 .field("form_layout", &self.form_layout)
659 .field("tabs", &self.tabs)
660 .field("default_active_tab", &self.default_active_tab)
661 .field("column_badges", &self.column_badges)
662 .field("tab_counts_follow_search", &self.tab_counts_follow_search)
663 .field("hide_empty_tabs", &self.hide_empty_tabs)
664 .field("row_actions", &self.row_actions)
665 .field("hide_default_delete_when", &self.hide_default_delete_when)
666 .field("repeaters", &self.repeaters)
667 .field("read_only", &self.read_only.is_some())
668 .field("record_route_key_name", &self.record_route_key_name)
669 .field("abilities", &self.abilities)
670 .field("access_ability", &self.access_ability)
671 .finish_non_exhaustive()
672 }
673}
674
675impl RuntimeResource {
676 /// A resource at `slug` with no fields or columns yet, whose rows come from `data`.
677 pub fn new(
678 slug: impl Into<String>,
679 title: impl Into<String>,
680 singular: impl Into<String>,
681 data: impl RuntimeData,
682 ) -> Self {
683 RuntimeResource {
684 slug: slug.into(),
685 title: title.into(),
686 singular: singular.into(),
687 per_page: 20,
688 fields: Vec::new(),
689 columns: Vec::new(),
690 data: Arc::new(data),
691 navigation_label: None,
692 navigation_group: None,
693 navigation_sort: None,
694 navigation_parent_item: None,
695 navigation_icon: None,
696 navigation_create_item: true,
697 navigation_create_label: None,
698 conditions: FieldConditions::new(),
699 form_layout: FormLayout::new(),
700 tabs: Vec::new(),
701 default_active_tab: None,
702 column_badges: ColumnBadges::new(),
703 tab_counts_follow_search: false,
704 hide_empty_tabs: true,
705 row_actions: Vec::new(),
706 hide_default_delete_when: None,
707 repeaters: Repeaters::new(),
708 read_only: None,
709 read_only_notice: None,
710 record_route_key_name: None,
711 abilities: BTreeMap::new(),
712 access_ability: None,
713 }
714 }
715
716 /// Adds a form field after the others.
717 pub fn field(mut self, field: FieldDef) -> Self {
718 self.fields.push(field);
719 self
720 }
721
722 /// Adds a list column after the others.
723 pub fn column(mut self, column: ColumnDef) -> Self {
724 self.columns.push(column);
725 self
726 }
727
728 /// Sets the rows per page of the list view.
729 pub fn per_page(mut self, per_page: i64) -> Self {
730 self.per_page = per_page;
731 self
732 }
733
734 /// Sets the label of the navigation entry, as Filament's `navigationLabel`.
735 pub fn navigation_label(mut self, label: impl Into<String>) -> Self {
736 self.navigation_label = Some(label.into());
737 self
738 }
739
740 /// Lists the resource under the navigation group `group`, as Filament's `navigationGroup`.
741 pub fn navigation_group(mut self, group: impl Into<String>) -> Self {
742 self.navigation_group = Some(group.into());
743 self
744 }
745
746 /// Sets the resource's place in the navigation, as Filament's `navigationSort`: lower first.
747 pub fn navigation_sort(mut self, sort: i32) -> Self {
748 self.navigation_sort = Some(sort);
749 self
750 }
751
752 /// Lists the resource under the navigation entry `parent` (its label or slug), as
753 /// Filament's `navigationParentItem`. See
754 /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
755 pub fn navigation_parent_item(mut self, parent: impl Into<String>) -> Self {
756 self.navigation_parent_item = Some(parent.into());
757 self
758 }
759
760 /// Sets the name of the navigation entry's icon, as Filament's `navigationIcon`: a name
761 /// such as `"post"` or a custom post type's own, which the admin theme maps to its icon.
762 /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
763 pub fn navigation_icon(mut self, name: impl Into<String>) -> Self {
764 self.navigation_icon = Some(name.into());
765 self
766 }
767
768 /// Whether the navigation entry lists a link to the create page, under the entry, in its
769 /// group. See [`IgniteResource::NAVIGATION_CREATE_ITEM`](crate::IgniteResource::NAVIGATION_CREATE_ITEM).
770 pub fn navigation_create_item(mut self, listed: bool) -> Self {
771 self.navigation_create_item = listed;
772 self
773 }
774
775 /// Sets the label of the create link, such as `"Add New Post"`. See
776 /// [`IgniteResource::NAVIGATION_CREATE_LABEL`](crate::IgniteResource::NAVIGATION_CREATE_LABEL).
777 pub fn navigation_create_label(mut self, label: impl Into<String>) -> Self {
778 self.navigation_create_label = Some(label.into());
779 self
780 }
781
782 /// Shows the field `field` only when `rule` holds, as Filament's `->visible()`. See
783 /// [`FieldConditions::visible`].
784 pub fn visible(
785 mut self,
786 field: impl Into<String>,
787 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
788 ) -> Self {
789 self.conditions = self.conditions.visible(field, rule);
790 self
791 }
792
793 /// Hides the field `field` when `rule` holds, as Filament's `->hidden()`. See
794 /// [`FieldConditions::hidden`].
795 pub fn hidden(
796 mut self,
797 field: impl Into<String>,
798 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
799 ) -> Self {
800 self.conditions = self.conditions.hidden(field, rule);
801 self
802 }
803
804 /// Shows the field `field` only on the forms of `operations`, as Filament's
805 /// `->visibleOn()`.
806 pub fn visible_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
807 self.conditions = self.conditions.visible_on(field, operations);
808 self
809 }
810
811 /// Hides the field `field` on the forms of `operations`, as Filament's `->hiddenOn()`.
812 pub fn hidden_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
813 self.conditions = self.conditions.hidden_on(field, operations);
814 self
815 }
816
817 /// Makes the field `field` live, as Filament's `->live()`: a change to it in the browser
818 /// shows the form's fields again for the new value. See [`FieldConditions::live`].
819 pub fn live(mut self, field: impl Into<String>) -> Self {
820 self.conditions = self.conditions.live(field);
821 self
822 }
823
824 /// Fills the field `field` with the slug of the field `source` until the user edits it, as
825 /// Filament's slug pattern. See [`FieldConditions::slug_from`].
826 pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
827 self.conditions = self.conditions.slug_from(field, source);
828 self
829 }
830
831 /// Stops the slug field `field` from following its source on the edit form of a record
832 /// with a stored slug, when `rule` holds, such as once the record is published. See
833 /// [`FieldConditions::slug_locked_when`].
834 pub fn slug_locked_when(
835 mut self,
836 field: impl Into<String>,
837 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
838 ) -> Self {
839 self.conditions = self.conditions.slug_locked_when(field, rule);
840 self
841 }
842
843 /// Sets the layout of the create and edit forms: columns, sections and groups, as
844 /// Filament's layout components. See [`FormLayout`].
845 pub fn form_layout(mut self, layout: FormLayout) -> Self {
846 self.form_layout = layout;
847 self
848 }
849
850 /// Adds a tab to the list page after the others, as a [`Tab`] in Filament's `getTabs()`.
851 /// The [`RuntimeData`] list is given the active tab's conditions in
852 /// [`ListQuery::filter`]: apply them with [`ListFilter::apply`](crate::ListFilter::apply)
853 /// or [`ListFilter::matches`](crate::ListFilter::matches).
854 pub fn tab(mut self, tab: Tab) -> Self {
855 self.tabs.push(tab);
856 self
857 }
858
859 /// Sets the tab shown when the list has no `tab` parameter, by its key, as Filament's
860 /// `getDefaultActiveTab()`. Without it, the first tab is shown.
861 pub fn default_active_tab(mut self, key: impl Into<String>) -> Self {
862 self.default_active_tab = Some(key.into());
863 self
864 }
865
866 /// Whether each tab's count is for the current search. The default, `false`, counts all
867 /// of a tab's rows. See
868 /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
869 pub fn tab_counts_follow_search(mut self, follow: bool) -> Self {
870 self.tab_counts_follow_search = follow;
871 self
872 }
873
874 /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
875 /// The default is `true`; `false` renders every tab. See
876 /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
877 pub fn hide_empty_tabs(mut self, hide: bool) -> Self {
878 self.hide_empty_tabs = hide;
879 self
880 }
881
882 /// Adds an action on each row of the list, after the others, as an action in Filament's
883 /// `recordActions()`. See [`RowAction`].
884 pub fn row_action(mut self, action: RowAction) -> Self {
885 self.row_actions.push(action);
886 self
887 }
888
889 /// Hides the built-in Delete button on the records that meet `filter`, and refuses their
890 /// delete, such as `ListFilter::new().where_eq("status", "trash")` for a post in the trash.
891 /// See [`IgniteResource::hide_default_delete_when`](crate::IgniteResource::hide_default_delete_when).
892 pub fn hide_default_delete_when(mut self, filter: ListFilter) -> Self {
893 self.hide_default_delete_when = Some(filter);
894 self
895 }
896
897 /// Sets the settings of the repeater or flexible content field at `path`, such as
898 /// `"members"`, or `"groups.rules"` for the repeater `rules` inside each row of `groups`:
899 /// its fewest and most rows, its row label and its buttons, as Filament's `Repeater`
900 /// methods. See [`RepeaterSettings`].
901 pub fn repeater(mut self, path: impl Into<String>, settings: RepeaterSettings) -> Self {
902 self.repeaters = self.repeaters.repeater(path, settings);
903 self
904 }
905
906 /// Names the ability that allows `action` on the resource, in place of `<slug>.<action>`,
907 /// as a Filament resource policy's method checks the permission it chooses: such as
908 /// `ability(ResourceAction::Update, "edit_books")` for a post type whose capability type
909 /// is `book`, as WordPress maps `edit_post` to `edit_books`. The ability gates the
910 /// resource as a whole (its list and navigation entry for `ViewAny`, its forms and saves
911 /// for `Create` and `Update`, its delete for `Delete`); a [`Policy`](crate::Policy) still
912 /// decides each record. The panel registers the ability as a permission on the next
913 /// signed-in request after the resource is registered (or at once with
914 /// `ignite_panel::register_runtime_permissions`), so the Roles screen lists it without a
915 /// restart. Several actions may share one ability.
916 pub fn ability(mut self, action: ResourceAction, name: impl Into<String>) -> Self {
917 self.abilities.insert(action, name.into());
918 self
919 }
920
921 /// Requires the ability `name` for every action on the resource, besides each action's
922 /// own, as Filament's `canAccess()` and WordPress's `manage_options` for the settings
923 /// screens: a user without it does not see the navigation entry and gets 403 on every
924 /// route of the resource.
925 pub fn access_ability(mut self, name: impl Into<String>) -> Self {
926 self.access_ability = Some(name.into());
927 self
928 }
929
930 /// Addresses each record in the panel's URLs by the row key `key` instead of the numeric
931 /// `id`, as Filament's `$recordRouteKeyName`: such as `"key"`, so a post type's edit form
932 /// is at `/admin/post-types/book/edit`. The rows the list gives must have the key, as text
933 /// or a number, and the data finds, updates and deletes them by it
934 /// ([`RuntimeData::find_by_key_for`], [`try_update_by_key_for`](RuntimeData::try_update_by_key_for)
935 /// and [`delete_by_key_for`](RuntimeData::delete_by_key_for)). A key that the form sets is
936 /// usually locked after the first save with [`disabled_on`](Self::disabled_on), as
937 /// WordPress keeps a post type's key.
938 pub fn record_route_key_name(mut self, key: impl Into<String>) -> Self {
939 self.record_route_key_name = Some(key.into());
940 self
941 }
942
943 /// Shows the field `field` but does not let the user change it when `rule` holds, as
944 /// Filament's `->disabled()`. A disabled field is not saved. See
945 /// [`FieldConditions::disabled`].
946 pub fn disabled(
947 mut self,
948 field: impl Into<String>,
949 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
950 ) -> Self {
951 self.conditions = self.conditions.disabled(field, rule);
952 self
953 }
954
955 /// Disables the field `field` on the forms of `operations`, as Filament's
956 /// `->disabledOn('edit')`. See [`FieldConditions::disabled_on`].
957 pub fn disabled_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
958 self.conditions = self.conditions.disabled_on(field, operations);
959 self
960 }
961
962 /// Makes the records for which `rule` holds read-only for the signed-in user, as Filament's
963 /// View page, a disabled form with the record's data: their edit form shows the values
964 /// with every input disabled and no Save, its heading says "View", the list's button says
965 /// "View", and their save (and the form's live URL) answers 403 Forbidden. `rule` is given
966 /// the edit form's [`FormContext`]: the record, the user and the stored values. Such as a
967 /// post type defined in code, which the admin screens may show but not change:
968 ///
969 /// ```ignore
970 /// .read_only_when(|form| form.record().and_then(|r| r.get("origin")) != Some(&json!("admin")))
971 /// ```
972 pub fn read_only_when(
973 mut self,
974 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
975 ) -> Self {
976 self.read_only = Some(Arc::new(rule));
977 self
978 }
979
980 /// The line the form of a read-only record shows above its fields, such as "This post type
981 /// is defined in code by the theme. Change it there.", or none.
982 pub fn read_only_notice(
983 mut self,
984 notice: impl Fn(&FormContext<'_>) -> Option<String> + Send + Sync + 'static,
985 ) -> Self {
986 self.read_only_notice = Some(Arc::new(notice));
987 self
988 }
989
990 /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`.
991 /// See [`ColumnBadges::badge`].
992 pub fn badge(mut self, column: impl Into<String>) -> Self {
993 self.column_badges = self.column_badges.badge(column);
994 self
995 }
996
997 /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
998 /// as Filament's `->badge()->color(fn (string $state) => ...)`. See
999 /// [`ColumnBadges::badge_color`].
1000 pub fn badge_color(
1001 mut self,
1002 column: impl Into<String>,
1003 color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
1004 ) -> Self {
1005 self.column_badges = self.column_badges.badge_color(column, color);
1006 self
1007 }
1008
1009 /// Shows the badge of the column `column` inside the cell of the column `target`, instead
1010 /// of in a column of its own. See [`ColumnBadges::badge_inside`].
1011 pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
1012 self.column_badges = self.column_badges.badge_inside(column, target);
1013 self
1014 }
1015
1016 /// Shows the badge of the column `column` only on the list's tabs `tabs`, by key. See
1017 /// [`ColumnBadges::badge_on_tabs`].
1018 pub fn badge_on_tabs<S: Into<String>>(
1019 mut self,
1020 column: impl Into<String>,
1021 tabs: impl IntoIterator<Item = S>,
1022 ) -> Self {
1023 self.column_badges = self.column_badges.badge_on_tabs(column, tabs);
1024 self
1025 }
1026}
1027
1028/// The checks of [`RegisteredResource::validate`]. Each error is keyed by its field's name.
1029/// The fields of `hidden` are skipped: they are not checked and the row has no key for them.
1030fn validate_fields(
1031 fields: &[FieldDef],
1032 form: &FormInput,
1033 creating: bool,
1034 hidden: &BTreeSet<String>,
1035 repeaters: &Repeaters,
1036) -> Result<Row, FieldErrors> {
1037 let mut errors = FieldErrors::new();
1038 let mut row = Row::new();
1039 for field in fields.iter().filter(|f| !hidden.contains(&f.name)) {
1040 let name = field.name.as_str();
1041 let label = field.label.as_str();
1042 // A checkbox is never blank: an unticked checkbox is false.
1043 if field.kind == FieldKindDef::Checkbox {
1044 row.insert(name.to_string(), Value::Bool(form.checkbox(name)));
1045 continue;
1046 }
1047 let is_password = field.kind == FieldKindDef::Password;
1048 // A password is required only when creating. On an edit a blank one keeps the hash.
1049 let present = if field.required && (creating || !is_password) {
1050 check::check_required(name, label, form, &mut errors)
1051 } else {
1052 form.get(name)
1053 };
1054 let Some(text) = present else {
1055 // On an update, a field the form did not send keeps its stored value, and a blank
1056 // password keeps its hash. A field sent blank is cleared to NULL.
1057 let keep = !creating && (is_password || !form.has(name));
1058 // A repeater sent with no rows has none, which its fewest rows may refuse.
1059 let min = match field.kind {
1060 FieldKindDef::Repeater(_) | FieldKindDef::FlexibleContent(_) if !keep => {
1061 repeaters.get(name).get_min_items().filter(|min| *min > 0)
1062 }
1063 _ => None,
1064 };
1065 if let (Some(min), false) = (min, errors.contains_key(name)) {
1066 errors.insert(
1067 name.to_string(),
1068 format!("{label} must have at least {min} items."),
1069 );
1070 }
1071 if !keep {
1072 row.insert(name.to_string(), Value::Null);
1073 }
1074 continue;
1075 };
1076 let value = match &field.kind {
1077 FieldKindDef::Password => match crate::hash_password(text) {
1078 Ok(hash) => Some(Value::String(hash)),
1079 Err(_) => {
1080 errors.insert(
1081 name.to_string(),
1082 "Could not save this password.".to_string(),
1083 );
1084 None
1085 }
1086 },
1087 FieldKindDef::Number => {
1088 check::check_whole_number::<i64>(name, label, text, &mut errors).map(Value::from)
1089 }
1090 FieldKindDef::Decimal(_) => {
1091 check::check_decimal::<f64>(name, label, text, &mut errors).map(Value::from)
1092 }
1093 FieldKindDef::Select(choices) => {
1094 let text = text.trim();
1095 let choices: Vec<(&str, &str)> = choices
1096 .iter()
1097 .map(|(value, label)| (value.as_str(), label.as_str()))
1098 .collect();
1099 check::check_choice(name, text, &choices, &mut errors)
1100 .then(|| Value::String(text.to_string()))
1101 }
1102 FieldKindDef::Lookup => Some(Value::String(text.trim().to_string())),
1103 FieldKindDef::Date => check::check_date(name, label, text, &mut errors)
1104 .map(|date| Value::String(date.format("%Y-%m-%d").to_string())),
1105 FieldKindDef::DateTime => check::check_datetime(name, label, text, &mut errors)
1106 .map(|stamp| Value::String(stamp.format("%Y-%m-%d %H:%M:%S").to_string())),
1107 FieldKindDef::Text | FieldKindDef::Textarea | FieldKindDef::Checkbox => {
1108 Some(Value::String(text.to_string()))
1109 }
1110 kind => crate::value::check_value_in(
1111 name,
1112 label,
1113 field.required,
1114 kind,
1115 text,
1116 &mut errors,
1117 repeaters,
1118 )
1119 .map(Value::String),
1120 };
1121 if let Some(value) = value {
1122 row.insert(name.to_string(), value);
1123 }
1124 }
1125 if errors.is_empty() {
1126 Ok(row)
1127 } else {
1128 Err(errors)
1129 }
1130}
1131
1132/// Why the registry refused a change.
1133#[derive(Debug, Clone, PartialEq, Eq)]
1134pub enum RuntimeError {
1135 /// The slug is not one URL segment of lowercase letters, digits, `-` and `_`.
1136 InvalidSlug(String),
1137 /// Another resource, static or runtime, or one of the panel's own pages, has the slug.
1138 SlugTaken(String),
1139 /// A field name is not a lowercase identifier: lowercase ASCII letters, digits and `_`,
1140 /// starting with a letter, at most 64 bytes ([`MAX_FIELD_NAME`]).
1141 InvalidFieldName {
1142 /// The slug of the resource.
1143 slug: String,
1144 /// The name that was refused.
1145 field: String,
1146 },
1147 /// Two fields of the resource have the same name.
1148 DuplicateField {
1149 /// The slug of the resource.
1150 slug: String,
1151 /// The name used twice.
1152 field: String,
1153 },
1154 /// No runtime resource has the slug.
1155 NotRegistered(String),
1156}
1157
1158impl fmt::Display for RuntimeError {
1159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160 match self {
1161 RuntimeError::InvalidSlug(slug) => write!(
1162 f,
1163 "the slug `{slug}` is not valid: use lowercase letters, digits, `-` and `_`"
1164 ),
1165 RuntimeError::SlugTaken(slug) => write!(
1166 f,
1167 "the slug `{slug}` is already used by another Ignite resource"
1168 ),
1169 RuntimeError::InvalidFieldName { slug, field } => write!(
1170 f,
1171 "the field `{field}` of the resource `{slug}` is not valid: use lowercase \
1172 letters, digits and `_`, starting with a letter, at most {MAX_FIELD_NAME} bytes"
1173 ),
1174 RuntimeError::DuplicateField { slug, field } => {
1175 write!(f, "the resource `{slug}` has two fields named `{field}`")
1176 }
1177 RuntimeError::NotRegistered(slug) => {
1178 write!(f, "no runtime resource is registered at `{slug}`")
1179 }
1180 }
1181 }
1182}
1183
1184impl std::error::Error for RuntimeError {}
1185
1186/// A runtime resource as the registry holds it: the definition, ready for the panel.
1187pub struct RegisteredResource {
1188 resource: RuntimeResource,
1189}
1190
1191impl RegisteredResource {
1192 /// Checks `resource` as [`register_runtime`] does, without adding it to the registry: its
1193 /// slug and its field names. The panel uses it for a resource defined by data that is part
1194 /// of the panel from its start (`Ignite::runtime_resource`), such as the Users screen.
1195 pub fn new(resource: RuntimeResource) -> Result<Self, RuntimeError> {
1196 check_definition(&resource)?;
1197 Ok(RegisteredResource { resource })
1198 }
1199
1200 /// The definition that was registered.
1201 pub fn resource(&self) -> &RuntimeResource {
1202 &self.resource
1203 }
1204
1205 /// The slug, as the panel's routes match it.
1206 pub fn slug(&self) -> &str {
1207 &self.resource.slug
1208 }
1209
1210 /// The heading and navigation label.
1211 pub fn title(&self) -> &str {
1212 &self.resource.title
1213 }
1214
1215 /// The name of one record.
1216 pub fn singular(&self) -> &str {
1217 &self.resource.singular
1218 }
1219
1220 /// The label of the navigation entry: the navigation label, or the title.
1221 pub fn navigation_label(&self) -> &str {
1222 self.resource
1223 .navigation_label
1224 .as_deref()
1225 .unwrap_or(&self.resource.title)
1226 }
1227
1228 /// The navigation group the resource is listed under, if any.
1229 pub fn navigation_group(&self) -> Option<&str> {
1230 self.resource.navigation_group.as_deref()
1231 }
1232
1233 /// The resource's place in the navigation, if set.
1234 pub fn navigation_sort(&self) -> Option<i32> {
1235 self.resource.navigation_sort
1236 }
1237
1238 /// The navigation entry the resource is listed under, if any.
1239 pub fn navigation_parent_item(&self) -> Option<&str> {
1240 self.resource.navigation_parent_item.as_deref()
1241 }
1242
1243 /// The name of the navigation entry's icon, if set.
1244 pub fn navigation_icon(&self) -> Option<&str> {
1245 self.resource.navigation_icon.as_deref()
1246 }
1247
1248 /// The label of the navigation entry's create link, or `None` when it lists none.
1249 pub fn navigation_create_item(&self) -> Option<&str> {
1250 self.resource.navigation_create_item.then(|| {
1251 self.resource
1252 .navigation_create_label
1253 .as_deref()
1254 .unwrap_or("Add new")
1255 })
1256 }
1257
1258 /// The form fields, in display order.
1259 pub fn fields(&self) -> &[FieldDef] {
1260 &self.resource.fields
1261 }
1262
1263 /// The list columns, in display order.
1264 pub fn columns(&self) -> &[ColumnDef] {
1265 &self.resource.columns
1266 }
1267
1268 /// Turns the submitted form into a [`Row`] for a create, or returns one message per
1269 /// field. It runs the same checks as a static resource, with the same messages:
1270 /// required fields ([`Field::check_required`](crate::Field::check_required)), whole
1271 /// numbers, decimals, dates, date-times and select choices. The row holds one key per
1272 /// field:
1273 ///
1274 /// - text, textarea, select, lookup: a string. A required value is trimmed.
1275 /// - email, URL, radio, color, image, file, link, wysiwyg, post object, checkbox list,
1276 /// relationship,
1277 /// taxonomy, user, repeater, group, flexible content, gallery, clone: the text
1278 /// [`Field::check_value`](crate::Field::check_value) returns. The structured kinds
1279 /// hold JSON text.
1280 /// - number: an integer. Decimal: a number.
1281 /// - checkbox: `true` or `false`; a checkbox is never blank.
1282 /// - date: `"YYYY-MM-DD"`. Date-time: `"YYYY-MM-DD HH:MM:SS"`.
1283 /// - password: the hash of the password ([`hash_password`](crate::hash_password)).
1284 /// - a blank field that is not required: `null`.
1285 ///
1286 /// Each error in [`FieldErrors`] is keyed by the field's name, an owned `String`.
1287 ///
1288 /// A lookup, post object, relationship, taxonomy or user value is checked against
1289 /// [`RuntimeData::options`] by the panel, which can read the database, and so is a media
1290 /// id against the registered [`MediaLibrary`](crate::MediaLibrary).
1291 pub fn validate(&self, form: &FormInput) -> Result<Row, FieldErrors> {
1292 validate_fields(
1293 &self.resource.fields,
1294 form,
1295 true,
1296 &BTreeSet::new(),
1297 &self.resource.repeaters,
1298 )
1299 }
1300
1301 /// Turns the submitted form into a [`Row`] for an update. It is
1302 /// [`validate`](Self::validate), except that:
1303 ///
1304 /// - a blank password is not an error: the row leaves its key out, so the stored
1305 /// password is kept;
1306 /// - an optional field the form did not send at all ([`FormInput::has`] is false) is left
1307 /// out of the row, so its stored value is kept;
1308 /// - an optional field sent blank is `null`, so clearing it on the edit form clears the
1309 /// stored value, as `#[derive(IgniteResource)]` does since 0.3.0;
1310 /// - a checkbox the form did not send is `false`, because an unticked HTML checkbox sends
1311 /// nothing.
1312 pub fn validate_update(&self, form: &FormInput) -> Result<Row, FieldErrors> {
1313 validate_fields(
1314 &self.resource.fields,
1315 form,
1316 false,
1317 &BTreeSet::new(),
1318 &self.resource.repeaters,
1319 )
1320 }
1321
1322 /// The conditions that show or hide the form's fields.
1323 pub fn conditions(&self) -> &FieldConditions {
1324 &self.resource.conditions
1325 }
1326
1327 /// The layout of the create and edit forms.
1328 pub fn form_layout(&self) -> &FormLayout {
1329 &self.resource.form_layout
1330 }
1331
1332 /// The tabs of the list page, in display order.
1333 pub fn tabs(&self) -> &[Tab] {
1334 &self.resource.tabs
1335 }
1336
1337 /// The key of the tab shown when the list has no `tab` parameter, if set.
1338 pub fn default_active_tab(&self) -> Option<&str> {
1339 self.resource.default_active_tab.as_deref()
1340 }
1341
1342 /// The list columns shown as coloured badges.
1343 pub fn column_badges(&self) -> &ColumnBadges {
1344 &self.resource.column_badges
1345 }
1346
1347 /// Whether each tab's count is for the current search.
1348 pub fn tab_counts_follow_search(&self) -> bool {
1349 self.resource.tab_counts_follow_search
1350 }
1351
1352 /// Whether a tab whose count is 0 is left out.
1353 pub fn hide_empty_tabs(&self) -> bool {
1354 self.resource.hide_empty_tabs
1355 }
1356
1357 /// The actions on each row of the list, in display order.
1358 pub fn row_actions(&self) -> &[RowAction] {
1359 &self.resource.row_actions
1360 }
1361
1362 /// The records whose built-in Delete button is hidden, if set.
1363 pub fn hide_default_delete_when(&self) -> Option<&ListFilter> {
1364 self.resource.hide_default_delete_when.as_ref()
1365 }
1366
1367 /// The settings of the form's repeaters and flexible content fields.
1368 pub fn repeaters(&self) -> &Repeaters {
1369 &self.resource.repeaters
1370 }
1371
1372 /// The ability `action` on the resource needs: the one [`RuntimeResource::ability`]
1373 /// names, or `<slug>.<action>`, such as `books.update`.
1374 pub fn ability_for(&self, action: ResourceAction) -> String {
1375 self.resource
1376 .abilities
1377 .get(&action)
1378 .cloned()
1379 .unwrap_or_else(|| format!("{}.{}", self.resource.slug, action.as_str()))
1380 }
1381
1382 /// The ability every action needs besides its own, if any
1383 /// ([`RuntimeResource::access_ability`]).
1384 pub fn access_ability(&self) -> Option<&str> {
1385 self.resource.access_ability.as_deref()
1386 }
1387
1388 /// Every ability `action` needs: the access ability, if any, and the action's own.
1389 pub fn required_abilities(&self, action: ResourceAction) -> Vec<String> {
1390 self.access_ability()
1391 .map(str::to_string)
1392 .into_iter()
1393 .chain(std::iter::once(self.ability_for(action)))
1394 .collect()
1395 }
1396
1397 /// Every ability the resource's actions need, without repeats, in action order: the
1398 /// permissions the panel registers for it.
1399 pub fn ability_names(&self) -> Vec<String> {
1400 let mut names: Vec<String> = Vec::new();
1401 for action in ResourceAction::ALL {
1402 for name in self.required_abilities(action) {
1403 if !names.contains(&name) {
1404 names.push(name);
1405 }
1406 }
1407 }
1408 names
1409 }
1410
1411 /// The row key that addresses a record in the panel's URLs: the
1412 /// [`record_route_key_name`](RuntimeResource::record_route_key_name), or `id`.
1413 pub fn record_route_key_name(&self) -> &str {
1414 self.resource
1415 .record_route_key_name
1416 .as_deref()
1417 .unwrap_or("id")
1418 }
1419
1420 /// Whether the record of the edit form `form` is read-only for its user
1421 /// ([`RuntimeResource::read_only_when`]).
1422 pub fn is_read_only(&self, form: &FormContext<'_>) -> bool {
1423 self.resource
1424 .read_only
1425 .as_ref()
1426 .is_some_and(|rule| rule(form))
1427 }
1428
1429 /// The line the form of a read-only record shows, if any.
1430 pub fn read_only_notice(&self, form: &FormContext<'_>) -> Option<String> {
1431 self.resource
1432 .read_only_notice
1433 .as_ref()
1434 .and_then(|notice| notice(form))
1435 }
1436
1437 /// [`validate`](Self::validate) for a form whose fields `hidden` are hidden (see
1438 /// [`FieldConditions::hidden_fields`]): they are not checked, a required one included, and
1439 /// the row has no key for them, so the source writes nothing for them. The panel calls it.
1440 pub fn validate_shown(
1441 &self,
1442 form: &FormInput,
1443 hidden: &BTreeSet<String>,
1444 ) -> Result<Row, FieldErrors> {
1445 validate_fields(
1446 &self.resource.fields,
1447 form,
1448 true,
1449 hidden,
1450 &self.resource.repeaters,
1451 )
1452 }
1453
1454 /// [`validate_update`](Self::validate_update) for a form whose fields `hidden` are hidden:
1455 /// the row has no key for them, so their stored values are kept, whatever the form sent.
1456 pub fn validate_update_shown(
1457 &self,
1458 form: &FormInput,
1459 hidden: &BTreeSet<String>,
1460 ) -> Result<Row, FieldErrors> {
1461 validate_fields(
1462 &self.resource.fields,
1463 form,
1464 false,
1465 hidden,
1466 &self.resource.repeaters,
1467 )
1468 }
1469}
1470
1471/// The registry: the runtime resources in registration order, and the slugs reserved for
1472/// static resources and for the panel's own pages.
1473#[derive(Default)]
1474struct Registry {
1475 resources: Vec<Arc<RegisteredResource>>,
1476 reserved: HashSet<String>,
1477}
1478
1479static REGISTRY: RwLock<Option<Registry>> = RwLock::new(None);
1480
1481/// Runs `f` on the registry, read-only. The lock is never held across an `.await`: every
1482/// caller is synchronous.
1483fn read<T>(f: impl FnOnce(&Registry) -> T) -> T {
1484 let guard = REGISTRY.read().unwrap_or_else(PoisonError::into_inner);
1485 match guard.as_ref() {
1486 Some(registry) => f(registry),
1487 None => f(&Registry::default()),
1488 }
1489}
1490
1491/// Runs `f` on the registry, to change it.
1492fn write<T>(f: impl FnOnce(&mut Registry) -> T) -> T {
1493 let mut guard = REGISTRY.write().unwrap_or_else(PoisonError::into_inner);
1494 f(guard.get_or_insert_with(Registry::default))
1495}
1496
1497/// The longest field name a runtime resource accepts, in bytes, as for a MySQL or MariaDB
1498/// column name. The limit is a validation rule: names are owned by their resource and freed
1499/// with it.
1500pub const MAX_FIELD_NAME: usize = 64;
1501
1502/// Whether `name` is a field name a runtime resource accepts: lowercase ASCII letters, digits
1503/// and `_`, starting with a letter, at most [`MAX_FIELD_NAME`] bytes, as a column name is.
1504fn valid_field_name(name: &str) -> bool {
1505 name.len() <= MAX_FIELD_NAME
1506 && name.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
1507 && name
1508 .bytes()
1509 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
1510}
1511
1512/// Whether `slug` is one URL segment the panel's `/<slug>` routes match: lowercase ASCII
1513/// letters, digits, `-` and `_`, as Filament's kebab-case slugs are.
1514fn valid_slug(slug: &str) -> bool {
1515 !slug.is_empty()
1516 && slug
1517 .bytes()
1518 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1519}
1520
1521/// Adds a runtime resource to the panel. It shows in the navigation and the dashboard, and
1522/// its list, forms and delete action answer at `/<mount>/<slug>`, from the next request on.
1523/// Create its permissions (`<slug>.viewAny` and the others) in the same request with
1524/// `ignite_panel::register_runtime_permissions`; otherwise the panel creates them on the next
1525/// signed-in request.
1526///
1527/// Refuses a slug that is not valid, a slug that a static resource, another runtime resource
1528/// or one of the panel's own pages (such as `login`) uses, and two fields with one name.
1529pub fn register_runtime(resource: RuntimeResource) -> Result<(), RuntimeError> {
1530 check_definition(&resource)?;
1531 write(|registry| {
1532 let slug = resource.slug.as_str();
1533 if registry.reserved.contains(slug) || registry.resources.iter().any(|r| r.slug() == slug) {
1534 return Err(RuntimeError::SlugTaken(resource.slug.clone()));
1535 }
1536 registry
1537 .resources
1538 .push(Arc::new(RegisteredResource { resource }));
1539 Ok(())
1540 })
1541}
1542
1543/// Checks a definition's slug and field names.
1544fn check_definition(resource: &RuntimeResource) -> Result<(), RuntimeError> {
1545 if !valid_slug(&resource.slug) {
1546 return Err(RuntimeError::InvalidSlug(resource.slug.clone()));
1547 }
1548 if let Some(field) = resource.fields.iter().find(|f| !valid_field_name(&f.name)) {
1549 return Err(RuntimeError::InvalidFieldName {
1550 slug: resource.slug.clone(),
1551 field: field.name.clone(),
1552 });
1553 }
1554 let mut names = HashSet::new();
1555 if let Some(field) = resource.fields.iter().find(|f| !names.insert(&f.name)) {
1556 return Err(RuntimeError::DuplicateField {
1557 slug: resource.slug.clone(),
1558 field: field.name.clone(),
1559 });
1560 }
1561 Ok(())
1562}
1563
1564/// Removes the runtime resource at `slug`. From the next request on, it is gone from the
1565/// navigation and its routes answer 404. Its permission rows stay, so the grants come back
1566/// if the resource is registered again.
1567pub fn unregister_runtime(slug: &str) -> Result<(), RuntimeError> {
1568 write(|registry| {
1569 let before = registry.resources.len();
1570 registry.resources.retain(|r| r.slug() != slug);
1571 if registry.resources.len() == before {
1572 Err(RuntimeError::NotRegistered(slug.to_string()))
1573 } else {
1574 Ok(())
1575 }
1576 })
1577}
1578
1579/// The runtime resource at `slug`, if one is registered.
1580pub fn runtime_resource(slug: &str) -> Option<Arc<RegisteredResource>> {
1581 read(|registry| {
1582 registry
1583 .resources
1584 .iter()
1585 .find(|r| r.slug() == slug)
1586 .cloned()
1587 })
1588}
1589
1590/// Every runtime resource, in registration order.
1591pub fn runtime_resources() -> Vec<Arc<RegisteredResource>> {
1592 read(|registry| registry.resources.clone())
1593}
1594
1595/// Reserves `slugs`, so no runtime resource can take them. The panel reserves the slugs of
1596/// its static resources and of its own pages when it is built. Reserving a slug twice is
1597/// fine. Refuses, and reserves none, when a runtime resource already has one of them.
1598pub fn reserve_slugs(slugs: &[&str]) -> Result<(), RuntimeError> {
1599 write(|registry| {
1600 if let Some(slug) = slugs
1601 .iter()
1602 .find(|slug| registry.resources.iter().any(|r| r.slug() == **slug))
1603 {
1604 return Err(RuntimeError::SlugTaken(slug.to_string()));
1605 }
1606 registry
1607 .reserved
1608 .extend(slugs.iter().map(|slug| slug.to_string()));
1609 Ok(())
1610 })
1611}
1612
1613#[cfg(test)]
1614mod tests {
1615 use super::*;
1616
1617 struct NoData;
1618
1619 impl RuntimeData for NoData {
1620 fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
1621 unreachable!()
1622 }
1623 fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
1624 unreachable!()
1625 }
1626 fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
1627 unreachable!()
1628 }
1629 fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
1630 unreachable!()
1631 }
1632 fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
1633 unreachable!()
1634 }
1635 }
1636
1637 /// A resource with the fields `growth_title` and `growth_status`, whose label and
1638 /// choices change with `n`.
1639 fn edited(slug: &str, n: usize) -> RuntimeResource {
1640 RuntimeResource::new(slug, format!("Title {n}"), format!("One {n}"), NoData)
1641 .field(FieldDef {
1642 name: "growth_title".into(),
1643 label: format!("Title {n}"),
1644 kind: FieldKindDef::Text,
1645 required: n.is_multiple_of(2),
1646 })
1647 .field(FieldDef {
1648 name: "growth_status".into(),
1649 label: format!("Status {n}"),
1650 kind: FieldKindDef::Select(vec![(format!("v{n}"), format!("Value {n}"))]),
1651 required: false,
1652 })
1653 .column(ColumnDef {
1654 key: "growth_title".into(),
1655 label: format!("Column {n}"),
1656 sortable: false,
1657 searchable: false,
1658 })
1659 }
1660
1661 // Field names are owned by their resource: editing a definition a thousand times keeps
1662 // nothing of the old ones, and an error is keyed by the field's own name.
1663 #[test]
1664 fn editing_a_definition_a_thousand_times_keeps_owned_names() {
1665 register_runtime(edited("growth", 0)).expect("register");
1666 for n in 1..=1000 {
1667 unregister_runtime("growth").expect("unregister");
1668 register_runtime(edited("growth", n)).expect("register again");
1669 let registered = runtime_resource("growth").expect("registered");
1670 let mut values = std::collections::HashMap::new();
1671 values.insert("growth_status".to_string(), "not a choice".to_string());
1672 let errors = registered
1673 .validate(&FormInput::new(values.clone()))
1674 .unwrap_err();
1675 assert!(errors.contains_key("growth_status"));
1676 let _ = registered.validate_update(&FormInput::new(values));
1677 }
1678 // The last registration is the only one the registry holds.
1679 let registered = runtime_resource("growth").expect("registered");
1680 assert_eq!(registered.title(), "Title 1000");
1681 assert_eq!(
1682 runtime_resources()
1683 .iter()
1684 .filter(|r| r.slug() == "growth")
1685 .count(),
1686 1
1687 );
1688 unregister_runtime("growth").expect("unregister");
1689 }
1690}