1use std::collections::{HashMap, HashSet};
31
32use serde::{Deserialize, Serialize};
33
34use crate::forms::schema::{is_valid_key, Choice, ConditionalRule};
35use crate::widget::WidgetKind;
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(tag = "kind", rename_all = "snake_case")]
40pub enum Node {
41 Field(FieldNode),
42 Row(RowNode),
43 Group(GroupNode),
44 Component(ComponentNode),
45 Repeater(RepeaterNode),
46 Flex(FlexNode),
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct FieldNode {
53 #[serde(default)]
56 pub id: String,
57 pub key: String,
58 #[serde(default)]
59 pub label: String,
60 #[serde(default = "default_widget")]
61 pub widget: WidgetKind,
62 #[serde(default)]
63 pub help: String,
64 #[serde(default)]
65 pub placeholder: String,
66 #[serde(default, rename = "default")]
68 pub default_value: String,
69 #[serde(default)]
70 pub required: bool,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub width: Option<u8>,
74 #[serde(default, skip_serializing_if = "Vec::is_empty")]
75 pub options: Vec<Choice>,
76 #[serde(default, skip_serializing_if = "Vec::is_empty")]
78 pub rules: Vec<ConditionalRule>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub min: Option<f64>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub max: Option<f64>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub step: Option<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub min_length: Option<u32>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub max_length: Option<u32>,
89 #[serde(default)]
90 pub pattern: String,
91}
92
93fn default_widget() -> WidgetKind {
94 WidgetKind::Text
95}
96
97impl Default for FieldNode {
98 fn default() -> Self {
99 Self {
100 id: String::new(),
101 key: String::new(),
102 label: String::new(),
103 widget: WidgetKind::Text,
104 help: String::new(),
105 placeholder: String::new(),
106 default_value: String::new(),
107 required: false,
108 width: None,
109 options: Vec::new(),
110 rules: Vec::new(),
111 min: None,
112 max: None,
113 step: None,
114 min_length: None,
115 max_length: None,
116 pattern: String::new(),
117 }
118 }
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize, Default)]
123pub struct RowNode {
124 #[serde(default)]
125 pub id: String,
126 #[serde(default)]
127 pub children: Vec<Node>,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize, Default)]
133pub struct GroupNode {
134 #[serde(default)]
135 pub id: String,
136 pub key: String,
137 #[serde(default)]
138 pub label: String,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub icon: Option<String>,
141 #[serde(default)]
142 pub children: Vec<Node>,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize, Default)]
148pub struct ComponentNode {
149 #[serde(default)]
150 pub id: String,
151 #[serde(rename = "ref")]
152 pub reference: String,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub key: Option<String>,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize, Default)]
159pub struct RepeaterNode {
160 #[serde(default)]
161 pub id: String,
162 pub key: String,
163 #[serde(default)]
164 pub label: String,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub min: Option<u32>,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub max: Option<u32>,
169 pub item: GroupDef,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize, Default)]
177pub struct FlexNode {
178 #[serde(default)]
179 pub id: String,
180 pub key: String,
181 #[serde(default)]
182 pub label: String,
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub min: Option<u32>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub max: Option<u32>,
187 #[serde(default)]
188 pub allowed: Vec<String>,
189 #[serde(default, skip_serializing_if = "Vec::is_empty")]
190 pub groups: Vec<GroupDef>,
191}
192
193#[derive(Debug, Clone, Serialize, Deserialize, Default)]
196pub struct GroupDef {
197 pub key: String,
198 #[serde(default)]
199 pub label: String,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub icon: Option<String>,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub description: Option<String>,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub label_format: Option<String>,
207 #[serde(default)]
208 pub children: Vec<Node>,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize, Default)]
213pub struct Document {
214 #[serde(default)]
215 pub nodes: Vec<Node>,
216}
217
218#[derive(Debug, Clone, Serialize, Deserialize, Default)]
220pub struct ComponentDoc {
221 #[serde(default, skip_serializing_if = "Option::is_none")]
222 pub label_format: Option<String>,
223 #[serde(default)]
224 pub children: Vec<Node>,
225}
226
227#[derive(Debug, Clone)]
229pub struct ComponentEntry {
230 pub doc: ComponentDoc,
231 pub version: u32,
234}
235
236pub fn parse(value: &serde_json::Value) -> Result<Document, serde_json::Error> {
242 serde_json::from_value(value.clone())
243}
244
245#[must_use]
250pub fn widget_allowed(kind: WidgetKind) -> bool {
251 !matches!(
252 kind,
253 WidgetKind::Custom
254 | WidgetKind::Stream
255 | WidgetKind::Hidden
256 | WidgetKind::Password
257 | WidgetKind::SnippetM2M
258 )
259}
260
261#[must_use]
263pub fn repeater_item_type(key: &str) -> String {
264 format!("r_{key}")
265}
266
267#[must_use]
269pub fn component_type(slug: &str) -> String {
270 format!("c_{slug}")
271}
272
273#[must_use]
278pub fn validate(doc: &Document, components: &HashMap<String, ComponentEntry>) -> Vec<String> {
279 let mut problems = Vec::new();
280 let mut top_keys: HashSet<String> = HashSet::new();
281 let mut top_fields: HashSet<String> = HashSet::new();
282
283 let claim = |key: &str, what: &str, problems: &mut Vec<String>, keys: &mut HashSet<String>| {
284 if !is_valid_key(key) {
285 problems.push(format!(
286 "{what} key `{key}` is invalid — use letters/digits/underscores, starting with a letter"
287 ));
288 }
289 if !keys.insert(key.to_owned()) {
290 problems.push(format!(
291 "duplicate key `{key}` — every top-level key must be unique"
292 ));
293 }
294 };
295
296 for node in &doc.nodes {
297 match node {
298 Node::Field(f) => {
299 claim(&f.key, "field", &mut problems, &mut top_keys);
300 top_fields.insert(f.key.clone());
301 check_field(f, "field", &mut problems);
302 }
303 Node::Row(row) => {
304 for child in &row.children {
305 match child {
306 Node::Field(f) => {
307 claim(&f.key, "field", &mut problems, &mut top_keys);
308 top_fields.insert(f.key.clone());
309 check_field(f, "row field", &mut problems);
310 if let Some(w) = f.width {
311 if !(1..=12).contains(&w) {
312 problems.push(format!(
313 "row field `{}` width {w} out of range 1..=12",
314 f.key
315 ));
316 }
317 }
318 }
319 _ => problems.push("rows may contain only fields".to_owned()),
320 }
321 }
322 }
323 Node::Group(g) => {
324 claim(&g.key, "group", &mut problems, &mut top_keys);
325 check_children(&g.children, &format!("group `{}`", g.key), &mut problems);
326 }
327 Node::Component(c) => {
328 let key = c.key.clone().unwrap_or_else(|| c.reference.clone());
329 claim(&key, "component", &mut problems, &mut top_keys);
330 if !components.contains_key(&c.reference) {
331 problems.push(format!(
332 "component `{}` references unknown library component `{}`",
333 key, c.reference
334 ));
335 }
336 }
337 Node::Repeater(r) => {
338 claim(&r.key, "repeater", &mut problems, &mut top_keys);
339 check_group_def(
340 &r.item,
341 &format!("repeater `{}` item", r.key),
342 &mut problems,
343 );
344 check_dyn_name_free(&repeater_item_type(&r.key), &mut problems);
345 if let (Some(min), Some(max)) = (r.min, r.max) {
346 if min > max {
347 problems.push(format!("repeater `{}` has min > max", r.key));
348 }
349 }
350 }
351 Node::Flex(z) => {
352 claim(&z.key, "flex zone", &mut problems, &mut top_keys);
353 let mut local: HashSet<&str> = HashSet::new();
354 for g in &z.groups {
355 if !local.insert(g.key.as_str()) {
356 problems.push(format!(
357 "flex zone `{}` defines group `{}` twice",
358 z.key, g.key
359 ));
360 }
361 check_group_def(
362 g,
363 &format!("zone `{}` group `{}`", z.key, g.key),
364 &mut problems,
365 );
366 check_dyn_name_free(&g.key, &mut problems);
367 }
368 if z.allowed.is_empty() {
369 problems.push(format!("flex zone `{}` allows no block types", z.key));
370 }
371 for a in &z.allowed {
372 let resolves = local.contains(a.as_str())
373 || a.strip_prefix("c_")
374 .is_some_and(|slug| components.contains_key(slug))
375 || crate::block::find_block(a).is_some();
376 if !resolves {
377 problems.push(format!(
378 "flex zone `{}` allows `{a}` which is neither a zone group, a \
379 library component (c_<slug>), nor a registered block",
380 z.key
381 ));
382 }
383 }
384 }
385 }
386 }
387
388 for node in &doc.nodes {
391 let fields: Vec<&FieldNode> = match node {
392 Node::Field(f) => vec![f],
393 Node::Row(r) => r
394 .children
395 .iter()
396 .filter_map(|n| match n {
397 Node::Field(f) => Some(f),
398 _ => None,
399 })
400 .collect(),
401 _ => Vec::new(),
402 };
403 for f in fields {
404 for rule in &f.rules {
405 for cond in &rule.conditions {
406 if !top_fields.contains(&cond.field) {
407 problems.push(format!(
408 "field `{}` has a rule referencing unknown field `{}`",
409 f.key, cond.field
410 ));
411 }
412 }
413 }
414 }
415 }
416
417 problems
418}
419
420#[must_use]
422pub fn validate_component(doc: &ComponentDoc) -> Vec<String> {
423 let mut problems = Vec::new();
424 check_children(&doc.children, "component", &mut problems);
425 for node in &doc.children {
426 if matches!(
427 node,
428 Node::Group(_) | Node::Component(_) | Node::Repeater(_) | Node::Flex(_)
429 ) {
430 problems.push(
431 "components may contain only fields and rows (no nested groups/repeaters/zones in v1)"
432 .to_owned(),
433 );
434 }
435 }
436 problems
437}
438
439#[must_use]
443pub fn references_component(doc: &Document, slug: &str) -> bool {
444 let tag = component_type(slug);
445 nodes_reference_component(&doc.nodes, slug, &tag)
446}
447
448fn nodes_reference_component(nodes: &[Node], slug: &str, tag: &str) -> bool {
449 nodes.iter().any(|node| match node {
450 Node::Component(c) => c.reference == slug,
451 Node::Row(r) => nodes_reference_component(&r.children, slug, tag),
452 Node::Group(g) => nodes_reference_component(&g.children, slug, tag),
453 Node::Repeater(r) => nodes_reference_component(&r.item.children, slug, tag),
454 Node::Flex(f) => {
455 f.allowed.iter().any(|a| a == tag)
456 || f.groups
457 .iter()
458 .any(|g| nodes_reference_component(&g.children, slug, tag))
459 }
460 Node::Field(_) => false,
461 })
462}
463
464fn check_field(f: &FieldNode, what: &str, problems: &mut Vec<String>) {
465 if !widget_allowed(f.widget) {
466 problems.push(format!(
467 "{what} `{}` uses widget kind `{}` which is not allowed in the builder",
468 f.key,
469 f.widget.as_tag()
470 ));
471 }
472 if matches!(
473 f.widget,
474 WidgetKind::Select | WidgetKind::Radio | WidgetKind::Checkboxes | WidgetKind::MultiSelect
475 ) && f.options.is_empty()
476 {
477 problems.push(format!(
478 "{what} `{}` is a choice widget with no options",
479 f.key
480 ));
481 }
482}
483
484fn check_children(children: &[Node], scope: &str, problems: &mut Vec<String>) {
487 let mut keys: HashSet<String> = HashSet::new();
488 let visit = |f: &FieldNode, problems: &mut Vec<String>, keys: &mut HashSet<String>| {
489 if !is_valid_key(&f.key) {
490 problems.push(format!("{scope}: field key `{}` is invalid", f.key));
491 }
492 if !keys.insert(f.key.clone()) {
493 problems.push(format!("{scope}: duplicate field key `{}`", f.key));
494 }
495 check_field(f, scope, problems);
496 };
497 for node in children {
498 match node {
499 Node::Field(f) => visit(f, problems, &mut keys),
500 Node::Row(row) => {
501 for child in &row.children {
502 match child {
503 Node::Field(f) => visit(f, problems, &mut keys),
504 _ => problems.push(format!("{scope}: rows may contain only fields")),
505 }
506 }
507 }
508 _ => problems.push(format!(
509 "{scope}: only fields and rows are allowed inside groups/items"
510 )),
511 }
512 }
513}
514
515fn check_group_def(g: &GroupDef, scope: &str, problems: &mut Vec<String>) {
516 if !is_valid_key(&g.key) {
517 problems.push(format!("{scope}: key `{}` is invalid", g.key));
518 }
519 check_children(&g.children, scope, problems);
520 let local: HashSet<&str> = g
522 .children
523 .iter()
524 .flat_map(|n| match n {
525 Node::Field(f) => vec![f.key.as_str()],
526 Node::Row(r) => r
527 .children
528 .iter()
529 .filter_map(|c| match c {
530 Node::Field(f) => Some(f.key.as_str()),
531 _ => None,
532 })
533 .collect(),
534 _ => Vec::new(),
535 })
536 .collect();
537 for node in &g.children {
538 if let Node::Field(f) = node {
539 for rule in &f.rules {
540 for cond in &rule.conditions {
541 if !local.contains(cond.field.as_str()) {
542 problems.push(format!(
543 "{scope}: field `{}` rule references `{}` which is not in the same item",
544 f.key, cond.field
545 ));
546 }
547 }
548 }
549 }
550 }
551}
552
553fn check_dyn_name_free(name: &str, problems: &mut Vec<String>) {
555 if crate::block::find_block(name).is_some() {
556 problems.push(format!(
557 "`{name}` collides with a code-registered block type — pick a different key"
558 ));
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565
566 fn components() -> HashMap<String, ComponentEntry> {
567 let mut m = HashMap::new();
568 m.insert(
569 "cta_banner".to_owned(),
570 ComponentEntry {
571 doc: ComponentDoc {
572 label_format: None,
573 children: vec![
574 Node::Field(FieldNode {
575 key: "text".into(),
576 label: "Text".into(),
577 widget: WidgetKind::Text,
578 ..Default::default()
579 }),
580 Node::Field(FieldNode {
581 key: "url".into(),
582 label: "URL".into(),
583 widget: WidgetKind::Url,
584 ..Default::default()
585 }),
586 ],
587 },
588 version: 3,
589 },
590 );
591 m
592 }
593
594 fn fixture_json() -> serde_json::Value {
595 serde_json::json!({
596 "nodes": [
597 { "kind": "field", "key": "subtitle", "label": "Subtitle",
598 "widget": "text", "required": true },
599 { "kind": "row", "children": [
600 { "kind": "field", "key": "layout", "label": "Layout", "widget": "select",
601 "width": 6, "options": [ {"value": "wide", "label": "Wide"},
602 {"value": "boxed", "label": "Boxed"} ] },
603 { "kind": "field", "key": "accent", "label": "Accent", "widget": "color",
604 "width": 6,
605 "rules": [ { "match": "all", "action": "show",
606 "conditions": [ {"field": "layout", "op": "eq", "value": "wide"} ] } ] }
607 ]},
608 { "kind": "group", "key": "hero", "label": "Hero", "children": [
609 { "kind": "field", "key": "image", "label": "Image", "widget": "mediapicker" },
610 { "kind": "field", "key": "heading", "label": "Heading", "widget": "text" }
611 ]},
612 { "kind": "component", "ref": "cta_banner" },
613 { "kind": "repeater", "key": "faqs", "label": "FAQs", "max": 10,
614 "item": { "key": "faq", "label": "FAQ", "label_format": "{question}",
615 "children": [
616 { "kind": "field", "key": "question", "label": "Question",
617 "widget": "text", "required": true },
618 { "kind": "field", "key": "answer", "label": "Answer", "widget": "richtext" }
619 ] } },
620 { "kind": "flex", "key": "sections", "label": "Sections",
621 "allowed": ["quote_pair", "c_cta_banner", "heading"],
622 "groups": [
623 { "key": "quote_pair", "label": "Quote pair", "children": [
624 { "kind": "field", "key": "quote", "label": "Quote", "widget": "textarea" },
625 { "kind": "field", "key": "attribution", "label": "By", "widget": "text" }
626 ] }
627 ] }
628 ]
629 })
630 }
631
632 #[test]
633 fn fixture_parses_and_validates_clean() {
634 let doc = parse(&fixture_json()).expect("parse");
635 assert_eq!(doc.nodes.len(), 6);
636 let problems = validate(&doc, &components());
637 assert!(problems.is_empty(), "unexpected problems: {problems:?}");
638 }
639
640 #[test]
641 fn duplicate_top_level_key_rejected() {
642 let mut doc = parse(&fixture_json()).unwrap();
643 doc.nodes.push(Node::Field(FieldNode {
644 key: "subtitle".into(),
645 ..Default::default()
646 }));
647 let problems = validate(&doc, &components());
648 assert!(
649 problems
650 .iter()
651 .any(|p| p.contains("duplicate key `subtitle`")),
652 "{problems:?}"
653 );
654 }
655
656 #[test]
657 fn banned_widget_kind_rejected() {
658 let doc = parse(&serde_json::json!({
659 "nodes": [ { "kind": "field", "key": "sneaky", "widget": "hidden" } ]
660 }))
661 .unwrap();
662 let problems = validate(&doc, &HashMap::new());
663 assert!(
664 problems.iter().any(|p| p.contains("not allowed")),
665 "{problems:?}"
666 );
667 }
668
669 #[test]
670 fn dangling_component_and_flex_refs_rejected() {
671 let doc = parse(&serde_json::json!({
672 "nodes": [
673 { "kind": "component", "ref": "nope" },
674 { "kind": "flex", "key": "z", "label": "Z",
675 "allowed": ["missing_thing"], "groups": [] }
676 ]
677 }))
678 .unwrap();
679 let problems = validate(&doc, &HashMap::new());
680 assert!(
681 problems
682 .iter()
683 .any(|p| p.contains("unknown library component `nope`")),
684 "{problems:?}"
685 );
686 assert!(
687 problems.iter().any(|p| p.contains("missing_thing")),
688 "{problems:?}"
689 );
690 }
691
692 #[test]
693 fn code_block_collision_rejected() {
694 let doc = parse(&serde_json::json!({
696 "nodes": [
697 { "kind": "flex", "key": "z", "label": "Z", "allowed": ["heading2"],
698 "groups": [ { "key": "heading2", "label": "H", "children": [] } ] },
699 { "kind": "repeater", "key": "items", "label": "Items",
700 "item": { "key": "item", "children": [] } }
701 ]
702 }))
703 .unwrap();
704 let doc2 = parse(&serde_json::json!({
706 "nodes": [
707 { "kind": "flex", "key": "z", "label": "Z", "allowed": ["heading"],
708 "groups": [ { "key": "heading", "label": "H", "children": [] } ] }
709 ]
710 }))
711 .unwrap();
712 assert!(validate(&doc, &HashMap::new()).is_empty());
713 let problems = validate(&doc2, &HashMap::new());
714 assert!(
715 problems
716 .iter()
717 .any(|p| p.contains("collides with a code-registered block")),
718 "{problems:?}"
719 );
720 }
721
722 #[test]
723 fn rule_referencing_unknown_field_rejected() {
724 let doc = parse(&serde_json::json!({
725 "nodes": [
726 { "kind": "field", "key": "a", "widget": "text",
727 "rules": [ { "conditions": [ {"field": "ghost", "op": "eq", "value": "1"} ] } ] }
728 ]
729 }))
730 .unwrap();
731 let problems = validate(&doc, &HashMap::new());
732 assert!(
733 problems.iter().any(|p| p.contains("unknown field `ghost`")),
734 "{problems:?}"
735 );
736 }
737
738 #[test]
739 fn references_component_finds_direct_and_flex_and_nested() {
740 let direct = parse(&serde_json::json!({
742 "nodes": [ { "kind": "component", "ref": "cta" } ]
743 }))
744 .unwrap();
745 assert!(references_component(&direct, "cta"));
746 assert!(!references_component(&direct, "other"));
747
748 let flex = parse(&serde_json::json!({
750 "nodes": [ { "kind": "flex", "key": "z", "allowed": ["c_cta", "quote"] } ]
751 }))
752 .unwrap();
753 assert!(references_component(&flex, "cta"));
754 assert!(!references_component(&flex, "quote"));
755
756 let nested = parse(&serde_json::json!({
758 "nodes": [ { "kind": "group", "key": "g", "children": [ { "kind": "component", "ref": "cta" } ] } ]
759 }))
760 .unwrap();
761 assert!(references_component(&nested, "cta"));
762
763 let none = parse(&serde_json::json!({
765 "nodes": [ { "kind": "field", "key": "a", "widget": "text" } ]
766 }))
767 .unwrap();
768 assert!(!references_component(&none, "cta"));
769 }
770}