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                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>"); // /stream-block-body
434    html.push_str("</div>"); // /stream-block
435    html
436}
437
438/// Convert a JSON value back to the string form widgets expect.
439/// Scalars stringify. Objects / arrays serialize back to JSON for
440/// multi-value widgets (`Checkboxes`, `MultiSelect`, `Stream`).
441fn 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
466/// Render a single widget by calling the existing `widgets::render(w)`
467/// Tera macro — same path the rest of the admin uses. We thread it
468/// through a one-shot inline template so we get the exact same HTML.
469pub fn render_widget_via_macro(w: &Widget, tera: &Tera) -> String {
470    render_widget_via_macro_with(w, tera, &[])
471}
472
473/// [`render_widget_via_macro`] with an explicit block picker.
474/// A `Stream` widget's `_widget.html` arm reads `picker_options` from
475/// context to populate its block-picker dialog; the plain macro path
476/// leaves it empty. Page-builder flex zones / repeaters need their
477/// allowed dyn blocks in the picker so editors can add entries.
478#[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    // `_widget.html` chrome strings (chooser/media buttons, "— no selection —")
488    // run through `translate(locale=LANG)`; without LANG those branches error
489    // and render empty. Block field labels are English source strings, so the
490    // English catalog is the right default here.
491    ctx.insert("LANG", "en");
492
493    // Fast path: `register_templates` registers the wrapper once, so we can
494    // render straight off the shared `&Tera`. This function is called once
495    // per widget (~173x on a content-heavy page edit); the old path did
496    // `tera.clone()` + `add_raw_template` EVERY time, deep-copying every
497    // compiled admin template -- ~2.4ms a call, 423ms a page.
498    if let Ok(html) = tera.render(SHARED_WRAPPER, &ctx) {
499        return html;
500    }
501
502    // Fallback for hosts that never called `register_templates`: register the
503    // wrapper on a throwaway clone (the original behaviour).
504    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
511/// Name of the one-shot widget wrapper registered by
512/// [`crate::admin::register_templates`].
513const SHARED_WRAPPER: &str = "rcms_admin/_stream_widget.html";
514/// Source for [`SHARED_WRAPPER`], used only by the un-registered fallback.
515const WRAPPER_SRC: &str =
516    "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}";
517
518/// Picker option metadata stamped into the page-edit Tera context.
519/// The block-picker dialog reads from `picker_options` and filters
520/// by `data-allowed` at click time.
521#[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    /// Picker-tile tooltip — `Block::description()`.
528    pub description: Option<String>,
529    /// Initial-value blob, serialized JSON of `Block::default_value()`.
530    /// The stream editor merges this into the empty-instance dict
531    /// when the editor adds a new block.
532    pub default_value: Option<serde_json::Value>,
533    /// Whether new instances start collapsed in the editor —
534    /// `Block::collapsed()`. The stream-block header reads this to
535    /// decide initial expand state.
536    pub collapsed: bool,
537    /// Pre-rendered preview HTML — `Block::preview_value()` run
538    /// through the block's render template (or
539    /// `Block::preview_template()` when set). The picker tile renders
540    /// this inline so editors can see "what does this look like"
541    /// before inserting. Empty for blocks that opt out of previews.
542    pub preview_html: String,
543}
544
545/// Build the picker-option list from the global registry. Stamped
546/// into Tera context as `picker_options` by `page_edit_form`.
547///
548/// `tera` is used to render each block's preview thumbnail. Pass the
549/// admin Tera instance — block templates live in the same namespace
550/// as the rest of the admin templates.
551#[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                    // Honour Block::preview_template() override —
559                    // wrap in a Tera context manually so we render
560                    // the chosen template (not the public one).
561
562                    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
585/// Render `sample_value` through `template` for picker preview.
586/// Mirrors the default-render Tera context shape so the same
587/// `{{ value.foo }}` markup works in both the preview and the public
588/// template.
589fn 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
602/// Substitute `{field_name}` tokens in a label-format string against
603/// a block's value dict. Missing fields render as empty (matches
604/// the JS-side substitution behaviour in stream_editor.js).
605///
606/// Used by [`render_block_inline`] for the initial server-rendered
607/// label and mirrored client-side by the JS for live updates on
608/// field input.
609fn 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            // Gobble the field name up to the next '}'.
616            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                // Unterminated `{…` — emit verbatim.
628                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}