Skip to main content

rustango_cms/forms/
schema.rs

1//! Form Builder schema.
2//!
3//! The visual builder stores a whole form as one JSON document in the
4//! backing snippet's `data` column (`type_name = "form"`). This module is
5//! the pure, IO-free contract for that document: serde types + validation
6//! + small traversal helpers. Everything downstream — the builder editor,
7//! the public renderer, the submit handler, the submissions admin — reads
8//! and writes through these types.
9//!
10//! Shape (mirrors the user's hierarchy):
11//!
12//! ```text
13//! Form
14//!  ├─ settings (submit label, success message/redirect, notify emails)
15//!  └─ pages[]            ← wizard steps (next/prev)
16//!      └─ sections[]     ← logical groupings within a page
17//!          └─ rows[]     ← a 12-column grid row
18//!              └─ columns[] (width 1..=12)
19//!                  └─ fields[]   ← the typed inputs
20//! ```
21//!
22//! IDs are client-minted UUID strings, stable across reorder (the builder
23//! JS reuses them); validation never depends on array position.
24
25use serde::{Deserialize, Serialize};
26
27/// One built form. Serialized as the snippet `data` JSON.
28#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
29pub struct Form {
30    #[serde(default)]
31    pub settings: FormSettings,
32    #[serde(default)]
33    pub pages: Vec<Page>,
34}
35
36/// Form-level defaults. An embed block may override the
37/// success redirect / message per placement.
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
39pub struct FormSettings {
40    #[serde(default)]
41    pub submit_label: String,
42    #[serde(default)]
43    pub success_message: String,
44    #[serde(default)]
45    pub redirect_url: String,
46    /// Comma-separated recipient list for submit notifications.
47    #[serde(default)]
48    pub notify_emails: String,
49    /// Auto-link the bundled `/forms/forms.css`. Turn off to fully replace
50    /// the styling with your own stylesheet. Default `true`.
51    #[serde(default = "default_true")]
52    pub builtin_css: bool,
53    /// The multi-page buttons and progress line; empty → the English
54    /// default ([`FormSettings::next_text`] and friends). Translatable.
55    #[serde(default)]
56    pub next_label: String,
57    #[serde(default)]
58    pub back_label: String,
59    /// `{n}` and `{total}` are replaced, e.g. `Step {n} of {total}`.
60    #[serde(default)]
61    pub progress_label: String,
62    /// Shown when the server refuses a submission.
63    #[serde(default)]
64    pub error_message: String,
65}
66
67impl Default for FormSettings {
68    fn default() -> Self {
69        Self {
70            submit_label: String::new(),
71            success_message: String::new(),
72            redirect_url: String::new(),
73            notify_emails: String::new(),
74            builtin_css: true,
75            next_label: String::new(),
76            back_label: String::new(),
77            progress_label: String::new(),
78            error_message: String::new(),
79        }
80    }
81}
82
83fn or_default<'a>(set: &'a str, default: &'a str) -> &'a str {
84    if set.trim().is_empty() {
85        default
86    } else {
87        set
88    }
89}
90
91impl FormSettings {
92    /// The submit button's text.
93    #[must_use]
94    pub fn submit_text(&self) -> &str {
95        or_default(&self.submit_label, "Submit")
96    }
97    /// The message shown after a successful submission.
98    #[must_use]
99    pub fn success_text(&self) -> &str {
100        or_default(&self.success_message, "Thanks! Your submission was received.")
101    }
102    /// The "next step" button's text.
103    #[must_use]
104    pub fn next_text(&self) -> &str {
105        or_default(&self.next_label, "Next")
106    }
107    /// The "previous step" button's text.
108    #[must_use]
109    pub fn back_text(&self) -> &str {
110        or_default(&self.back_label, "Back")
111    }
112    /// The progress line, with `{n}` / `{total}` placeholders.
113    #[must_use]
114    pub fn progress_text(&self) -> &str {
115        or_default(&self.progress_label, "Step {n} of {total}")
116    }
117    /// The banner shown when the server refused the submission.
118    #[must_use]
119    pub fn error_text(&self) -> &str {
120        or_default(
121            &self.error_message,
122            "Your answers could not be sent. Please check the highlighted question and try again.",
123        )
124    }
125}
126
127const fn default_true() -> bool {
128    true
129}
130
131/// A wizard step.
132#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
133pub struct Page {
134    #[serde(default)]
135    pub id: String,
136    #[serde(default)]
137    pub label: String,
138    #[serde(default)]
139    pub sections: Vec<Section>,
140}
141
142/// A labelled grouping of rows within a page.
143#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
144pub struct Section {
145    #[serde(default)]
146    pub id: String,
147    #[serde(default)]
148    pub title: String,
149    #[serde(default)]
150    pub rows: Vec<Row>,
151}
152
153/// A 12-column grid row.
154#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
155pub struct Row {
156    #[serde(default)]
157    pub id: String,
158    #[serde(default)]
159    pub columns: Vec<Column>,
160}
161
162/// A grid cell holding fields. `width` is in 12ths.
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164pub struct Column {
165    #[serde(default)]
166    pub id: String,
167    #[serde(default = "default_width")]
168    pub width: u8,
169    #[serde(default)]
170    pub fields: Vec<Field>,
171}
172
173impl Default for Column {
174    fn default() -> Self {
175        Self {
176            id: String::new(),
177            width: default_width(),
178            fields: Vec::new(),
179        }
180    }
181}
182
183const fn default_width() -> u8 {
184    12
185}
186
187/// One input (or presentational element) in a column.
188#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
189pub struct Field {
190    #[serde(default)]
191    pub id: String,
192    /// Submission key — the `name` attribute and the `data_json` key.
193    /// Empty for presentational types (`static` / `richtext`).
194    #[serde(default)]
195    pub key: String,
196    #[serde(rename = "type", default)]
197    pub field_type: FieldType,
198    #[serde(default)]
199    pub label: String,
200    #[serde(default)]
201    pub help: String,
202    #[serde(default)]
203    pub required: bool,
204    #[serde(default)]
205    pub placeholder: String,
206    #[serde(default)]
207    pub default: String,
208    /// Choices for select / radio / checkboxes / multiselect.
209    #[serde(default)]
210    pub options: Vec<Choice>,
211    /// Validation rules.
212    #[serde(default)]
213    pub validation: Vec<ValidationRule>,
214    /// Conditional show/hide/require rules.
215    #[serde(default)]
216    pub rules: Vec<ConditionalRule>,
217    // ---- per-type config (omitted from JSON when unset) ----
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub min: Option<f64>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub max: Option<f64>,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub step: Option<f64>,
224    /// Accepted MIME/extension list for `file`.
225    #[serde(default, skip_serializing_if = "String::is_empty")]
226    pub accept: String,
227    /// Number of points for `rating`.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub scale: Option<u8>,
230    /// Static/richtext body (presentational types carry their content here).
231    #[serde(default, skip_serializing_if = "String::is_empty")]
232    pub content: String,
233    // ---- text validation (FB-13) ----
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub min_length: Option<u32>,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub max_length: Option<u32>,
238    /// Client-side HTML5 `pattern` (regex). Enforced in the browser; the
239    /// server enforces length + type-format checks.
240    #[serde(default, skip_serializing_if = "String::is_empty")]
241    pub pattern: String,
242}
243
244/// Server-side validation of one submitted value against a field's rules.
245/// Returns an error message, or `None` when valid. Empty values
246/// pass here — "required" is enforced separately by the submit handler.
247#[must_use]
248pub fn validate_value(field: &Field, value: &str) -> Option<String> {
249    let v = value.trim();
250    if v.is_empty() {
251        return None;
252    }
253    let name = if field.label.is_empty() {
254        &field.key
255    } else {
256        &field.label
257    };
258    let n = v.chars().count() as u32;
259    if let Some(min) = field.min_length {
260        if n < min {
261            return Some(format!("{name} must be at least {min} characters."));
262        }
263    }
264    if let Some(max) = field.max_length {
265        if n > max {
266            return Some(format!("{name} must be at most {max} characters."));
267        }
268    }
269    match field.field_type {
270        FieldType::Email => {
271            if !is_email_like(v) {
272                return Some(format!("{name} must be a valid email address."));
273            }
274        }
275        FieldType::Url => {
276            if !is_url_like(v) {
277                return Some(format!("{name} must be a valid URL."));
278            }
279        }
280        FieldType::Number => match v.parse::<f64>() {
281            Ok(num) => {
282                if let Some(min) = field.min {
283                    if num < min {
284                        return Some(format!("{name} must be ≥ {min}."));
285                    }
286                }
287                if let Some(max) = field.max {
288                    if num > max {
289                        return Some(format!("{name} must be ≤ {max}."));
290                    }
291                }
292            }
293            Err(_) => return Some(format!("{name} must be a number.")),
294        },
295        _ => {}
296    }
297    None
298}
299
300fn is_email_like(v: &str) -> bool {
301    match v.split_once('@') {
302        Some((local, domain)) => {
303            !local.is_empty()
304                && domain.contains('.')
305                && !domain.starts_with('.')
306                && !domain.ends_with('.')
307        }
308        None => false,
309    }
310}
311
312fn is_url_like(v: &str) -> bool {
313    v.starts_with("http://") || v.starts_with("https://") || v.starts_with('/')
314}
315
316// ===================================================================== i18n (FB-17)
317
318/// One translatable text leaf in a form, for the per-locale editor.
319#[derive(Debug, Clone, PartialEq, Serialize)]
320pub struct TransLeaf {
321    /// Stable `cms_snippet_translation.field_path` key (id-based).
322    pub path: String,
323    /// The field the text belongs to (its label, or its key when it has
324    /// none); empty for form-wide texts. The editor groups rows by it.
325    pub group: String,
326    /// Which text of the group this is: `submit`, `success`, `page`,
327    /// `section`, `label`, `help`, `ph`, `content` or `opt`. The editor
328    /// maps it to a translated row label.
329    pub part: &'static str,
330    /// 1-based option number for `opt`; 0 otherwise.
331    pub n: usize,
332    /// Canonical (default-locale) text.
333    pub text: String,
334}
335
336/// List every translatable text leaf in document order: settings messages,
337/// then page labels / section titles / field label+help+placeholder /
338/// choice option labels / presentational content. Keys are id-based so they
339/// survive reorder. A single-page form's page label is left out: it is
340/// never shown.
341#[must_use]
342pub fn translatable_leaves(form: &Form) -> Vec<TransLeaf> {
343    let mut out = Vec::new();
344    let mut push = |path: String, group: &str, part: &'static str, n: usize, text: &str| {
345        if !text.is_empty() {
346            out.push(TransLeaf {
347                path,
348                group: group.to_owned(),
349                part,
350                n,
351                text: text.to_owned(),
352            });
353        }
354    };
355    // The effective texts, defaults included: an untouched form still has a
356    // Submit button and a thanks message to translate.
357    let st = &form.settings;
358    push("settings.submit_label".into(), "", "submit", 0, st.submit_text());
359    push("settings.success_message".into(), "", "success", 0, st.success_text());
360    push("settings.error_message".into(), "", "error", 0, st.error_text());
361    let multi_page = form.pages.len() > 1;
362    if multi_page {
363        push("settings.next_label".into(), "", "next", 0, st.next_text());
364        push("settings.back_label".into(), "", "back", 0, st.back_text());
365        push("settings.progress_label".into(), "", "progress", 0, st.progress_text());
366    }
367    for page in &form.pages {
368        if multi_page {
369            push(format!("page.{}.label", page.id), "", "page", 0, &page.label);
370        }
371        for section in &page.sections {
372            push(format!("section.{}.title", section.id), "", "section", 0, &section.title);
373            for row in &section.rows {
374                for col in &row.columns {
375                    for f in &col.fields {
376                        let name = if f.label.is_empty() {
377                            f.key.as_str()
378                        } else {
379                            f.label.as_str()
380                        };
381                        push(format!("{}.label", f.id), name, "label", 0, &f.label);
382                        push(format!("{}.help", f.id), name, "help", 0, &f.help);
383                        push(format!("{}.ph", f.id), name, "ph", 0, &f.placeholder);
384                        push(format!("{}.content", f.id), name, "content", 0, &f.content);
385                        for (i, opt) in f.options.iter().enumerate() {
386                            push(format!("{}.opt.{i}", f.id), name, "opt", i + 1, &opt.label);
387                        }
388                    }
389                }
390            }
391        }
392    }
393    out
394}
395
396/// Apply per-locale `overrides` (field_path → text) to a form's text leaves,
397/// in place. Missing/empty overrides leave the canonical text. Mirror of the
398/// keys produced by [`translatable_leaves`].
399pub fn apply_translations(form: &mut Form, overrides: &std::collections::HashMap<String, String>) {
400    if overrides.is_empty() {
401        return;
402    }
403    let get = |path: &str| overrides.get(path).filter(|v| !v.is_empty()).cloned();
404    if let Some(v) = get("settings.submit_label") {
405        form.settings.submit_label = v;
406    }
407    if let Some(v) = get("settings.success_message") {
408        form.settings.success_message = v;
409    }
410    if let Some(v) = get("settings.error_message") {
411        form.settings.error_message = v;
412    }
413    if let Some(v) = get("settings.next_label") {
414        form.settings.next_label = v;
415    }
416    if let Some(v) = get("settings.back_label") {
417        form.settings.back_label = v;
418    }
419    if let Some(v) = get("settings.progress_label") {
420        form.settings.progress_label = v;
421    }
422    for page in &mut form.pages {
423        if let Some(v) = get(&format!("page.{}.label", page.id)) {
424            page.label = v;
425        }
426        for section in &mut page.sections {
427            if let Some(v) = get(&format!("section.{}.title", section.id)) {
428                section.title = v;
429            }
430            for row in &mut section.rows {
431                for col in &mut row.columns {
432                    for f in &mut col.fields {
433                        if let Some(v) = get(&format!("{}.label", f.id)) {
434                            f.label = v;
435                        }
436                        if let Some(v) = get(&format!("{}.help", f.id)) {
437                            f.help = v;
438                        }
439                        if let Some(v) = get(&format!("{}.ph", f.id)) {
440                            f.placeholder = v;
441                        }
442                        if let Some(v) = get(&format!("{}.content", f.id)) {
443                            f.content = v;
444                        }
445                        for (i, opt) in f.options.iter_mut().enumerate() {
446                            if let Some(v) = get(&format!("{}.opt.{i}", f.id)) {
447                                opt.label = v;
448                            }
449                        }
450                    }
451                }
452            }
453        }
454    }
455}
456
457// ===================================================================== conditional logic (FB-14)
458
459/// Whether `field` is visible given the current `answers` (key → value).
460/// Rules apply in order: a `show` rule makes visibility equal to its match;
461/// a `hide` rule hides when matched. No rules → always visible. The runtime
462/// (`form_runtime`) mirrors this logic in JS; the server uses it so hidden
463/// fields are excused from "required".
464#[must_use]
465pub fn is_visible(field: &Field, answers: &std::collections::HashMap<String, Vec<String>>) -> bool {
466    let mut visible = true;
467    for rule in &field.rules {
468        let matched = eval_conditions(rule, answers);
469        match rule.action.as_str() {
470            "show" => visible = matched,
471            "hide" => {
472                if matched {
473                    visible = false;
474                }
475            }
476            _ => {}
477        }
478    }
479    visible
480}
481
482fn eval_conditions(
483    rule: &ConditionalRule,
484    answers: &std::collections::HashMap<String, Vec<String>>,
485) -> bool {
486    if rule.conditions.is_empty() {
487        return true;
488    }
489    let any = rule.match_mode == "any";
490    if any {
491        rule.conditions.iter().any(|c| eval_condition(c, answers))
492    } else {
493        rule.conditions.iter().all(|c| eval_condition(c, answers))
494    }
495}
496
497/// A checkbox group or multi-select has several answers: `eq` / `contains`
498/// match when any of them does, `ne` when none equals the value.
499fn eval_condition(c: &Condition, answers: &std::collections::HashMap<String, Vec<String>>) -> bool {
500    let actual: Vec<&str> = answers
501        .get(&c.field)
502        .map(|v| v.iter().map(String::as_str).filter(|a| !a.is_empty()).collect())
503        .unwrap_or_default();
504    match c.op.as_str() {
505        "eq" => actual.iter().any(|a| *a == c.value),
506        "ne" => !actual.iter().any(|a| *a == c.value),
507        "contains" => actual.iter().any(|a| a.contains(c.value.as_str())),
508        "empty" => actual.is_empty(),
509        "not_empty" => !actual.is_empty(),
510        _ => true,
511    }
512}
513
514/// A choice option for selection field types.
515#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
516pub struct Choice {
517    #[serde(default)]
518    pub value: String,
519    #[serde(default)]
520    pub label: String,
521    /// The label in other languages, by locale code (`{"fr": "Bleu lune"}`).
522    /// Page-type select options use it; forms translate through
523    /// `cms_snippet_translation` instead. Empty → the `label` everywhere.
524    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
525    pub labels: std::collections::BTreeMap<String, String>,
526}
527
528impl Choice {
529    /// The label to show in `locale` (a locale code): its translation,
530    /// else the label, else the stored value.
531    #[must_use]
532    pub fn label_in(&self, locale: Option<&str>) -> &str {
533        locale
534            .and_then(|code| self.labels.get(code))
535            .map(String::as_str)
536            .filter(|l| !l.is_empty())
537            .or(Some(self.label.as_str()).filter(|l| !l.is_empty()))
538            .unwrap_or(&self.value)
539    }
540}
541
542/// A validation rule (this is the storage shape).
543#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
544pub struct ValidationRule {
545    /// e.g. `min_length`, `max_length`, `pattern`, `email`, `min`, `max`.
546    pub rule: String,
547    #[serde(default)]
548    pub param: String,
549    #[serde(default)]
550    pub message: String,
551}
552
553/// A conditional rule (this is the storage shape).
554#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
555pub struct ConditionalRule {
556    /// `all` (default) or `any` — how to combine `conditions`.
557    #[serde(default, rename = "match")]
558    pub match_mode: String,
559    #[serde(default)]
560    pub conditions: Vec<Condition>,
561    /// `show`, `hide`, `require`, `optional`, `set_value`.
562    #[serde(default)]
563    pub action: String,
564    /// Argument for `set_value`.
565    #[serde(default)]
566    pub value: String,
567}
568
569/// One predicate of a [`ConditionalRule`].
570#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
571pub struct Condition {
572    /// The key of the field this condition reads.
573    #[serde(default)]
574    pub field: String,
575    /// `eq`, `ne`, `contains`, `gt`, `lt`, `empty`, `not_empty`.
576    #[serde(default)]
577    pub op: String,
578    #[serde(default)]
579    pub value: String,
580}
581
582/// Every field/input type the builder offers.
583#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
584#[serde(rename_all = "snake_case")]
585pub enum FieldType {
586    #[default]
587    Text,
588    Textarea,
589    Email,
590    Url,
591    Tel,
592    Number,
593    Date,
594    Datetime,
595    Time,
596    Select,
597    Radio,
598    /// Single boolean checkbox.
599    Checkbox,
600    /// Multi-select checkbox group.
601    Checkboxes,
602    Multiselect,
603    File,
604    Rating,
605    Hidden,
606    /// Presentational heading / message (no submitted value).
607    Static,
608    /// Presentational rich-text message (no submitted value).
609    Richtext,
610}
611
612impl FieldType {
613    /// Stable wire string (matches the serde representation).
614    #[must_use]
615    pub fn as_str(self) -> &'static str {
616        match self {
617            FieldType::Text => "text",
618            FieldType::Textarea => "textarea",
619            FieldType::Email => "email",
620            FieldType::Url => "url",
621            FieldType::Tel => "tel",
622            FieldType::Number => "number",
623            FieldType::Date => "date",
624            FieldType::Datetime => "datetime",
625            FieldType::Time => "time",
626            FieldType::Select => "select",
627            FieldType::Radio => "radio",
628            FieldType::Checkbox => "checkbox",
629            FieldType::Checkboxes => "checkboxes",
630            FieldType::Multiselect => "multiselect",
631            FieldType::File => "file",
632            FieldType::Rating => "rating",
633            FieldType::Hidden => "hidden",
634            FieldType::Static => "static",
635            FieldType::Richtext => "richtext",
636        }
637    }
638
639    /// True when the type submits a value (i.e. needs a `key` and shows up
640    /// in submissions). Presentational types return false.
641    #[must_use]
642    pub fn collects_value(self) -> bool {
643        !matches!(self, FieldType::Static | FieldType::Richtext)
644    }
645
646    /// True for types whose submitted value is a list (checkbox group /
647    /// multi-select), which the submit handler collects into a JSON array.
648    #[must_use]
649    pub fn is_multi_value(self) -> bool {
650        matches!(self, FieldType::Checkboxes | FieldType::Multiselect)
651    }
652
653    /// True for types that draw from a fixed `options` list.
654    #[must_use]
655    pub fn has_choices(self) -> bool {
656        matches!(
657            self,
658            FieldType::Select | FieldType::Radio | FieldType::Checkboxes | FieldType::Multiselect
659        )
660    }
661}
662
663// ===================================================================== parse / serialize
664
665/// Parse a form from a snippet `data` JSON value. Missing keys default,
666/// so a partial/empty `{}` yields an empty form rather than an error.
667pub fn parse(value: &serde_json::Value) -> Result<Form, serde_json::Error> {
668    serde_json::from_value(value.clone())
669}
670
671/// Parse from a JSON string (e.g. a hidden builder input).
672pub fn parse_str(s: &str) -> Result<Form, serde_json::Error> {
673    if s.trim().is_empty() {
674        return Ok(Form::default());
675    }
676    serde_json::from_str(s)
677}
678
679// ===================================================================== draft / publish (FB-15)
680//
681// The snippet `data` top level is the PUBLISHED form (what the public render
682// reads — `parse` ignores the extra `_draft` key). The builder edits a DRAFT
683// stored under `data._draft`; Publish copies the draft up to the top level.
684
685/// Parse the DRAFT a builder should edit: `data._draft` when present, else
686/// the published top level (forms predating draft/publish edit live).
687#[must_use]
688pub fn parse_draft(data: &serde_json::Value) -> Form {
689    if let Some(d) = data.get("_draft") {
690        if d.is_object() {
691            return parse(d).unwrap_or_default();
692        }
693    }
694    parse(data).unwrap_or_default()
695}
696
697/// Produce new `data` that stores `draft` under `_draft` while leaving the
698/// published top level untouched. Save-draft path.
699#[must_use]
700pub fn save_draft_value(current: &serde_json::Value, draft: &Form) -> serde_json::Value {
701    let mut out = match current {
702        serde_json::Value::Object(_) => current.clone(),
703        _ => serde_json::Value::Object(serde_json::Map::new()),
704    };
705    if let serde_json::Value::Object(map) = &mut out {
706        map.insert("_draft".to_owned(), to_value(draft));
707    }
708    out
709}
710
711/// Produce new `data` that publishes `draft`: top level := draft, and
712/// `_draft` := the same (so editing continues from the published state).
713#[must_use]
714pub fn publish_value(draft: &Form) -> serde_json::Value {
715    let mut out = to_value(draft);
716    if let serde_json::Value::Object(map) = &mut out {
717        map.insert("_draft".to_owned(), to_value(draft));
718    }
719    out
720}
721
722/// True when the draft differs from the published top level.
723#[must_use]
724pub fn has_unpublished_changes(data: &serde_json::Value) -> bool {
725    data.get("_draft")
726        .is_some_and(|_| parse_draft(data) != parse(data).unwrap_or_default())
727}
728
729/// Serialize a form back to a JSON value for storage in `snippet.data`.
730///
731/// # Panics
732/// Never in practice — the schema types are plain data and always serialize.
733#[must_use]
734pub fn to_value(form: &Form) -> serde_json::Value {
735    serde_json::to_value(form).unwrap_or(serde_json::Value::Null)
736}
737
738// ===================================================================== traversal
739
740impl Form {
741    /// Sanitize the HTML of every rich-text field in place, with the same
742    /// policy Markdown and rich-text blocks use. Applied to what is stored
743    /// and to what the builder is handed, so no admin surface receives raw
744    /// author HTML; the public render sanitizes again on its own.
745    pub fn sanitize_rich_text(&mut self) {
746        for page in &mut self.pages {
747            for section in &mut page.sections {
748                for row in &mut section.rows {
749                    for col in &mut row.columns {
750                        for f in &mut col.fields {
751                            if matches!(f.field_type, FieldType::Richtext) {
752                                f.content = crate::markdown::sanitize_html(&f.content);
753                            }
754                        }
755                    }
756                }
757            }
758        }
759    }
760
761    /// Iterate every field across all pages/sections/rows/columns, in
762    /// document order.
763    pub fn fields(&self) -> impl Iterator<Item = &Field> {
764        self.pages.iter().flat_map(|p| {
765            p.sections.iter().flat_map(|s| {
766                s.rows
767                    .iter()
768                    .flat_map(|r| r.columns.iter().flat_map(|c| c.fields.iter()))
769            })
770        })
771    }
772
773    /// Ordered list of submission keys for value-collecting fields —
774    /// the column order for the submissions table / CSV.
775    #[must_use]
776    pub fn value_keys(&self) -> Vec<String> {
777        self.fields()
778            .filter(|f| f.field_type.collects_value() && !f.key.is_empty())
779            .map(|f| f.key.clone())
780            .collect()
781    }
782
783    /// Find a value-collecting field by its key.
784    #[must_use]
785    pub fn field_by_key(&self, key: &str) -> Option<&Field> {
786        self.fields().find(|f| f.key == key)
787    }
788
789    #[must_use]
790    pub fn page_count(&self) -> usize {
791        self.pages.len()
792    }
793
794    #[must_use]
795    pub fn field_count(&self) -> usize {
796        self.fields()
797            .filter(|f| f.field_type.collects_value())
798            .count()
799    }
800}
801
802// ===================================================================== validation
803
804/// Validate a form for save. Returns a list of human-readable problems
805/// (empty = valid). Non-fatal in the builder UI; the save handler may
806/// surface these as field errors.
807#[must_use]
808pub fn validate(form: &Form) -> Vec<String> {
809    let mut errors = Vec::new();
810
811    if form.pages.is_empty() {
812        errors.push("A form needs at least one page.".to_owned());
813    }
814
815    // Column widths.
816    for (pi, page) in form.pages.iter().enumerate() {
817        for section in &page.sections {
818            for row in &section.rows {
819                for col in &row.columns {
820                    if col.width < 1 || col.width > 12 {
821                        errors.push(format!(
822                            "Page {} has a column with width {} (must be 1–12).",
823                            pi + 1,
824                            col.width
825                        ));
826                    }
827                }
828            }
829        }
830    }
831
832    // Field keys: value-collecting fields need a unique, valid key.
833    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
834    for field in form.fields() {
835        if !field.field_type.collects_value() {
836            continue;
837        }
838        if field.key.is_empty() {
839            errors.push(format!(
840                "Field \"{}\" ({}) needs a key.",
841                if field.label.is_empty() {
842                    "untitled"
843                } else {
844                    &field.label
845                },
846                field.field_type.as_str()
847            ));
848            continue;
849        }
850        if !is_valid_key(&field.key) {
851            errors.push(format!(
852                "Field key \"{}\" is invalid (use letters, digits, underscores; start with a letter).",
853                field.key
854            ));
855        }
856        if !seen.insert(field.key.as_str()) {
857            errors.push(format!("Duplicate field key \"{}\".", field.key));
858        }
859    }
860
861    errors
862}
863
864/// A field key must be a simple identifier: `[A-Za-z][A-Za-z0-9_]*`.
865#[must_use]
866pub fn is_valid_key(key: &str) -> bool {
867    let mut chars = key.chars();
868    match chars.next() {
869        Some(c) if c.is_ascii_alphabetic() => {}
870        _ => return false,
871    }
872    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
873}
874
875/// Derive a valid field key from a human label (builder auto-slug helper).
876/// Lowercases, replaces runs of non-alphanumerics with `_`, and ensures
877/// it starts with a letter. Returns `field` when nothing usable remains.
878#[must_use]
879pub fn slugify_key(label: &str) -> String {
880    let mut out = String::with_capacity(label.len());
881    let mut prev_us = false;
882    for c in label.chars() {
883        if c.is_ascii_alphanumeric() {
884            out.push(c.to_ascii_lowercase());
885            prev_us = false;
886        } else if !prev_us {
887            out.push('_');
888            prev_us = true;
889        }
890    }
891    let trimmed = out.trim_matches('_');
892    let candidate = if trimmed.is_empty() { "field" } else { trimmed };
893    if candidate
894        .chars()
895        .next()
896        .is_some_and(|c| c.is_ascii_alphabetic())
897    {
898        candidate.to_owned()
899    } else {
900        format!("f_{candidate}")
901    }
902}
903
904#[cfg(test)]
905mod tests {
906    use super::*;
907    use serde_json::json;
908
909    fn sample() -> Form {
910        Form {
911            settings: FormSettings {
912                submit_label: "Send".into(),
913                success_message: "Thanks!".into(),
914                ..Default::default()
915            },
916            pages: vec![Page {
917                id: "p1".into(),
918                label: "Page 1".into(),
919                sections: vec![Section {
920                    id: "s1".into(),
921                    title: "Contact".into(),
922                    rows: vec![Row {
923                        id: "r1".into(),
924                        columns: vec![
925                            Column {
926                                id: "c1".into(),
927                                width: 6,
928                                fields: vec![Field {
929                                    id: "f1".into(),
930                                    key: "name".into(),
931                                    field_type: FieldType::Text,
932                                    label: "Name".into(),
933                                    required: true,
934                                    ..Default::default()
935                                }],
936                            },
937                            Column {
938                                id: "c2".into(),
939                                width: 6,
940                                fields: vec![Field {
941                                    id: "f2".into(),
942                                    key: "email".into(),
943                                    field_type: FieldType::Email,
944                                    label: "Email".into(),
945                                    required: true,
946                                    ..Default::default()
947                                }],
948                            },
949                        ],
950                    }],
951                }],
952            }],
953        }
954    }
955
956    #[test]
957    fn round_trip_preserves_form() {
958        let form = sample();
959        let value = to_value(&form);
960        let back = parse(&value).expect("parse");
961        assert_eq!(form, back);
962    }
963
964    #[test]
965    fn empty_and_partial_json_default() {
966        assert_eq!(parse(&json!({})).unwrap(), Form::default());
967        assert_eq!(parse_str("").unwrap(), Form::default());
968        let partial = parse(&json!({"pages": [{"label": "Only"}]})).unwrap();
969        assert_eq!(partial.pages.len(), 1);
970        assert_eq!(partial.pages[0].label, "Only");
971        // Column width defaults to 12 when omitted.
972        let c: Column = serde_json::from_value(json!({})).unwrap();
973        assert_eq!(c.width, 12);
974    }
975
976    #[test]
977    fn field_type_serializes_snake_case() {
978        assert_eq!(
979            serde_json::to_value(FieldType::Multiselect).unwrap(),
980            json!("multiselect")
981        );
982        let f: Field = serde_json::from_value(json!({"key": "x", "type": "checkboxes"})).unwrap();
983        assert_eq!(f.field_type, FieldType::Checkboxes);
984        assert!(f.field_type.is_multi_value());
985        assert!(f.field_type.has_choices());
986    }
987
988    #[test]
989    fn value_keys_skip_presentational_and_order_is_document() {
990        let mut form = sample();
991        // Insert a static heading before the inputs — must not appear in keys.
992        form.pages[0].sections[0].rows[0].columns[0].fields.insert(
993            0,
994            Field {
995                id: "h".into(),
996                field_type: FieldType::Static,
997                content: "Hi".into(),
998                ..Default::default()
999            },
1000        );
1001        assert_eq!(form.value_keys(), vec!["name", "email"]);
1002        assert_eq!(form.field_count(), 2);
1003        assert_eq!(form.page_count(), 1);
1004    }
1005
1006    #[test]
1007    fn validate_accepts_good_form() {
1008        assert!(validate(&sample()).is_empty());
1009    }
1010
1011    #[test]
1012    fn validate_flags_duplicate_and_bad_keys() {
1013        let mut form = sample();
1014        // duplicate key
1015        form.pages[0].sections[0].rows[0].columns[1].fields[0].key = "name".into();
1016        let errs = validate(&form);
1017        assert!(
1018            errs.iter().any(|e| e.contains("Duplicate field key")),
1019            "{errs:?}"
1020        );
1021
1022        let mut form2 = sample();
1023        form2.pages[0].sections[0].rows[0].columns[0].fields[0].key = "1bad".into();
1024        assert!(validate(&form2).iter().any(|e| e.contains("invalid")));
1025    }
1026
1027    #[test]
1028    fn validate_flags_bad_width_and_no_pages() {
1029        let mut form = sample();
1030        form.pages[0].sections[0].rows[0].columns[0].width = 0;
1031        assert!(validate(&form).iter().any(|e| e.contains("width")));
1032        assert!(validate(&Form::default())
1033            .iter()
1034            .any(|e| e.contains("at least one page")));
1035    }
1036
1037    #[test]
1038    fn presentational_field_without_key_is_ok() {
1039        let mut form = sample();
1040        form.pages[0].sections[0].rows[0].columns[0]
1041            .fields
1042            .push(Field {
1043                id: "msg".into(),
1044                field_type: FieldType::Richtext,
1045                content: "<p>hi</p>".into(),
1046                ..Default::default()
1047            });
1048        assert!(validate(&form).is_empty());
1049    }
1050
1051    #[test]
1052    fn validate_value_rules() {
1053        let mut f = Field {
1054            key: "x".into(),
1055            field_type: FieldType::Text,
1056            label: "X".into(),
1057            ..Default::default()
1058        };
1059        f.min_length = Some(3);
1060        f.max_length = Some(5);
1061        assert!(validate_value(&f, "").is_none()); // empty passes (required handled elsewhere)
1062        assert!(validate_value(&f, "ab").unwrap().contains("at least 3"));
1063        assert!(validate_value(&f, "abcdef").unwrap().contains("at most 5"));
1064        assert!(validate_value(&f, "abcd").is_none());
1065
1066        let email = Field {
1067            key: "e".into(),
1068            field_type: FieldType::Email,
1069            label: "E".into(),
1070            ..Default::default()
1071        };
1072        assert!(validate_value(&email, "nope").is_some());
1073        assert!(validate_value(&email, "a@b.com").is_none());
1074
1075        let mut num = Field {
1076            key: "n".into(),
1077            field_type: FieldType::Number,
1078            label: "N".into(),
1079            ..Default::default()
1080        };
1081        num.min = Some(1.0);
1082        num.max = Some(10.0);
1083        assert!(validate_value(&num, "abc").unwrap().contains("number"));
1084        assert!(validate_value(&num, "0").unwrap().contains("≥"));
1085        assert!(validate_value(&num, "11").unwrap().contains("≤"));
1086        assert!(validate_value(&num, "5").is_none());
1087    }
1088
1089    #[test]
1090    fn draft_publish_round_trip() {
1091        let published = sample();
1092        let data = to_value(&published);
1093        // No _draft yet → draft == published; no unpublished changes.
1094        assert_eq!(parse_draft(&data), published);
1095        assert!(!has_unpublished_changes(&data));
1096
1097        // Save a draft with a changed title — published top level untouched.
1098        let mut draft = published.clone();
1099        draft.settings.submit_label = "Changed".into();
1100        let with_draft = save_draft_value(&data, &draft);
1101        assert_eq!(parse(&with_draft).unwrap().settings.submit_label, "Send"); // published
1102        assert_eq!(parse_draft(&with_draft).settings.submit_label, "Changed"); // draft
1103        assert!(has_unpublished_changes(&with_draft));
1104
1105        // Publish → top level becomes the draft.
1106        let published_data = publish_value(&draft);
1107        assert_eq!(
1108            parse(&published_data).unwrap().settings.submit_label,
1109            "Changed"
1110        );
1111        assert!(!has_unpublished_changes(&published_data));
1112    }
1113
1114    #[test]
1115    fn choice_label_falls_back_translation_label_value() {
1116        let mut c = Choice {
1117            value: "moon-blue".into(),
1118            label: "Moon blue".into(),
1119            ..Default::default()
1120        };
1121        c.labels.insert("fr".into(), "Bleu lune".into());
1122        c.labels.insert("de".into(), String::new());
1123        assert_eq!(c.label_in(Some("fr")), "Bleu lune");
1124        assert_eq!(c.label_in(Some("de")), "Moon blue"); // empty = untranslated
1125        assert_eq!(c.label_in(None), "Moon blue");
1126        c.label.clear();
1127        assert_eq!(c.label_in(None), "moon-blue");
1128        // Untranslated options keep the old storage shape.
1129        let plain = Choice { value: "a".into(), label: "A".into(), ..Default::default() };
1130        assert_eq!(serde_json::to_value(&plain).unwrap(), serde_json::json!({"value": "a", "label": "A"}));
1131    }
1132
1133    #[test]
1134    fn i18n_leaves_and_apply() {
1135        use std::collections::HashMap;
1136        let form = sample();
1137        let leaves = translatable_leaves(&form);
1138        // field labels present, keyed by field id
1139        assert!(leaves
1140            .iter()
1141            .any(|l| l.path == "f1.label" && l.text == "Name"));
1142        assert!(leaves
1143            .iter()
1144            .any(|l| l.path == "f2.label" && l.text == "Email"));
1145        // grouped by field, tagged by part; a one-page form has no page row
1146        assert!(leaves
1147            .iter()
1148            .any(|l| l.path == "f1.label" && l.group == "Name" && l.part == "label"));
1149        assert_eq!(form.pages.len(), 1);
1150        assert!(leaves.iter().all(|l| l.part != "page"));
1151        // The defaults are translatable too; paging texts only on multi-page forms.
1152        assert!(leaves.iter().any(|l| l.part == "submit"));
1153        let bare = Form { pages: form.pages.clone(), ..Default::default() };
1154        assert!(translatable_leaves(&bare).iter().any(|l| l.part == "submit" && l.text == "Submit"));
1155        assert!(leaves.iter().any(|l| l.part == "error"));
1156        assert!(leaves.iter().all(|l| l.part != "next"));
1157        let mut paged = form.clone();
1158        paged.pages.push(Page { id: "p2".into(), label: "Two".into(), ..Default::default() });
1159        let paged_leaves = translatable_leaves(&paged);
1160        assert!(paged_leaves.iter().any(|l| l.path == "settings.progress_label" && l.text == "Step {n} of {total}"));
1161
1162        let mut t = HashMap::new();
1163        t.insert("f1.label".to_owned(), "Nom".to_owned());
1164        t.insert("settings.submit_label".to_owned(), "Envoyer".to_owned());
1165        let mut fr = form.clone();
1166        apply_translations(&mut fr, &t);
1167        assert_eq!(fr.field_by_key("name").unwrap().label, "Nom");
1168        assert_eq!(fr.field_by_key("email").unwrap().label, "Email"); // untouched
1169        assert_eq!(fr.settings.submit_label, "Envoyer");
1170        t.insert("settings.next_label".to_owned(), "Suivant".to_owned());
1171        apply_translations(&mut fr, &t);
1172        assert_eq!(fr.settings.next_text(), "Suivant");
1173    }
1174
1175    #[test]
1176    fn conditional_visibility() {
1177        use std::collections::HashMap;
1178        let mut field = Field {
1179            key: "extra".into(),
1180            field_type: FieldType::Text,
1181            required: true,
1182            ..Default::default()
1183        };
1184        field.rules = vec![ConditionalRule {
1185            match_mode: "all".into(),
1186            conditions: vec![Condition {
1187                field: "kind".into(),
1188                op: "eq".into(),
1189                value: "other".into(),
1190            }],
1191            action: "show".into(),
1192            value: String::new(),
1193        }];
1194        let mut a = HashMap::new();
1195        a.insert("kind".to_owned(), vec!["standard".to_owned()]);
1196        assert!(!is_visible(&field, &a)); // show-rule unmatched → hidden
1197        a.insert("kind".to_owned(), vec!["other".to_owned()]);
1198        assert!(is_visible(&field, &a)); // matched → visible
1199        // A checkbox group matches when any ticked box does.
1200        a.insert("kind".to_owned(), vec!["standard".to_owned(), "other".to_owned()]);
1201        assert!(is_visible(&field, &a));
1202        field.rules[0].conditions[0].op = "ne".into();
1203        assert!(!is_visible(&field, &a), "ne: none may equal");
1204        field.rules[0].conditions[0].op = "eq".into();
1205
1206        // hide rule
1207        field.rules[0].action = "hide".into();
1208        assert!(!is_visible(&field, &a)); // matched hide → hidden
1209        let empty = HashMap::new();
1210        assert!(is_visible(&field, &empty)); // unmatched hide → visible
1211    }
1212
1213    #[test]
1214    fn is_valid_key_table() {
1215        assert!(is_valid_key("name"));
1216        assert!(is_valid_key("first_name2"));
1217        assert!(!is_valid_key("2name"));
1218        assert!(!is_valid_key("first-name"));
1219        assert!(!is_valid_key(""));
1220        assert!(!is_valid_key("has space"));
1221    }
1222
1223    #[test]
1224    fn slugify_key_table() {
1225        assert_eq!(slugify_key("First Name"), "first_name");
1226        assert_eq!(slugify_key("  Email  "), "email");
1227        assert_eq!(slugify_key("Café déjà"), "caf_d_j"); // non-ascii dropped
1228        assert_eq!(slugify_key("123"), "f_123");
1229        assert_eq!(slugify_key("!!!"), "field");
1230    }
1231}