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 let item_label = crate::block::find_block(&item_type)
414 .map_or_else(|| item_type.replace('_', " "), |b| b.verbose_name().to_lowercase());
415 html.push_str(&format!(
416 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>"#,
417 tera::escape_html(&item_label),
418 ));
419 html.push_str("</fieldset>");
420 }
421 BlockField::Computed {
422 name,
423 label,
424 render,
425 ..
426 } => {
427 let value_html = render(value, &block::BlockRenderCtx::new(tera));
428 html.push_str(&format!(
429 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>"#,
430 name = tera::escape_html(&name),
431 label = tera::escape_html(&label),
432 value_html = value_html,
433 ));
434 }
435 }
436 }
437 html.push_str("</div>"); html.push_str("</div>"); html
440}
441
442fn json_to_widget_value(value: &Value, kind: &WidgetKind) -> String {
446 match value {
447 Value::Null => String::new(),
448 Value::String(s) => s.clone(),
449 Value::Bool(b) => {
450 if *b {
451 "true".to_owned()
452 } else {
453 String::new()
454 }
455 }
456 Value::Number(n) => n.to_string(),
457 Value::Array(_) | Value::Object(_) => {
458 if matches!(
459 kind,
460 WidgetKind::Checkboxes | WidgetKind::MultiSelect | WidgetKind::Stream
461 ) {
462 serde_json::to_string(value).unwrap_or_else(|_| "[]".to_owned())
463 } else {
464 value.to_string()
465 }
466 }
467 }
468}
469
470pub fn render_widget_via_macro(w: &Widget, tera: &Tera) -> String {
474 render_widget_via_macro_with(w, tera, &[])
475}
476
477#[must_use]
483pub fn render_widget_via_macro_with(
484 w: &Widget,
485 tera: &Tera,
486 picker_options: &[PickerOption],
487) -> String {
488 let mut ctx = Context::new();
489 ctx.insert("w", w);
490 ctx.insert("picker_options", picker_options);
491 ctx.insert("LANG", "en");
496
497 if let Ok(html) = tera.render(SHARED_WRAPPER, &ctx) {
503 return html;
504 }
505
506 let mut t = tera.clone();
509 if t.add_raw_template(SHARED_WRAPPER, WRAPPER_SRC).is_err() {
510 return String::new();
511 }
512 t.render(SHARED_WRAPPER, &ctx).unwrap_or_default()
513}
514
515const SHARED_WRAPPER: &str = "rcms_admin/_stream_widget.html";
518const WRAPPER_SRC: &str =
520 "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}";
521
522#[derive(serde::Serialize)]
526pub struct PickerOption {
527 pub type_name: String,
528 pub verbose_name: String,
529 pub icon: Option<String>,
530 pub group: Option<String>,
531 pub description: Option<String>,
533 pub default_value: Option<serde_json::Value>,
537 pub collapsed: bool,
541 pub preview_html: String,
547}
548
549#[must_use]
556pub fn picker_options(tera: &Tera) -> Vec<PickerOption> {
557 let render_ctx = block::BlockRenderCtx::new(tera);
558 block::registered_blocks()
559 .map(|b| {
560 let preview_html = match b.preview_value() {
561 Some(sample) => {
562 match b.preview_template() {
567 Some(custom_tpl) => {
568 render_with_template(custom_tpl, &sample, b.type_name(), tera)
569 }
570 None => b.render(&sample, &render_ctx).unwrap_or_default(),
571 }
572 }
573 None => String::new(),
574 };
575 PickerOption {
576 type_name: b.type_name().to_owned(),
577 verbose_name: b.verbose_name().to_owned(),
578 icon: b.icon().map(str::to_owned),
579 group: b.group().map(str::to_owned),
580 description: b.description().map(str::to_owned),
581 default_value: b.default_value(),
582 collapsed: b.collapsed(),
583 preview_html,
584 }
585 })
586 .collect()
587}
588
589fn render_with_template(
594 template: &str,
595 sample_value: &Value,
596 type_name: &str,
597 tera: &Tera,
598) -> String {
599 let mut ctx = Context::new();
600 ctx.insert("value", sample_value);
601 ctx.insert("block_type", type_name);
602 ctx.insert("computed", &Value::Object(serde_json::Map::new()));
603 tera.render(template, &ctx).unwrap_or_default()
604}
605
606fn format_label(fmt: &str, value: &Value) -> String {
614 let obj = value.as_object();
615 let mut out = String::with_capacity(fmt.len());
616 let mut chars = fmt.chars().peekable();
617 while let Some(c) = chars.next() {
618 if c == '{' {
619 let mut name = String::new();
621 let mut closed = false;
622 while let Some(&next) = chars.peek() {
623 chars.next();
624 if next == '}' {
625 closed = true;
626 break;
627 }
628 name.push(next);
629 }
630 if !closed {
631 out.push('{');
633 out.push_str(&name);
634 continue;
635 }
636 let resolved = obj
637 .and_then(|m| m.get(name.trim()))
638 .map(|v| match v {
639 Value::String(s) => s.clone(),
640 Value::Null => String::new(),
641 other => other.to_string().trim_matches('"').to_owned(),
642 })
643 .unwrap_or_default();
644 out.push_str(&resolved);
645 } else {
646 out.push(c);
647 }
648 }
649 out
650}
651
652#[cfg(test)]
653mod label_format_tests {
654 use super::*;
655
656 #[test]
657 fn substitutes_single_field() {
658 let v = serde_json::json!({"text": "Welcome"});
659 assert_eq!(format_label("{text}", &v), "Welcome");
660 }
661
662 #[test]
663 fn substitutes_multiple_fields() {
664 let v = serde_json::json!({"text": "Welcome", "level": "2"});
665 assert_eq!(format_label("{text} (H{level})", &v), "Welcome (H2)");
666 }
667
668 #[test]
669 fn empty_for_missing_fields() {
670 let v = serde_json::json!({"text": "Welcome"});
671 assert_eq!(format_label("{text} — {missing}", &v), "Welcome — ");
672 }
673
674 #[test]
675 fn unterminated_brace_passes_through() {
676 let v = serde_json::json!({});
677 assert_eq!(format_label("hello {oops", &v), "hello {oops");
678 }
679
680 #[test]
681 fn null_field_is_empty() {
682 let v = serde_json::json!({"text": null});
683 assert_eq!(format_label("[{text}]", &v), "[]");
684 }
685}