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