Skip to main content

rustango_cms/block/
render.rs

1//! Default render path + recursive stream walker.
2//!
3//! Templates reach this through the `stream_render` Tera function
4//! (`block::tera_helpers`).
5//!
6//! ## Default render
7//!
8//! [`default_render`] walks a block's [`crate::Block::fields`] in
9//! order, deserializes each field's slice of the block value, and
10//! feeds the lot into the block's Tera template
11//! (`blocks/<type_name>.html` unless [`crate::Block::template`]
12//! overrides). Nested `Stream` / `Repeat` fields recurse via
13//! [`prerender_stream`].
14//!
15//! ## Stream walker
16//!
17//! [`prerender_stream`] takes a JSON `Value::Array` of
18//! `{type, id, value}` entries, looks up each block in the registry,
19//! calls [`crate::Block::render`], and concatenates the result. Unknown
20//! `type` values surface a minimal yellow drift-banner snippet rather
21//! than panicking — admins fix this in the editor by removing the
22//! orphan block.
23
24use serde_json::Value;
25use tera::Context;
26
27use super::{Block, BlockError, BlockRenderCtx};
28
29/// Walk a block's fields and render its template.
30///
31/// Template lookup precedence:
32/// 1. `block.template()` if it returns `Some(path)`.
33/// 2. Otherwise `blocks/<type_name>.html`.
34///
35/// The rendered template receives the following Tera context:
36/// - `value`: the block's whole value dict (mirrors what authors
37///   actually want — addressing fields by name as
38///   `{{ value.heading }}`).
39/// - `block_type`: the wire `type_name`.
40/// - Every [`crate::block::BlockField::Computed`] field's `render`
41///   output as `computed.<field_name>` so templates can pull
42///   derived chips inline.
43///
44/// # Errors
45/// [`BlockError::TemplateRender`] on Tera failure;
46/// [`BlockError::Shape`] when the block value isn't an object (the
47/// only shape the field walker accepts).
48pub fn default_render<B: Block + ?Sized>(
49    block: &B,
50    value: &Value,
51    ctx: &BlockRenderCtx<'_>,
52) -> Result<String, BlockError> {
53    let template = block.template().map_or_else(
54        || format!("blocks/{}.html", block.type_name()),
55        str::to_owned,
56    );
57
58    let value_object = match value {
59        Value::Object(_) => value.clone(),
60        Value::Null => Value::Object(serde_json::Map::new()),
61        // Single-field blocks may stash a bare scalar at `value`;
62        // canonicalize to the {field_name: scalar} shape by looking
63        // up the first field. Both shapes are accepted on input.
64        scalar => {
65            let mut map = serde_json::Map::new();
66            if let Some(first) = block.fields().into_iter().next() {
67                map.insert(first.name().to_owned(), scalar.clone());
68            }
69            Value::Object(map)
70        }
71    };
72
73    // Evaluate every Computed field once, stash as `computed.<name>`.
74    let mut computed = serde_json::Map::new();
75    for field in block.fields() {
76        if let super::BlockField::Computed { name, render, .. } = field {
77            computed.insert(name, Value::String(render(&value_object, ctx)));
78        }
79    }
80
81    // Stamp `Block::extra_context()` first — the framework's
82    // canonical keys (`value`, `block_type`, `computed`) are stamped
83    // afterwards so they always win, preventing a block from
84    // accidentally shadowing them.
85    let mut tera_ctx = Context::new();
86    let extras = block.extra_context(&value_object, ctx);
87    for (k, v) in extras {
88        tera_ctx.insert(&k, &v);
89    }
90    tera_ctx.insert("value", &value_object);
91    tera_ctx.insert("block_type", &block.type_name());
92    tera_ctx.insert("computed", &Value::Object(computed));
93
94    ctx.tera
95        .render(&template, &tera_ctx)
96        .map_err(|source| BlockError::TemplateRender {
97            block_type: block.type_name().to_owned(),
98            template,
99            source,
100        })
101}
102
103/// Walk a JSON array of `{type, id, value}` entries and concatenate
104/// each block's [`Block::render`] output.
105///
106/// Unknown / unregistered `type` values emit a minimal `<div
107/// class="rcms-stream-drift">` chrome carrying the unknown type name —
108/// authors see exactly what's orphaned + can remove it via the editor.
109/// This matches the schema-drift "yellow banner" UX from the plan
110/// (`stream_block.py:235-287` filters silently; we render visibly).
111///
112/// A block that fails to render — a template error, a bad value — leaves a
113/// hidden `rcms-stream-error` marker naming its type and is logged; the rest
114/// of the stream still renders. It used to fail the whole stream, and
115/// the page then rendered with its body missing.
116///
117/// # Errors
118/// Non-array input returns a shape error.
119pub fn prerender_stream(value: &Value, ctx: &BlockRenderCtx<'_>) -> Result<String, BlockError> {
120    let items = match value {
121        Value::Array(items) => items,
122        Value::Null => return Ok(String::new()),
123        _ => {
124            return Err(BlockError::Shape {
125                block_type: "<stream>".to_owned(),
126                path: String::new(),
127                reason: "expected JSON array of block entries".to_owned(),
128            })
129        }
130    };
131
132    let mut out = String::new();
133    for (idx, entry) in items.iter().enumerate() {
134        let Some(type_name) = entry.get("type").and_then(Value::as_str) else {
135            tracing::warn!(target: "rustango_cms::block", index = idx, "stream entry has no `type`; skipped");
136            out.push_str(&failed_block_marker("<missing type>"));
137            continue;
138        };
139        let inner_value = entry.get("value").unwrap_or(&Value::Null);
140        // #559 — the page-builder dyn-block overlay wins over the
141        // inventory registry so UI-defined groups render like code blocks.
142        match crate::page_builder::resolve_block(ctx.dyn_blocks, type_name) {
143            Some(block) => match block.render(inner_value, ctx) {
144                Ok(rendered) => out.push_str(&rendered),
145                Err(e) => {
146                    tracing::warn!(
147                        target: "rustango_cms::block",
148                        block_type = type_name, index = idx, error = %e,
149                        "block failed to render; the rest of the stream still renders"
150                    );
151                    out.push_str(&failed_block_marker(type_name));
152                }
153            },
154            None => {
155                out.push_str(&format!(
156                    "<div class=\"rcms-stream-drift\" data-unknown-type=\"{}\">\
157                       Schema drift: unknown block type \"{}\" — \
158                       was it removed without a migration?\
159                     </div>",
160                    tera::escape_html(type_name),
161                    tera::escape_html(type_name),
162                ));
163            }
164        }
165    }
166    Ok(out)
167}
168
169/// The stand-in for a block that failed to render: hidden, so visitors see
170/// nothing broken, but findable in the page source by its type.
171fn failed_block_marker(type_name: &str) -> String {
172    format!(
173        "<div class=\"rcms-stream-error\" data-block-type=\"{}\" hidden></div>",
174        tera::escape_html(type_name)
175    )
176}