Skip to main content

rustango_cms/page_builder/
compile.rs

1//! Schema → runtime compilation. Turns a validated
2//! [`Document`] into the shapes the
3//! existing engines consume:
4//!
5//! - fixed fields / rows / groups → [`Widget`]s (rendered by the shared
6//!   `_widget.html` macro; inputs namespaced `pb__…`),
7//! - repeaters / flex zones → one `WidgetKind::Stream` [`Widget`] each +
8//!   [`DynBlockDef`]s in a [`DynBlockSet`] overlay,
9//! - conditional rules → flat [`RuleBinding`]s for the editor's rules
10//!   island + server-side visibility checks.
11//!
12//! Compilation is cheap (no I/O) — callers compile per request from the
13//! published schema row + the component library.
14
15use std::collections::HashMap;
16use std::sync::Arc;
17
18use crate::forms::schema::ConditionalRule;
19use crate::page_builder::dyn_block::{DynBlockDef, DynBlockSet};
20use crate::page_builder::schema::{
21    repeater_item_type, ComponentEntry, Document, FieldNode, GroupDef, Node,
22};
23use crate::widget::Widget;
24
25/// Prefix for every builder-owned form input — keeps UI-defined fields
26/// from colliding with base-page fields and code handlers' extension
27/// fields.
28pub const FIELD_PREFIX: &str = "pb__";
29
30/// One editor-facing layout item, in authored order.
31#[derive(Debug, Clone)]
32pub enum BodyItem {
33    /// A stacked scalar input.
34    Field(Widget),
35    /// Side-by-side inputs with 1–12 widths.
36    Row(Vec<(Widget, u8)>),
37    /// A named fieldset of stacked/row inputs (values nest under `key`).
38    Group {
39        key: String,
40        label: String,
41        items: Vec<BodyItem>,
42    },
43    /// A repeater or flex zone — one stream editor.
44    Zone {
45        key: String,
46        label: String,
47        widget: Widget,
48        min: Option<u32>,
49        max: Option<u32>,
50    },
51}
52
53/// A conditional rule bound to the field it governs.
54#[derive(Debug, Clone)]
55pub struct RuleBinding {
56    /// The governed field's key (top-level namespace).
57    pub field: String,
58    pub rule: ConditionalRule,
59}
60
61/// The compiled, render-ready schema.
62#[derive(Debug, Clone, Default)]
63pub struct CompiledSchema {
64    pub body: Vec<BodyItem>,
65    pub dyn_blocks: DynBlockSet,
66    pub rules: Vec<RuleBinding>,
67    /// The published schema version this was compiled from.
68    pub version: u32,
69}
70
71impl CompiledSchema {
72    /// Every value-bearing top-level key, in authored order — the save
73    /// path walks this.
74    #[must_use]
75    pub fn top_level_keys(&self) -> Vec<String> {
76        let mut out = Vec::new();
77        for item in &self.body {
78            match item {
79                BodyItem::Field(w) => out.push(strip_prefix(&w.name)),
80                BodyItem::Row(cells) => {
81                    out.extend(cells.iter().map(|(w, _)| strip_prefix(&w.name)));
82                }
83                BodyItem::Group { key, .. } | BodyItem::Zone { key, .. } => out.push(key.clone()),
84            }
85        }
86        out
87    }
88}
89
90fn strip_prefix(name: &str) -> String {
91    name.strip_prefix(FIELD_PREFIX).unwrap_or(name).to_owned()
92}
93
94/// Compile a validated document. `schema_version` is the published
95/// version (stamped on zone/repeater dyn blocks so stored entries carry
96/// it); component dyn blocks carry their own component version.
97#[must_use]
98pub fn compile(
99    doc: &Document,
100    components: &HashMap<String, ComponentEntry>,
101    schema_version: u32,
102) -> CompiledSchema {
103    let mut out = CompiledSchema {
104        version: schema_version,
105        ..Default::default()
106    };
107
108    for node in &doc.nodes {
109        match node {
110            Node::Field(f) => {
111                collect_rules(f, &mut out.rules);
112                out.body
113                    .push(BodyItem::Field(field_to_widget(f, FIELD_PREFIX)));
114            }
115            Node::Row(row) => {
116                let mut cells = Vec::new();
117                let fields: Vec<&FieldNode> = row
118                    .children
119                    .iter()
120                    .filter_map(|n| match n {
121                        Node::Field(f) => Some(f),
122                        _ => None,
123                    })
124                    .collect();
125                let equal = (12 / fields.len().max(1)) as u8;
126                for f in fields {
127                    collect_rules(f, &mut out.rules);
128                    cells.push((field_to_widget(f, FIELD_PREFIX), f.width.unwrap_or(equal)));
129                }
130                out.body.push(BodyItem::Row(cells));
131            }
132            Node::Group(g) => {
133                // Group members namespace as pb__<group>__<field>.
134                let prefix = format!("{FIELD_PREFIX}{}__", g.key);
135                let mut items = Vec::new();
136                for child in &g.children {
137                    match child {
138                        Node::Field(f) => items.push(BodyItem::Field(field_to_widget(f, &prefix))),
139                        Node::Row(row) => {
140                            let fields: Vec<&FieldNode> = row
141                                .children
142                                .iter()
143                                .filter_map(|n| match n {
144                                    Node::Field(f) => Some(f),
145                                    _ => None,
146                                })
147                                .collect();
148                            let equal = (12 / fields.len().max(1)) as u8;
149                            items.push(BodyItem::Row(
150                                fields
151                                    .iter()
152                                    .map(|f| {
153                                        (field_to_widget(f, &prefix), f.width.unwrap_or(equal))
154                                    })
155                                    .collect(),
156                            ));
157                        }
158                        _ => {}
159                    }
160                }
161                out.body.push(BodyItem::Group {
162                    key: g.key.clone(),
163                    label: if g.label.is_empty() {
164                        g.key.clone()
165                    } else {
166                        g.label.clone()
167                    },
168                    items,
169                });
170            }
171            Node::Component(c) => {
172                let key = c.key.clone().unwrap_or_else(|| c.reference.clone());
173                let Some(entry) = components.get(&c.reference) else {
174                    continue; // validate() flags this; compile degrades
175                };
176                // A component instance = a single-item repeater-style
177                // zone locked to exactly one entry? No — v1 semantics:
178                // an always-present group. Compile it like a group with
179                // the component's children.
180                let prefix = format!("{FIELD_PREFIX}{key}__");
181                let mut items = Vec::new();
182                for child in &entry.doc.children {
183                    if let Node::Field(f) = child {
184                        items.push(BodyItem::Field(field_to_widget(f, &prefix)));
185                    } else if let Node::Row(row) = child {
186                        let fields: Vec<&FieldNode> = row
187                            .children
188                            .iter()
189                            .filter_map(|n| match n {
190                                Node::Field(f) => Some(f),
191                                _ => None,
192                            })
193                            .collect();
194                        let equal = (12 / fields.len().max(1)) as u8;
195                        items.push(BodyItem::Row(
196                            fields
197                                .iter()
198                                .map(|f| (field_to_widget(f, &prefix), f.width.unwrap_or(equal)))
199                                .collect(),
200                        ));
201                    }
202                }
203                out.body.push(BodyItem::Group {
204                    key: key.clone(),
205                    label: key.clone(),
206                    items,
207                });
208            }
209            Node::Repeater(r) => {
210                let item_type = repeater_item_type(&r.key);
211                out.dyn_blocks.insert(
212                    item_type.clone(),
213                    Arc::new(DynBlockDef::from_group(&item_type, &r.item, schema_version)),
214                );
215                let name = format!("{FIELD_PREFIX}{}", r.key);
216                let widget = Widget::stream(
217                    &name,
218                    if r.label.is_empty() { &r.key } else { &r.label },
219                    [item_type.as_str()],
220                );
221                out.body.push(BodyItem::Zone {
222                    key: r.key.clone(),
223                    label: if r.label.is_empty() {
224                        r.key.clone()
225                    } else {
226                        r.label.clone()
227                    },
228                    widget,
229                    min: r.min,
230                    max: r.max,
231                });
232            }
233            Node::Flex(z) => {
234                // Zone-local groups become dyn blocks under their key.
235                for g in &z.groups {
236                    out.dyn_blocks.insert(
237                        g.key.clone(),
238                        Arc::new(DynBlockDef::from_group(&g.key, g, schema_version)),
239                    );
240                }
241                // Component refs in `allowed` (c_<slug>) become dyn
242                // blocks compiled from the library entry.
243                for a in &z.allowed {
244                    if let Some(slug) = a.strip_prefix("c_") {
245                        if let Some(entry) = components.get(slug) {
246                            let def = GroupDef {
247                                key: a.clone(),
248                                label: slug.replace('_', " "),
249                                icon: None,
250                                description: None,
251                                label_format: entry.doc.label_format.clone(),
252                                children: entry.doc.children.clone(),
253                            };
254                            out.dyn_blocks.insert(
255                                a.clone(),
256                                Arc::new(DynBlockDef::from_group(a, &def, entry.version)),
257                            );
258                        }
259                    }
260                }
261                let name = format!("{FIELD_PREFIX}{}", z.key);
262                let allowed: Vec<&str> = z.allowed.iter().map(String::as_str).collect();
263                let widget = Widget::stream(
264                    &name,
265                    if z.label.is_empty() { &z.key } else { &z.label },
266                    allowed,
267                );
268                out.body.push(BodyItem::Zone {
269                    key: z.key.clone(),
270                    label: if z.label.is_empty() {
271                        z.key.clone()
272                    } else {
273                        z.label.clone()
274                    },
275                    widget,
276                    min: z.min,
277                    max: z.max,
278                });
279            }
280        }
281    }
282    out
283}
284
285fn collect_rules(f: &FieldNode, rules: &mut Vec<RuleBinding>) {
286    for rule in &f.rules {
287        rules.push(RuleBinding {
288            field: f.key.clone(),
289            rule: rule.clone(),
290        });
291    }
292}
293
294/// Map one authored field into an admin [`Widget`], namespaced by
295/// `prefix` (`pb__` or `pb__<group>__`).
296#[must_use]
297pub fn field_to_widget(f: &FieldNode, prefix: &str) -> Widget {
298    let name = format!("{prefix}{}", f.key);
299    let label = if f.label.is_empty() { &f.key } else { &f.label };
300    let mut w = Widget::new(f.widget, name, label);
301    if f.required {
302        w = w.required();
303    }
304    if !f.help.is_empty() {
305        w = w.with_help(&f.help);
306    }
307    if !f.placeholder.is_empty() {
308        w = w.with_placeholder(&f.placeholder);
309    }
310    if !f.default_value.is_empty() {
311        w = w.with_value(&f.default_value);
312    }
313    if !f.options.is_empty() {
314        w = w.with_options(f.options.iter().map(|c| (c.value.clone(), c.label.clone())));
315    }
316    if let Some(min) = f.min {
317        w = w.with_min(min);
318    }
319    if let Some(max) = f.max {
320        w = w.with_max(max);
321    }
322    if let Some(step) = &f.step {
323        w = w.with_step(step.clone());
324    }
325    if let Some(n) = f.max_length {
326        w = w.with_max_length(n);
327    }
328    if let Some(n) = f.min_length {
329        w = w.with_min_length(n);
330    }
331    if !f.pattern.is_empty() {
332        w = w.with_pattern(&f.pattern);
333    }
334    // Choice widgets need `pb` marking for the save path? No — the save
335    // path walks CompiledSchema, not the form blindly. Nothing else.
336    w
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342    use crate::block::Block as _;
343    use crate::page_builder::schema::{parse, validate, ComponentDoc};
344    use crate::widget::WidgetKind;
345
346    fn components() -> HashMap<String, ComponentEntry> {
347        let mut m = HashMap::new();
348        m.insert(
349            "cta_banner".to_owned(),
350            ComponentEntry {
351                doc: ComponentDoc {
352                    label_format: None,
353                    children: vec![Node::Field(FieldNode {
354                        key: "text".into(),
355                        label: "Text".into(),
356                        widget: WidgetKind::Text,
357                        ..Default::default()
358                    })],
359                },
360                version: 3,
361            },
362        );
363        m
364    }
365
366    fn fixture() -> Document {
367        parse(&serde_json::json!({
368            "nodes": [
369                { "kind": "field", "key": "subtitle", "label": "Subtitle", "widget": "text",
370                  "rules": [ { "conditions": [ {"field": "subtitle", "op": "not_empty", "value": ""} ] } ] },
371                { "kind": "row", "children": [
372                    { "kind": "field", "key": "a", "widget": "text" },
373                    { "kind": "field", "key": "b", "widget": "text", "width": 4 }
374                ]},
375                { "kind": "group", "key": "hero", "label": "Hero", "children": [
376                    { "kind": "field", "key": "image", "widget": "mediapicker" }
377                ]},
378                { "kind": "component", "ref": "cta_banner" },
379                { "kind": "repeater", "key": "faqs", "label": "FAQs",
380                  "item": { "key": "faq", "children": [
381                      { "kind": "field", "key": "q", "widget": "text" } ] } },
382                { "kind": "flex", "key": "sections", "label": "Sections",
383                  "allowed": ["quote_pair", "c_cta_banner", "heading"],
384                  "groups": [ { "key": "quote_pair", "label": "Quote", "children": [
385                      { "kind": "field", "key": "quote", "widget": "textarea" } ] } ] }
386            ]
387        }))
388        .expect("fixture parses")
389    }
390
391    #[test]
392    fn compiles_expected_shapes() {
393        let doc = fixture();
394        assert!(validate(&doc, &components()).is_empty());
395        let c = compile(&doc, &components(), 5);
396
397        assert_eq!(c.body.len(), 6);
398        assert!(matches!(&c.body[0], BodyItem::Field(w) if w.name == "pb__subtitle"));
399        match &c.body[1] {
400            BodyItem::Row(cells) => {
401                assert_eq!(cells.len(), 2);
402                assert_eq!(cells[0].1, 6, "equal split default");
403                assert_eq!(cells[1].1, 4, "explicit width kept");
404            }
405            other => panic!("expected row, got {other:?}"),
406        }
407        match &c.body[2] {
408            BodyItem::Group { key, items, .. } => {
409                assert_eq!(key, "hero");
410                assert!(matches!(&items[0], BodyItem::Field(w) if w.name == "pb__hero__image"));
411            }
412            other => panic!("expected group, got {other:?}"),
413        }
414        match &c.body[4] {
415            BodyItem::Zone { widget, .. } => {
416                assert_eq!(widget.kind, WidgetKind::Stream);
417                assert_eq!(widget.allowed, vec!["r_faqs".to_owned()]);
418            }
419            other => panic!("expected repeater zone, got {other:?}"),
420        }
421        match &c.body[5] {
422            BodyItem::Zone { widget, .. } => {
423                assert_eq!(
424                    widget.allowed,
425                    vec![
426                        "quote_pair".to_owned(),
427                        "c_cta_banner".to_owned(),
428                        "heading".to_owned()
429                    ]
430                );
431            }
432            other => panic!("expected flex zone, got {other:?}"),
433        }
434
435        // Dyn blocks: repeater item + zone group + component ref.
436        assert!(c.dyn_blocks.contains_key("r_faqs"));
437        assert!(c.dyn_blocks.contains_key("quote_pair"));
438        assert!(c.dyn_blocks.contains_key("c_cta_banner"));
439        assert_eq!(
440            c.dyn_blocks["c_cta_banner"].version(),
441            3,
442            "component keeps its own version"
443        );
444        assert_eq!(
445            c.dyn_blocks["r_faqs"].version(),
446            5,
447            "schema-local uses schema version"
448        );
449
450        // Rules + keys.
451        assert_eq!(c.rules.len(), 1);
452        assert_eq!(
453            c.top_level_keys(),
454            vec![
455                "subtitle",
456                "a",
457                "b",
458                "hero",
459                "cta_banner",
460                "faqs",
461                "sections"
462            ]
463        );
464    }
465}