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