1use serde_json::Value;
37use tera::{Context, Tera};
38
39use crate::block::{self, BlockField};
40use crate::widget::{Widget, WidgetKind};
41
42#[must_use]
50pub fn render_stream_editor(
51 widget: &Widget,
52 tera: &Tera,
53) -> String {
54 render_stream_editor_with(widget, tera, None)
55}
56
57#[must_use]
62pub fn render_stream_editor_with(
63 widget: &Widget,
64 tera: &Tera,
65 dyn_set: Option<&crate::page_builder::DynBlockSet>,
66) -> String {
67 let parsed: Value = serde_json::from_str(&widget.value).unwrap_or(Value::Array(Vec::new()));
68 let blocks_arr = parsed.as_array().cloned().unwrap_or_default();
69
70 let mut out = String::new();
71
72 out.push_str(r#"<div class="rcms-stream-list" data-stream-list>"#);
74 for entry in &blocks_arr {
75 if let Some(html) = render_block_entry(entry, tera, dyn_set) {
76 out.push_str(&html);
77 }
78 }
79 out.push_str("</div>");
80
81 let mut needed: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
87 let mut frontier: Vec<String> = widget.allowed.to_vec();
88 while let Some(name) = frontier.pop() {
89 if !needed.insert(name.clone()) {
90 continue;
91 }
92 if let Some(block) = crate::page_builder::resolve_block(dyn_set, &name) {
93 for field in block.fields() {
94 match field {
95 BlockField::Stream { allowed, .. } => {
96 for a in allowed {
97 if !needed.contains(&a) {
98 frontier.push(a);
99 }
100 }
101 }
102 BlockField::Repeat { item_type, .. } => {
103 if !needed.contains(&item_type) {
104 frontier.push(item_type);
105 }
106 }
107 _ => {}
108 }
109 }
110 }
111 }
112 for ref_name in &needed {
122 let is_dyn = dyn_set.map_or(false, |s| s.get(ref_name).is_some());
123 if is_dyn {
124 if let Some(block) = crate::page_builder::resolve_block(dyn_set, ref_name) {
125 let empty_body = render_block_inline(
126 &*block,
127 &Value::Object(Default::default()),
128 None,
129 tera,
130 dyn_set,
131 );
132 out.push_str(&format!(
133 r#"<template data-block-template="{}">{}</template>"#,
134 tera::escape_html(ref_name),
135 empty_body,
136 ));
137 }
138 continue;
139 }
140 let key = ref_name.clone();
141 if let Some(hit) = template_cache()
142 .lock()
143 .ok()
144 .and_then(|c| c.get(&key).cloned())
145 {
146 out.push_str(&hit);
147 continue;
148 }
149 if let Some(block) = crate::page_builder::resolve_block(dyn_set, ref_name) {
150 let empty_body = render_block_inline(
151 &*block,
152 &Value::Object(Default::default()),
153 None,
154 tera,
155 dyn_set,
156 );
157 let rendered = format!(
158 r#"<template data-block-template="{}">{}</template>"#,
159 tera::escape_html(ref_name),
160 empty_body,
161 );
162 if let Ok(mut c) = template_cache().lock() {
163 c.insert(key, rendered.clone());
164 }
165 out.push_str(&rendered);
166 }
167 }
168 out
169}
170
171type TemplateCache = std::sync::Mutex<std::collections::HashMap<String, String>>;
176
177fn template_cache() -> &'static TemplateCache {
178 static CACHE: std::sync::OnceLock<TemplateCache> = std::sync::OnceLock::new();
179 CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
180}
181
182fn render_block_entry(
186 entry: &Value,
187 tera: &Tera,
188 dyn_set: Option<&crate::page_builder::DynBlockSet>,
189) -> Option<String> {
190 let type_name = entry.get("type").and_then(Value::as_str)?;
191 let id = entry.get("id").and_then(Value::as_str).map(str::to_owned);
192 let value = entry.get("value").unwrap_or(&Value::Null);
193
194 let block = crate::page_builder::resolve_block(dyn_set, type_name)?;
195 Some(render_block_inline(
196 &*block,
197 value,
198 id.as_deref(),
199 tera,
200 dyn_set,
201 ))
202}
203
204fn render_block_inline(
207 block: &dyn block::Block,
208 value: &Value,
209 id: Option<&str>,
210 tera: &Tera,
211 dyn_set: Option<&crate::page_builder::DynBlockSet>,
212) -> String {
213 let mut html = String::new();
214 let id_attr = match id {
215 Some(s) => format!(r#" data-id="{}""#, tera::escape_html(s)),
216 None => String::new(),
217 };
218 let label_format_attr = match block.label_format() {
225 Some(fmt) => format!(r#" data-label-format="{}""#, tera::escape_html(fmt),),
226 None => String::new(),
227 };
228 html.push_str(&format!(
229 r#"<div class="rcms-stream-block" data-stream-block data-type="{type}"{id} data-version="{version}"{label_format}>"#,
230 type = tera::escape_html(block.type_name()),
231 id = id_attr,
232 version = block.version(),
233 label_format = label_format_attr,
234 ));
235
236 let initial_label = match block.label_format() {
240 Some(fmt) => {
241 let rendered = format_label(fmt, value);
242 if rendered.trim().is_empty() {
243 block.verbose_name().to_owned()
244 } else {
245 rendered
246 }
247 }
248 None => block.verbose_name().to_owned(),
249 };
250
251 html.push_str(r#"<div class="rcms-stream-block-header">"#);
253 if let Some(icon) = block.icon() {
254 html.push_str(&format!(
255 r#"<span class="material-symbols-rounded sm rcms-stream-block-icon">{}</span>"#,
256 tera::escape_html(icon),
257 ));
258 }
259 html.push_str(&format!(
260 r#"<strong class="rcms-stream-block-title" data-stream-block-title>{}</strong>"#,
261 tera::escape_html(&initial_label),
262 ));
263 html.push_str(concat!(
264 r#"<span class="rcms-stream-block-actions">"#,
265 r#"<button type="button" class="rcms-btn" data-action="toggle-collapse" title="Collapse / expand"><span class="material-symbols-rounded sm">unfold_less</span></button>"#,
266 r#"<button type="button" class="rcms-btn" data-action="move-up" title="Move up"><span class="material-symbols-rounded sm">arrow_upward</span></button>"#,
267 r#"<button type="button" class="rcms-btn" data-action="move-down" title="Move down"><span class="material-symbols-rounded sm">arrow_downward</span></button>"#,
268 r#"<button type="button" class="rcms-btn" data-action="duplicate" title="Duplicate"><span class="material-symbols-rounded sm">content_copy</span></button>"#,
269 r#"<button type="button" class="rcms-btn" data-action="remove" title="Remove"><span class="material-symbols-rounded sm">close</span></button>"#,
270 r#"</span>"#,
271 ));
272 html.push_str("</div>");
273
274 html.push_str(r#"<div class="rcms-stream-block-body">"#);
276 for field in block.fields() {
277 match field {
278 BlockField::Widget {
279 name,
280 label,
281 widget,
282 options,
283 help,
284 required,
285 meta,
286 } => {
287 let field_value = value.get(&name).cloned().unwrap_or(Value::Null);
288 let widget_value = json_to_widget_value(&field_value, &widget);
289 let instance_name = match id {
296 Some(block_id) => format!("blk_{block_id}__{name}"),
297 None => format!("blk_tpl__{name}"),
298 };
299 let mut w = Widget::new(widget, instance_name, label);
300 w.value = widget_value;
301 if let Some(h) = help {
302 w.help = h;
303 }
304 w.required = required;
305 w.options = options
306 .iter()
307 .map(|(v, l)| (v.clone(), l.clone()))
308 .collect();
309 if let Some(n) = meta.min_length {
314 w.min_length = Some(n);
315 }
316 if let Some(n) = meta.max_length {
317 w.max_length = Some(n);
318 }
319 if let Some(p) = meta.pattern.clone() {
320 w.pattern = p;
321 }
322 if let Some(v) = meta.min_value {
323 w.min = Some(v);
324 }
325 if let Some(v) = meta.max_value {
326 w.max = Some(v);
327 }
328 if let Some(f) = meta.chooser_filter.clone() {
330 w.custom_name = f;
331 }
332 if w.value.is_empty() {
336 if let Some(d) = meta.default_value.clone() {
337 w.value = d;
338 }
339 }
340 let widget_html = render_widget_via_macro(&w, tera);
341 html.push_str(&format!(
342 r#"<div class="rcms-stream-field" data-stream-field="{}">{}</div>"#,
343 tera::escape_html(&name),
344 widget_html,
345 ));
346 }
347 BlockField::Stream {
348 name,
349 label,
350 allowed,
351 ..
352 } => {
353 let nested_value = value
354 .get(&name)
355 .cloned()
356 .unwrap_or(Value::Array(Vec::new()));
357 let nested_arr = nested_value.as_array().cloned().unwrap_or_default();
358 let allowed_csv = allowed.join(",");
359 html.push_str(&format!(
360 r#"<fieldset class="rcms-stream-nested" data-stream-field="{name}"><legend>{label}</legend>"#,
361 name = tera::escape_html(&name),
362 label = tera::escape_html(&label),
363 ));
364 html.push_str(&format!(
365 r#"<div class="rcms-stream-list" data-stream-list data-allowed="{}">"#,
366 tera::escape_html(&allowed_csv),
367 ));
368 for entry in &nested_arr {
369 if let Some(inner) = render_block_entry(entry, tera, dyn_set) {
370 html.push_str(&inner);
371 }
372 }
373 html.push_str("</div>");
374 html.push_str(
378 r#"<div class="rcms-stream-picker"><button type="button" class="rcms-btn" data-action="open-picker" data-insert-at="end"><span class="material-symbols-rounded sm">add</span> Add block</button></div>"#,
379 );
380 html.push_str("</fieldset>");
381 }
382 BlockField::Repeat {
383 name,
384 label,
385 item_type,
386 ..
387 } => {
388 let nested_value = value
389 .get(&name)
390 .cloned()
391 .unwrap_or(Value::Array(Vec::new()));
392 let nested_arr = nested_value.as_array().cloned().unwrap_or_default();
393 html.push_str(&format!(
394 r#"<fieldset class="rcms-stream-nested" data-stream-field="{name}"><legend>{label}</legend>"#,
395 name = tera::escape_html(&name),
396 label = tera::escape_html(&label),
397 ));
398 html.push_str(&format!(
399 r#"<div class="rcms-stream-list" data-stream-list data-allowed="{}" data-repeat="1">"#,
400 tera::escape_html(&item_type),
401 ));
402 for entry in &nested_arr {
403 if let Some(inner) = render_block_entry(entry, tera, dyn_set) {
404 html.push_str(&inner);
405 }
406 }
407 html.push_str("</div>");
408 html.push_str(&format!(
412 r#"<div class="rcms-stream-picker"><button type="button" class="rcms-btn" data-action="open-picker" data-insert-at="end"><span class="material-symbols-rounded sm">add</span> Add {}</button></div>"#,
413 tera::escape_html(&item_type),
414 ));
415 html.push_str("</fieldset>");
416 }
417 BlockField::Computed {
418 name,
419 label,
420 render,
421 ..
422 } => {
423 let value_html = render(value, &block::BlockRenderCtx::new(tera));
424 html.push_str(&format!(
425 r#"<div class="rcms-stream-field rcms-stream-field-computed" data-stream-field="{name}"><label>{label}</label><div class="rcms-computed-value">{value_html}</div></div>"#,
426 name = tera::escape_html(&name),
427 label = tera::escape_html(&label),
428 value_html = value_html,
429 ));
430 }
431 }
432 }
433 html.push_str("</div>"); html.push_str("</div>"); html
436}
437
438fn json_to_widget_value(value: &Value, kind: &WidgetKind) -> String {
442 match value {
443 Value::Null => String::new(),
444 Value::String(s) => s.clone(),
445 Value::Bool(b) => {
446 if *b {
447 "true".to_owned()
448 } else {
449 String::new()
450 }
451 }
452 Value::Number(n) => n.to_string(),
453 Value::Array(_) | Value::Object(_) => {
454 if matches!(
455 kind,
456 WidgetKind::Checkboxes | WidgetKind::MultiSelect | WidgetKind::Stream
457 ) {
458 serde_json::to_string(value).unwrap_or_else(|_| "[]".to_owned())
459 } else {
460 value.to_string()
461 }
462 }
463 }
464}
465
466pub fn render_widget_via_macro(w: &Widget, tera: &Tera) -> String {
470 render_widget_via_macro_with(w, tera, &[])
471}
472
473#[must_use]
479pub fn render_widget_via_macro_with(
480 w: &Widget,
481 tera: &Tera,
482 picker_options: &[PickerOption],
483) -> String {
484 let mut ctx = Context::new();
485 ctx.insert("w", w);
486 ctx.insert("picker_options", picker_options);
487 ctx.insert("LANG", "en");
492
493 if let Ok(html) = tera.render(SHARED_WRAPPER, &ctx) {
499 return html;
500 }
501
502 let mut t = tera.clone();
505 if t.add_raw_template(SHARED_WRAPPER, WRAPPER_SRC).is_err() {
506 return String::new();
507 }
508 t.render(SHARED_WRAPPER, &ctx).unwrap_or_default()
509}
510
511const SHARED_WRAPPER: &str = "rcms_admin/_stream_widget.html";
514const WRAPPER_SRC: &str =
516 "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}";
517
518#[derive(serde::Serialize)]
522pub struct PickerOption {
523 pub type_name: String,
524 pub verbose_name: String,
525 pub icon: Option<String>,
526 pub group: Option<String>,
527 pub description: Option<String>,
529 pub default_value: Option<serde_json::Value>,
533 pub collapsed: bool,
537 pub preview_html: String,
543}
544
545#[must_use]
552pub fn picker_options(tera: &Tera) -> Vec<PickerOption> {
553 let render_ctx = block::BlockRenderCtx::new(tera);
554 block::registered_blocks()
555 .map(|b| {
556 let preview_html = match b.preview_value() {
557 Some(sample) => {
558 match b.preview_template() {
563 Some(custom_tpl) => {
564 render_with_template(custom_tpl, &sample, b.type_name(), tera)
565 }
566 None => b.render(&sample, &render_ctx).unwrap_or_default(),
567 }
568 }
569 None => String::new(),
570 };
571 PickerOption {
572 type_name: b.type_name().to_owned(),
573 verbose_name: b.verbose_name().to_owned(),
574 icon: b.icon().map(str::to_owned),
575 group: b.group().map(str::to_owned),
576 description: b.description().map(str::to_owned),
577 default_value: b.default_value(),
578 collapsed: b.collapsed(),
579 preview_html,
580 }
581 })
582 .collect()
583}
584
585fn render_with_template(
590 template: &str,
591 sample_value: &Value,
592 type_name: &str,
593 tera: &Tera,
594) -> String {
595 let mut ctx = Context::new();
596 ctx.insert("value", sample_value);
597 ctx.insert("block_type", type_name);
598 ctx.insert("computed", &Value::Object(serde_json::Map::new()));
599 tera.render(template, &ctx).unwrap_or_default()
600}
601
602fn format_label(fmt: &str, value: &Value) -> String {
610 let obj = value.as_object();
611 let mut out = String::with_capacity(fmt.len());
612 let mut chars = fmt.chars().peekable();
613 while let Some(c) = chars.next() {
614 if c == '{' {
615 let mut name = String::new();
617 let mut closed = false;
618 while let Some(&next) = chars.peek() {
619 chars.next();
620 if next == '}' {
621 closed = true;
622 break;
623 }
624 name.push(next);
625 }
626 if !closed {
627 out.push('{');
629 out.push_str(&name);
630 continue;
631 }
632 let resolved = obj
633 .and_then(|m| m.get(name.trim()))
634 .map(|v| match v {
635 Value::String(s) => s.clone(),
636 Value::Null => String::new(),
637 other => other.to_string().trim_matches('"').to_owned(),
638 })
639 .unwrap_or_default();
640 out.push_str(&resolved);
641 } else {
642 out.push(c);
643 }
644 }
645 out
646}
647
648#[cfg(test)]
649mod label_format_tests {
650 use super::*;
651
652 #[test]
653 fn substitutes_single_field() {
654 let v = serde_json::json!({"text": "Welcome"});
655 assert_eq!(format_label("{text}", &v), "Welcome");
656 }
657
658 #[test]
659 fn substitutes_multiple_fields() {
660 let v = serde_json::json!({"text": "Welcome", "level": "2"});
661 assert_eq!(format_label("{text} (H{level})", &v), "Welcome (H2)");
662 }
663
664 #[test]
665 fn empty_for_missing_fields() {
666 let v = serde_json::json!({"text": "Welcome"});
667 assert_eq!(format_label("{text} — {missing}", &v), "Welcome — ");
668 }
669
670 #[test]
671 fn unterminated_brace_passes_through() {
672 let v = serde_json::json!({});
673 assert_eq!(format_label("hello {oops", &v), "hello {oops");
674 }
675
676 #[test]
677 fn null_field_is_empty() {
678 let v = serde_json::json!({"text": null});
679 assert_eq!(format_label("[{text}]", &v), "[]");
680 }
681}