Skip to main content

ignite_core/
condition.rs

1//! Fields that show only when a condition holds, as Filament's `visible()`, `hidden()`,
2//! `visibleOn()`, `hiddenOn()` and `live()`, and fields shown but not editable, as its
3//! `disabled()` and `disabledOn()`.
4//!
5//! A condition is a closure the server runs each time it builds or saves a form, given a
6//! [`FormContext`]: the operation, the record being edited (none on create), the signed-in
7//! user and the form's current values, as a Filament closure is given `$operation`, `$record`,
8//! `auth()->user()` and `$get`. A field whose condition fails is hidden: the panel does not
9//! render it, does not check it, and does not save it, so a request that sends it anyway
10//! cannot change the stored value.
11//!
12//! A field marked [`live`](FieldConditions::live) re-renders the form when its value changes in
13//! the browser: the panel's script sends the form to the server, which runs the conditions on
14//! the new values and returns the fields to show.
15//!
16//! ```ignore
17//! RuntimeResource::new("posts", "Posts", "Post", PostData)
18//!     .field(kind_field)
19//!     .field(company_field)
20//!     .live("kind")
21//!     .visible("company", |form| form.get("kind") == Some("business"))
22//!     .hidden_on("slug", &[Operation::Create])
23//!     .visible("featured", |form| form.user().can("posts.feature"));
24//! ```
25
26use std::collections::{BTreeSet, HashMap};
27use std::fmt;
28use std::sync::Arc;
29
30use serde_json::Value;
31
32use crate::form::FormInput;
33use crate::policy::ActingUser;
34use crate::runtime_resource::{FieldDef, Row};
35
36/// What the form is for, as Filament's `$operation`.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Operation {
39    /// The new-record form and its save.
40    Create,
41    /// The edit form of a record and its save.
42    Edit,
43}
44
45impl Operation {
46    /// The operation's name as Filament spells it: `"create"` or `"edit"`.
47    pub fn as_str(self) -> &'static str {
48        match self {
49            Operation::Create => "create",
50            Operation::Edit => "edit",
51        }
52    }
53}
54
55/// What a condition is given: the operation, the record, the signed-in user and the form's
56/// current values.
57#[derive(Debug, Clone, Copy)]
58pub struct FormContext<'a> {
59    operation: Operation,
60    record: Option<&'a Row>,
61    user: &'a ActingUser,
62    values: &'a FormInput,
63}
64
65impl<'a> FormContext<'a> {
66    /// The context of a form for `operation`, editing `record` (none on create), for `user`,
67    /// whose fields hold `values`. The panel builds it; an app builds one to test a condition.
68    pub fn new(
69        operation: Operation,
70        record: Option<&'a Row>,
71        user: &'a ActingUser,
72        values: &'a FormInput,
73    ) -> Self {
74        FormContext {
75            operation,
76            record,
77            user,
78            values,
79        }
80    }
81
82    /// Whether the form creates a record or edits one, as Filament's `$operation`.
83    pub fn operation(&self) -> Operation {
84        self.operation
85    }
86
87    /// The record being edited, as stored, as Filament's `$record`: a runtime resource's
88    /// [`Row`], or a static resource's record serialized to JSON. `None` on create.
89    pub fn record(&self) -> Option<&'a Row> {
90        self.record
91    }
92
93    /// The signed-in user, as `auth()->user()` in a Filament closure.
94    pub fn user(&self) -> &'a ActingUser {
95        self.user
96    }
97
98    /// The current value of the field `name`, as Filament's `$get('name')`: the value the
99    /// user has typed or chosen, or `None` when it is blank. When the form is first shown it
100    /// is the stored value. A field that is itself hidden gives its stored value, never one a
101    /// request sent for it. The value is not checked.
102    pub fn get(&self, name: &str) -> Option<&'a str> {
103        self.values.get(name)
104    }
105
106    /// Whether the checkbox `name` is ticked. See [`FormInput::checkbox`].
107    pub fn checked(&self, name: &str) -> bool {
108        self.values.checkbox(name)
109    }
110}
111
112/// A condition on a field.
113type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
114
115/// The conditions of a form's fields, by field name, and the fields that are live. Each
116/// method takes the field's name and returns the conditions, so they chain.
117///
118/// As in Filament, a field has one `hidden` condition and one `visible` condition, and shows
119/// only when its `hidden` condition fails and its `visible` condition holds. A later
120/// [`hidden`](Self::hidden) or [`hidden_on`](Self::hidden_on) for the same field replaces the
121/// earlier one, and so does a later [`visible`](Self::visible) or
122/// [`visible_on`](Self::visible_on). A field with no condition always shows.
123#[derive(Clone, Default)]
124pub struct FieldConditions {
125    hidden: HashMap<String, Rule>,
126    visible: HashMap<String, Rule>,
127    live: BTreeSet<String>,
128    /// The field each slug field is filled from, by slug field name.
129    slugs: HashMap<String, String>,
130    /// When each slug field stops following its source, by slug field name.
131    slug_locks: HashMap<String, Rule>,
132    /// When each field is shown but not editable, by field name.
133    disabled: HashMap<String, Rule>,
134}
135
136impl fmt::Debug for FieldConditions {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
139        f.debug_struct("FieldConditions")
140            .field("hidden", &names(&self.hidden))
141            .field("visible", &names(&self.visible))
142            .field("live", &self.live)
143            .field("slugs", &self.slugs)
144            .field("slug_locks", &names(&self.slug_locks))
145            .field("disabled", &names(&self.disabled))
146            .finish()
147    }
148}
149
150impl FieldConditions {
151    /// No conditions: every field shows, and none is live.
152    pub fn new() -> Self {
153        FieldConditions::default()
154    }
155
156    /// Shows `field` only when `rule` holds, as Filament's `->visible(fn () => ...)`.
157    pub fn visible(
158        mut self,
159        field: impl Into<String>,
160        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
161    ) -> Self {
162        self.visible.insert(field.into(), Arc::new(rule));
163        self
164    }
165
166    /// Hides `field` when `rule` holds, as Filament's `->hidden(fn () => ...)`.
167    pub fn hidden(
168        mut self,
169        field: impl Into<String>,
170        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
171    ) -> Self {
172        self.hidden.insert(field.into(), Arc::new(rule));
173        self
174    }
175
176    /// Shows `field` only on the forms of `operations`, as Filament's `->visibleOn('edit')`.
177    pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
178        let operations = operations.to_vec();
179        self.visible(field, move |form| operations.contains(&form.operation()))
180    }
181
182    /// Hides `field` on the forms of `operations`, as Filament's `->hiddenOn('edit')`.
183    pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
184        let operations = operations.to_vec();
185        self.hidden(field, move |form| operations.contains(&form.operation()))
186    }
187
188    /// Shows `field` but does not let the user change it when `rule` holds, as Filament's
189    /// `->disabled(fn () => ...)`: its input is disabled and, as in Filament, a disabled field
190    /// is not saved, so its stored value is kept whatever a request sends. A later
191    /// [`disabled`](Self::disabled) or [`disabled_on`](Self::disabled_on) for the field
192    /// replaces the earlier one.
193    pub fn disabled(
194        mut self,
195        field: impl Into<String>,
196        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
197    ) -> Self {
198        self.disabled.insert(field.into(), Arc::new(rule));
199        self
200    }
201
202    /// Disables `field` on the forms of `operations`, as Filament's `->disabledOn('edit')`:
203    /// such as a key that is set when the record is created and locked after its first save.
204    pub fn disabled_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
205        let operations = operations.to_vec();
206        self.disabled(field, move |form| operations.contains(&form.operation()))
207    }
208
209    /// Whether `field` is disabled on `form`.
210    pub fn is_disabled(&self, field: &str, form: &FormContext<'_>) -> bool {
211        self.disabled.get(field).is_some_and(|rule| rule(form))
212    }
213
214    /// Makes `field` live, as Filament's `->live()`: when its value changes in the browser,
215    /// the form's fields are shown again for the new value, so a field whose condition reads
216    /// it with [`FormContext::get`] appears or disappears. The browser sends the change when
217    /// the input fires `change`: at once for a select, a checkbox or a radio, and when a text
218    /// input loses focus.
219    pub fn live(mut self, field: impl Into<String>) -> Self {
220        self.live.insert(field.into());
221        self
222    }
223
224    /// Fills the field `field` with the slug of the field `source` as the user types, until the
225    /// user edits `field` by hand, as Filament's documented slug pattern:
226    /// `->afterStateUpdated(...)` on the title sets `slug` to `Str::slug($state)` unless the slug
227    /// no longer matches `Str::slug($old)`. Filament writes that with a closure on the server;
228    /// the panel's script does it in the browser, so it needs no round trip. The slug is the
229    /// text in lowercase ASCII, accents removed, with each run of other characters turned into
230    /// one `-`, as `Str::slug` gives it. The value is not checked: `validate` still checks it.
231    ///
232    /// On the edit form, a slug that is not the slug of the stored title counts as edited by
233    /// hand, so it is not replaced. [`slug_locked_when`](Self::slug_locked_when) stops it from
234    /// following the title at all, such as once the record is published.
235    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
236        self.slugs.insert(field.into(), source.into());
237        self
238    }
239
240    /// Stops the slug field `field` from following its source on the edit form of a record
241    /// whose stored slug is not blank, when `rule` holds, such as when the stored record is
242    /// published: the slug of a published post's URL then stays as it is when the title
243    /// changes. On the create form, and while `rule` fails (such as for a draft), the slug
244    /// follows the title as [`slug_from`](Self::slug_from) says. The user can still edit the
245    /// slug by hand. The input is marked `data-ignite-slug-locked`, which the panel's script
246    /// reads.
247    ///
248    /// Filament's slug example has no such rule: it stops when the user has edited the slug.
249    /// Ignite keeps that, and adds this one.
250    ///
251    /// ```ignore
252    /// conditions
253    ///     .slug_from("slug", "title")
254    ///     .slug_locked_when("slug", |form| {
255    ///         form.record().and_then(|r| r.get("status")).and_then(|s| s.as_str()) == Some("publish")
256    ///     })
257    /// ```
258    pub fn slug_locked_when(
259        mut self,
260        field: impl Into<String>,
261        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
262    ) -> Self {
263        self.slug_locks.insert(field.into(), Arc::new(rule));
264        self
265    }
266
267    /// Whether the slug field `field` no longer follows its source on `form`: the form edits a
268    /// record whose stored `field` is not blank, and the rule of
269    /// [`slug_locked_when`](Self::slug_locked_when) holds.
270    pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
271        let Some(rule) = self.slug_locks.get(field) else {
272            return false;
273        };
274        let stored = form
275            .record()
276            .and_then(|record| record.get(field))
277            .is_some_and(|value| match value {
278                Value::Null => false,
279                Value::String(text) => !text.trim().is_empty(),
280                _ => true,
281            });
282        form.operation() == Operation::Edit && stored && rule(form)
283    }
284
285    /// The field `field` is filled from by [`slug_from`](Self::slug_from), if any.
286    pub fn slug_source(&self, field: &str) -> Option<&str> {
287        self.slugs.get(field).map(String::as_str)
288    }
289
290    /// Whether `field` is live.
291    pub fn is_live(&self, field: &str) -> bool {
292        self.live.contains(field)
293    }
294
295    /// Whether no field has a condition or is live.
296    pub fn is_empty(&self) -> bool {
297        self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
298    }
299
300    /// Whether `field` shows in `form`: its `hidden` condition, if any, fails and its
301    /// `visible` condition, if any, holds.
302    pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
303        let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
304        let visible = self.visible.get(field).is_none_or(|rule| rule(form));
305        !hidden && visible
306    }
307
308    /// The names of the `fields` that are hidden on the form for `operation`, editing
309    /// `record`, for `user`, whose fields hold `values`.
310    ///
311    /// A condition that reads a hidden field gets the field's stored value, not the one in
312    /// `values`, so a request cannot show a field by sending a value for a field it may not
313    /// see. The conditions run again until the hidden fields settle.
314    pub fn hidden_fields(
315        &self,
316        fields: &[FieldDef],
317        operation: Operation,
318        record: Option<&Row>,
319        user: &ActingUser,
320        values: &FormInput,
321    ) -> BTreeSet<String> {
322        let mut hidden = BTreeSet::new();
323        if self.hidden.is_empty() && self.visible.is_empty() {
324            return hidden;
325        }
326        for _ in 0..=fields.len() {
327            let state = stored_when_hidden(values, record, &hidden);
328            let form = FormContext::new(operation, record, user, &state);
329            let next: BTreeSet<String> = fields
330                .iter()
331                .filter(|field| !self.is_shown(&field.name, &form))
332                .map(|field| field.name.clone())
333                .collect();
334            if next == hidden {
335                break;
336            }
337            hidden = next;
338        }
339        hidden
340    }
341}
342
343/// `values`, with each field of `hidden` holding its stored value in `record` instead, or no
344/// value when there is none.
345fn stored_when_hidden(
346    values: &FormInput,
347    record: Option<&Row>,
348    hidden: &BTreeSet<String>,
349) -> FormInput {
350    let mut state = values.without(hidden.iter().map(String::as_str));
351    for name in hidden {
352        let stored = match record.and_then(|record| record.get(name)) {
353            None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
354            Some(Value::Bool(true)) => "on".to_string(),
355            Some(Value::String(text)) => text.clone(),
356            Some(other) => other.to_string(),
357        };
358        state.insert(name.clone(), stored);
359    }
360    state
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use crate::runtime_resource::FieldKindDef;
367
368    fn field(name: &str) -> FieldDef {
369        FieldDef {
370            name: name.into(),
371            label: name.into(),
372            kind: FieldKindDef::Text,
373            required: true,
374        }
375    }
376
377    fn form(pairs: &[(&str, &str)]) -> FormInput {
378        FormInput::new(
379            pairs
380                .iter()
381                .map(|(k, v)| (k.to_string(), v.to_string()))
382                .collect(),
383        )
384    }
385
386    fn user() -> ActingUser {
387        ActingUser::new(1, "Ada", "ada@example.test")
388    }
389
390    #[test]
391    fn a_field_with_no_condition_shows() {
392        let conditions = FieldConditions::new();
393        let user = user();
394        let values = form(&[]);
395        let context = FormContext::new(Operation::Create, None, &user, &values);
396        assert!(conditions.is_shown("title", &context));
397        assert!(conditions.is_empty());
398    }
399
400    #[test]
401    fn hidden_on_and_visible_on_follow_the_operation() {
402        let conditions = FieldConditions::new()
403            .hidden_on("slug", &[Operation::Create])
404            .visible_on("published_at", &[Operation::Edit]);
405        let fields = [field("slug"), field("published_at"), field("title")];
406        let user = user();
407        let values = form(&[]);
408        let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
409        assert_eq!(
410            on_create,
411            BTreeSet::from(["published_at".into(), "slug".into()])
412        );
413        let record = Row::new();
414        let on_edit =
415            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
416        assert!(on_edit.is_empty());
417    }
418
419    #[test]
420    fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
421        let conditions = FieldConditions::new()
422            .hidden("note", |_| true)
423            .hidden_on("note", &[Operation::Create])
424            .visible("note", |form| form.user().can("notes.edit"));
425        let user = user();
426        let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
427        let values = form(&[]);
428        let record = Row::new();
429        let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
430        assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
431        assert!(conditions.is_shown("note", &edit(&editor)));
432        let create = FormContext::new(Operation::Create, None, &editor, &values);
433        assert!(!conditions.is_shown("note", &create), "hidden on create");
434    }
435
436    #[test]
437    fn a_condition_reads_the_record_and_the_current_values() {
438        let conditions = FieldConditions::new()
439            .live("kind")
440            .visible("company", |form| form.get("kind") == Some("business"))
441            .visible("archived_note", |form| {
442                form.record()
443                    .and_then(|record| record.get("status"))
444                    .and_then(Value::as_str)
445                    == Some("archived")
446            });
447        assert!(conditions.is_live("kind"));
448        assert!(!conditions.is_live("company"));
449        let fields = [field("kind"), field("company"), field("archived_note")];
450        let user = user();
451        let mut record = Row::new();
452        record.insert("status".into(), Value::from("archived"));
453        let hidden = conditions.hidden_fields(
454            &fields,
455            Operation::Edit,
456            Some(&record),
457            &user,
458            &form(&[("kind", "business")]),
459        );
460        assert!(hidden.is_empty(), "{hidden:?}");
461        let hidden = conditions.hidden_fields(
462            &fields,
463            Operation::Create,
464            None,
465            &user,
466            &form(&[("kind", "person")]),
467        );
468        assert_eq!(
469            hidden,
470            BTreeSet::from(["archived_note".into(), "company".into()])
471        );
472    }
473
474    // `secret` is hidden from this user, and `extra` shows when `secret` is "yes". A request
475    // that sends `secret=yes` must not show `extra`: the condition reads the stored value.
476    #[test]
477    fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
478        let conditions = FieldConditions::new()
479            .visible("secret", |form| form.user().can("secret.edit"))
480            .visible("extra", |form| form.get("secret") == Some("yes"));
481        let fields = [field("secret"), field("extra")];
482        let user = user();
483        let sent = form(&[("secret", "yes"), ("extra", "changed")]);
484
485        let mut record = Row::new();
486        record.insert("secret".into(), Value::from("no"));
487        let hidden =
488            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
489        assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
490
491        record.insert("secret".into(), Value::from("yes"));
492        let hidden =
493            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
494        assert_eq!(hidden, BTreeSet::from(["secret".into()]));
495    }
496}