Skip to main content

rustango_cms/page_builder/
values.rs

1//! Page-value bridge — turns a compiled schema + a page's
2//! stored values into editor HTML, and a posted form back into stored
3//! values.
4//!
5//! Values live in `cms_page_builder_data.data` as one JSON object keyed
6//! by field/group/zone key. Scalars coerce per widget kind (shared with
7//! the page-type `preview_extension` rules); groups nest; repeaters/flex
8//! zones store the stream wire format `[{type,id,value,version}]`.
9//! Structure edits never touch stored data — [`load_upgraded`] fills
10//! defaults for new keys and parks removed keys under `_orphaned`, lazily,
11//! on next open (persisted only on the next save).
12
13use std::collections::HashMap;
14
15use serde_json::{Map, Value};
16
17use crate::page_builder::compile::{BodyItem, CompiledSchema, FIELD_PREFIX};
18use crate::page_builder::model;
19use crate::widget::{Widget, WidgetKind};
20
21/// Coerce one posted form value into typed JSON per widget kind. The only
22/// copy of the rule: `PageTypeHandler::preview_extension` calls it too, so
23/// a builder field and a page field of the same kind serialize identically.
24/// Chooser ids become `i64` (empty = null), as they are stored.
25#[must_use]
26pub fn coerce(kind: WidgetKind, raw: &str) -> Value {
27    match kind {
28        WidgetKind::Checkboxes
29        | WidgetKind::MultiSelect
30        | WidgetKind::Stream
31        | WidgetKind::SnippetM2M => {
32            serde_json::from_str::<Value>(raw).unwrap_or_else(|_| Value::Array(Vec::new()))
33        }
34        WidgetKind::Boolean => Value::Bool(matches!(raw, "on" | "true" | "1" | "yes")),
35        WidgetKind::MediaPicker
36        | WidgetKind::PageChooser
37        | WidgetKind::SnippetChooser
38        | WidgetKind::DocumentChooser => {
39            if raw.trim().is_empty() {
40                Value::Null
41            } else {
42                raw.parse::<i64>().map(Value::from).unwrap_or(Value::Null)
43            }
44        }
45        WidgetKind::Integer => raw.parse::<i64>().map(Value::from).unwrap_or(Value::Null),
46        WidgetKind::Number | WidgetKind::Float | WidgetKind::Range => raw
47            .parse::<f64>()
48            .ok()
49            .and_then(serde_json::Number::from_f64)
50            .map(Value::Number)
51            .unwrap_or(Value::Null),
52        _ => Value::String(raw.to_owned()),
53    }
54}
55
56/// Turn a stored JSON value back into an input string for prefilling a
57/// widget (`value` field). Arrays/objects re-serialize to JSON (stream
58/// widgets); scalars stringify.
59fn value_to_input(v: &Value) -> String {
60    match v {
61        Value::Null => String::new(),
62        Value::String(s) => s.clone(),
63        Value::Bool(b) => {
64            if *b {
65                "on".to_owned()
66            } else {
67                String::new()
68            }
69        }
70        Value::Array(_) | Value::Object(_) => serde_json::to_string(v).unwrap_or_default(),
71        // Numbers are stored as floats; a whole one shows as `32`, not `32.0`.
72        Value::Number(n) if n.as_f64().is_some_and(|f| f.fract() == 0.0 && f.abs() < 1e15) => {
73            format!("{}", n.as_f64().unwrap_or_default() as i64)
74        }
75        other => other.to_string(),
76    }
77}
78
79/// Component versions referenced by a compiled schema (`slug → version`),
80/// for the lazy-upgrade snapshot.
81fn component_versions(compiled: &CompiledSchema) -> Value {
82    use crate::block::Block as _;
83    let mut m = Map::new();
84    for (name, def) in &compiled.dyn_blocks {
85        if let Some(slug) = name.strip_prefix("c_") {
86            m.insert(slug.to_owned(), Value::from(def.version()));
87        }
88    }
89    Value::Object(m)
90}
91
92/// Walk the compiled body → a typed value map from a posted form. Only
93/// declared keys are kept; groups reassemble to nested objects, zones
94/// keep the stream array. Shared by [`save_from_form`] and the unsaved
95/// preview path so on-screen edits render identically to saves.
96#[must_use]
97pub fn build_values(
98    compiled: &CompiledSchema,
99    form: &HashMap<String, String>,
100) -> Map<String, Value> {
101    let mut data = Map::new();
102    for item in &compiled.body {
103        match item {
104            BodyItem::Field(w) => {
105                data.insert(
106                    strip(&w.name),
107                    coerce(w.kind, form.get(&w.name).map_or("", String::as_str)),
108                );
109            }
110            BodyItem::Row(cells) => {
111                for (w, _) in cells {
112                    data.insert(
113                        strip(&w.name),
114                        coerce(w.kind, form.get(&w.name).map_or("", String::as_str)),
115                    );
116                }
117            }
118            BodyItem::Group { key, items, .. } => {
119                let mut obj = Map::new();
120                collect_group(items, form, &mut obj);
121                data.insert(key.clone(), Value::Object(obj));
122            }
123            BodyItem::Zone { key, widget, .. } => {
124                let raw = form.get(&widget.name).map_or("", String::as_str);
125                data.insert(
126                    key.clone(),
127                    serde_json::from_str::<Value>(raw).unwrap_or_else(|_| Value::Array(Vec::new())),
128                );
129            }
130        }
131    }
132    data
133}
134
135/// The inverse of [`build_values`]: seed a form map from a page's stored
136/// values.
137///
138/// [`save_from_form`] rebuilds the whole body from the form, so any
139/// declared key the form does not carry is written back **empty** — a
140/// zone becomes `[]`. That is right for the admin editor, which always
141/// posts every widget, and catastrophic for a partial programmatic edit
142/// (the MCP `update_page`), where changing only an SEO title would
143/// otherwise delete the page's entire body. Callers that build a form
144/// by hand prefill with this first.
145pub fn prefill_form(compiled: &CompiledSchema, values: &Value, form: &mut HashMap<String, String>) {
146    let Some(obj) = values.as_object() else {
147        return;
148    };
149    for item in &compiled.body {
150        match item {
151            BodyItem::Field(w) => prefill_one(form, &w.name, obj.get(&strip(&w.name))),
152            BodyItem::Row(cells) => {
153                for (w, _) in cells {
154                    prefill_one(form, &w.name, obj.get(&strip(&w.name)));
155                }
156            }
157            BodyItem::Group { key, items, .. } => {
158                if let Some(g) = obj.get(key).and_then(Value::as_object) {
159                    prefill_group(items, g, form);
160                }
161            }
162            BodyItem::Zone { key, widget, .. } => {
163                prefill_one(form, &widget.name, obj.get(key));
164            }
165        }
166    }
167}
168
169fn prefill_one(form: &mut HashMap<String, String>, name: &str, v: Option<&Value>) {
170    if let Some(v) = v {
171        form.insert(name.to_owned(), value_to_input(v));
172    }
173}
174
175fn prefill_group(items: &[BodyItem], stored: &Map<String, Value>, form: &mut HashMap<String, String>) {
176    for item in items {
177        match item {
178            BodyItem::Field(w) => prefill_one(form, &w.name, stored.get(&strip_group(&w.name))),
179            BodyItem::Row(cells) => {
180                for (w, _) in cells {
181                    prefill_one(form, &w.name, stored.get(&strip_group(&w.name)));
182                }
183            }
184            BodyItem::Group { key, items, .. } => {
185                if let Some(g) = stored.get(key).and_then(Value::as_object) {
186                    prefill_group(items, g, form);
187                }
188            }
189            BodyItem::Zone { key, widget, .. } => {
190                prefill_one(form, &widget.name, stored.get(key));
191            }
192        }
193    }
194}
195
196/// Persist a page's builder values from the posted form. Walks the
197/// compiled body (not the raw form) so only declared keys are stored;
198/// groups reassemble to nested objects, zones keep the stream array.
199///
200/// # Errors
201/// Propagates the value upsert's DB failures.
202pub async fn save_from_form(
203    pool: &rustango::sql::Pool,
204    page_id: i64,
205    compiled: &CompiledSchema,
206    form: &HashMap<String, String>,
207) -> Result<(), rustango::sql::ExecError> {
208    let mut data = build_values(compiled, form);
209    // Carry forward removed-field data. Any stored top-level key the
210    // current schema no longer declares is parked under `_orphaned`
211    // (never silently dropped) alongside any pre-existing parked bag —
212    // re-adding the field later recovers it. Keys the schema still
213    // declares were already rebuilt from the form above.
214    if let Ok(Some(existing)) = model::data_for_page(pool, page_id).await {
215        park_orphans(&mut data, &existing.data, &compiled.top_level_keys());
216    }
217    model::upsert_data(
218        pool,
219        page_id,
220        compiled.version as i32,
221        component_versions(compiled),
222        Value::Object(data),
223    )
224    .await
225}
226
227/// Fold removed-field data into `data["_orphaned"]`. Every top-level key
228/// in `existing` that the schema no longer declares (`known`) — plus any
229/// pre-existing `_orphaned` bag — is parked so it survives the save. Keys
230/// the schema still declares are left to the freshly-rebuilt `data`.
231fn park_orphans(data: &mut Map<String, Value>, existing: &Value, known: &[String]) {
232    let mut orphaned = existing
233        .get("_orphaned")
234        .and_then(Value::as_object)
235        .cloned()
236        .unwrap_or_default();
237    let known: std::collections::HashSet<&str> = known.iter().map(String::as_str).collect();
238    if let Some(stored) = existing.as_object() {
239        for (k, v) in stored {
240            if k == "_orphaned" || known.contains(k.as_str()) {
241                continue;
242            }
243            orphaned.insert(k.clone(), v.clone());
244        }
245    }
246    if !orphaned.is_empty() {
247        data.insert("_orphaned".to_owned(), Value::Object(orphaned));
248    }
249}
250
251fn collect_group(items: &[BodyItem], form: &HashMap<String, String>, out: &mut Map<String, Value>) {
252    for item in items {
253        match item {
254            BodyItem::Field(w) => {
255                out.insert(
256                    strip_group(&w.name),
257                    coerce(w.kind, form.get(&w.name).map_or("", String::as_str)),
258                );
259            }
260            BodyItem::Row(cells) => {
261                for (w, _) in cells {
262                    out.insert(
263                        strip_group(&w.name),
264                        coerce(w.kind, form.get(&w.name).map_or("", String::as_str)),
265                    );
266                }
267            }
268            _ => {}
269        }
270    }
271}
272
273/// `pb__key` → `key`.
274fn strip(name: &str) -> String {
275    name.strip_prefix(FIELD_PREFIX).unwrap_or(name).to_owned()
276}
277/// `pb__group__field` → `field` (last segment).
278fn strip_group(name: &str) -> String {
279    name.rsplit("__").next().unwrap_or(name).to_owned()
280}
281
282/// Whether a lazy upgrade happened (new keys defaulted / removed keys
283/// parked) so the editor can show a non-blocking notice.
284#[derive(Debug, Default, Clone, Copy)]
285pub struct UpgradeReport {
286    pub upgraded: bool,
287}
288
289/// Load a page's builder values, lazily upgraded against the compiled
290/// (published) schema. New top-level keys get their default; keys no
291/// longer in the schema move to `data._orphaned` (never deleted). The
292/// returned value is NOT persisted — the next save writes it back.
293///
294/// # Errors
295/// Propagates the load query's DB failures.
296pub async fn load_upgraded(
297    pool: &rustango::sql::Pool,
298    page_id: i64,
299    compiled: &CompiledSchema,
300) -> Result<(Value, UpgradeReport), rustango::sql::ExecError> {
301    let stored = model::data_for_page(pool, page_id).await?;
302    Ok(upgrade(stored.as_ref(), compiled))
303}
304
305/// The [`load_upgraded`] half that needs no query: fill `stored` (a
306/// page's saved row, if any) up to `compiled`'s shape.
307#[must_use]
308pub fn upgrade(stored: Option<&model::PageBuilderData>, compiled: &CompiledSchema) -> (Value, UpgradeReport) {
309    let mut data: Map<String, Value> = stored
310        .as_ref()
311        .and_then(|d| d.data.as_object().cloned())
312        .unwrap_or_default();
313
314    let known: Vec<String> = compiled.top_level_keys();
315    let mut report = UpgradeReport::default();
316    let stale = stored
317        .as_ref()
318        .map_or(false, |d| d.schema_version != compiled.version as i32);
319
320    // Fill defaults for keys the schema declares but the page lacks.
321    for item in &compiled.body {
322        let (key, default) = match item {
323            BodyItem::Field(w) => (strip(&w.name), Value::String(w.value.clone())),
324            BodyItem::Row(_) => continue, // handled per-field below
325            BodyItem::Group { key, .. } => (key.clone(), Value::Object(Map::new())),
326            BodyItem::Zone { key, .. } => (key.clone(), Value::Array(Vec::new())),
327        };
328        if !data.contains_key(&key) {
329            data.insert(key, default);
330            if stored.is_some() {
331                report.upgraded = true;
332            }
333        }
334    }
335    // Row fields default individually.
336    for item in &compiled.body {
337        if let BodyItem::Row(cells) = item {
338            for (w, _) in cells {
339                let key = strip(&w.name);
340                if !data.contains_key(&key) {
341                    data.insert(key, Value::String(w.value.clone()));
342                    if stored.is_some() {
343                        report.upgraded = true;
344                    }
345                }
346            }
347        }
348    }
349
350    // Park keys the schema no longer declares (only when the stored
351    // version is stale, so a fresh save's extra `_orphaned` survives).
352    if stale {
353        let mut orphaned = data
354            .get("_orphaned")
355            .and_then(Value::as_object)
356            .cloned()
357            .unwrap_or_default();
358        let remove: Vec<String> = data
359            .keys()
360            .filter(|k| *k != "_orphaned" && !known.contains(k))
361            .cloned()
362            .collect();
363        for k in remove {
364            if let Some(v) = data.remove(&k) {
365                orphaned.insert(k, v);
366                report.upgraded = true;
367            }
368        }
369        if !orphaned.is_empty() {
370            data.insert("_orphaned".to_owned(), Value::Object(orphaned));
371        }
372    }
373
374    (Value::Object(data), report)
375}
376
377/// The builder values, choice labels and first photo of each child page
378/// whose type has a published schema, in the visitor's language — what a
379/// listing shows on its cards as `child.builder.*` /
380/// `child.builder_labels.*`, and the card image when no share image is
381/// chosen.
382/// One schema load per page type and one data query for all children,
383/// whatever their number. `translations_by_page` holds each child's
384/// per-locale overrides (empty on the default language).
385///
386/// # Errors
387/// Driver / query failures.
388pub async fn children_builder(
389    pool: &rustango::sql::Pool,
390    children: &[crate::page::Page],
391    translations_by_page: &HashMap<i64, HashMap<String, String>>,
392    locale_code: Option<&str>,
393) -> Result<HashMap<i64, (Value, Value, Option<i64>)>, rustango::sql::ExecError> {
394    use rustango::core::Column as _;
395    use rustango::sql::FetcherPool as _;
396    let mut out = HashMap::new();
397    if children.is_empty() {
398        return Ok(out);
399    }
400    let mut schemas: HashMap<i64, Option<(CompiledSchema, crate::page_builder::Document)>> = HashMap::new();
401    let mut components = None;
402    for child in children {
403        if schemas.contains_key(&child.page_type_id) {
404            continue;
405        }
406        let entry = match model::published_for(pool, child.page_type_id).await? {
407            Some(row) => match crate::page_builder::parse_schema(&row.document) {
408                Ok(doc) => {
409                    if components.is_none() {
410                        components = Some(model::component_map(pool).await.unwrap_or_default());
411                    }
412                    let compiled = crate::page_builder::compile(
413                        &doc,
414                        components.as_ref().expect("loaded above"),
415                        row.version.max(1) as u32,
416                    );
417                    Some((compiled, doc))
418                }
419                Err(_) => None,
420            },
421            None => None,
422        };
423        schemas.insert(child.page_type_id, entry);
424    }
425    let ids: Vec<i64> = children
426        .iter()
427        .filter(|c| schemas.get(&c.page_type_id).is_some_and(Option::is_some))
428        .filter_map(|c| c.id.get().copied())
429        .collect();
430    if ids.is_empty() {
431        return Ok(out);
432    }
433    let rows: HashMap<i64, model::PageBuilderData> = model::PageBuilderData::objects()
434        .where_(model::PageBuilderData::page_id.is_in(ids))
435        .fetch(pool)
436        .await?
437        .into_iter()
438        .map(|r| (r.page_id, r))
439        .collect();
440    let none = HashMap::new();
441    for child in children {
442        let (Some(id), Some(Some((compiled, doc)))) = (child.id.get().copied(), schemas.get(&child.page_type_id)) else {
443            continue;
444        };
445        let (mut values, _) = upgrade(rows.get(&id), compiled);
446        if let Some(map) = values.as_object_mut() {
447            apply_builder_translations(compiled, map, translations_by_page.get(&id).unwrap_or(&none));
448        }
449        let labels = choice_labels(doc, &values, locale_code);
450        let photo = first_media_id(compiled, &values);
451        out.insert(id, (values, labels, photo));
452    }
453    Ok(out)
454}
455
456/// Public-render context for a page whose type has a published schema.
457/// Returns `(builder_values, zone_html)` where `builder_values`
458/// is the whole value tree (scalars + nested groups + zone arrays) for
459/// `ctx.builder.*`, and `zone_html` maps each flexible-content/repeater
460/// zone key → pre-rendered HTML (through the stream pipeline with the
461/// dyn-block overlay) for `{{ stream_render(name="<zone>") | safe }}`.
462///
463/// `preview_form` (when present) builds the values from the posted edit
464/// form instead of the stored row, so the preview iframe reflects
465/// on-screen edits before save — identical coercion to [`save_from_form`].
466/// Returns `None` when the type has no published schema.
467/// Compile the published schema and fill it — the value half of
468/// [`public_render_ctx`], without the zone-HTML prerender.
469///
470/// JSON consumers want values only (they render themselves), and the
471/// prerender is the expensive part. Factored out so the HTML renderer,
472/// the v2 API and the `Accept`-negotiated JSON view all compile the
473/// schema through one path instead of three near-copies.
474///
475/// Returns `(values, compiled)` so a caller that also needs the zones
476/// doesn't compile twice. `None` when the type has no published schema.
477pub async fn values_for(
478    pool: &rustango::sql::Pool,
479    page_id: i64,
480    page_type_id: i64,
481    preview_form: Option<&HashMap<String, String>>,
482) -> Option<(Value, CompiledSchema)> {
483    values_for_doc(pool, page_id, page_type_id, preview_form)
484        .await
485        .map(|(values, compiled, _)| (values, compiled))
486}
487
488/// [`values_for`], plus the published schema document it compiled.
489async fn values_for_doc(
490    pool: &rustango::sql::Pool,
491    page_id: i64,
492    page_type_id: i64,
493    preview_form: Option<&HashMap<String, String>>,
494) -> Option<(Value, CompiledSchema, crate::page_builder::Document)> {
495    let row = model::published_for(pool, page_type_id).await.ok()??;
496    let doc = crate::page_builder::parse_schema(&row.document).ok()?;
497    let components = model::component_map(pool).await.unwrap_or_default();
498    let compiled = crate::page_builder::compile(&doc, &components, row.version.max(1) as u32);
499    let values = match preview_form {
500        Some(form) => Value::Object(build_values(&compiled, form)),
501        None => load_upgraded(pool, page_id, &compiled).await.ok()?.0,
502    };
503    Some((values, compiled, doc))
504}
505
506/// The display labels of a page's choice fields (select, radio, checkboxes)
507/// in `locale` (a locale code; `None` = the default language), with the
508/// same nesting as `builder.*`: `builder_labels.glaze` is "Bleu lune" where
509/// `builder.glaze` is the stored value "Moon blue". A multi-choice
510/// field gives a list. Fields with no value are left out.
511#[must_use]
512pub fn choice_labels(doc: &crate::page_builder::Document, values: &Value, locale: Option<&str>) -> Value {
513    use crate::page_builder::schema::Node;
514    fn walk(nodes: &[Node], values: Option<&Map<String, Value>>, locale: Option<&str>, out: &mut Map<String, Value>) {
515        for node in nodes {
516            match node {
517                Node::Field(f) if !f.options.is_empty() => {
518                    let label = |v: &str| {
519                        f.options
520                            .iter()
521                            .find(|c| c.value == v)
522                            .map_or_else(|| v.to_owned(), |c| c.label_in(locale).to_owned())
523                    };
524                    match values.and_then(|m| m.get(&f.key)) {
525                        Some(Value::String(v)) if !v.is_empty() => {
526                            out.insert(f.key.clone(), Value::String(label(v)));
527                        }
528                        Some(Value::Array(vs)) => {
529                            let list = vs.iter().filter_map(Value::as_str).map(|v| Value::String(label(v))).collect();
530                            out.insert(f.key.clone(), Value::Array(list));
531                        }
532                        _ => {}
533                    }
534                }
535                Node::Row(r) => walk(&r.children, values, locale, out),
536                Node::Group(g) => {
537                    let mut inner = Map::new();
538                    let group_values = values.and_then(|m| m.get(&g.key)).and_then(Value::as_object);
539                    walk(&g.children, group_values, locale, &mut inner);
540                    if !inner.is_empty() {
541                        out.insert(g.key.clone(), Value::Object(inner));
542                    }
543                }
544                _ => {}
545            }
546        }
547    }
548    let mut out = Map::new();
549    walk(&doc.nodes, values.as_object(), locale, &mut out);
550    Value::Object(out)
551}
552
553/// `form_locale_id`, `enrich_page_id` and `tenant` exist only to feed the
554/// enrichment pass, and mirror the arguments the extension-stream path
555/// already passes to `prerender_extension_streams_async_with`.
556/// `enrich_page_id` is the **page's** id, which is not always `page_id`:
557/// that one addresses the builder value store, and an alias reads its
558/// source row's values while still being its own page.
559#[allow(clippy::too_many_arguments)]
560pub async fn public_render_ctx(
561    pool: &rustango::sql::Pool,
562    page_id: i64,
563    page_type_id: i64,
564    preview_form: Option<&HashMap<String, String>>,
565    translations: &HashMap<String, String>,
566    tera: &tera::Tera,
567    form_locale_id: Option<i64>,
568    enrich_page_id: Option<i64>,
569    tenant: &str,
570) -> Option<(Value, HashMap<String, String>, String)> {
571    public_render(
572        pool,
573        page_id,
574        page_type_id,
575        preview_form,
576        translations,
577        tera,
578        form_locale_id,
579        enrich_page_id,
580        tenant,
581        None,
582    )
583    .await
584    .map(|r| (r.values, r.zone_html, r.body_html))
585}
586
587/// What [`public_render`] hands the page renderer.
588#[derive(Debug, Clone)]
589pub struct PublicRender {
590    /// The filled values, exposed to templates as `builder.*`.
591    pub values: Value,
592    /// Each zone's rendered HTML, by zone key.
593    pub zone_html: HashMap<String, String>,
594    /// The generic body for templates that don't know the schema.
595    pub body_html: String,
596    /// The first photo a media-picker field holds — the page's share
597    /// image when none is chosen on the Promote tab.
598    pub first_media_id: Option<i64>,
599    /// The choice fields' display labels, exposed as `builder_labels.*`
600    /// (see [`choice_labels`]).
601    pub labels: Value,
602}
603
604/// [`public_render_ctx`], plus the first photo among the fields.
605#[allow(clippy::too_many_arguments)]
606pub async fn public_render(
607    pool: &rustango::sql::Pool,
608    page_id: i64,
609    page_type_id: i64,
610    preview_form: Option<&HashMap<String, String>>,
611    translations: &HashMap<String, String>,
612    tera: &tera::Tera,
613    form_locale_id: Option<i64>,
614    enrich_page_id: Option<i64>,
615    tenant: &str,
616    locale_code: Option<&str>,
617) -> Option<PublicRender> {
618    let (mut values, compiled, doc) = values_for_doc(pool, page_id, page_type_id, preview_form).await?;
619    let first_media_id = first_media_id(&compiled, &values);
620    let labels = choice_labels(&doc, &values, locale_code);
621    // #567 — overlay the per-locale builder text leaves (fixed / group /
622    // zone) before rendering; empty overrides fall back to canonical.
623    if let Some(map) = values.as_object_mut() {
624        apply_builder_translations(&compiled, map, translations);
625    }
626    // Prerender each zone's stream with the dyn-block overlay so UI-defined
627    // groups resolve as `Block`s exactly like code-registered blocks.
628    let ctx = crate::block::BlockRenderCtx::new(tera).with_dyn_blocks(&compiled.dyn_blocks);
629    let mut zone_html = HashMap::new();
630    for item in &compiled.body {
631        let BodyItem::Zone { key, .. } = item else {
632            continue;
633        };
634        let Some(zv) = values.get(key) else {
635            continue;
636        };
637        // Enrich before the sync render, exactly as the extension-stream
638        // path does — `Block::render` cannot await, so a block that needs
639        // a row, an image URL or a query result has to be handed it here
640        // or it renders empty. Without this a chooser in a zone loses its
641        // `_url`/`_title` and a host's report block never gets `_rows`:
642        // UI-defined blocks could hold values but never carry data.
643        //
644        // On a clone, so `builder.*` keeps exactly what the author typed
645        // and the injected `_` keys stay confined to the render.
646        let mut zv = zv.clone();
647        crate::block::tera_helpers::enrich_chooser_refs_async(&mut zv, pool, form_locale_id).await;
648        crate::block::enrich::fire(
649            &mut zv,
650            crate::block::enrich::EnrichCtx {
651                pool,
652                tenant,
653                page_id: enrich_page_id,
654            },
655        )
656        .await;
657        if let Ok(html) = crate::block::render::prerender_stream(&zv, &ctx) {
658            zone_html.insert(key.clone(), html);
659        }
660    }
661    // Generic public body — for UI-created types whose (host-overridable)
662    // template doesn't know the schema's keys; code templates ignore it
663    // and read `builder.*` / `stream_render` directly.
664    let chooser_html = render_chooser_fields(&compiled.body, values.as_object(), pool, form_locale_id, &ctx).await;
665    // #863 — the generic body shows choice labels in the visitor's language.
666    let localized = locale_code.map(|_| {
667        let mut c = compiled.clone();
668        localize_choice_options(&mut c.body, &doc, locale_code);
669        c
670    });
671    let body_html = render_public_body(localized.as_ref().unwrap_or(&compiled), values.as_object(), &zone_html, &chooser_html);
672    Some(PublicRender {
673        values,
674        zone_html,
675        body_html,
676        first_media_id,
677        labels,
678    })
679}
680
681/// Replace the option labels of the compiled choice widgets with their
682/// `locale` labels from the schema document. Widget names encode the key
683/// path: `pb__glaze`, `pb__details__finish` (group `details`).
684fn localize_choice_options(items: &mut [BodyItem], doc: &crate::page_builder::Document, locale: Option<&str>) {
685    use crate::page_builder::schema::Node;
686    fn collect(nodes: &[Node], prefix: &str, out: &mut HashMap<String, Vec<crate::forms::schema::Choice>>) {
687        for node in nodes {
688            match node {
689                Node::Field(f) if !f.options.is_empty() => {
690                    out.insert(format!("{FIELD_PREFIX}{prefix}{}", f.key), f.options.clone());
691                }
692                Node::Row(r) => collect(&r.children, prefix, out),
693                Node::Group(g) => collect(&g.children, &format!("{prefix}{}__", g.key), out),
694                _ => {}
695            }
696        }
697    }
698    fn apply(items: &mut [BodyItem], choices: &HashMap<String, Vec<crate::forms::schema::Choice>>, locale: Option<&str>) {
699        let relabel = |w: &mut Widget| {
700            if let Some(opts) = choices.get(&w.name) {
701                for (value, label) in &mut w.options {
702                    if let Some(c) = opts.iter().find(|c| &c.value == value) {
703                        *label = c.label_in(locale).to_owned();
704                    }
705                }
706            }
707        };
708        for item in items {
709            match item {
710                BodyItem::Field(w) => relabel(w),
711                BodyItem::Row(cells) => cells.iter_mut().for_each(|(w, _)| relabel(w)),
712                BodyItem::Group { items, .. } => apply(items, choices, locale),
713                BodyItem::Zone { .. } => {}
714            }
715        }
716    }
717    let mut choices = HashMap::new();
718    collect(&doc.nodes, "", &mut choices);
719    apply(items, &choices, locale);
720}
721
722/// The id held by the first media-picker field of the body (top level,
723/// rows and groups, in order), if any is filled.
724#[must_use]
725pub fn first_media_id(compiled: &CompiledSchema, values: &Value) -> Option<i64> {
726    fn in_items(items: &[BodyItem], values: &Value, group: bool) -> Option<i64> {
727        let key = |w: &Widget| if group { strip_group(&w.name) } else { strip(&w.name) };
728        for item in items {
729            let found = match item {
730                BodyItem::Field(w) if w.kind == WidgetKind::MediaPicker => {
731                    crate::meta_tags::media_id(values.get(key(w)))
732                }
733                BodyItem::Row(cells) => cells
734                    .iter()
735                    .filter(|(w, _)| w.kind == WidgetKind::MediaPicker)
736                    .find_map(|(w, _)| crate::meta_tags::media_id(values.get(key(w)))),
737                BodyItem::Group { key, items, .. } => values.get(key).and_then(|g| in_items(items, g, true)),
738                _ => None,
739            };
740            if found.is_some() {
741                return found;
742            }
743        }
744        None
745    }
746    in_items(&compiled.body, values, false)
747}
748
749/// The built-in block that renders a chooser widget's value, and the key
750/// its id goes under.
751fn chooser_block(kind: crate::widget::WidgetKind) -> Option<(&'static str, &'static str)> {
752    use crate::widget::WidgetKind as K;
753    match kind {
754        K::MediaPicker => Some(("image", "media_id")),
755        K::PageChooser => Some(("page_chooser", "page_id")),
756        K::SnippetChooser => Some(("snippet_chooser", "snippet_id")),
757        K::DocumentChooser => Some(("document_chooser", "document_id")),
758        _ => None,
759    }
760}
761
762/// Every fixed field (top level or in a group) with its value-path key:
763/// `name`, or `group.name` inside a group.
764fn fixed_fields<'a>(items: &'a [BodyItem], prefix: &str, out: &mut Vec<(String, &'a Widget)>) {
765    for item in items {
766        match item {
767            BodyItem::Field(w) => out.push((field_path(prefix, w), w)),
768            BodyItem::Row(cells) => out.extend(cells.iter().map(|(w, _)| (field_path(prefix, w), w))),
769            BodyItem::Group { key, items, .. } => fixed_fields(items, key, out),
770            BodyItem::Zone { .. } => {}
771        }
772    }
773}
774
775fn field_path(prefix: &str, w: &Widget) -> String {
776    if prefix.is_empty() {
777        strip(&w.name)
778    } else {
779        format!("{prefix}.{}", strip_group(&w.name))
780    }
781}
782
783fn value_at<'v>(values: Option<&'v Map<String, Value>>, path: &str) -> Option<&'v Value> {
784    let mut parts = path.split('.');
785    let first = values?.get(parts.next()?)?;
786    parts.try_fold(first, |v, key| v.get(key))
787}
788
789/// Chooser fields rendered through the built-in chooser blocks, so a photo
790/// is an `<img>` and a page is a link exactly as the same block in a zone
791/// would be. One enrichment pass looks up every referenced row.
792async fn render_chooser_fields(
793    body: &[BodyItem],
794    values: Option<&Map<String, Value>>,
795    pool: &rustango::sql::Pool,
796    form_locale_id: Option<i64>,
797    ctx: &crate::block::BlockRenderCtx<'_>,
798) -> HashMap<String, String> {
799    let mut fields = Vec::new();
800    fixed_fields(body, "", &mut fields);
801    let mut paths = Vec::new();
802    let mut blocks = Vec::new();
803    for (path, w) in fields {
804        let (Some((block_type, id_key)), Some(id)) =
805            (chooser_block(w.kind), value_at(values, &path).and_then(Value::as_i64))
806        else {
807            continue;
808        };
809        blocks.push(serde_json::json!({ "type": block_type, "id": path, "value": { id_key: id } }));
810        paths.push(path);
811    }
812    let mut out = HashMap::new();
813    if blocks.is_empty() {
814        return out;
815    }
816    let mut stream = Value::Array(blocks);
817    crate::block::tera_helpers::enrich_chooser_refs_async(&mut stream, pool, form_locale_id).await;
818    if let Value::Array(blocks) = stream {
819        for (path, block) in paths.into_iter().zip(blocks) {
820            if let Ok(html) = crate::block::render::prerender_stream(&Value::Array(vec![block]), ctx) {
821                out.insert(path, html);
822            }
823        }
824    }
825    out
826}
827
828/// A fixed field's value as public HTML, by widget kind: rich text
829/// sanitized, markdown rendered, choices by label, links clickable (http,
830/// https, mailto and tel only). `None` for an empty value or a kind that is
831/// never shown (password, hidden) or rendered elsewhere (choosers).
832pub(crate) fn public_value_html(w: &Widget, v: &Value) -> Option<String> {
833    use crate::widget::WidgetKind as K;
834    let esc = |s: &str| tera::escape_html(s);
835    let label_of = |raw: &str| {
836        w.options
837            .iter()
838            .find(|(value, _)| value == raw)
839            .map_or_else(|| esc(raw), |(_, label)| esc(label))
840    };
841    let text = match v {
842        Value::Null => return None,
843        Value::String(s) if s.trim().is_empty() => return None,
844        Value::Array(a) if a.is_empty() => return None,
845        Value::String(s) => Some(s.as_str()),
846        _ => None,
847    };
848    let html = match (w.kind, text) {
849        (K::Password | K::Hidden, _) => return None,
850        (kind, _) if chooser_block(kind).is_some() => return None,
851        (K::Markdown, Some(s)) => crate::markdown::render(s),
852        (K::RichText, Some(s)) => crate::markdown::sanitize_html(s),
853        (K::Textarea, Some(s)) => esc(s).replace('\n', "<br>"),
854        (K::Url, Some(s)) if s.starts_with("https://") || s.starts_with("http://") => {
855            format!(r#"<a href="{0}">{0}</a>"#, esc(s))
856        }
857        (K::Email, Some(s)) if s.contains('@') && !s.contains(char::is_whitespace) => {
858            format!(r#"<a href="mailto:{0}">{0}</a>"#, esc(s))
859        }
860        (K::Tel, Some(s)) => format!(r#"<a href="tel:{}">{}</a>"#, esc(&s.replace(' ', "")), esc(s)),
861        (K::Select | K::Radio, Some(s)) => label_of(s),
862        (K::Checkboxes | K::MultiSelect, _) => {
863            let items: Vec<String> = match v {
864                Value::Array(a) => a
865                    .iter()
866                    .map(|x| x.as_str().map_or_else(|| x.to_string(), str::to_owned))
867                    .collect(),
868                _ => return None,
869            };
870            items.iter().map(|i| label_of(i)).collect::<Vec<_>>().join(", ")
871        }
872        (K::Boolean, _) => (if v.as_bool().unwrap_or(false) { "Yes" } else { "No" }).to_owned(),
873        (_, Some(s)) => esc(s),
874        (_, None) => match v {
875            Value::Array(_) | Value::Object(_) => return None,
876            // Numbers are stored as floats; 24.0 reads as 24.
877            Value::Number(n) if n.as_f64().is_some_and(|f| f.fract() == 0.0 && f.abs() < 1e15) => {
878                format!("{}", n.as_f64().unwrap_or_default() as i64)
879            }
880            other => esc(&other.to_string()),
881        },
882    };
883    Some(html)
884}
885
886/// Kinds whose value reads as a short fact ("Price: 24"), shown with its
887/// label; the rest (long text, images) stand on their own.
888fn labelled(kind: crate::widget::WidgetKind) -> bool {
889    use crate::widget::WidgetKind as K;
890    !matches!(
891        kind,
892        K::Markdown | K::RichText | K::Textarea | K::MediaPicker | K::SnippetChooser | K::PageChooser | K::DocumentChooser
893    )
894}
895
896/// The `cms_translation.field_path` prefix for page-builder leaves.
897pub const BUILDER_PATH_PREFIX: &str = "builder";
898
899/// Enumerate translatable text leaves in a page's builder values:
900/// fixed text fields + group text members (`builder.<key>` /
901/// `builder.<group>.<field>`) and stream text leaves inside repeater/flex
902/// zones (`builder.<zone>.<uuid>.<name>`, via the block walker with the
903/// dyn-block overlay). Only `is_translatable_text` widget kinds qualify.
904/// Reuses [`crate::block::translate::TranslatableLeaf`] so the admin
905/// translation surface lists builder leaves alongside stream leaves.
906#[must_use]
907pub fn builder_translatable_leaves(
908    compiled: &CompiledSchema,
909    values: &Value,
910) -> Vec<crate::block::translate::TranslatableLeaf> {
911    let obj = values.as_object();
912    let mut out = Vec::new();
913    for item in &compiled.body {
914        match item {
915            BodyItem::Field(w) => push_fixed_leaf(&mut out, &strip(&w.name), &w.label, w, obj),
916            BodyItem::Row(cells) => {
917                for (w, _) in cells {
918                    push_fixed_leaf(&mut out, &strip(&w.name), &w.label, w, obj);
919                }
920            }
921            BodyItem::Group { key, items, .. } => {
922                for it in items {
923                    match it {
924                        BodyItem::Field(w) => {
925                            push_fixed_leaf(
926                                &mut out,
927                                &format!("{key}.{}", strip_group(&w.name)),
928                                &w.label,
929                                w,
930                                obj,
931                            );
932                        }
933                        BodyItem::Row(cells) => {
934                            for (w, _) in cells {
935                                push_fixed_leaf(
936                                    &mut out,
937                                    &format!("{key}.{}", strip_group(&w.name)),
938                                    &w.label,
939                                    w,
940                                    obj,
941                                );
942                            }
943                        }
944                        _ => {}
945                    }
946                }
947            }
948            BodyItem::Zone { key, .. } => {
949                let arr = obj
950                    .and_then(|o| o.get(key))
951                    .cloned()
952                    .unwrap_or_else(|| Value::Array(Vec::new()));
953                out.extend(crate::block::translate::collect_translatable_leaves_with(
954                    &format!("{BUILDER_PATH_PREFIX}.{key}"),
955                    &arr,
956                    Some(&compiled.dyn_blocks),
957                ));
958            }
959        }
960    }
961    out
962}
963
964/// Read a (possibly dotted `group.field`) key out of the top-level value
965/// object, descending one group level.
966fn leaf_at<'a>(obj: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {
967    match key.split_once('.') {
968        Some((g, f)) => obj.get(g).and_then(Value::as_object).and_then(|m| m.get(f)),
969        None => obj.get(key),
970    }
971}
972
973/// Push a translatable fixed-field / group-member leaf into `out`. `key`
974/// is the value-store key (`<field>` or `<group>.<field>`); the emitted
975/// path is `builder.<key>`. No-op for non-text widgets.
976fn push_fixed_leaf(
977    out: &mut Vec<crate::block::translate::TranslatableLeaf>,
978    key: &str,
979    label: &str,
980    w: &Widget,
981    obj: Option<&Map<String, Value>>,
982) {
983    if !w.kind.is_translatable_text() {
984        return;
985    }
986    out.push(crate::block::translate::TranslatableLeaf {
987        path: format!("{BUILDER_PATH_PREFIX}.{key}"),
988        widget_kind: w.kind,
989        canonical_text: obj
990            .and_then(|o| leaf_at(o, key))
991            .and_then(Value::as_str)
992            .unwrap_or("")
993            .to_owned(),
994        block_type: "builder".to_owned(),
995        block_label: "Body".to_owned(),
996        field_label: label.to_owned(),
997        block_id: "builder".to_owned(),
998        depth: 0,
999    });
1000}
1001
1002/// Apply per-locale overrides to a page's builder values in place.
1003/// Fixed/group text leaves keyed `builder.<path>` are replaced when the
1004/// override is non-empty; zone streams delegate to the block overlay with
1005/// the dyn-block set. Missing/empty overrides leave the canonical value.
1006pub fn apply_builder_translations(
1007    compiled: &CompiledSchema,
1008    values: &mut Map<String, Value>,
1009    tr: &HashMap<String, String>,
1010) {
1011    if tr.is_empty() {
1012        return;
1013    }
1014    let ov = |path: &str| tr.get(path).map(|s| s.trim()).filter(|s| !s.is_empty());
1015    for item in &compiled.body {
1016        match item {
1017            BodyItem::Field(w) => {
1018                let k = strip(&w.name);
1019                if w.kind.is_translatable_text() {
1020                    if let Some(v) = ov(&format!("{BUILDER_PATH_PREFIX}.{k}")) {
1021                        values.insert(k, Value::String(v.to_owned()));
1022                    }
1023                }
1024            }
1025            BodyItem::Row(cells) => {
1026                for (w, _) in cells {
1027                    let k = strip(&w.name);
1028                    if w.kind.is_translatable_text() {
1029                        if let Some(v) = ov(&format!("{BUILDER_PATH_PREFIX}.{k}")) {
1030                            values.insert(k, Value::String(v.to_owned()));
1031                        }
1032                    }
1033                }
1034            }
1035            BodyItem::Group { key, items, .. } => {
1036                let Some(gobj) = values.get_mut(key).and_then(Value::as_object_mut) else {
1037                    continue;
1038                };
1039                for it in items {
1040                    let widgets: Vec<&Widget> = match it {
1041                        BodyItem::Field(w) => vec![w],
1042                        BodyItem::Row(cells) => cells.iter().map(|(w, _)| w).collect(),
1043                        _ => Vec::new(),
1044                    };
1045                    for w in widgets {
1046                        let f = strip_group(&w.name);
1047                        if w.kind.is_translatable_text() {
1048                            if let Some(v) = ov(&format!("{BUILDER_PATH_PREFIX}.{key}.{f}")) {
1049                                gobj.insert(f, Value::String(v.to_owned()));
1050                            }
1051                        }
1052                    }
1053                }
1054            }
1055            BodyItem::Zone { key, .. } => {
1056                if let Some(zv) = values.get(key) {
1057                    let localized = crate::block::translate::apply_translatable_overrides_with(
1058                        &format!("{BUILDER_PATH_PREFIX}.{key}"),
1059                        zv,
1060                        tr,
1061                        Some(&compiled.dyn_blocks),
1062                    );
1063                    values.insert(key.clone(), localized);
1064                }
1065            }
1066        }
1067    }
1068}
1069
1070/// Render a compiled schema's filled values as generic, semantically
1071/// classed public HTML (`pb-*`) — the fallback body for UI-created types.
1072/// Zones use the already-rendered `zone_html`, chooser fields
1073/// `chooser_html`; other fields are rendered by widget kind. Hosts can
1074/// style it or replace it with a per-type template.
1075#[must_use]
1076fn render_public_body(
1077    compiled: &CompiledSchema,
1078    values: Option<&Map<String, Value>>,
1079    zone_html: &HashMap<String, String>,
1080    chooser_html: &HashMap<String, String>,
1081) -> String {
1082    let mut out = String::new();
1083    out.push_str(r#"<div class="pb-body">"#);
1084    public_items(&compiled.body, "", values, zone_html, chooser_html, &mut out);
1085    out.push_str("</div>");
1086    out
1087}
1088
1089fn public_items(
1090    items: &[BodyItem],
1091    prefix: &str,
1092    values: Option<&Map<String, Value>>,
1093    zone_html: &HashMap<String, String>,
1094    chooser_html: &HashMap<String, String>,
1095    out: &mut String,
1096) {
1097    for item in items {
1098        match item {
1099            BodyItem::Field(w) => out.push_str(&public_field(w, prefix, values, chooser_html)),
1100            BodyItem::Row(cells) => {
1101                out.push_str(r#"<div class="pb-row">"#);
1102                for (w, _) in cells {
1103                    out.push_str(&public_field(w, prefix, values, chooser_html));
1104                }
1105                out.push_str("</div>");
1106            }
1107            BodyItem::Group { key, label, items } => {
1108                out.push_str(&format!(r#"<section class="pb-group pb-group--{}">"#, tera::escape_html(key)));
1109                if !label.is_empty() {
1110                    out.push_str(&format!("<h3>{}</h3>", tera::escape_html(label)));
1111                }
1112                public_items(items, key, values, zone_html, chooser_html, out);
1113                out.push_str("</section>");
1114            }
1115            BodyItem::Zone { key, .. } => {
1116                out.push_str(&format!(
1117                    r#"<div class="pb-zone pb-zone--{}">{}</div>"#,
1118                    tera::escape_html(key),
1119                    zone_html.get(key).map_or("", String::as_str),
1120                ));
1121            }
1122        }
1123    }
1124}
1125
1126fn public_field(
1127    w: &Widget,
1128    prefix: &str,
1129    values: Option<&Map<String, Value>>,
1130    chooser_html: &HashMap<String, String>,
1131) -> String {
1132    let path = field_path(prefix, w);
1133    let inner = match chooser_html.get(&path) {
1134        Some(html) => Some(html.clone()),
1135        None => value_at(values, &path).and_then(|v| public_value_html(w, v)),
1136    };
1137    let Some(inner) = inner else {
1138        return String::new();
1139    };
1140    let key = tera::escape_html(path.rsplit('.').next().unwrap_or(&path));
1141    if labelled(w.kind) && !w.label.is_empty() {
1142        format!(
1143            r#"<div class="pb-field pb-field--{key}"><span class="pb-label">{}</span> <span class="pb-value">{inner}</span></div>"#,
1144            tera::escape_html(&w.label)
1145        )
1146    } else {
1147        format!(r#"<div class="pb-field pb-field--{key}">{inner}</div>"#)
1148    }
1149}
1150
1151/// Pre-render the editor HTML for a compiled schema, prefilled from
1152/// `values`. Fixed fields/rows/groups render through the shared
1153/// `_widget.html` macro; repeater/flex zones render through the stream
1154/// editor with the dyn-block overlay so `stream_editor.js` drives them
1155/// unchanged.
1156#[must_use]
1157pub fn render_body(
1158    compiled: &CompiledSchema,
1159    values: &Value,
1160    tera: &tera::Tera,
1161) -> String {
1162    let obj = values.as_object();
1163    let mut out = String::new();
1164    for item in &compiled.body {
1165        match item {
1166            BodyItem::Field(w) => out.push_str(&render_field(w, obj, tera)),
1167            BodyItem::Row(cells) => {
1168                out.push_str(r#"<div class="rcms-field-row rcms-flex rcms-gap-3 rcms-flex-wrap">"#);
1169                for (w, width) in cells {
1170                    out.push_str(&format!(
1171                        r#"<div style="flex:{width} 1 0;min-width:140px;">"#
1172                    ));
1173                    out.push_str(&render_field(w, obj, tera));
1174                    out.push_str("</div>");
1175                }
1176                out.push_str("</div>");
1177            }
1178            BodyItem::Group { key, label, items } => {
1179                let group_obj = obj.and_then(|o| o.get(key)).and_then(Value::as_object);
1180                let legend = if label.is_empty() { key } else { label };
1181                out.push_str(&format!(
1182                    r#"<fieldset class="rcms-panel-group"><legend>{}</legend>"#,
1183                    tera::escape_html(legend)
1184                ));
1185                render_group_items(items, group_obj, tera, &mut out);
1186                out.push_str("</fieldset>");
1187            }
1188            BodyItem::Zone {
1189                key, label, widget, ..
1190            } => {
1191                let mut zw = widget.clone();
1192                zw.value = obj
1193                    .and_then(|o| o.get(key))
1194                    .map(|v| serde_json::to_string(v).unwrap_or_default())
1195                    .unwrap_or_else(|| "[]".to_owned());
1196                // The stream-list + per-type clone templates sit on
1197                // `custom_html`; the `_widget.html` stream arm wraps them
1198                // with the `data-stream-root` hidden input (so the zone
1199                // round-trips) + the picker dialog (so editors can add
1200                // entries). `render_stream_editor_with` alone emits neither.
1201                zw.custom_html = crate::block::admin::render_stream_editor_with(
1202                    &zw,
1203                    tera,
1204                    Some(&compiled.dyn_blocks),
1205                );
1206                let picker = zone_picker_options(&zw.allowed, &compiled.dyn_blocks);
1207                out.push_str(&format!(
1208                    r#"<fieldset class="rcms-panel-group"><legend>{}</legend>"#,
1209                    tera::escape_html(label)
1210                ));
1211                out.push_str(&crate::block::admin::render_widget_via_macro_with(
1212                    &zw, tera, &picker,
1213                ));
1214                out.push_str("</fieldset>");
1215            }
1216        }
1217    }
1218    out
1219}
1220
1221fn render_field(w: &Widget, values: Option<&Map<String, Value>>, tera: &tera::Tera) -> String {
1222    let mut w = w.clone();
1223    let key = strip(&w.name);
1224    if let Some(v) = values.and_then(|o| o.get(&key)) {
1225        w.value = value_to_input(v);
1226    }
1227    crate::block::admin::render_widget_via_macro(&w, tera)
1228}
1229
1230/// Build the block-picker options for a flex zone / repeater from its
1231/// allowed dyn-block type names. Editors pick these to add entries; the
1232/// `_widget.html` stream arm renders them into its `<dialog>`.
1233fn zone_picker_options(
1234    allowed: &[String],
1235    dyn_blocks: &crate::page_builder::DynBlockSet,
1236) -> Vec<crate::block::admin::PickerOption> {
1237    allowed
1238        .iter()
1239        .filter_map(|name| {
1240            let block = crate::page_builder::resolve_block(Some(dyn_blocks), name)?;
1241            Some(crate::block::admin::PickerOption {
1242                type_name: block.type_name().to_owned(),
1243                verbose_name: block.verbose_name().to_owned(),
1244                icon: block.icon().map(str::to_owned),
1245                group: None,
1246                description: None,
1247                default_value: None,
1248                collapsed: false,
1249                preview_html: String::new(),
1250            })
1251        })
1252        .collect()
1253}
1254
1255fn render_group_items(
1256    items: &[BodyItem],
1257    group_obj: Option<&Map<String, Value>>,
1258    tera: &tera::Tera,
1259    out: &mut String,
1260) {
1261    for item in items {
1262        match item {
1263            BodyItem::Field(w) => {
1264                let mut w = w.clone();
1265                let key = strip_group(&w.name);
1266                if let Some(v) = group_obj.and_then(|o| o.get(&key)) {
1267                    w.value = value_to_input(v);
1268                }
1269                out.push_str(&crate::block::admin::render_widget_via_macro(&w, tera));
1270            }
1271            BodyItem::Row(cells) => {
1272                out.push_str(r#"<div class="rcms-field-row rcms-flex rcms-gap-3 rcms-flex-wrap">"#);
1273                for (w, width) in cells {
1274                    let mut w = w.clone();
1275                    let key = strip_group(&w.name);
1276                    if let Some(v) = group_obj.and_then(|o| o.get(&key)) {
1277                        w.value = value_to_input(v);
1278                    }
1279                    out.push_str(&format!(
1280                        r#"<div style="flex:{width} 1 0;min-width:140px;">"#
1281                    ));
1282                    out.push_str(&crate::block::admin::render_widget_via_macro(&w, tera));
1283                    out.push_str("</div>");
1284                }
1285                out.push_str("</div>");
1286            }
1287            _ => {}
1288        }
1289    }
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294
1295    #[test]
1296    fn whole_numbers_prefill_without_a_decimal() {
1297        assert_eq!(super::value_to_input(&serde_json::json!(32.0)), "32");
1298        assert_eq!(super::value_to_input(&serde_json::json!(12.5)), "12.5");
1299        assert_eq!(super::value_to_input(&serde_json::json!("x")), "x");
1300    }
1301
1302    use super::*;
1303    use crate::page_builder::compile;
1304    use crate::page_builder::schema::{parse, ComponentEntry};
1305    use std::collections::HashMap;
1306
1307    fn compiled() -> CompiledSchema {
1308        let doc = parse(&serde_json::json!({
1309            "nodes": [
1310                { "kind": "field", "key": "subtitle", "widget": "text" },
1311                { "kind": "row", "children": [
1312                    { "kind": "field", "key": "a", "widget": "integer" },
1313                    { "kind": "field", "key": "flag", "widget": "boolean" }
1314                ]},
1315                { "kind": "group", "key": "hero", "label": "Hero", "children": [
1316                    { "kind": "field", "key": "heading", "widget": "text" }
1317                ]},
1318                { "kind": "repeater", "key": "faqs", "label": "FAQs",
1319                  "item": { "key": "faq", "children": [ { "kind": "field", "key": "q", "widget": "text" } ] } }
1320            ]
1321        }))
1322        .unwrap();
1323        compile::compile(&doc, &HashMap::<String, ComponentEntry>::new(), 3)
1324    }
1325
1326    #[test]
1327    fn save_walks_body_into_typed_json() {
1328        let c = compiled();
1329        let mut form = HashMap::new();
1330        form.insert("pb__subtitle".to_owned(), "Hello".to_owned());
1331        form.insert("pb__a".to_owned(), "42".to_owned());
1332        form.insert("pb__flag".to_owned(), "on".to_owned());
1333        form.insert("pb__hero__heading".to_owned(), "Hi".to_owned());
1334        form.insert(
1335            "pb__faqs".to_owned(),
1336            r#"[{"type":"r_faqs","id":"x","value":{"q":"?"}}]"#.to_owned(),
1337        );
1338
1339        // The shared pure transform used by both save + unsaved preview.
1340        let data = build_values(&c, &form);
1341        assert_eq!(data["subtitle"], serde_json::json!("Hello"));
1342        assert_eq!(data["a"], serde_json::json!(42));
1343        assert_eq!(data["flag"], serde_json::json!(true));
1344        assert_eq!(data["hero"], serde_json::json!({"heading": "Hi"}));
1345        assert!(data["faqs"].is_array());
1346    }
1347
1348    #[test]
1349    fn builder_leaves_and_overlay_roundtrip() {
1350        let c = compiled();
1351        let mut form = HashMap::new();
1352        form.insert("pb__subtitle".to_owned(), "Hello".to_owned());
1353        form.insert("pb__a".to_owned(), "42".to_owned());
1354        form.insert("pb__hero__heading".to_owned(), "Hi".to_owned());
1355        form.insert(
1356            "pb__faqs".to_owned(),
1357            r#"[{"type":"r_faqs","id":"x1","value":{"q":"Question?"}}]"#.to_owned(),
1358        );
1359        let values = Value::Object(build_values(&c, &form));
1360
1361        // Extraction: text leaves only (subtitle, hero.heading, faq q);
1362        // the integer `a` and boolean `flag` are excluded.
1363        let leaves = builder_translatable_leaves(&c, &values);
1364        let paths: Vec<&str> = leaves.iter().map(|l| l.path.as_str()).collect();
1365        assert!(paths.contains(&"builder.subtitle"), "{paths:?}");
1366        assert!(paths.contains(&"builder.hero.heading"), "{paths:?}");
1367        assert!(paths.contains(&"builder.faqs.x1.q"), "{paths:?}");
1368        assert!(!paths.iter().any(|p| p.ends_with(".a")), "{paths:?}");
1369
1370        // Overlay: non-empty overrides win; untranslated leaves keep canonical.
1371        let mut tr = HashMap::new();
1372        tr.insert("builder.subtitle".to_owned(), "Bonjour".to_owned());
1373        tr.insert("builder.hero.heading".to_owned(), "Salut".to_owned());
1374        tr.insert("builder.faqs.x1.q".to_owned(), "Question ?".to_owned());
1375        let mut map = values.as_object().unwrap().clone();
1376        apply_builder_translations(&c, &mut map, &tr);
1377        assert_eq!(map["subtitle"], serde_json::json!("Bonjour"));
1378        assert_eq!(map["hero"]["heading"], serde_json::json!("Salut"));
1379        assert_eq!(
1380            map["faqs"][0]["value"]["q"],
1381            serde_json::json!("Question ?")
1382        );
1383        // `a` (untranslated, non-text) stays canonical.
1384        assert_eq!(map["a"], serde_json::json!(42));
1385    }
1386
1387    #[test]
1388    fn coerce_kinds() {
1389        assert_eq!(coerce(WidgetKind::Integer, "7"), serde_json::json!(7));
1390        assert_eq!(coerce(WidgetKind::Boolean, "on"), serde_json::json!(true));
1391        assert_eq!(coerce(WidgetKind::Boolean, ""), serde_json::json!(false));
1392        assert_eq!(coerce(WidgetKind::MediaPicker, ""), Value::Null);
1393        assert_eq!(coerce(WidgetKind::MediaPicker, "9"), serde_json::json!(9));
1394        assert_eq!(coerce(WidgetKind::Text, "x"), serde_json::json!("x"));
1395    }
1396
1397    #[test]
1398    fn park_orphans_moves_dropped_keys_and_keeps_prior_bag() {
1399        // Freshly-rebuilt data for the current schema (declares subtitle + kept).
1400        let mut data = serde_json::Map::new();
1401        data.insert("subtitle".to_owned(), serde_json::json!("new"));
1402        data.insert("kept".to_owned(), serde_json::json!("v"));
1403        // Stored data still carries a since-removed `hero_caption`, plus an
1404        // already-parked bag from an earlier upgrade.
1405        let existing = serde_json::json!({
1406            "subtitle": "old",
1407            "kept": "v",
1408            "hero_caption": "Cover photo",
1409            "_orphaned": { "ancient": "kept-forever" }
1410        });
1411        let known = vec!["subtitle".to_owned(), "kept".to_owned()];
1412        park_orphans(&mut data, &existing, &known);
1413
1414        let orphaned = data["_orphaned"].as_object().unwrap();
1415        // Dropped key parked; prior bag preserved.
1416        assert_eq!(orphaned["hero_caption"], serde_json::json!("Cover photo"));
1417        assert_eq!(orphaned["ancient"], serde_json::json!("kept-forever"));
1418        // Declared keys are NOT parked and keep the fresh values.
1419        assert!(!orphaned.contains_key("subtitle"));
1420        assert!(!orphaned.contains_key("kept"));
1421        assert_eq!(data["subtitle"], serde_json::json!("new"));
1422    }
1423
1424    #[test]
1425    fn park_orphans_noop_when_nothing_dropped() {
1426        let mut data = serde_json::Map::new();
1427        data.insert("subtitle".to_owned(), serde_json::json!("x"));
1428        let existing = serde_json::json!({ "subtitle": "x" });
1429        park_orphans(&mut data, &existing, &["subtitle".to_owned()]);
1430        assert!(!data.contains_key("_orphaned"));
1431    }
1432
1433    #[test]
1434    fn a_partial_edit_that_omits_the_builder_keeps_the_body() {
1435        // `save_from_form` rebuilds the whole body from the form, so a
1436        // caller that hand-builds one (the MCP `update_page`) and does not
1437        // prefill writes every zone back empty. That turned "set an SEO
1438        // title" into "delete the page's content".
1439        let c = compiled();
1440        let stored = serde_json::json!({
1441            "subtitle": "Hello",
1442            "a": 42,
1443            "flag": true,
1444            "hero": { "heading": "Hi" },
1445            "faqs": [{ "type": "r_faqs", "id": "x", "value": { "q": "?" } }]
1446        });
1447
1448        // Round-trip: stored values -> form -> stored values.
1449        let mut form = HashMap::new();
1450        prefill_form(&c, &stored, &mut form);
1451        let rebuilt = Value::Object(build_values(&c, &form));
1452
1453        assert_eq!(rebuilt["subtitle"], serde_json::json!("Hello"));
1454        assert_eq!(rebuilt["a"], serde_json::json!(42));
1455        assert_eq!(rebuilt["flag"], serde_json::json!(true));
1456        assert_eq!(rebuilt["hero"]["heading"], serde_json::json!("Hi"));
1457        assert_eq!(
1458            rebuilt["faqs"].as_array().map(Vec::len),
1459            Some(1),
1460            "the repeater zone was emptied by a partial edit: {rebuilt}"
1461        );
1462    }
1463}
1464
1465#[cfg(test)]
1466mod public_value_tests {
1467    use super::public_value_html;
1468    use crate::widget::{Widget, WidgetKind as K};
1469    use serde_json::json;
1470
1471    fn html(kind: K, v: serde_json::Value) -> Option<String> {
1472        let w = Widget::new(kind, "f", "F").with_options([("blue", "Blue glaze"), ("white", "White")]);
1473        public_value_html(&w, &v)
1474    }
1475
1476    /// Values render by kind instead of as escaped raw text.
1477    #[test]
1478    fn values_render_by_widget_kind() {
1479        assert_eq!(html(K::RichText, json!("<p>Hi<script>x</script></p>")).unwrap(), "<p>Hi</p>");
1480        assert!(html(K::Markdown, json!("**Hand-made**")).unwrap().contains("<strong>Hand-made</strong>"));
1481        assert_eq!(html(K::Select, json!("blue")).unwrap(), "Blue glaze");
1482        assert_eq!(html(K::Checkboxes, json!(["blue", "white"])).unwrap(), "Blue glaze, White");
1483        assert_eq!(html(K::Boolean, json!(true)).unwrap(), "Yes");
1484        assert_eq!(html(K::Number, json!(24.5)).unwrap(), "24.5");
1485        assert_eq!(html(K::Number, json!(24.0)).unwrap(), "24");
1486        assert_eq!(html(K::Textarea, json!("a\nb<")).unwrap(), "a<br>b&lt;");
1487        // Escaped like any template output (`/` as `&#x2F;`), still a link.
1488        let link = html(K::Url, json!("https://x.test/a")).unwrap();
1489        assert!(link.starts_with(r#"<a href="https:"#) && link.contains("x.test") && link.ends_with("</a>"), "{link}");
1490    }
1491
1492    #[test]
1493    fn unsafe_links_and_hidden_kinds_do_not_render_as_links() {
1494        assert_eq!(html(K::Url, json!("javascript:alert(1)")).unwrap(), "javascript:alert(1)");
1495        assert!(html(K::Password, json!("secret")).is_none());
1496        assert!(html(K::Hidden, json!("x")).is_none());
1497        assert!(html(K::MediaPicker, json!(7)).is_none(), "choosers render through their block");
1498        assert!(html(K::Text, json!("")).is_none());
1499        assert!(html(K::Text, json!(null)).is_none());
1500    }
1501}