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