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