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}
130
131impl fmt::Debug for FieldConditions {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
134        f.debug_struct("FieldConditions")
135            .field("hidden", &names(&self.hidden))
136            .field("visible", &names(&self.visible))
137            .field("live", &self.live)
138            .field("slugs", &self.slugs)
139            .finish()
140    }
141}
142
143impl FieldConditions {
144    /// No conditions: every field shows, and none is live.
145    pub fn new() -> Self {
146        FieldConditions::default()
147    }
148
149    /// Shows `field` only when `rule` holds, as Filament's `->visible(fn () => ...)`.
150    pub fn visible(
151        mut self,
152        field: impl Into<String>,
153        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
154    ) -> Self {
155        self.visible.insert(field.into(), Arc::new(rule));
156        self
157    }
158
159    /// Hides `field` when `rule` holds, as Filament's `->hidden(fn () => ...)`.
160    pub fn hidden(
161        mut self,
162        field: impl Into<String>,
163        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
164    ) -> Self {
165        self.hidden.insert(field.into(), Arc::new(rule));
166        self
167    }
168
169    /// Shows `field` only on the forms of `operations`, as Filament's `->visibleOn('edit')`.
170    pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
171        let operations = operations.to_vec();
172        self.visible(field, move |form| operations.contains(&form.operation()))
173    }
174
175    /// Hides `field` on the forms of `operations`, as Filament's `->hiddenOn('edit')`.
176    pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
177        let operations = operations.to_vec();
178        self.hidden(field, move |form| operations.contains(&form.operation()))
179    }
180
181    /// Makes `field` live, as Filament's `->live()`: when its value changes in the browser,
182    /// the form's fields are shown again for the new value, so a field whose condition reads
183    /// it with [`FormContext::get`] appears or disappears. The browser sends the change when
184    /// the input fires `change`: at once for a select, a checkbox or a radio, and when a text
185    /// input loses focus.
186    pub fn live(mut self, field: impl Into<String>) -> Self {
187        self.live.insert(field.into());
188        self
189    }
190
191    /// Fills the field `field` with the slug of the field `source` as the user types, until the
192    /// user edits `field` by hand, as Filament's documented slug pattern:
193    /// `->afterStateUpdated(...)` on the title sets `slug` to `Str::slug($state)` unless the slug
194    /// no longer matches `Str::slug($old)`. Filament writes that with a closure on the server;
195    /// the panel's script does it in the browser, so it needs no round trip. The slug is the
196    /// text in lowercase ASCII, accents removed, with each run of other characters turned into
197    /// one `-`, as `Str::slug` gives it. The value is not checked: `validate` still checks it.
198    ///
199    /// On the edit form, a slug that is not the slug of the stored title counts as edited by
200    /// hand, so it is not replaced.
201    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
202        self.slugs.insert(field.into(), source.into());
203        self
204    }
205
206    /// The field `field` is filled from by [`slug_from`](Self::slug_from), if any.
207    pub fn slug_source(&self, field: &str) -> Option<&str> {
208        self.slugs.get(field).map(String::as_str)
209    }
210
211    /// Whether `field` is live.
212    pub fn is_live(&self, field: &str) -> bool {
213        self.live.contains(field)
214    }
215
216    /// Whether no field has a condition or is live.
217    pub fn is_empty(&self) -> bool {
218        self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
219    }
220
221    /// Whether `field` shows in `form`: its `hidden` condition, if any, fails and its
222    /// `visible` condition, if any, holds.
223    pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
224        let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
225        let visible = self.visible.get(field).is_none_or(|rule| rule(form));
226        !hidden && visible
227    }
228
229    /// The names of the `fields` that are hidden on the form for `operation`, editing
230    /// `record`, for `user`, whose fields hold `values`.
231    ///
232    /// A condition that reads a hidden field gets the field's stored value, not the one in
233    /// `values`, so a request cannot show a field by sending a value for a field it may not
234    /// see. The conditions run again until the hidden fields settle.
235    pub fn hidden_fields(
236        &self,
237        fields: &[FieldDef],
238        operation: Operation,
239        record: Option<&Row>,
240        user: &ActingUser,
241        values: &FormInput,
242    ) -> BTreeSet<String> {
243        let mut hidden = BTreeSet::new();
244        if self.hidden.is_empty() && self.visible.is_empty() {
245            return hidden;
246        }
247        for _ in 0..=fields.len() {
248            let state = stored_when_hidden(values, record, &hidden);
249            let form = FormContext::new(operation, record, user, &state);
250            let next: BTreeSet<String> = fields
251                .iter()
252                .filter(|field| !self.is_shown(&field.name, &form))
253                .map(|field| field.name.clone())
254                .collect();
255            if next == hidden {
256                break;
257            }
258            hidden = next;
259        }
260        hidden
261    }
262}
263
264/// `values`, with each field of `hidden` holding its stored value in `record` instead, or no
265/// value when there is none.
266fn stored_when_hidden(
267    values: &FormInput,
268    record: Option<&Row>,
269    hidden: &BTreeSet<String>,
270) -> FormInput {
271    let mut state = values.without(hidden.iter().map(String::as_str));
272    for name in hidden {
273        let stored = match record.and_then(|record| record.get(name)) {
274            None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
275            Some(Value::Bool(true)) => "on".to_string(),
276            Some(Value::String(text)) => text.clone(),
277            Some(other) => other.to_string(),
278        };
279        state.insert(name.clone(), stored);
280    }
281    state
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use crate::runtime_resource::FieldKindDef;
288
289    fn field(name: &str) -> FieldDef {
290        FieldDef {
291            name: name.into(),
292            label: name.into(),
293            kind: FieldKindDef::Text,
294            required: true,
295        }
296    }
297
298    fn form(pairs: &[(&str, &str)]) -> FormInput {
299        FormInput::new(
300            pairs
301                .iter()
302                .map(|(k, v)| (k.to_string(), v.to_string()))
303                .collect(),
304        )
305    }
306
307    fn user() -> ActingUser {
308        ActingUser::new(1, "Ada", "ada@example.test")
309    }
310
311    #[test]
312    fn a_field_with_no_condition_shows() {
313        let conditions = FieldConditions::new();
314        let user = user();
315        let values = form(&[]);
316        let context = FormContext::new(Operation::Create, None, &user, &values);
317        assert!(conditions.is_shown("title", &context));
318        assert!(conditions.is_empty());
319    }
320
321    #[test]
322    fn hidden_on_and_visible_on_follow_the_operation() {
323        let conditions = FieldConditions::new()
324            .hidden_on("slug", &[Operation::Create])
325            .visible_on("published_at", &[Operation::Edit]);
326        let fields = [field("slug"), field("published_at"), field("title")];
327        let user = user();
328        let values = form(&[]);
329        let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
330        assert_eq!(
331            on_create,
332            BTreeSet::from(["published_at".into(), "slug".into()])
333        );
334        let record = Row::new();
335        let on_edit =
336            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
337        assert!(on_edit.is_empty());
338    }
339
340    #[test]
341    fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
342        let conditions = FieldConditions::new()
343            .hidden("note", |_| true)
344            .hidden_on("note", &[Operation::Create])
345            .visible("note", |form| form.user().can("notes.edit"));
346        let user = user();
347        let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
348        let values = form(&[]);
349        let record = Row::new();
350        let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
351        assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
352        assert!(conditions.is_shown("note", &edit(&editor)));
353        let create = FormContext::new(Operation::Create, None, &editor, &values);
354        assert!(!conditions.is_shown("note", &create), "hidden on create");
355    }
356
357    #[test]
358    fn a_condition_reads_the_record_and_the_current_values() {
359        let conditions = FieldConditions::new()
360            .live("kind")
361            .visible("company", |form| form.get("kind") == Some("business"))
362            .visible("archived_note", |form| {
363                form.record()
364                    .and_then(|record| record.get("status"))
365                    .and_then(Value::as_str)
366                    == Some("archived")
367            });
368        assert!(conditions.is_live("kind"));
369        assert!(!conditions.is_live("company"));
370        let fields = [field("kind"), field("company"), field("archived_note")];
371        let user = user();
372        let mut record = Row::new();
373        record.insert("status".into(), Value::from("archived"));
374        let hidden = conditions.hidden_fields(
375            &fields,
376            Operation::Edit,
377            Some(&record),
378            &user,
379            &form(&[("kind", "business")]),
380        );
381        assert!(hidden.is_empty(), "{hidden:?}");
382        let hidden = conditions.hidden_fields(
383            &fields,
384            Operation::Create,
385            None,
386            &user,
387            &form(&[("kind", "person")]),
388        );
389        assert_eq!(
390            hidden,
391            BTreeSet::from(["archived_note".into(), "company".into()])
392        );
393    }
394
395    // `secret` is hidden from this user, and `extra` shows when `secret` is "yes". A request
396    // that sends `secret=yes` must not show `extra`: the condition reads the stored value.
397    #[test]
398    fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
399        let conditions = FieldConditions::new()
400            .visible("secret", |form| form.user().can("secret.edit"))
401            .visible("extra", |form| form.get("secret") == Some("yes"));
402        let fields = [field("secret"), field("extra")];
403        let user = user();
404        let sent = form(&[("secret", "yes"), ("extra", "changed")]);
405
406        let mut record = Row::new();
407        record.insert("secret".into(), Value::from("no"));
408        let hidden =
409            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
410        assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
411
412        record.insert("secret".into(), Value::from("yes"));
413        let hidden =
414            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
415        assert_eq!(hidden, BTreeSet::from(["secret".into()]));
416    }
417}