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//! A condition on a sub-field of a repeater, group or flexible content field is keyed by the
17//! sub-field's path without row numbers, such as `"fields.choices"` for the sub-field `choices`
18//! of each row of the repeater `fields` (a flexible content block's sub-field adds the block's
19//! name: `"content.hero.style"`). It runs once per row, and its [`FormContext::get`] reads the
20//! row's own values, as Filament's `$get` is scoped to the repeater item; `get("../../name")`
21//! reads the field `name` around the repeater, as Filament's `$get('../../name')`. A sub-field
22//! that is hidden in its row is not rendered, not checked and not saved.
23//!
24//! A field can also have a default value on the create form, as Filament's `default()`: see
25//! [`FieldConditions::default_value`].
26//!
27//! ```ignore
28//! RuntimeResource::new("posts", "Posts", "Post", PostData)
29//!     .field(kind_field)
30//!     .field(company_field)
31//!     .live("kind")
32//!     .visible("company", |form| form.get("kind") == Some("business"))
33//!     .hidden_on("slug", &[Operation::Create])
34//!     .visible("featured", |form| form.user().can("posts.feature"));
35//! ```
36
37use std::collections::{BTreeSet, HashMap};
38use std::fmt;
39use std::sync::Arc;
40
41use serde_json::Value;
42
43use crate::form::FormInput;
44use crate::policy::ActingUser;
45use crate::runtime_resource::{FieldDef, Row};
46
47/// What the form is for, as Filament's `$operation`.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub enum Operation {
50    /// The new-record form and its save.
51    Create,
52    /// The edit form of a record and its save.
53    Edit,
54}
55
56impl Operation {
57    /// The operation's name as Filament spells it: `"create"` or `"edit"`.
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Operation::Create => "create",
61            Operation::Edit => "edit",
62        }
63    }
64}
65
66/// What a condition is given: the operation, the record, the signed-in user and the form's
67/// current values.
68#[derive(Debug, Clone, Copy)]
69pub struct FormContext<'a> {
70    operation: Operation,
71    record: Option<&'a Row>,
72    user: &'a ActingUser,
73    values: &'a FormInput,
74    /// The context around a repeater row or group whose sub-fields this context is for.
75    parent: Option<&'a FormContext<'a>>,
76}
77
78impl<'a> FormContext<'a> {
79    /// The context of a form for `operation`, editing `record` (none on create), for `user`,
80    /// whose fields hold `values`. The panel builds it; an app builds one to test a condition.
81    pub fn new(
82        operation: Operation,
83        record: Option<&'a Row>,
84        user: &'a ActingUser,
85        values: &'a FormInput,
86    ) -> Self {
87        FormContext {
88            operation,
89            record,
90            user,
91            values,
92            parent: None,
93        }
94    }
95
96    /// The context of the sub-fields of a repeater row, a flexible content block or a group,
97    /// whose values are `values`, inside the context `parent`: the operation, the record and the
98    /// user are `parent`'s, and [`get`](Self::get) reads `values`, as Filament's `$get` is
99    /// scoped to the repeater item. `get("../../name")` reads `name` in `parent`.
100    pub fn row(parent: &'a FormContext<'a>, values: &'a FormInput) -> Self {
101        FormContext {
102            operation: parent.operation,
103            record: parent.record,
104            user: parent.user,
105            values,
106            parent: Some(parent),
107        }
108    }
109
110    /// Whether the form creates a record or edits one, as Filament's `$operation`.
111    pub fn operation(&self) -> Operation {
112        self.operation
113    }
114
115    /// The record being edited, as stored, as Filament's `$record`: a runtime resource's
116    /// [`Row`], or a static resource's record serialized to JSON. `None` on create.
117    pub fn record(&self) -> Option<&'a Row> {
118        self.record
119    }
120
121    /// The signed-in user, as `auth()->user()` in a Filament closure.
122    pub fn user(&self) -> &'a ActingUser {
123        self.user
124    }
125
126    /// The current value of the field `name`, as Filament's `$get('name')`: the value the
127    /// user has typed or chosen, or `None` when it is blank. When the form is first shown it
128    /// is the stored value. A field that is itself hidden gives its stored value, never one a
129    /// request sent for it. The value is not checked.
130    ///
131    /// In the context of a repeater row (see [`row`](Self::row)), `name` is a sibling in the
132    /// row, and a sibling hidden in its row reads as blank; `"../../name"` reads `name` around
133    /// the repeater, as Filament's `$get('../../name')`. A structured field's value is its JSON
134    /// text.
135    pub fn get(&self, name: &str) -> Option<&'a str> {
136        match (name.strip_prefix("../../"), self.parent) {
137            (Some(outer), Some(parent)) => parent.get(outer),
138            _ => self.values.get(name),
139        }
140    }
141
142    /// Whether the checkbox `name` is ticked. See [`FormInput::checkbox`]. `"../../name"`
143    /// reads around a repeater row, as [`get`](Self::get) does.
144    pub fn checked(&self, name: &str) -> bool {
145        match (name.strip_prefix("../../"), self.parent) {
146            (Some(outer), Some(parent)) => parent.checked(outer),
147            _ => self.values.checkbox(name),
148        }
149    }
150}
151
152/// A condition on a field.
153type Rule = Arc<dyn Fn(&FormContext<'_>) -> bool + Send + Sync>;
154
155/// A field's default value on the create form, from the form's state.
156type DefaultRule = Arc<dyn Fn(&FormContext<'_>) -> Value + Send + Sync>;
157
158/// The conditions of a form's fields, by field name, and the fields that are live. Each
159/// method takes the field's name and returns the conditions, so they chain.
160///
161/// As in Filament, a field has one `hidden` condition and one `visible` condition, and shows
162/// only when its `hidden` condition fails and its `visible` condition holds. A later
163/// [`hidden`](Self::hidden) or [`hidden_on`](Self::hidden_on) for the same field replaces the
164/// earlier one, and so does a later [`visible`](Self::visible) or
165/// [`visible_on`](Self::visible_on). A field with no condition always shows.
166#[derive(Clone, Default)]
167pub struct FieldConditions {
168    hidden: HashMap<String, Rule>,
169    visible: HashMap<String, Rule>,
170    live: BTreeSet<String>,
171    /// The field each slug field is filled from, by slug field name.
172    slugs: HashMap<String, String>,
173    /// When each slug field stops following its source, by slug field name.
174    slug_locks: HashMap<String, Rule>,
175    /// When each field is shown but not editable, by field name.
176    disabled: HashMap<String, Rule>,
177    /// The default value of each field on the create form, by field name.
178    defaults: HashMap<String, DefaultRule>,
179}
180
181impl fmt::Debug for FieldConditions {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        let names = |rules: &HashMap<String, Rule>| rules.keys().cloned().collect::<BTreeSet<_>>();
184        f.debug_struct("FieldConditions")
185            .field("hidden", &names(&self.hidden))
186            .field("visible", &names(&self.visible))
187            .field("live", &self.live)
188            .field("slugs", &self.slugs)
189            .field("slug_locks", &names(&self.slug_locks))
190            .field("disabled", &names(&self.disabled))
191            .field(
192                "defaults",
193                &self.defaults.keys().cloned().collect::<BTreeSet<_>>(),
194            )
195            .finish()
196    }
197}
198
199impl FieldConditions {
200    /// No conditions: every field shows, and none is live.
201    pub fn new() -> Self {
202        FieldConditions::default()
203    }
204
205    /// Shows `field` only when `rule` holds, as Filament's `->visible(fn () => ...)`.
206    pub fn visible(
207        mut self,
208        field: impl Into<String>,
209        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
210    ) -> Self {
211        self.visible.insert(field.into(), Arc::new(rule));
212        self
213    }
214
215    /// Hides `field` when `rule` holds, as Filament's `->hidden(fn () => ...)`.
216    pub fn hidden(
217        mut self,
218        field: impl Into<String>,
219        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
220    ) -> Self {
221        self.hidden.insert(field.into(), Arc::new(rule));
222        self
223    }
224
225    /// Shows `field` only on the forms of `operations`, as Filament's `->visibleOn('edit')`.
226    pub fn visible_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
227        let operations = operations.to_vec();
228        self.visible(field, move |form| operations.contains(&form.operation()))
229    }
230
231    /// Hides `field` on the forms of `operations`, as Filament's `->hiddenOn('edit')`.
232    pub fn hidden_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
233        let operations = operations.to_vec();
234        self.hidden(field, move |form| operations.contains(&form.operation()))
235    }
236
237    /// Shows `field` but does not let the user change it when `rule` holds, as Filament's
238    /// `->disabled(fn () => ...)`: its input is disabled and, as in Filament, a disabled field
239    /// is not saved, so its stored value is kept whatever a request sends. A later
240    /// [`disabled`](Self::disabled) or [`disabled_on`](Self::disabled_on) for the field
241    /// replaces the earlier one.
242    pub fn disabled(
243        mut self,
244        field: impl Into<String>,
245        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
246    ) -> Self {
247        self.disabled.insert(field.into(), Arc::new(rule));
248        self
249    }
250
251    /// Disables `field` on the forms of `operations`, as Filament's `->disabledOn('edit')`:
252    /// such as a key that is set when the record is created and locked after its first save.
253    pub fn disabled_on(self, field: impl Into<String>, operations: &[Operation]) -> Self {
254        let operations = operations.to_vec();
255        self.disabled(field, move |form| operations.contains(&form.operation()))
256    }
257
258    /// Whether `field` is disabled on `form`.
259    pub fn is_disabled(&self, field: &str, form: &FormContext<'_>) -> bool {
260        self.disabled.get(field).is_some_and(|rule| rule(form))
261    }
262
263    /// Makes `field` live, as Filament's `->live()`: when its value changes in the browser,
264    /// the form's fields are shown again for the new value, so a field whose condition reads
265    /// it with [`FormContext::get`] appears or disappears. The browser sends the change when
266    /// the input fires `change`: at once for a select, a checkbox or a radio, and when a text
267    /// input loses focus.
268    pub fn live(mut self, field: impl Into<String>) -> Self {
269        self.live.insert(field.into());
270        self
271    }
272
273    /// Fills the field `field` with the slug of the field `source` as the user types, until the
274    /// user edits `field` by hand, as Filament's documented slug pattern:
275    /// `->afterStateUpdated(...)` on the title sets `slug` to `Str::slug($state)` unless the slug
276    /// no longer matches `Str::slug($old)`. Filament writes that with a closure on the server;
277    /// the panel's script does it in the browser, so it needs no round trip. The slug is the
278    /// text in lowercase ASCII, accents removed, with each run of other characters turned into
279    /// one `-`, as `Str::slug` gives it. The value is not checked: `validate` still checks it.
280    ///
281    /// On the edit form, a slug that is not the slug of the stored title counts as edited by
282    /// hand, so it is not replaced. [`slug_locked_when`](Self::slug_locked_when) stops it from
283    /// following the title at all, such as once the record is published.
284    pub fn slug_from(mut self, field: impl Into<String>, source: impl Into<String>) -> Self {
285        self.slugs.insert(field.into(), source.into());
286        self
287    }
288
289    /// Stops the slug field `field` from following its source on the edit form of a record
290    /// whose stored slug is not blank, when `rule` holds, such as when the stored record is
291    /// published: the slug of a published post's URL then stays as it is when the title
292    /// changes. On the create form, and while `rule` fails (such as for a draft), the slug
293    /// follows the title as [`slug_from`](Self::slug_from) says. The user can still edit the
294    /// slug by hand. The input is marked `data-ignite-slug-locked`, which the panel's script
295    /// reads.
296    ///
297    /// Filament's slug example has no such rule: it stops when the user has edited the slug.
298    /// Ignite keeps that, and adds this one.
299    ///
300    /// ```ignore
301    /// conditions
302    ///     .slug_from("slug", "title")
303    ///     .slug_locked_when("slug", |form| {
304    ///         form.record().and_then(|r| r.get("status")).and_then(|s| s.as_str()) == Some("publish")
305    ///     })
306    /// ```
307    pub fn slug_locked_when(
308        mut self,
309        field: impl Into<String>,
310        rule: impl Fn(&FormContext<'_>) -> bool + Send + Sync + 'static,
311    ) -> Self {
312        self.slug_locks.insert(field.into(), Arc::new(rule));
313        self
314    }
315
316    /// Whether the slug field `field` no longer follows its source on `form`: the form edits a
317    /// record whose stored `field` is not blank, and the rule of
318    /// [`slug_locked_when`](Self::slug_locked_when) holds.
319    pub fn is_slug_locked(&self, field: &str, form: &FormContext<'_>) -> bool {
320        let Some(rule) = self.slug_locks.get(field) else {
321            return false;
322        };
323        let stored = form
324            .record()
325            .and_then(|record| record.get(field))
326            .is_some_and(|value| match value {
327                Value::Null => false,
328                Value::String(text) => !text.trim().is_empty(),
329                _ => true,
330            });
331        form.operation() == Operation::Edit && stored && rule(form)
332    }
333
334    /// The field `field` is filled from by [`slug_from`](Self::slug_from), if any.
335    pub fn slug_source(&self, field: &str) -> Option<&str> {
336        self.slugs.get(field).map(String::as_str)
337    }
338
339    /// Whether `field` is live.
340    pub fn is_live(&self, field: &str) -> bool {
341        self.live.contains(field)
342    }
343
344    /// Whether no field has a condition or is live.
345    pub fn is_empty(&self) -> bool {
346        self.hidden.is_empty() && self.visible.is_empty() && self.live.is_empty()
347    }
348
349    /// Whether `field` shows in `form`: its `hidden` condition, if any, fails and its
350    /// `visible` condition, if any, holds.
351    pub fn is_shown(&self, field: &str, form: &FormContext<'_>) -> bool {
352        let hidden = self.hidden.get(field).is_some_and(|rule| rule(form));
353        let visible = self.visible.get(field).is_none_or(|rule| rule(form));
354        !hidden && visible
355    }
356
357    /// The names of the `fields` that are hidden on the form for `operation`, editing
358    /// `record`, for `user`, whose fields hold `values`.
359    ///
360    /// A condition that reads a hidden field gets the field's stored value, not the one in
361    /// `values`, so a request cannot show a field by sending a value for a field it may not
362    /// see. The conditions run again until the hidden fields settle.
363    pub fn hidden_fields(
364        &self,
365        fields: &[FieldDef],
366        operation: Operation,
367        record: Option<&Row>,
368        user: &ActingUser,
369        values: &FormInput,
370    ) -> BTreeSet<String> {
371        let mut hidden = BTreeSet::new();
372        if self.hidden.is_empty() && self.visible.is_empty() {
373            return hidden;
374        }
375        for _ in 0..=fields.len() {
376            let state = stored_when_hidden(values, record, &hidden);
377            let form = FormContext::new(operation, record, user, &state);
378            let next: BTreeSet<String> = fields
379                .iter()
380                .filter(|field| !self.is_shown(&field.name, &form))
381                .map(|field| field.name.clone())
382                .collect();
383            if next == hidden {
384                break;
385            }
386            hidden = next;
387        }
388        hidden
389    }
390
391    /// Gives `field` the default value `value` on the create form, as Filament's
392    /// `->default(...)`: the create form shows it (a checkbox is ticked by `true`, a select has
393    /// the value chosen, a checkbox list or a repeater takes JSON such as `["a","b"]`), and a
394    /// create whose request does not send the field saves it, as Laravel's
395    /// `$request->input('name', $default)`. The edit form always shows the stored value, as
396    /// Filament uses defaults on the Create page only. A field with no default shows blank, as
397    /// before.
398    ///
399    /// An unticked checkbox sends nothing, so a checkbox default only ticks the box on the
400    /// create form: a create that does not send the checkbox saves `false`, as Laravel's
401    /// `$request->boolean()`. A field hidden or disabled on the create form is not saved,
402    /// default or not. A later default for the same field replaces the earlier one.
403    pub fn default_value(self, field: impl Into<String>, value: impl Into<Value>) -> Self {
404        let value = value.into();
405        self.default_with(field, move |_| value.clone())
406    }
407
408    /// Gives `field` a default computed from the create form's state, as Filament's
409    /// `->default(fn (Get $get) => ...)`: `rule` is given the create form's [`FormContext`]
410    /// (no record, the signed-in user, and the form's values so far: on the form shown, the
411    /// defaults of the fields before `field` in the form's order; on a save, the values the
412    /// request sent and those defaults). Otherwise as
413    /// [`default_value`](Self::default_value).
414    pub fn default_with(
415        mut self,
416        field: impl Into<String>,
417        rule: impl Fn(&FormContext<'_>) -> Value + Send + Sync + 'static,
418    ) -> Self {
419        self.defaults.insert(field.into(), Arc::new(rule));
420        self
421    }
422
423    /// Whether `field` has a default value on the create form.
424    pub fn has_default(&self, field: &str) -> bool {
425        self.defaults.contains_key(field)
426    }
427
428    /// The values the create form shows for `user` before anything is typed: the default of
429    /// each field of `fields` that has one, in the fields' order, as form text.
430    pub fn default_form(&self, fields: &[FieldDef], user: &ActingUser) -> FormInput {
431        self.fill_defaults(fields, user, &FormInput::default(), true)
432    }
433
434    /// `values`, a submitted create form, with the default of each field the request did not
435    /// send ([`FormInput::has`] is false), except a checkbox: an unticked checkbox sends
436    /// nothing, so it stays unticked. The panel calls it before it checks a create.
437    pub fn with_defaults(
438        &self,
439        fields: &[FieldDef],
440        user: &ActingUser,
441        values: &FormInput,
442    ) -> FormInput {
443        self.fill_defaults(fields, user, values, false)
444    }
445
446    fn fill_defaults(
447        &self,
448        fields: &[FieldDef],
449        user: &ActingUser,
450        values: &FormInput,
451        checkboxes: bool,
452    ) -> FormInput {
453        let mut state = values.clone();
454        if self.defaults.is_empty() {
455            return state;
456        }
457        for field in fields {
458            let Some(rule) = self.defaults.get(&field.name) else {
459                continue;
460            };
461            if state.has(&field.name)
462                || (!checkboxes && field.kind == crate::FieldKindDef::Checkbox)
463            {
464                continue;
465            }
466            let value = rule(&FormContext::new(Operation::Create, None, user, &state));
467            if let Some(text) = form_text(&value) {
468                state.insert(field.name.clone(), text);
469            }
470        }
471        state
472    }
473
474    /// The sub-fields of the repeaters, groups and flexible content of `fields` that their
475    /// conditions hide in their own row, by the dotted path of their value, such as
476    /// `fields.0.choices` (a block's: `content.0.data.style`), on the form for `operation`,
477    /// editing `record`, for `user`, whose fields hold `values` (a structured field's value as
478    /// JSON text). A condition is keyed by the sub-field's path without row numbers
479    /// (`fields.choices`) and reads its row's values (see [`FormContext::row`]); a sibling the
480    /// row hides reads as blank. The panel leaves these sub-fields out of the form and out of
481    /// the saved value.
482    pub fn hidden_sub_fields(
483        &self,
484        fields: &[FieldDef],
485        operation: Operation,
486        record: Option<&Row>,
487        user: &ActingUser,
488        values: &FormInput,
489    ) -> BTreeSet<String> {
490        let mut hidden = BTreeSet::new();
491        if !self
492            .hidden
493            .keys()
494            .chain(self.visible.keys())
495            .any(|key| key.contains('.'))
496        {
497            return hidden;
498        }
499        let form = FormContext::new(operation, record, user, values);
500        for field in fields
501            .iter()
502            .filter(|f| crate::structure::is_structured(&f.kind))
503        {
504            let Some(value) = values
505                .get(&field.name)
506                .and_then(|text| serde_json::from_str::<Value>(text).ok())
507            else {
508                continue;
509            };
510            self.hidden_in(
511                &field.kind,
512                &field.name,
513                &field.name,
514                &value,
515                &form,
516                &mut hidden,
517            );
518        }
519        hidden
520    }
521
522    /// Adds to `hidden` the hidden sub-fields inside `value`, a value of `kind` at the dotted
523    /// path `path`, whose conditions are keyed under `schema`.
524    fn hidden_in(
525        &self,
526        kind: &crate::FieldKindDef,
527        path: &str,
528        schema: &str,
529        value: &Value,
530        form: &FormContext<'_>,
531        hidden: &mut BTreeSet<String>,
532    ) {
533        use crate::FieldKindDef as Kind;
534        match kind {
535            Kind::Repeater(fields) => {
536                for (index, row) in value.as_array().into_iter().flatten().enumerate() {
537                    if let Some(row) = row.as_object() {
538                        let at = format!("{path}.{index}");
539                        self.hidden_in_row(fields, row, &at, schema, form, hidden);
540                    }
541                }
542            }
543            Kind::FlexibleContent(blocks) => {
544                for (index, row) in value.as_array().into_iter().flatten().enumerate() {
545                    let block = row
546                        .get("type")
547                        .and_then(Value::as_str)
548                        .and_then(|name| blocks.iter().find(|b| b.name == name));
549                    let (Some(block), Some(data)) =
550                        (block, row.get("data").and_then(Value::as_object))
551                    else {
552                        continue;
553                    };
554                    let at = format!("{path}.{index}.data");
555                    let schema = format!("{schema}.{}", block.name);
556                    self.hidden_in_row(&block.fields, data, &at, &schema, form, hidden);
557                }
558            }
559            Kind::Group(fields) | Kind::Clone(fields) => {
560                if let Some(values) = value.as_object() {
561                    self.hidden_in_row(fields, values, path, schema, form, hidden);
562                }
563            }
564            _ => {}
565        }
566    }
567
568    /// Adds to `hidden` the sub-fields of one row (or group), holding `values`, at `path`.
569    fn hidden_in_row(
570        &self,
571        fields: &[FieldDef],
572        values: &serde_json::Map<String, Value>,
573        path: &str,
574        schema: &str,
575        form: &FormContext<'_>,
576        hidden: &mut BTreeSet<String>,
577    ) {
578        let all = row_form(values);
579        let mut hidden_here: BTreeSet<String> = BTreeSet::new();
580        for _ in 0..=fields.len() {
581            let state = all.without(hidden_here.iter().map(String::as_str));
582            let row = FormContext::row(form, &state);
583            let next: BTreeSet<String> = fields
584                .iter()
585                .filter(|field| !self.is_shown(&format!("{schema}.{}", field.name), &row))
586                .map(|field| field.name.clone())
587                .collect();
588            if next == hidden_here {
589                break;
590            }
591            hidden_here = next;
592        }
593        let state = all.without(hidden_here.iter().map(String::as_str));
594        let row = FormContext::row(form, &state);
595        for field in fields {
596            let at = format!("{path}.{}", field.name);
597            if hidden_here.contains(&field.name) {
598                hidden.insert(at);
599                continue;
600            }
601            if let Some(value) = values.get(&field.name) {
602                let inner = format!("{schema}.{}", field.name);
603                self.hidden_in(&field.kind, &at, &inner, value, &row, hidden);
604            }
605        }
606    }
607}
608
609/// A JSON value as a form sends it: `true` as `on`, text as it is, a number or a structured
610/// value as JSON text. `null` and `false` are not sent.
611fn form_text(value: &Value) -> Option<String> {
612    match value {
613        Value::Null | Value::Bool(false) => None,
614        Value::Bool(true) => Some("on".to_string()),
615        Value::String(text) => Some(text.clone()),
616        other => Some(other.to_string()),
617    }
618}
619
620/// The values of a repeater row or group as form values, for its sub-fields' conditions.
621fn row_form(values: &serde_json::Map<String, Value>) -> FormInput {
622    FormInput::new(
623        values
624            .iter()
625            .filter_map(|(name, value)| form_text(value).map(|text| (name.clone(), text)))
626            .collect(),
627    )
628}
629
630/// `values`, with each field of `hidden` holding its stored value in `record` instead, or no
631/// value when there is none.
632fn stored_when_hidden(
633    values: &FormInput,
634    record: Option<&Row>,
635    hidden: &BTreeSet<String>,
636) -> FormInput {
637    let mut state = values.without(hidden.iter().map(String::as_str));
638    for name in hidden {
639        let stored = match record.and_then(|record| record.get(name)) {
640            None | Some(Value::Null) | Some(Value::Bool(false)) => continue,
641            Some(Value::Bool(true)) => "on".to_string(),
642            Some(Value::String(text)) => text.clone(),
643            Some(other) => other.to_string(),
644        };
645        state.insert(name.clone(), stored);
646    }
647    state
648}
649
650#[cfg(test)]
651mod tests {
652    use super::*;
653    use crate::runtime_resource::FieldKindDef;
654
655    fn field(name: &str) -> FieldDef {
656        FieldDef {
657            name: name.into(),
658            label: name.into(),
659            kind: FieldKindDef::Text,
660            required: true,
661        }
662    }
663
664    fn form(pairs: &[(&str, &str)]) -> FormInput {
665        FormInput::new(
666            pairs
667                .iter()
668                .map(|(k, v)| (k.to_string(), v.to_string()))
669                .collect(),
670        )
671    }
672
673    fn user() -> ActingUser {
674        ActingUser::new(1, "Ada", "ada@example.test")
675    }
676
677    #[test]
678    fn a_field_with_no_condition_shows() {
679        let conditions = FieldConditions::new();
680        let user = user();
681        let values = form(&[]);
682        let context = FormContext::new(Operation::Create, None, &user, &values);
683        assert!(conditions.is_shown("title", &context));
684        assert!(conditions.is_empty());
685    }
686
687    #[test]
688    fn hidden_on_and_visible_on_follow_the_operation() {
689        let conditions = FieldConditions::new()
690            .hidden_on("slug", &[Operation::Create])
691            .visible_on("published_at", &[Operation::Edit]);
692        let fields = [field("slug"), field("published_at"), field("title")];
693        let user = user();
694        let values = form(&[]);
695        let on_create = conditions.hidden_fields(&fields, Operation::Create, None, &user, &values);
696        assert_eq!(
697            on_create,
698            BTreeSet::from(["published_at".into(), "slug".into()])
699        );
700        let record = Row::new();
701        let on_edit =
702            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &values);
703        assert!(on_edit.is_empty());
704    }
705
706    #[test]
707    fn a_later_hidden_replaces_the_earlier_one_and_both_slots_must_agree() {
708        let conditions = FieldConditions::new()
709            .hidden("note", |_| true)
710            .hidden_on("note", &[Operation::Create])
711            .visible("note", |form| form.user().can("notes.edit"));
712        let user = user();
713        let editor = ActingUser::new(2, "Bo", "bo@example.test").with_ability("notes.edit");
714        let values = form(&[]);
715        let record = Row::new();
716        let edit = |user| FormContext::new(Operation::Edit, Some(&record), user, &values);
717        assert!(!conditions.is_shown("note", &edit(&user)), "not visible");
718        assert!(conditions.is_shown("note", &edit(&editor)));
719        let create = FormContext::new(Operation::Create, None, &editor, &values);
720        assert!(!conditions.is_shown("note", &create), "hidden on create");
721    }
722
723    #[test]
724    fn a_condition_reads_the_record_and_the_current_values() {
725        let conditions = FieldConditions::new()
726            .live("kind")
727            .visible("company", |form| form.get("kind") == Some("business"))
728            .visible("archived_note", |form| {
729                form.record()
730                    .and_then(|record| record.get("status"))
731                    .and_then(Value::as_str)
732                    == Some("archived")
733            });
734        assert!(conditions.is_live("kind"));
735        assert!(!conditions.is_live("company"));
736        let fields = [field("kind"), field("company"), field("archived_note")];
737        let user = user();
738        let mut record = Row::new();
739        record.insert("status".into(), Value::from("archived"));
740        let hidden = conditions.hidden_fields(
741            &fields,
742            Operation::Edit,
743            Some(&record),
744            &user,
745            &form(&[("kind", "business")]),
746        );
747        assert!(hidden.is_empty(), "{hidden:?}");
748        let hidden = conditions.hidden_fields(
749            &fields,
750            Operation::Create,
751            None,
752            &user,
753            &form(&[("kind", "person")]),
754        );
755        assert_eq!(
756            hidden,
757            BTreeSet::from(["archived_note".into(), "company".into()])
758        );
759    }
760
761    // `secret` is hidden from this user, and `extra` shows when `secret` is "yes". A request
762    // that sends `secret=yes` must not show `extra`: the condition reads the stored value.
763    #[test]
764    fn a_condition_reads_a_hidden_field_as_stored_not_as_sent() {
765        let conditions = FieldConditions::new()
766            .visible("secret", |form| form.user().can("secret.edit"))
767            .visible("extra", |form| form.get("secret") == Some("yes"));
768        let fields = [field("secret"), field("extra")];
769        let user = user();
770        let sent = form(&[("secret", "yes"), ("extra", "changed")]);
771
772        let mut record = Row::new();
773        record.insert("secret".into(), Value::from("no"));
774        let hidden =
775            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
776        assert_eq!(hidden, BTreeSet::from(["extra".into(), "secret".into()]));
777
778        record.insert("secret".into(), Value::from("yes"));
779        let hidden =
780            conditions.hidden_fields(&fields, Operation::Edit, Some(&record), &user, &sent);
781        assert_eq!(hidden, BTreeSet::from(["secret".into()]));
782    }
783
784    #[test]
785    fn defaults_fill_the_create_form_in_order_and_skip_sent_fields() {
786        let conditions = FieldConditions::new()
787            .default_value("status", "draft")
788            .default_value("featured", true)
789            .default_with("summary", |form| {
790                Value::from(format!("{} post", form.get("status").unwrap_or("?")))
791            });
792        let mut featured = field("featured");
793        featured.kind = FieldKindDef::Checkbox;
794        let fields = [field("status"), featured, field("summary"), field("title")];
795        let user = user();
796        let shown = conditions.default_form(&fields, &user);
797        assert_eq!(shown.get("status"), Some("draft"));
798        assert!(shown.checkbox("featured"));
799        assert_eq!(shown.get("summary"), Some("draft post"));
800        assert!(!shown.has("title"));
801        let saved = conditions.with_defaults(&fields, &user, &form(&[("status", "publish")]));
802        assert_eq!(saved.get("summary"), Some("publish post"));
803        assert!(
804            !saved.has("featured"),
805            "an unticked checkbox stays unticked"
806        );
807    }
808
809    #[test]
810    fn a_row_condition_reads_its_row_and_the_form_around_it() {
811        let conditions = FieldConditions::new()
812            .visible("fields.choices", |row| row.get("type") == Some("select"))
813            .visible("fields.note", |row| row.get("../../mode") == Some("expert"));
814        let repeater = FieldDef {
815            name: "fields".into(),
816            label: "Fields".into(),
817            kind: FieldKindDef::Repeater(vec![field("type"), field("choices"), field("note")]),
818            required: false,
819        };
820        let user = user();
821        let values = form(&[
822            ("mode", "simple"),
823            (
824                "fields",
825                r#"[{"type":"select"},{"type":"text","choices":"x"}]"#,
826            ),
827        ]);
828        let hidden = conditions.hidden_sub_fields(
829            std::slice::from_ref(&repeater),
830            Operation::Create,
831            None,
832            &user,
833            &values,
834        );
835        assert_eq!(
836            hidden,
837            BTreeSet::from([
838                "fields.0.note".into(),
839                "fields.1.choices".into(),
840                "fields.1.note".into()
841            ])
842        );
843        let pruned = crate::structure::without_sub_fields(&[repeater], &values, &hidden);
844        assert_eq!(
845            pruned.get("fields"),
846            Some(r#"[{"type":"select"},{"type":"text"}]"#)
847        );
848    }
849
850    #[test]
851    fn a_block_condition_is_keyed_by_the_block_and_reads_the_block_row() {
852        let conditions =
853            FieldConditions::new().visible("content.hero.style", |row| row.checked("styled"));
854        let content = FieldDef {
855            name: "content".into(),
856            label: "Content".into(),
857            kind: FieldKindDef::FlexibleContent(vec![crate::runtime_resource::BlockDef {
858                name: "hero".into(),
859                label: "Hero".into(),
860                fields: vec![field("styled"), field("style")],
861            }]),
862            required: false,
863        };
864        let user = user();
865        let values = form(&[(
866            "content",
867            r#"[{"type":"hero","data":{"styled":true,"style":"a"}},{"type":"hero","data":{"style":"b"}}]"#,
868        )]);
869        let hidden = conditions.hidden_sub_fields(
870            std::slice::from_ref(&content),
871            Operation::Edit,
872            None,
873            &user,
874            &values,
875        );
876        assert_eq!(hidden, BTreeSet::from(["content.1.data.style".into()]));
877        let pruned = crate::structure::without_sub_fields(&[content], &values, &hidden);
878        let pruned: Value = serde_json::from_str(pruned.get("content").unwrap()).unwrap();
879        assert_eq!(
880            pruned,
881            serde_json::json!([
882                {"type": "hero", "data": {"styled": true, "style": "a"}},
883                {"type": "hero", "data": {}}
884            ])
885        );
886    }
887}