Skip to main content

ignite_core/
structure.rs

1//! Repeaters, groups and flexible content edited as sub-fields, as Filament's `Repeater`,
2//! `Fieldset` and `Builder`: the settings of a repeater or flexible content
3//! ([`RepeaterSettings`]), the values a form sends for one ([`structured_input`]), and the
4//! add, delete and move buttons ([`apply_operation`]).
5//!
6//! The form names each sub-field input after its place, as PHP and Laravel read nested
7//! arrays: `members[0][name]` is the `name` of the first row of `members`, `seo[title]` the
8//! `title` of the group `seo`, and `content[1][data][heading]` the `heading` of the second
9//! block of `content`, whose type is `content[1][type]`. The panel turns them into the JSON
10//! value the field stores, a list of rows or one object, so the checks and the data layer see
11//! the same value as when the form sends the field as JSON text.
12//!
13//! An error on a sub-field is keyed by its dotted path, as Laravel keys the errors of a nested
14//! array: `members.0.name`, `seo.title`, `content.1.data.heading`. The settings path of a
15//! block's sub-field names the block: `content.hero.items`. A repeater's settings are
16//! keyed by the names of the fields that lead to it, without row numbers: `members`, or
17//! `groups.rules` for the repeater `rules` inside each row of `groups`, as Filament's state
18//! path without the item keys.
19
20use std::collections::{BTreeMap, BTreeSet};
21
22use serde_json::{Map, Value};
23
24use crate::form::FormInput;
25use crate::runtime_resource::{FieldDef, FieldKindDef};
26
27/// The settings of a repeater or flexible content field, as Filament's `Repeater` and
28/// `Builder` methods. The default allows any number of rows, adds, deletes and moves rows,
29/// and labels each row by its number.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct RepeaterSettings {
32    min_items: Option<usize>,
33    max_items: Option<usize>,
34    item_label: Option<String>,
35    add_action_label: Option<String>,
36    addable: bool,
37    deletable: bool,
38    reorderable: bool,
39}
40
41impl Default for RepeaterSettings {
42    fn default() -> Self {
43        RepeaterSettings {
44            min_items: None,
45            max_items: None,
46            item_label: None,
47            add_action_label: None,
48            addable: true,
49            deletable: true,
50            reorderable: true,
51        }
52    }
53}
54
55impl RepeaterSettings {
56    /// The default settings.
57    pub fn new() -> Self {
58        RepeaterSettings::default()
59    }
60
61    /// The fewest rows the field saves with, as Filament's `minItems()`. Fewer is refused with
62    /// "<label> must have at least <n> items.", as Laravel's array `min` rule words it.
63    pub fn min_items(mut self, count: usize) -> Self {
64        self.min_items = Some(count);
65        self
66    }
67
68    /// The most rows the field takes, as Filament's `maxItems()`. The add button hides at the
69    /// limit, and more is refused with "<label> must not have more than <n> items.".
70    pub fn max_items(mut self, count: usize) -> Self {
71        self.max_items = Some(count);
72        self
73    }
74
75    /// Labels each row by the value of its sub-field `field`, as Filament's
76    /// `itemLabel(fn (array $state) => $state['name'])` and ACF's "collapsed" setting. A row
77    /// whose value is blank shows its number.
78    pub fn item_label(mut self, field: impl Into<String>) -> Self {
79        self.item_label = Some(field.into());
80        self
81    }
82
83    /// The label of the add button, as Filament's `addActionLabel()`. The default is "Add to
84    /// <label>", as Filament's.
85    pub fn add_action_label(mut self, label: impl Into<String>) -> Self {
86        self.add_action_label = Some(label.into());
87        self
88    }
89
90    /// Whether rows can be added, as Filament's `addable()`. The default is `true`.
91    pub fn addable(mut self, addable: bool) -> Self {
92        self.addable = addable;
93        self
94    }
95
96    /// Whether rows can be deleted, as Filament's `deletable()`. The default is `true`.
97    pub fn deletable(mut self, deletable: bool) -> Self {
98        self.deletable = deletable;
99        self
100    }
101
102    /// Whether rows can be moved up and down, as Filament's `reorderableWithButtons()`. The
103    /// default is `true`; `false` is Filament's `reorderable(false)`.
104    pub fn reorderable(mut self, reorderable: bool) -> Self {
105        self.reorderable = reorderable;
106        self
107    }
108
109    /// The fewest rows, if set.
110    pub fn get_min_items(&self) -> Option<usize> {
111        self.min_items
112    }
113
114    /// The most rows, if set.
115    pub fn get_max_items(&self) -> Option<usize> {
116        self.max_items
117    }
118
119    /// The sub-field whose value labels each row, if set.
120    pub fn get_item_label(&self) -> Option<&str> {
121        self.item_label.as_deref()
122    }
123
124    /// The label of the add button, if set.
125    pub fn get_add_action_label(&self) -> Option<&str> {
126        self.add_action_label.as_deref()
127    }
128
129    /// Whether rows can be added.
130    pub fn is_addable(&self) -> bool {
131        self.addable
132    }
133
134    /// Whether rows can be deleted.
135    pub fn is_deletable(&self) -> bool {
136        self.deletable
137    }
138
139    /// Whether rows can be moved.
140    pub fn is_reorderable(&self) -> bool {
141        self.reorderable
142    }
143}
144
145/// The settings of a form's repeaters and flexible content fields, by path (see the [module
146/// documentation](self)). A field with no settings has the default ones.
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
148pub struct Repeaters(BTreeMap<String, RepeaterSettings>);
149
150impl Repeaters {
151    /// No settings: every repeater has the default ones.
152    pub fn new() -> Self {
153        Repeaters::default()
154    }
155
156    /// Sets the settings of the repeater at `path`, such as `"members"` or `"groups.rules"`.
157    pub fn repeater(mut self, path: impl Into<String>, settings: RepeaterSettings) -> Self {
158        self.0.insert(path.into(), settings);
159        self
160    }
161
162    /// The settings of the repeater at `path`, or the default ones.
163    pub fn get(&self, path: &str) -> RepeaterSettings {
164        self.0.get(path).cloned().unwrap_or_default()
165    }
166}
167
168/// Whether a field of `kind` is edited as sub-fields: a repeater, a group, flexible content
169/// or a clone.
170pub fn is_structured(kind: &FieldKindDef) -> bool {
171    matches!(
172        kind,
173        FieldKindDef::Repeater(_)
174            | FieldKindDef::Group(_)
175            | FieldKindDef::FlexibleContent(_)
176            | FieldKindDef::Clone(_)
177    )
178}
179
180/// `form`, with the value of each structured field of `fields` built from the sub-field
181/// inputs it sent (`members[0][name]` and so on), as JSON text under the field's name: a list
182/// of rows for a repeater or flexible content, one object for a group or a clone. Rows come
183/// in the order of their numbers, numbered again from 0. A field the form sent no sub-field
184/// input for keeps what the form sent under its name, such as JSON text, or nothing.
185pub fn structured_input(fields: &[FieldDef], form: &FormInput) -> FormInput {
186    let mut values = form.clone();
187    for field in fields.iter().filter(|f| is_structured(&f.kind)) {
188        let prefix = format!("{}[", field.name);
189        if !form.names().any(|name| name.starts_with(&prefix)) {
190            continue;
191        }
192        let value = collect(&field.kind, &field.name, form);
193        values.insert(field.name.clone(), value.to_string());
194    }
195    values
196}
197
198/// The value of a structured `kind` whose inputs are named after `base`.
199fn collect(kind: &FieldKindDef, base: &str, form: &FormInput) -> Value {
200    match kind {
201        FieldKindDef::Repeater(fields) => Value::Array(
202            rows(base, form)
203                .iter()
204                .map(|row| Value::Object(object(fields, &format!("{base}[{row}]"), form)))
205                .collect(),
206        ),
207        FieldKindDef::FlexibleContent(blocks) => Value::Array(
208            rows(base, form)
209                .iter()
210                .filter_map(|row| {
211                    let at = format!("{base}[{row}]");
212                    let kind = form.raw(&format!("{at}[type]"))?.trim().to_string();
213                    let fields = blocks
214                        .iter()
215                        .find(|block| block.name == kind)
216                        .map(|block| block.fields.as_slice())
217                        .unwrap_or(&[]);
218                    let data = object(fields, &format!("{at}[data]"), form);
219                    Some(serde_json::json!({ "type": kind, "data": data }))
220                })
221                .collect(),
222        ),
223        FieldKindDef::Group(fields) | FieldKindDef::Clone(fields) => {
224            Value::Object(object(fields, base, form))
225        }
226        _ => Value::Null,
227    }
228}
229
230/// The values of `fields` whose inputs are named `{base}[{name}]`. A sub-field the form did
231/// not send is left out, except an unticked checkbox, which is `false`.
232fn object(fields: &[FieldDef], base: &str, form: &FormInput) -> Map<String, Value> {
233    let mut values = Map::new();
234    for field in fields {
235        let name = format!("{base}[{}]", field.name);
236        let value = match &field.kind {
237            kind if is_structured(kind) => {
238                let prefix = format!("{name}[");
239                if form.names().any(|key| key.starts_with(&prefix)) {
240                    collect(kind, &name, form)
241                } else {
242                    // A list with no rows sends only its blank marker.
243                    match form.raw(&name) {
244                        Some(text) if text.trim().is_empty() => Value::Array(Vec::new()),
245                        Some(text) => serde_json::from_str(text).unwrap_or(Value::Null),
246                        None => continue,
247                    }
248                }
249            }
250            FieldKindDef::Checkbox => Value::Bool(form.checkbox(&name)),
251            FieldKindDef::Link => {
252                let part = |key: &str| form.raw(&format!("{name}[{key}]")).unwrap_or_default();
253                if ["url", "title", "target"]
254                    .iter()
255                    .all(|key| part(key).trim().is_empty())
256                {
257                    match form.raw(&name) {
258                        Some(text) => Value::from(text),
259                        None => continue,
260                    }
261                } else {
262                    serde_json::json!({
263                        "url": part("url"),
264                        "title": part("title"),
265                        "target": part("target"),
266                    })
267                }
268            }
269            kind if takes_list(kind) => match form.raw(&name) {
270                Some(text) if text.trim().is_empty() => Value::Array(Vec::new()),
271                Some(text) => serde_json::from_str(text).unwrap_or_else(|_| Value::from(text)),
272                None => continue,
273            },
274            _ => match form.raw(&name) {
275                Some(text) => Value::from(text),
276                None => continue,
277            },
278        };
279        values.insert(field.name.clone(), value);
280    }
281    values
282}
283
284/// Whether a field of `kind` sends a list (`name[]`): a checkbox list, a relationship or a
285/// gallery.
286fn takes_list(kind: &FieldKindDef) -> bool {
287    matches!(
288        kind,
289        FieldKindDef::CheckboxList(_) | FieldKindDef::Relationship | FieldKindDef::Gallery
290    )
291}
292
293/// The row keys the form sent under `base` (`{base}[{row}]...`), in the order of their
294/// numbers. A key that is not a number comes after the numbered ones.
295fn rows(base: &str, form: &FormInput) -> Vec<String> {
296    let prefix = format!("{base}[");
297    let mut keys: Vec<String> = form
298        .names()
299        .filter_map(|name| {
300            let rest = name.strip_prefix(&prefix)?;
301            let (row, after) = rest.split_once(']')?;
302            (after.starts_with('[') && !row.is_empty()).then(|| row.to_string())
303        })
304        .collect();
305    keys.sort_by(|a, b| match (a.parse::<u64>(), b.parse::<u64>()) {
306        (Ok(a), Ok(b)) => a.cmp(&b),
307        (Ok(_), Err(_)) => std::cmp::Ordering::Less,
308        (Err(_), Ok(_)) => std::cmp::Ordering::Greater,
309        (Err(_), Err(_)) => a.cmp(b),
310    });
311    keys.dedup();
312    keys
313}
314
315/// Runs `f`, a check of a submitted form, with the sub-fields at `paths` hidden: the dotted
316/// paths of their values, as [`FieldConditions::hidden_sub_fields`](crate::FieldConditions::hidden_sub_fields)
317/// gives them, such as `fields.0.choices`. The checks of structured values that `f` runs on
318/// this thread ([`Field::check_value_in`](crate::Field::check_value_in),
319/// [`RegisteredResource::validate_shown`](crate::RegisteredResource::validate_shown) and the
320/// others) skip those sub-fields, a required one included, and leave them out of the checked
321/// value, as a hidden field is not validated or saved in Filament. Paths that are not dotted
322/// (the names of top-level fields) are ignored. The panel calls it around a resource's
323/// validation.
324pub fn with_hidden_sub_fields<T>(paths: &BTreeSet<String>, f: impl FnOnce() -> T) -> T {
325    crate::value::with_hidden_sub_fields(paths, f)
326}
327
328/// `form` without the sub-fields at `paths` (dotted value paths, such as `fields.0.choices` or
329/// `content.0.data.style`) in the JSON values of the structured fields of `fields`, as if the
330/// form had not sent them. Paths that are not dotted are ignored.
331pub fn without_sub_fields(
332    fields: &[FieldDef],
333    form: &FormInput,
334    paths: &BTreeSet<String>,
335) -> FormInput {
336    let mut values = form.clone();
337    for field in fields.iter().filter(|f| is_structured(&f.kind)) {
338        let prefix = format!("{}.", field.name);
339        let inside: Vec<&str> = paths
340            .iter()
341            .filter_map(|path| path.strip_prefix(&prefix))
342            .collect();
343        if inside.is_empty() {
344            continue;
345        }
346        let Some(mut value) = form
347            .get(&field.name)
348            .and_then(|text| serde_json::from_str::<Value>(text).ok())
349        else {
350            continue;
351        };
352        for path in inside {
353            remove_path(&mut value, &path.split('.').collect::<Vec<_>>());
354        }
355        values.insert(field.name.clone(), value.to_string());
356    }
357    values
358}
359
360/// Removes the value at `segments` (keys and row numbers) inside `value`, if it is there.
361fn remove_path(value: &mut Value, segments: &[&str]) {
362    let Some((first, rest)) = segments.split_first() else {
363        return;
364    };
365    if rest.is_empty() {
366        if let Some(object) = value.as_object_mut() {
367            object.remove(*first);
368        }
369        return;
370    }
371    let inner = match value {
372        Value::Array(rows) => first.parse::<usize>().ok().and_then(|i| rows.get_mut(i)),
373        Value::Object(object) => object.get_mut(*first),
374        _ => None,
375    };
376    if let Some(inner) = inner {
377        remove_path(inner, rest);
378    }
379}
380
381/// `form`, with the button `operation` applied to the structured fields of `fields`, as
382/// Filament's repeater actions change the form's state without saving it. An operation is
383/// `add:<path>` (a blank row at the end of the repeater at `path`), `add:<path>:<block>` (a
384/// blank block of flexible content, as Filament's block picker adds one), `delete:<path>.<row>`, `up:<path>.<row>` or
385/// `down:<path>.<row>`. `path` is the dotted path of the field's value, such as `members` or
386/// `groups.0.rules`. An operation that does not apply, or that the field's settings in
387/// `repeaters` do not allow, changes nothing.
388pub fn apply_operation(
389    fields: &[FieldDef],
390    repeaters: &Repeaters,
391    form: &FormInput,
392    operation: &str,
393) -> FormInput {
394    let Some((verb, target)) = operation.split_once(':') else {
395        return form.clone();
396    };
397    let (path, block) = match target.split_once(':') {
398        Some((path, block)) => (path, Some(block)),
399        None => (target, None),
400    };
401    let mut segments: Vec<&str> = path.split('.').collect();
402    let row = if verb == "add" {
403        None
404    } else {
405        match segments.pop().and_then(|row| row.parse::<usize>().ok()) {
406            Some(row) => Some(row),
407            None => return form.clone(),
408        }
409    };
410    let Some(field) = fields
411        .iter()
412        .find(|f| Some(f.name.as_str()) == segments.first().copied())
413    else {
414        return form.clone();
415    };
416    let mut value = form
417        .get(&field.name)
418        .and_then(|text| serde_json::from_str::<Value>(text).ok())
419        .unwrap_or(Value::Null);
420    let Some((kind, schema, list)) = locate(&field.kind, &field.name, &mut value, &segments[1..])
421    else {
422        return form.clone();
423    };
424    let settings = repeaters.get(&schema);
425    let changed = match (verb, row) {
426        ("add", None) if settings.is_addable() => {
427            let full = settings
428                .get_max_items()
429                .is_some_and(|max| list.len() >= max);
430            let blank = match (kind, block) {
431                (FieldKindDef::Repeater(_), None) => Some(Value::Object(Map::new())),
432                (FieldKindDef::FlexibleContent(blocks), Some(block))
433                    if blocks.iter().any(|b| b.name == block) =>
434                {
435                    Some(serde_json::json!({ "type": block, "data": {} }))
436                }
437                _ => None,
438            };
439            match blank.filter(|_| !full) {
440                Some(blank) => {
441                    list.push(blank);
442                    true
443                }
444                None => false,
445            }
446        }
447        ("delete", Some(row)) if settings.is_deletable() && row < list.len() => {
448            list.remove(row);
449            true
450        }
451        ("up", Some(row)) if settings.is_reorderable() && row > 0 && row < list.len() => {
452            list.swap(row - 1, row);
453            true
454        }
455        ("down", Some(row)) if settings.is_reorderable() && row + 1 < list.len() => {
456            list.swap(row, row + 1);
457            true
458        }
459        _ => false,
460    };
461    let mut values = form.clone();
462    if changed {
463        values.insert(field.name.clone(), value.to_string());
464    }
465    values
466}
467
468/// The list of rows at `segments` inside `value`, a value of `kind`, with the kind of the field
469/// that holds it and its settings path (`schema`, the names without row numbers). A missing
470/// list is created empty, so a first row can be added to a field that has no value yet.
471fn locate<'k, 'v>(
472    kind: &'k FieldKindDef,
473    schema: &str,
474    value: &'v mut Value,
475    segments: &[&str],
476) -> Option<(&'k FieldKindDef, String, &'v mut Vec<Value>)> {
477    let Some((first, rest)) = segments.split_first() else {
478        if !matches!(
479            kind,
480            FieldKindDef::Repeater(_) | FieldKindDef::FlexibleContent(_)
481        ) {
482            return None;
483        }
484        if !value.is_array() {
485            *value = Value::Array(Vec::new());
486        }
487        return Some((kind, schema.to_string(), value.as_array_mut()?));
488    };
489    match kind {
490        FieldKindDef::Repeater(fields) => {
491            let row = value
492                .as_array_mut()?
493                .get_mut(first.parse::<usize>().ok()?)?;
494            let (name, rest) = rest.split_first()?;
495            let field = fields.iter().find(|f| f.name == *name)?;
496            let inner = row
497                .as_object_mut()?
498                .entry(name.to_string())
499                .or_insert(Value::Null);
500            locate(&field.kind, &format!("{schema}.{name}"), inner, rest)
501        }
502        FieldKindDef::FlexibleContent(blocks) => {
503            let row = value
504                .as_array_mut()?
505                .get_mut(first.parse::<usize>().ok()?)?;
506            let block = row.get("type")?.as_str()?.to_string();
507            let fields = &blocks.iter().find(|b| b.name == block)?.fields;
508            let (data, rest) = rest.split_first()?;
509            if *data != "data" {
510                return None;
511            }
512            let (name, rest) = rest.split_first()?;
513            let field = fields.iter().find(|f| f.name == *name)?;
514            let inner = row
515                .as_object_mut()?
516                .entry("data")
517                .or_insert_with(|| Value::Object(Map::new()))
518                .as_object_mut()?
519                .entry(name.to_string())
520                .or_insert(Value::Null);
521            locate(
522                &field.kind,
523                &format!("{schema}.{block}.{name}"),
524                inner,
525                rest,
526            )
527        }
528        FieldKindDef::Group(fields) | FieldKindDef::Clone(fields) => {
529            let field = fields.iter().find(|f| f.name == *first)?;
530            if !value.is_object() {
531                *value = Value::Object(Map::new());
532            }
533            let inner = value
534                .as_object_mut()?
535                .entry(first.to_string())
536                .or_insert(Value::Null);
537            locate(&field.kind, &format!("{schema}.{first}"), inner, rest)
538        }
539        _ => None,
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546    use std::collections::HashMap;
547
548    fn text(name: &str) -> FieldDef {
549        FieldDef {
550            name: name.into(),
551            label: name.into(),
552            kind: FieldKindDef::Text,
553            required: false,
554        }
555    }
556
557    fn members() -> FieldDef {
558        FieldDef {
559            name: "members".into(),
560            label: "Members".into(),
561            kind: FieldKindDef::Repeater(vec![
562                text("name"),
563                FieldDef {
564                    name: "admin".into(),
565                    label: "Admin".into(),
566                    kind: FieldKindDef::Checkbox,
567                    required: false,
568                },
569            ]),
570            required: false,
571        }
572    }
573
574    fn form(pairs: &[(&str, &str)]) -> FormInput {
575        FormInput::new(
576            pairs
577                .iter()
578                .map(|(k, v)| (k.to_string(), v.to_string()))
579                .collect::<HashMap<_, _>>(),
580        )
581    }
582
583    #[test]
584    fn rows_are_built_in_the_order_of_their_numbers() {
585        let sent = form(&[
586            ("members", ""),
587            ("members[10][name]", "Ten"),
588            ("members[2][name]", "Two"),
589            ("members[2][admin]", "on"),
590        ]);
591        let values = structured_input(&[members()], &sent);
592        assert_eq!(
593            values.get("members"),
594            Some(r#"[{"admin":true,"name":"Two"},{"admin":false,"name":"Ten"}]"#)
595        );
596    }
597
598    #[test]
599    fn a_field_sent_as_json_is_kept() {
600        let sent = form(&[("members", r#"[{"name":"A"}]"#)]);
601        let values = structured_input(&[members()], &sent);
602        assert_eq!(values.get("members"), Some(r#"[{"name":"A"}]"#));
603    }
604
605    #[test]
606    fn buttons_add_move_and_delete_rows() {
607        let fields = [members()];
608        let sent = form(&[("members", r#"[{"name":"A"},{"name":"B"}]"#)]);
609        let repeaters = Repeaters::new();
610        let moved = apply_operation(&fields, &repeaters, &sent, "down:members.0");
611        assert_eq!(moved.get("members"), Some(r#"[{"name":"B"},{"name":"A"}]"#));
612        let added = apply_operation(&fields, &repeaters, &moved, "add:members");
613        assert_eq!(
614            added.get("members"),
615            Some(r#"[{"name":"B"},{"name":"A"},{}]"#)
616        );
617        let deleted = apply_operation(&fields, &repeaters, &added, "delete:members.1");
618        assert_eq!(deleted.get("members"), Some(r#"[{"name":"B"},{}]"#));
619        let limited = Repeaters::new().repeater("members", RepeaterSettings::new().max_items(2));
620        let full = apply_operation(&fields, &limited, &deleted, "add:members");
621        assert_eq!(full.get("members"), deleted.get("members"));
622    }
623}