1use serde::{Deserialize, Serialize};
26
27#[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#[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 #[serde(default)]
48 pub notify_emails: String,
49 #[serde(default = "default_true")]
52 pub builtin_css: bool,
53 #[serde(default)]
56 pub next_label: String,
57 #[serde(default)]
58 pub back_label: String,
59 #[serde(default)]
61 pub progress_label: String,
62 #[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 #[must_use]
94 pub fn submit_text(&self) -> &str {
95 or_default(&self.submit_label, "Submit")
96 }
97 #[must_use]
99 pub fn success_text(&self) -> &str {
100 or_default(&self.success_message, "Thanks! Your submission was received.")
101 }
102 #[must_use]
104 pub fn next_text(&self) -> &str {
105 or_default(&self.next_label, "Next")
106 }
107 #[must_use]
109 pub fn back_text(&self) -> &str {
110 or_default(&self.back_label, "Back")
111 }
112 #[must_use]
114 pub fn progress_text(&self) -> &str {
115 or_default(&self.progress_label, "Step {n} of {total}")
116 }
117 #[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#[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#[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#[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#[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
189pub struct Field {
190 #[serde(default)]
191 pub id: String,
192 #[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 #[serde(default)]
210 pub options: Vec<Choice>,
211 #[serde(default)]
213 pub validation: Vec<ValidationRule>,
214 #[serde(default)]
216 pub rules: Vec<ConditionalRule>,
217 #[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 #[serde(default, skip_serializing_if = "String::is_empty")]
226 pub accept: String,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub scale: Option<u8>,
230 #[serde(default, skip_serializing_if = "String::is_empty")]
232 pub content: String,
233 #[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 #[serde(default, skip_serializing_if = "String::is_empty")]
241 pub pattern: String,
242}
243
244#[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#[derive(Debug, Clone, PartialEq, Serialize)]
320pub struct TransLeaf {
321 pub path: String,
323 pub group: String,
326 pub part: &'static str,
330 pub n: usize,
332 pub text: String,
334}
335
336#[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 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, §ion.title);
373 for row in §ion.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
396pub 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#[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
497fn 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#[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 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
525 pub labels: std::collections::BTreeMap<String, String>,
526}
527
528impl Choice {
529 #[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
544pub struct ValidationRule {
545 pub rule: String,
547 #[serde(default)]
548 pub param: String,
549 #[serde(default)]
550 pub message: String,
551}
552
553#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
555pub struct ConditionalRule {
556 #[serde(default, rename = "match")]
558 pub match_mode: String,
559 #[serde(default)]
560 pub conditions: Vec<Condition>,
561 #[serde(default)]
563 pub action: String,
564 #[serde(default)]
566 pub value: String,
567}
568
569#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
571pub struct Condition {
572 #[serde(default)]
574 pub field: String,
575 #[serde(default)]
577 pub op: String,
578 #[serde(default)]
579 pub value: String,
580}
581
582#[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 Checkbox,
600 Checkboxes,
602 Multiselect,
603 File,
604 Rating,
605 Hidden,
606 Static,
608 Richtext,
610}
611
612impl FieldType {
613 #[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 #[must_use]
642 pub fn collects_value(self) -> bool {
643 !matches!(self, FieldType::Static | FieldType::Richtext)
644 }
645
646 #[must_use]
649 pub fn is_multi_value(self) -> bool {
650 matches!(self, FieldType::Checkboxes | FieldType::Multiselect)
651 }
652
653 #[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
663pub fn parse(value: &serde_json::Value) -> Result<Form, serde_json::Error> {
668 serde_json::from_value(value.clone())
669}
670
671pub 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#[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#[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#[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#[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#[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
738impl Form {
741 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 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 #[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 #[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#[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 for (pi, page) in form.pages.iter().enumerate() {
817 for section in &page.sections {
818 for row in §ion.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 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#[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#[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 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 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 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()); 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 assert_eq!(parse_draft(&data), published);
1095 assert!(!has_unpublished_changes(&data));
1096
1097 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"); assert_eq!(parse_draft(&with_draft).settings.submit_label, "Changed"); assert!(has_unpublished_changes(&with_draft));
1104
1105 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"); assert_eq!(c.label_in(None), "Moon blue");
1126 c.label.clear();
1127 assert_eq!(c.label_in(None), "moon-blue");
1128 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 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 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 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"); 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)); a.insert("kind".to_owned(), vec!["other".to_owned()]);
1198 assert!(is_visible(&field, &a)); 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 field.rules[0].action = "hide".into();
1208 assert!(!is_visible(&field, &a)); let empty = HashMap::new();
1210 assert!(is_visible(&field, &empty)); }
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"); assert_eq!(slugify_key("123"), "f_123");
1229 assert_eq!(slugify_key("!!!"), "field");
1230 }
1231}