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 /// Whether each tab's count is for the current search. The default is `false`: a tab
431 /// counts all its rows. See
432 /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
433 pub tab_counts_follow_search: bool,
434 /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
435 /// The default is `true`. See
436 /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
437 pub hide_empty_tabs: bool,
438}
439
440impl fmt::Debug for RuntimeResource {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 f.debug_struct("RuntimeResource")
443 .field("slug", &self.slug)
444 .field("title", &self.title)
445 .field("singular", &self.singular)
446 .field("per_page", &self.per_page)
447 .field("fields", &self.fields)
448 .field("columns", &self.columns)
449 .field("navigation_label", &self.navigation_label)
450 .field("navigation_group", &self.navigation_group)
451 .field("navigation_sort", &self.navigation_sort)
452 .field("navigation_parent_item", &self.navigation_parent_item)
453 .field("navigation_icon", &self.navigation_icon)
454 .field("conditions", &self.conditions)
455 .field("form_layout", &self.form_layout)
456 .field("tabs", &self.tabs)
457 .field("default_active_tab", &self.default_active_tab)
458 .field("column_badges", &self.column_badges)
459 .field("tab_counts_follow_search", &self.tab_counts_follow_search)
460 .field("hide_empty_tabs", &self.hide_empty_tabs)
461 .finish_non_exhaustive()
462 }
463}
464
465impl RuntimeResource {
466 /// A resource at `slug` with no fields or columns yet, whose rows come from `data`.
467 pub fn new(
468 slug: impl Into<String>,
469 title: impl Into<String>,
470 singular: impl Into<String>,
471 data: impl RuntimeData,
472 ) -> Self {
473 RuntimeResource {
474 slug: slug.into(),
475 title: title.into(),
476 singular: singular.into(),
477 per_page: 20,
478 fields: Vec::new(),
479 columns: Vec::new(),
480 data: Arc::new(data),
481 navigation_label: None,
482 navigation_group: None,
483 navigation_sort: None,
484 navigation_parent_item: None,
485 navigation_icon: None,
486 conditions: FieldConditions::new(),
487 form_layout: FormLayout::new(),
488 tabs: Vec::new(),
489 default_active_tab: None,
490 column_badges: ColumnBadges::new(),
491 tab_counts_follow_search: false,
492 hide_empty_tabs: true,
493 }
494 }
495
496 /// Adds a form field after the others.
497 pub fn field(mut self, field: FieldDef) -> Self {
498 self.fields.push(field);
499 self
500 }
501
502 /// Adds a list column after the others.
503 pub fn column(mut self, column: ColumnDef) -> Self {
504 self.columns.push(column);
505 self
506 }
507
508 /// Sets the rows per page of the list view.
509 pub fn per_page(mut self, per_page: i64) -> Self {
510 self.per_page = per_page;
511 self
512 }
513
514 /// Sets the label of the navigation entry, as Filament's `navigationLabel`.
515 pub fn navigation_label(mut self, label: impl Into<String>) -> Self {
516 self.navigation_label = Some(label.into());
517 self
518 }
519
520 /// Lists the resource under the navigation group `group`, as Filament's `navigationGroup`.
521 pub fn navigation_group(mut self, group: impl Into<String>) -> Self {
522 self.navigation_group = Some(group.into());
523 self
524 }
525
526 /// Sets the resource's place in the navigation, as Filament's `navigationSort`: lower first.
527 pub fn navigation_sort(mut self, sort: i32) -> Self {
528 self.navigation_sort = Some(sort);
529 self
530 }
531
532 /// Lists the resource under the navigation entry `parent` (its label or slug), as
533 /// Filament's `navigationParentItem`. See
534 /// [`IgniteResource::NAVIGATION_PARENT_ITEM`](crate::IgniteResource::NAVIGATION_PARENT_ITEM).
535 pub fn navigation_parent_item(mut self, parent: impl Into<String>) -> Self {
536 self.navigation_parent_item = Some(parent.into());
537 self
538 }
539
540 /// Sets the name of the navigation entry's icon, as Filament's `navigationIcon`: a name
541 /// such as `"post"` or a custom post type's own, which the admin theme maps to its icon.
542 /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
543 pub fn navigation_icon(mut self, name: impl Into<String>) -> Self {
544 self.navigation_icon = Some(name.into());
545 self
546 }
547
548 /// Shows the field `field` only when `rule` holds, as Filament's `->visible()`. See
549 /// [`FieldConditions::visible`].
550 pub fn visible(
551 mut self,
552 field: impl Into<String>,
553 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
554 ) -> Self {
555 self.conditions = self.conditions.visible(field, rule);
556 self
557 }
558
559 /// Hides the field `field` when `rule` holds, as Filament's `->hidden()`. See
560 /// [`FieldConditions::hidden`].
561 pub fn hidden(
562 mut self,
563 field: impl Into<String>,
564 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
565 ) -> Self {
566 self.conditions = self.conditions.hidden(field, rule);
567 self
568 }
569
570 /// Shows the field `field` only on the forms of `operations`, as Filament's
571 /// `->visibleOn()`.
572 pub fn visible_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
573 self.conditions = self.conditions.visible_on(field, operations);
574 self
575 }
576
577 /// Hides the field `field` on the forms of `operations`, as Filament's `->hiddenOn()`.
578 pub fn hidden_on(mut self, field: impl Into<String>, operations: &[Operation]) -> Self {
579 self.conditions = self.conditions.hidden_on(field, operations);
580 self
581 }
582
583 /// Makes the field `field` live, as Filament's `->live()`: a change to it in the browser
584 /// shows the form's fields again for the new value. See [`FieldConditions::live`].
585 pub fn live(mut self, field: impl Into<String>) -> Self {
586 self.conditions = self.conditions.live(field);
587 self
588 }
589
590 /// Fills the field `field` with the slug of the field `source` until the user edits it, as
591 /// Filament's slug pattern. See [`FieldConditions::slug_from`].
592 pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
593 self.conditions = self.conditions.slug_from(field, source);
594 self
595 }
596
597 /// Stops the slug field `field` from following its source on the edit form of a record
598 /// with a stored slug, when `rule` holds, such as once the record is published. See
599 /// [`FieldConditions::slug_locked_when`].
600 pub fn slug_locked_when(
601 mut self,
602 field: impl Into<String>,
603 rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
604 ) -> Self {
605 self.conditions = self.conditions.slug_locked_when(field, rule);
606 self
607 }
608
609 /// Sets the layout of the create and edit forms: columns, sections and groups, as
610 /// Filament's layout components. See [`FormLayout`].
611 pub fn form_layout(mut self, layout: FormLayout) -> Self {
612 self.form_layout = layout;
613 self
614 }
615
616 /// Adds a tab to the list page after the others, as a [`Tab`] in Filament's `getTabs()`.
617 /// The [`RuntimeData`] list is given the active tab's conditions in
618 /// [`ListQuery::filter`]: apply them with [`ListFilter::apply`](crate::ListFilter::apply)
619 /// or [`ListFilter::matches`](crate::ListFilter::matches).
620 pub fn tab(mut self, tab: Tab) -> Self {
621 self.tabs.push(tab);
622 self
623 }
624
625 /// Sets the tab shown when the list has no `tab` parameter, by its key, as Filament's
626 /// `getDefaultActiveTab()`. Without it, the first tab is shown.
627 pub fn default_active_tab(mut self, key: impl Into<String>) -> Self {
628 self.default_active_tab = Some(key.into());
629 self
630 }
631
632 /// Whether each tab's count is for the current search. The default, `false`, counts all
633 /// of a tab's rows. See
634 /// [`IgniteResource::tab_counts_follow_search`](crate::IgniteResource::tab_counts_follow_search).
635 pub fn tab_counts_follow_search(mut self, follow: bool) -> Self {
636 self.tab_counts_follow_search = follow;
637 self
638 }
639
640 /// Whether a tab whose count is 0 is left out, except the default tab and the tab shown.
641 /// The default is `true`; `false` renders every tab. See
642 /// [`IgniteResource::hide_empty_tabs`](crate::IgniteResource::hide_empty_tabs).
643 pub fn hide_empty_tabs(mut self, hide: bool) -> Self {
644 self.hide_empty_tabs = hide;
645 self
646 }
647
648 /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`.
649 /// See [`ColumnBadges::badge`].
650 pub fn badge(mut self, column: impl Into<String>) -> Self {
651 self.column_badges = self.column_badges.badge(column);
652 self
653 }
654
655 /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
656 /// as Filament's `->badge()->color(fn (string $state) => ...)`. See
657 /// [`ColumnBadges::badge_color`].
658 pub fn badge_color(
659 mut self,
660 column: impl Into<String>,
661 color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
662 ) -> Self {
663 self.column_badges = self.column_badges.badge_color(column, color);
664 self
665 }
666
667 /// Shows the badge of the column `column` inside the cell of the column `target`, instead
668 /// of in a column of its own. See [`ColumnBadges::badge_inside`].
669 pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
670 self.column_badges = self.column_badges.badge_inside(column, target);
671 self
672 }
673
674 /// Shows the badge of the column `column` only on the list's tabs `tabs`, by key. See
675 /// [`ColumnBadges::badge_on_tabs`].
676 pub fn badge_on_tabs<S: Into<String>>(
677 mut self,
678 column: impl Into<String>,
679 tabs: impl IntoIterator<Item = S>,
680 ) -> Self {
681 self.column_badges = self.column_badges.badge_on_tabs(column, tabs);
682 self
683 }
684}
685
686/// The checks of [`RegisteredResource::validate`]. Each error is keyed by its field's name.
687/// The fields of `hidden` are skipped: they are not checked and the row has no key for them.
688fn validate_fields(
689 fields: &[FieldDef],
690 form: &FormInput,
691 creating: bool,
692 hidden: &BTreeSet<String>,
693) -> Result<Row, FieldErrors> {
694 let mut errors = FieldErrors::new();
695 let mut row = Row::new();
696 for field in fields.iter().filter(|f| !hidden.contains(&f.name)) {
697 let name = field.name.as_str();
698 let label = field.label.as_str();
699 // A checkbox is never blank: an unticked checkbox is false.
700 if field.kind == FieldKindDef::Checkbox {
701 row.insert(name.to_string(), Value::Bool(form.checkbox(name)));
702 continue;
703 }
704 let is_password = field.kind == FieldKindDef::Password;
705 // A password is required only when creating. On an edit a blank one keeps the hash.
706 let present = if field.required && (creating || !is_password) {
707 check::check_required(name, label, form, &mut errors)
708 } else {
709 form.get(name)
710 };
711 let Some(text) = present else {
712 // On an update, a field the form did not send keeps its stored value, and a blank
713 // password keeps its hash. A field sent blank is cleared to NULL.
714 let keep = !creating && (is_password || !form.has(name));
715 if !keep {
716 row.insert(name.to_string(), Value::Null);
717 }
718 continue;
719 };
720 let value = match &field.kind {
721 FieldKindDef::Password => match crate::hash_password(text) {
722 Ok(hash) => Some(Value::String(hash)),
723 Err(_) => {
724 errors.insert(
725 name.to_string(),
726 "Could not save this password.".to_string(),
727 );
728 None
729 }
730 },
731 FieldKindDef::Number => {
732 check::check_whole_number::<i64>(name, label, text, &mut errors).map(Value::from)
733 }
734 FieldKindDef::Decimal(_) => {
735 check::check_decimal::<f64>(name, label, text, &mut errors).map(Value::from)
736 }
737 FieldKindDef::Select(choices) => {
738 let text = text.trim();
739 let choices: Vec<(&str, &str)> = choices
740 .iter()
741 .map(|(value, label)| (value.as_str(), label.as_str()))
742 .collect();
743 check::check_choice(name, text, &choices, &mut errors)
744 .then(|| Value::String(text.to_string()))
745 }
746 FieldKindDef::Lookup => Some(Value::String(text.trim().to_string())),
747 FieldKindDef::Date => check::check_date(name, label, text, &mut errors)
748 .map(|date| Value::String(date.format("%Y-%m-%d").to_string())),
749 FieldKindDef::DateTime => check::check_datetime(name, label, text, &mut errors)
750 .map(|stamp| Value::String(stamp.format("%Y-%m-%d %H:%M:%S").to_string())),
751 FieldKindDef::Text | FieldKindDef::Textarea | FieldKindDef::Checkbox => {
752 Some(Value::String(text.to_string()))
753 }
754 kind => crate::value::check_value(name, label, field.required, kind, text, &mut errors)
755 .map(Value::String),
756 };
757 if let Some(value) = value {
758 row.insert(name.to_string(), value);
759 }
760 }
761 if errors.is_empty() {
762 Ok(row)
763 } else {
764 Err(errors)
765 }
766}
767
768/// Why the registry refused a change.
769#[derive(Debug, Clone, PartialEq, Eq)]
770pub enum RuntimeError {
771 /// The slug is not one URL segment of lowercase letters, digits, `-` and `_`.
772 InvalidSlug(String),
773 /// Another resource, static or runtime, or one of the panel's own pages, has the slug.
774 SlugTaken(String),
775 /// A field name is not a lowercase identifier: lowercase ASCII letters, digits and `_`,
776 /// starting with a letter, at most 64 bytes ([`MAX_FIELD_NAME`]).
777 InvalidFieldName {
778 /// The slug of the resource.
779 slug: String,
780 /// The name that was refused.
781 field: String,
782 },
783 /// Two fields of the resource have the same name.
784 DuplicateField {
785 /// The slug of the resource.
786 slug: String,
787 /// The name used twice.
788 field: String,
789 },
790 /// No runtime resource has the slug.
791 NotRegistered(String),
792}
793
794impl fmt::Display for RuntimeError {
795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796 match self {
797 RuntimeError::InvalidSlug(slug) => write!(
798 f,
799 "the slug `{slug}` is not valid: use lowercase letters, digits, `-` and `_`"
800 ),
801 RuntimeError::SlugTaken(slug) => write!(
802 f,
803 "the slug `{slug}` is already used by another Ignite resource"
804 ),
805 RuntimeError::InvalidFieldName { slug, field } => write!(
806 f,
807 "the field `{field}` of the resource `{slug}` is not valid: use lowercase \
808 letters, digits and `_`, starting with a letter, at most {MAX_FIELD_NAME} bytes"
809 ),
810 RuntimeError::DuplicateField { slug, field } => {
811 write!(f, "the resource `{slug}` has two fields named `{field}`")
812 }
813 RuntimeError::NotRegistered(slug) => {
814 write!(f, "no runtime resource is registered at `{slug}`")
815 }
816 }
817 }
818}
819
820impl std::error::Error for RuntimeError {}
821
822/// A runtime resource as the registry holds it: the definition, ready for the panel.
823pub struct RegisteredResource {
824 resource: RuntimeResource,
825}
826
827impl RegisteredResource {
828 /// The definition that was registered.
829 pub fn resource(&self) -> &RuntimeResource {
830 &self.resource
831 }
832
833 /// The slug, as the panel's routes match it.
834 pub fn slug(&self) -> &str {
835 &self.resource.slug
836 }
837
838 /// The heading and navigation label.
839 pub fn title(&self) -> &str {
840 &self.resource.title
841 }
842
843 /// The name of one record.
844 pub fn singular(&self) -> &str {
845 &self.resource.singular
846 }
847
848 /// The label of the navigation entry: the navigation label, or the title.
849 pub fn navigation_label(&self) -> &str {
850 self.resource
851 .navigation_label
852 .as_deref()
853 .unwrap_or(&self.resource.title)
854 }
855
856 /// The navigation group the resource is listed under, if any.
857 pub fn navigation_group(&self) -> Option<&str> {
858 self.resource.navigation_group.as_deref()
859 }
860
861 /// The resource's place in the navigation, if set.
862 pub fn navigation_sort(&self) -> Option<i32> {
863 self.resource.navigation_sort
864 }
865
866 /// The navigation entry the resource is listed under, if any.
867 pub fn navigation_parent_item(&self) -> Option<&str> {
868 self.resource.navigation_parent_item.as_deref()
869 }
870
871 /// The name of the navigation entry's icon, if set.
872 pub fn navigation_icon(&self) -> Option<&str> {
873 self.resource.navigation_icon.as_deref()
874 }
875
876 /// The form fields, in display order.
877 pub fn fields(&self) -> &[FieldDef] {
878 &self.resource.fields
879 }
880
881 /// The list columns, in display order.
882 pub fn columns(&self) -> &[ColumnDef] {
883 &self.resource.columns
884 }
885
886 /// Turns the submitted form into a [`Row`] for a create, or returns one message per
887 /// field. It runs the same checks as a static resource, with the same messages:
888 /// required fields ([`Field::check_required`](crate::Field::check_required)), whole
889 /// numbers, decimals, dates, date-times and select choices. The row holds one key per
890 /// field:
891 ///
892 /// - text, textarea, select, lookup: a string. A required value is trimmed.
893 /// - email, URL, radio, color, image, file, link, wysiwyg, post object, relationship,
894 /// taxonomy, user, repeater, group, flexible content, gallery, clone: the text
895 /// [`Field::check_value`](crate::Field::check_value) returns. The structured kinds
896 /// hold JSON text.
897 /// - number: an integer. Decimal: a number.
898 /// - checkbox: `true` or `false`; a checkbox is never blank.
899 /// - date: `"YYYY-MM-DD"`. Date-time: `"YYYY-MM-DD HH:MM:SS"`.
900 /// - password: the hash of the password ([`hash_password`](crate::hash_password)).
901 /// - a blank field that is not required: `null`.
902 ///
903 /// Each error in [`FieldErrors`] is keyed by the field's name, an owned `String`.
904 ///
905 /// A lookup, post object, relationship, taxonomy or user value is checked against
906 /// [`RuntimeData::options`] by the panel, which can read the database, and so is a media
907 /// id against the registered [`MediaLibrary`](crate::MediaLibrary).
908 pub fn validate(&self, form: &FormInput) -> Result<Row, FieldErrors> {
909 validate_fields(&self.resource.fields, form, true, &BTreeSet::new())
910 }
911
912 /// Turns the submitted form into a [`Row`] for an update. It is
913 /// [`validate`](Self::validate), except that:
914 ///
915 /// - a blank password is not an error: the row leaves its key out, so the stored
916 /// password is kept;
917 /// - an optional field the form did not send at all ([`FormInput::has`] is false) is left
918 /// out of the row, so its stored value is kept;
919 /// - an optional field sent blank is `null`, so clearing it on the edit form clears the
920 /// stored value, as `#[derive(IgniteResource)]` does since 0.3.0;
921 /// - a checkbox the form did not send is `false`, because an unticked HTML checkbox sends
922 /// nothing.
923 pub fn validate_update(&self, form: &FormInput) -> Result<Row, FieldErrors> {
924 validate_fields(&self.resource.fields, form, false, &BTreeSet::new())
925 }
926
927 /// The conditions that show or hide the form's fields.
928 pub fn conditions(&self) -> &FieldConditions {
929 &self.resource.conditions
930 }
931
932 /// The layout of the create and edit forms.
933 pub fn form_layout(&self) -> &FormLayout {
934 &self.resource.form_layout
935 }
936
937 /// The tabs of the list page, in display order.
938 pub fn tabs(&self) -> &[Tab] {
939 &self.resource.tabs
940 }
941
942 /// The key of the tab shown when the list has no `tab` parameter, if set.
943 pub fn default_active_tab(&self) -> Option<&str> {
944 self.resource.default_active_tab.as_deref()
945 }
946
947 /// The list columns shown as coloured badges.
948 pub fn column_badges(&self) -> &ColumnBadges {
949 &self.resource.column_badges
950 }
951
952 /// Whether each tab's count is for the current search.
953 pub fn tab_counts_follow_search(&self) -> bool {
954 self.resource.tab_counts_follow_search
955 }
956
957 /// Whether a tab whose count is 0 is left out.
958 pub fn hide_empty_tabs(&self) -> bool {
959 self.resource.hide_empty_tabs
960 }
961
962 /// [`validate`](Self::validate) for a form whose fields `hidden` are hidden (see
963 /// [`FieldConditions::hidden_fields`]): they are not checked, a required one included, and
964 /// the row has no key for them, so the source writes nothing for them. The panel calls it.
965 pub fn validate_shown(
966 &self,
967 form: &FormInput,
968 hidden: &BTreeSet<String>,
969 ) -> Result<Row, FieldErrors> {
970 validate_fields(&self.resource.fields, form, true, hidden)
971 }
972
973 /// [`validate_update`](Self::validate_update) for a form whose fields `hidden` are hidden:
974 /// the row has no key for them, so their stored values are kept, whatever the form sent.
975 pub fn validate_update_shown(
976 &self,
977 form: &FormInput,
978 hidden: &BTreeSet<String>,
979 ) -> Result<Row, FieldErrors> {
980 validate_fields(&self.resource.fields, form, false, hidden)
981 }
982}
983
984/// The registry: the runtime resources in registration order, and the slugs reserved for
985/// static resources and for the panel's own pages.
986#[derive(Default)]
987struct Registry {
988 resources: Vec<Arc<RegisteredResource>>,
989 reserved: HashSet<String>,
990}
991
992static REGISTRY: RwLock<Option<Registry>> = RwLock::new(None);
993
994/// Runs `f` on the registry, read-only. The lock is never held across an `.await`: every
995/// caller is synchronous.
996fn read<T>(f: impl FnOnce(&Registry) -> T) -> T {
997 let guard = REGISTRY.read().unwrap_or_else(PoisonError::into_inner);
998 match guard.as_ref() {
999 Some(registry) => f(registry),
1000 None => f(&Registry::default()),
1001 }
1002}
1003
1004/// Runs `f` on the registry, to change it.
1005fn write<T>(f: impl FnOnce(&mut Registry) -> T) -> T {
1006 let mut guard = REGISTRY.write().unwrap_or_else(PoisonError::into_inner);
1007 f(guard.get_or_insert_with(Registry::default))
1008}
1009
1010/// The longest field name a runtime resource accepts, in bytes, as for a MySQL or MariaDB
1011/// column name. The limit is a validation rule: names are owned by their resource and freed
1012/// with it.
1013pub const MAX_FIELD_NAME: usize = 64;
1014
1015/// Whether `name` is a field name a runtime resource accepts: lowercase ASCII letters, digits
1016/// and `_`, starting with a letter, at most [`MAX_FIELD_NAME`] bytes, as a column name is.
1017fn valid_field_name(name: &str) -> bool {
1018 name.len() <= MAX_FIELD_NAME
1019 && name.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
1020 && name
1021 .bytes()
1022 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
1023}
1024
1025/// Whether `slug` is one URL segment the panel's `/<slug>` routes match: lowercase ASCII
1026/// letters, digits, `-` and `_`, as Filament's kebab-case slugs are.
1027fn valid_slug(slug: &str) -> bool {
1028 !slug.is_empty()
1029 && slug
1030 .bytes()
1031 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1032}
1033
1034/// Adds a runtime resource to the panel. It shows in the navigation and the dashboard, and
1035/// its list, forms and delete action answer at `/<mount>/<slug>`, from the next request on.
1036/// Create its permissions (`<slug>.viewAny` and the others) in the same request with
1037/// `ignite_panel::register_runtime_permissions`; otherwise the panel creates them on the next
1038/// signed-in request.
1039///
1040/// Refuses a slug that is not valid, a slug that a static resource, another runtime resource
1041/// or one of the panel's own pages (such as `login`) uses, and two fields with one name.
1042pub fn register_runtime(resource: RuntimeResource) -> Result<(), RuntimeError> {
1043 if !valid_slug(&resource.slug) {
1044 return Err(RuntimeError::InvalidSlug(resource.slug));
1045 }
1046 if let Some(field) = resource.fields.iter().find(|f| !valid_field_name(&f.name)) {
1047 return Err(RuntimeError::InvalidFieldName {
1048 slug: resource.slug.clone(),
1049 field: field.name.clone(),
1050 });
1051 }
1052 let mut names = HashSet::new();
1053 if let Some(field) = resource.fields.iter().find(|f| !names.insert(&f.name)) {
1054 return Err(RuntimeError::DuplicateField {
1055 slug: resource.slug.clone(),
1056 field: field.name.clone(),
1057 });
1058 }
1059 write(|registry| {
1060 let slug = resource.slug.as_str();
1061 if registry.reserved.contains(slug) || registry.resources.iter().any(|r| r.slug() == slug) {
1062 return Err(RuntimeError::SlugTaken(resource.slug.clone()));
1063 }
1064 registry
1065 .resources
1066 .push(Arc::new(RegisteredResource { resource }));
1067 Ok(())
1068 })
1069}
1070
1071/// Removes the runtime resource at `slug`. From the next request on, it is gone from the
1072/// navigation and its routes answer 404. Its permission rows stay, so the grants come back
1073/// if the resource is registered again.
1074pub fn unregister_runtime(slug: &str) -> Result<(), RuntimeError> {
1075 write(|registry| {
1076 let before = registry.resources.len();
1077 registry.resources.retain(|r| r.slug() != slug);
1078 if registry.resources.len() == before {
1079 Err(RuntimeError::NotRegistered(slug.to_string()))
1080 } else {
1081 Ok(())
1082 }
1083 })
1084}
1085
1086/// The runtime resource at `slug`, if one is registered.
1087pub fn runtime_resource(slug: &str) -> Option<Arc<RegisteredResource>> {
1088 read(|registry| {
1089 registry
1090 .resources
1091 .iter()
1092 .find(|r| r.slug() == slug)
1093 .cloned()
1094 })
1095}
1096
1097/// Every runtime resource, in registration order.
1098pub fn runtime_resources() -> Vec<Arc<RegisteredResource>> {
1099 read(|registry| registry.resources.clone())
1100}
1101
1102/// Reserves `slugs`, so no runtime resource can take them. The panel reserves the slugs of
1103/// its static resources and of its own pages when it is built. Reserving a slug twice is
1104/// fine. Refuses, and reserves none, when a runtime resource already has one of them.
1105pub fn reserve_slugs(slugs: &[&str]) -> Result<(), RuntimeError> {
1106 write(|registry| {
1107 if let Some(slug) = slugs
1108 .iter()
1109 .find(|slug| registry.resources.iter().any(|r| r.slug() == **slug))
1110 {
1111 return Err(RuntimeError::SlugTaken(slug.to_string()));
1112 }
1113 registry
1114 .reserved
1115 .extend(slugs.iter().map(|slug| slug.to_string()));
1116 Ok(())
1117 })
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122 use super::*;
1123
1124 struct NoData;
1125
1126 impl RuntimeData for NoData {
1127 fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
1128 unreachable!()
1129 }
1130 fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
1131 unreachable!()
1132 }
1133 fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
1134 unreachable!()
1135 }
1136 fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
1137 unreachable!()
1138 }
1139 fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
1140 unreachable!()
1141 }
1142 }
1143
1144 /// A resource with the fields `growth_title` and `growth_status`, whose label and
1145 /// choices change with `n`.
1146 fn edited(slug: &str, n: usize) -> RuntimeResource {
1147 RuntimeResource::new(slug, format!("Title {n}"), format!("One {n}"), NoData)
1148 .field(FieldDef {
1149 name: "growth_title".into(),
1150 label: format!("Title {n}"),
1151 kind: FieldKindDef::Text,
1152 required: n.is_multiple_of(2),
1153 })
1154 .field(FieldDef {
1155 name: "growth_status".into(),
1156 label: format!("Status {n}"),
1157 kind: FieldKindDef::Select(vec![(format!("v{n}"), format!("Value {n}"))]),
1158 required: false,
1159 })
1160 .column(ColumnDef {
1161 key: "growth_title".into(),
1162 label: format!("Column {n}"),
1163 sortable: false,
1164 searchable: false,
1165 })
1166 }
1167
1168 // Field names are owned by their resource: editing a definition a thousand times keeps
1169 // nothing of the old ones, and an error is keyed by the field's own name.
1170 #[test]
1171 fn editing_a_definition_a_thousand_times_keeps_owned_names() {
1172 register_runtime(edited("growth", 0)).expect("register");
1173 for n in 1..=1000 {
1174 unregister_runtime("growth").expect("unregister");
1175 register_runtime(edited("growth", n)).expect("register again");
1176 let registered = runtime_resource("growth").expect("registered");
1177 let mut values = std::collections::HashMap::new();
1178 values.insert("growth_status".to_string(), "not a choice".to_string());
1179 let errors = registered
1180 .validate(&FormInput::new(values.clone()))
1181 .unwrap_err();
1182 assert!(errors.contains_key("growth_status"));
1183 let _ = registered.validate_update(&FormInput::new(values));
1184 }
1185 // The last registration is the only one the registry holds.
1186 let registered = runtime_resource("growth").expect("registered");
1187 assert_eq!(registered.title(), "Title 1000");
1188 assert_eq!(
1189 runtime_resources()
1190 .iter()
1191 .filter(|r| r.slug() == "growth")
1192 .count(),
1193 1
1194 );
1195 unregister_runtime("growth").expect("unregister");
1196 }
1197}