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;
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/// `form`, with the button `operation` applied to the structured fields of `fields`, as
316/// Filament's repeater actions change the form's state without saving it. An operation is
317/// `add:<path>` (a blank row at the end of the repeater at `path`), `add:<path>:<block>` (a
318/// blank block of flexible content, as Filament's block picker adds one), `delete:<path>.<row>`, `up:<path>.<row>` or
319/// `down:<path>.<row>`. `path` is the dotted path of the field's value, such as `members` or
320/// `groups.0.rules`. An operation that does not apply, or that the field's settings in
321/// `repeaters` do not allow, changes nothing.
322pub fn apply_operation(
323    fields: &[FieldDef],
324    repeaters: &Repeaters,
325    form: &FormInput,
326    operation: &str,
327) -> FormInput {
328    let Some((verb, target)) = operation.split_once(':') else {
329        return form.clone();
330    };
331    let (path, block) = match target.split_once(':') {
332        Some((path, block)) => (path, Some(block)),
333        None => (target, None),
334    };
335    let mut segments: Vec<&str> = path.split('.').collect();
336    let row = if verb == "add" {
337        None
338    } else {
339        match segments.pop().and_then(|row| row.parse::<usize>().ok()) {
340            Some(row) => Some(row),
341            None => return form.clone(),
342        }
343    };
344    let Some(field) = fields
345        .iter()
346        .find(|f| Some(f.name.as_str()) == segments.first().copied())
347    else {
348        return form.clone();
349    };
350    let mut value = form
351        .get(&field.name)
352        .and_then(|text| serde_json::from_str::<Value>(text).ok())
353        .unwrap_or(Value::Null);
354    let Some((kind, schema, list)) = locate(&field.kind, &field.name, &mut value, &segments[1..])
355    else {
356        return form.clone();
357    };
358    let settings = repeaters.get(&schema);
359    let changed = match (verb, row) {
360        ("add", None) if settings.is_addable() => {
361            let full = settings
362                .get_max_items()
363                .is_some_and(|max| list.len() >= max);
364            let blank = match (kind, block) {
365                (FieldKindDef::Repeater(_), None) => Some(Value::Object(Map::new())),
366                (FieldKindDef::FlexibleContent(blocks), Some(block))
367                    if blocks.iter().any(|b| b.name == block) =>
368                {
369                    Some(serde_json::json!({ "type": block, "data": {} }))
370                }
371                _ => None,
372            };
373            match blank.filter(|_| !full) {
374                Some(blank) => {
375                    list.push(blank);
376                    true
377                }
378                None => false,
379            }
380        }
381        ("delete", Some(row)) if settings.is_deletable() && row < list.len() => {
382            list.remove(row);
383            true
384        }
385        ("up", Some(row)) if settings.is_reorderable() && row > 0 && row < list.len() => {
386            list.swap(row - 1, row);
387            true
388        }
389        ("down", Some(row)) if settings.is_reorderable() && row + 1 < list.len() => {
390            list.swap(row, row + 1);
391            true
392        }
393        _ => false,
394    };
395    let mut values = form.clone();
396    if changed {
397        values.insert(field.name.clone(), value.to_string());
398    }
399    values
400}
401
402/// The list of rows at `segments` inside `value`, a value of `kind`, with the kind of the field
403/// that holds it and its settings path (`schema`, the names without row numbers). A missing
404/// list is created empty, so a first row can be added to a field that has no value yet.
405fn locate<'k, 'v>(
406    kind: &'k FieldKindDef,
407    schema: &str,
408    value: &'v mut Value,
409    segments: &[&str],
410) -> Option<(&'k FieldKindDef, String, &'v mut Vec<Value>)> {
411    let Some((first, rest)) = segments.split_first() else {
412        if !matches!(
413            kind,
414            FieldKindDef::Repeater(_) | FieldKindDef::FlexibleContent(_)
415        ) {
416            return None;
417        }
418        if !value.is_array() {
419            *value = Value::Array(Vec::new());
420        }
421        return Some((kind, schema.to_string(), value.as_array_mut()?));
422    };
423    match kind {
424        FieldKindDef::Repeater(fields) => {
425            let row = value
426                .as_array_mut()?
427                .get_mut(first.parse::<usize>().ok()?)?;
428            let (name, rest) = rest.split_first()?;
429            let field = fields.iter().find(|f| f.name == *name)?;
430            let inner = row
431                .as_object_mut()?
432                .entry(name.to_string())
433                .or_insert(Value::Null);
434            locate(&field.kind, &format!("{schema}.{name}"), inner, rest)
435        }
436        FieldKindDef::FlexibleContent(blocks) => {
437            let row = value
438                .as_array_mut()?
439                .get_mut(first.parse::<usize>().ok()?)?;
440            let block = row.get("type")?.as_str()?.to_string();
441            let fields = &blocks.iter().find(|b| b.name == block)?.fields;
442            let (data, rest) = rest.split_first()?;
443            if *data != "data" {
444                return None;
445            }
446            let (name, rest) = rest.split_first()?;
447            let field = fields.iter().find(|f| f.name == *name)?;
448            let inner = row
449                .as_object_mut()?
450                .entry("data")
451                .or_insert_with(|| Value::Object(Map::new()))
452                .as_object_mut()?
453                .entry(name.to_string())
454                .or_insert(Value::Null);
455            locate(
456                &field.kind,
457                &format!("{schema}.{block}.{name}"),
458                inner,
459                rest,
460            )
461        }
462        FieldKindDef::Group(fields) | FieldKindDef::Clone(fields) => {
463            let field = fields.iter().find(|f| f.name == *first)?;
464            if !value.is_object() {
465                *value = Value::Object(Map::new());
466            }
467            let inner = value
468                .as_object_mut()?
469                .entry(first.to_string())
470                .or_insert(Value::Null);
471            locate(&field.kind, &format!("{schema}.{first}"), inner, rest)
472        }
473        _ => None,
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use std::collections::HashMap;
481
482    fn text(name: &str) -> FieldDef {
483        FieldDef {
484            name: name.into(),
485            label: name.into(),
486            kind: FieldKindDef::Text,
487            required: false,
488        }
489    }
490
491    fn members() -> FieldDef {
492        FieldDef {
493            name: "members".into(),
494            label: "Members".into(),
495            kind: FieldKindDef::Repeater(vec![
496                text("name"),
497                FieldDef {
498                    name: "admin".into(),
499                    label: "Admin".into(),
500                    kind: FieldKindDef::Checkbox,
501                    required: false,
502                },
503            ]),
504            required: false,
505        }
506    }
507
508    fn form(pairs: &[(&str, &str)]) -> FormInput {
509        FormInput::new(
510            pairs
511                .iter()
512                .map(|(k, v)| (k.to_string(), v.to_string()))
513                .collect::<HashMap<_, _>>(),
514        )
515    }
516
517    #[test]
518    fn rows_are_built_in_the_order_of_their_numbers() {
519        let sent = form(&[
520            ("members", ""),
521            ("members[10][name]", "Ten"),
522            ("members[2][name]", "Two"),
523            ("members[2][admin]", "on"),
524        ]);
525        let values = structured_input(&[members()], &sent);
526        assert_eq!(
527            values.get("members"),
528            Some(r#"[{"admin":true,"name":"Two"},{"admin":false,"name":"Ten"}]"#)
529        );
530    }
531
532    #[test]
533    fn a_field_sent_as_json_is_kept() {
534        let sent = form(&[("members", r#"[{"name":"A"}]"#)]);
535        let values = structured_input(&[members()], &sent);
536        assert_eq!(values.get("members"), Some(r#"[{"name":"A"}]"#));
537    }
538
539    #[test]
540    fn buttons_add_move_and_delete_rows() {
541        let fields = [members()];
542        let sent = form(&[("members", r#"[{"name":"A"},{"name":"B"}]"#)]);
543        let repeaters = Repeaters::new();
544        let moved = apply_operation(&fields, &repeaters, &sent, "down:members.0");
545        assert_eq!(moved.get("members"), Some(r#"[{"name":"B"},{"name":"A"}]"#));
546        let added = apply_operation(&fields, &repeaters, &moved, "add:members");
547        assert_eq!(
548            added.get("members"),
549            Some(r#"[{"name":"B"},{"name":"A"},{}]"#)
550        );
551        let deleted = apply_operation(&fields, &repeaters, &added, "delete:members.1");
552        assert_eq!(deleted.get("members"), Some(r#"[{"name":"B"},{}]"#));
553        let limited = Repeaters::new().repeater("members", RepeaterSettings::new().max_items(2));
554        let full = apply_operation(&fields, &limited, &deleted, "add:members");
555        assert_eq!(full.get("members"), deleted.get("members"));
556    }
557}