Skip to main content

rustango_cms/block/
admin.rs

1//! Admin-side editor rendering for `WidgetKind::Stream` widgets.
2//!
3//! The page-edit form pre-renders the entire stream editor HTML in
4//! Rust before passing it through Tera — mirrors the existing
5//! `Widget::custom_html` stash pattern in `src/admin/handlers.rs`.
6//! The output is one big string of `<div data-stream-block>` nodes
7//! plus `<template>` clones the client-side JS uses on insert.
8//!
9//! ## Walk shape
10//!
11//! Top-level entrypoint: [`render_stream_editor`].
12//!
13//! For each existing block in the stored JSON:
14//! 1. Look up the [`crate::Block`] via the registry.
15//! 2. Render its header (icon + verbose_name + reorder/remove buttons).
16//! 3. Render its body — one wrapper per [`crate::BlockField`]:
17//!    - `Widget`: build a one-off [`crate::Widget`] with `name = ""`
18//!      so it doesn't accidentally submit, then call the existing
19//!      `widgets::render(w)` Tera macro.
20//!    - `Stream` / `Repeat`: recurse.
21//!    - `Computed`: render inline via the field's render fn.
22//!
23//! For each registered block type, render an *empty-block* clone
24//! into a `<template data-block-template="X">` element — the JS
25//! clones these on insert so new blocks land with the right shape
26//! without an admin round-trip.
27//!
28//! ## Form submission
29//!
30//! Every nested `<input>` / `<select>` / `<textarea>` is rendered with
31//! `name=""` so the browser skips it on submit per HTML5
32//! § 4.10.18.3 (5.5). Only the single hidden `<input>` carrying the
33//! serialized JSON tree (`name="{stream_name}"`) participates in the
34//! POST. The JS rewrites this hidden value on every `input` event.
35
36use serde_json::Value;
37use tera::{Context, Tera};
38
39use crate::block::{self, BlockField};
40use crate::widget::{Widget, WidgetKind};
41
42/// Top-level entry: render the entire editor HTML for one
43/// `WidgetKind::Stream` widget.
44///
45/// `widget.value` is the JSON-string the handler loaded; allowed
46/// types live in `widget.allowed`. Returns the editor body — the
47/// caller stamps it onto `widget.custom_html` so `_widget.html`'s
48/// stream arm can emit it via `{{ w.custom_html | safe }}`.
49#[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/// [`render_stream_editor`] with a page-builder dyn-block overlay:
58/// UI-defined block types resolve through `dyn_set` before the inventory
59/// registry, so their entries + clone-templates render exactly like code
60/// blocks — `stream_editor.js` needs no changes.
61#[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    // List of existing blocks (top-level stream).
73    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    // Per-block-type clone templates. JS reads
82    // `<template data-block-template="X">` and clones its content on
83    // insert. Walk `widget.allowed` transitively — nested Stream /
84    // Repeat fields reference other block types whose templates must
85    // also be available at the root for the JS to clone from.
86    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    // Clone-template bodies are rendered from an EMPTY value, so for a
113    // code-registered block the output depends only on the block type —
114    // never on page content. Rendering them per request was
115    // the single most expensive thing the page editor did (measured: 63ms of
116    // a 69ms release-build request, ~91%, on a page with an *empty* stream —
117    // 25 `_widget.html` sub-renders). Memoize them process-wide.
118    //
119    // UI-defined (page-builder) blocks are NOT cached: their schema can
120    // change at runtime, so they always render live.
121    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
171/// Process-wide memo of rendered clone-templates for **code-registered**
172/// blocks, keyed by block type — bounded by the registered block types.
173/// Image blocks render the shared chooser, not an option list, so the
174/// media library is no part of the key.
175type 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
182/// Render one block entry from the stored JSON. Returns `None` for
183/// unrecognized `type` — the caller treats this as drift and emits
184/// the yellow banner.
185fn 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
204/// Render one block — header + body. `id` is `None` for the empty
205/// clone-template (JS mints a fresh UUID on insert).
206fn 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    // Block::label_format() — sprintf-like template ({field}
219    // placeholders). When set, stamps the format string as
220    // `data-label-format` so the JS live-updates the collapsed header
221    // on field edits. Also pre-substitutes the initial value
222    // server-side so the first paint shows the right label without a
223    // JS round-trip.
224    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    // Compute the initial label — substitute the format string
237    // against the current block value. Empty / no-format → fall
238    // back to verbose_name.
239    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    // -- header --
252    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    // -- body --
275    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                // #155 — uniquify widget name per block instance so
290                // duplicate `id="w_…"` attributes don't collide
291                // across multiple blocks of the same type. The JSON
292                // serializer reads via `data-stream-field` (not by
293                // widget name) so the namespaced name is purely a
294                // DOM-hygiene fix.
295                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                // Phase A (field validators) — thread the
310                // BlockFieldMeta sub-struct into the rendered Widget.
311                // Meta entries win when both meta + widget-level slot
312                // are set; defaults preserve existing behaviour.
313                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                // Read by `_widget.html` as `data-chooser-filter`.
329                if let Some(f) = meta.chooser_filter.clone() {
330                    w.custom_name = f;
331                }
332                // Default value seeds the editor's initial render
333                // when there's no stored row yet (the empty-block
334                // template gets the default in its value attr).
335                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                // Nested Add-block trigger — the JS resolves the
375                // target list (the previous sibling `[data-stream-list]`)
376                // and the templates from the outer `[data-stream-root]`.
377                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                // Repeat fields skip the picker (only one type allowed)
409                // — the JS recognises `data-repeat="1"` on the list and
410                // mints a row of that type directly.
411                // "Add picture", from the item block's name (its type name
412                // when it isn't registered).
413                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>"); // /stream-block-body
438    html.push_str("</div>"); // /stream-block
439    html
440}
441
442/// Convert a JSON value back to the string form widgets expect.
443/// Scalars stringify. Objects / arrays serialize back to JSON for
444/// multi-value widgets (`Checkboxes`, `MultiSelect`, `Stream`).
445fn 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
470/// Render a single widget by calling the existing `widgets::render(w)`
471/// Tera macro — same path the rest of the admin uses. We thread it
472/// through a one-shot inline template so we get the exact same HTML.
473pub fn render_widget_via_macro(w: &Widget, tera: &Tera) -> String {
474    render_widget_via_macro_with(w, tera, &[])
475}
476
477/// [`render_widget_via_macro`] with an explicit block picker.
478/// A `Stream` widget's `_widget.html` arm reads `picker_options` from
479/// context to populate its block-picker dialog; the plain macro path
480/// leaves it empty. Page-builder flex zones / repeaters need their
481/// allowed dyn blocks in the picker so editors can add entries.
482#[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    // `_widget.html` chrome strings (chooser/media buttons, "— no selection —")
492    // run through `translate(locale=LANG)`; without LANG those branches error
493    // and render empty. Block field labels are English source strings, so the
494    // English catalog is the right default here.
495    ctx.insert("LANG", "en");
496
497    // Fast path: `register_templates` registers the wrapper once, so we can
498    // render straight off the shared `&Tera`. This function is called once
499    // per widget (~173x on a content-heavy page edit); the old path did
500    // `tera.clone()` + `add_raw_template` EVERY time, deep-copying every
501    // compiled admin template -- ~2.4ms a call, 423ms a page.
502    if let Ok(html) = tera.render(SHARED_WRAPPER, &ctx) {
503        return html;
504    }
505
506    // Fallback for hosts that never called `register_templates`: register the
507    // wrapper on a throwaway clone (the original behaviour).
508    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
515/// Name of the one-shot widget wrapper registered by
516/// [`crate::admin::register_templates`].
517const SHARED_WRAPPER: &str = "rcms_admin/_stream_widget.html";
518/// Source for [`SHARED_WRAPPER`], used only by the un-registered fallback.
519const WRAPPER_SRC: &str =
520    "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}";
521
522/// Picker option metadata stamped into the page-edit Tera context.
523/// The block-picker dialog reads from `picker_options` and filters
524/// by `data-allowed` at click time.
525#[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    /// Picker-tile tooltip — `Block::description()`.
532    pub description: Option<String>,
533    /// Initial-value blob, serialized JSON of `Block::default_value()`.
534    /// The stream editor merges this into the empty-instance dict
535    /// when the editor adds a new block.
536    pub default_value: Option<serde_json::Value>,
537    /// Whether new instances start collapsed in the editor —
538    /// `Block::collapsed()`. The stream-block header reads this to
539    /// decide initial expand state.
540    pub collapsed: bool,
541    /// Pre-rendered preview HTML — `Block::preview_value()` run
542    /// through the block's render template (or
543    /// `Block::preview_template()` when set). The picker tile renders
544    /// this inline so editors can see "what does this look like"
545    /// before inserting. Empty for blocks that opt out of previews.
546    pub preview_html: String,
547}
548
549/// Build the picker-option list from the global registry. Stamped
550/// into Tera context as `picker_options` by `page_edit_form`.
551///
552/// `tera` is used to render each block's preview thumbnail. Pass the
553/// admin Tera instance — block templates live in the same namespace
554/// as the rest of the admin templates.
555#[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                    // Honour Block::preview_template() override —
563                    // wrap in a Tera context manually so we render
564                    // the chosen template (not the public one).
565
566                    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
589/// Render `sample_value` through `template` for picker preview.
590/// Mirrors the default-render Tera context shape so the same
591/// `{{ value.foo }}` markup works in both the preview and the public
592/// template.
593fn 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
606/// Substitute `{field_name}` tokens in a label-format string against
607/// a block's value dict. Missing fields render as empty (matches
608/// the JS-side substitution behaviour in stream_editor.js).
609///
610/// Used by [`render_block_inline`] for the initial server-rendered
611/// label and mirrored client-side by the JS for live updates on
612/// field input.
613fn 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            // Gobble the field name up to the next '}'.
620            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                // Unterminated `{…` — emit verbatim.
632                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}