Skip to main content

rustango_cms/block/
tera_helpers.rs

1//! Public-side `stream_render` Tera function.
2//!
3//! Mirrors the [`crate::snippet`] pattern (`src/snippet.rs:140-183`):
4//! the request handler pre-renders every stream value into HTML
5//! BEFORE Tera runs (Tera functions are sync; recursive block render
6//! is async-clean only after pre-flight), stashes the result into a
7//! `slug → html` map under context key `_stream_html`, and this
8//! function just reads from that map at template-render time.
9//!
10//! ## Usage in templates
11//!
12//! ```text
13//! {{ stream_render(name="body_stream") | safe }}
14//! ```
15//!
16//! `name` is the [`crate::widget::Widget::name`] of the stream
17//! widget (i.e. the field on the extension row carrying the JSON).
18//! Missing name → empty string.
19
20use tera::{Tera, Value};
21
22use super::render;
23use super::BlockRenderCtx;
24
25thread_local! {
26    /// Per-thread `field/zone name → pre-rendered HTML` map. Set for the
27    /// duration of one `tera.render` call via [`install`]. Tera 1.20
28    /// functions can't see the render context, so `stream_render` reads
29    /// this instead of its args (the args path stays as a fallback for
30    /// callers that pass `_stream_html=` explicitly).
31    static CURRENT_STREAM_HTML: std::cell::RefCell<Option<std::sync::Arc<std::collections::HashMap<String, String>>>>
32        = const { std::cell::RefCell::new(None) };
33}
34
35/// RAII guard: while alive the thread-local stream-HTML map is set; on
36/// drop it clears. Bind it across `tera.render(…)` and drop right after.
37#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
38pub struct StreamHtmlGuard {
39    _priv: (),
40}
41
42impl Drop for StreamHtmlGuard {
43    fn drop(&mut self) {
44        CURRENT_STREAM_HTML.with(|cell| *cell.borrow_mut() = None);
45    }
46}
47
48/// Install the `name → HTML` map for the duration of the returned guard,
49/// so `stream_render(name="…")` resolves against it during `tera.render`.
50pub fn install(stream_html: std::collections::HashMap<String, String>) -> StreamHtmlGuard {
51    CURRENT_STREAM_HTML.with(|cell| *cell.borrow_mut() = Some(std::sync::Arc::new(stream_html)));
52    StreamHtmlGuard { _priv: () }
53}
54
55/// Register `stream_render` on `tera`. Call once at Tera setup.
56///
57/// Resolves `name` against the thread-local map installed by [`install`]
58/// (the public render pipeline installs it just before `tera.render`);
59/// falls back to an explicit `_stream_html=` arg for direct callers.
60pub fn register_tera_function(tera: &mut Tera) {
61    tera.register_function(
62        "stream_render",
63        move |args: &std::collections::HashMap<String, Value>| {
64            let name = args
65                .get("name")
66                .and_then(Value::as_str)
67                .ok_or_else(|| tera::Error::msg("stream_render: `name` is required"))?;
68            // Thread-local first (Tera 1.20 functions can't read context).
69            if let Some(html) = CURRENT_STREAM_HTML
70                .with(|cell| cell.borrow().as_ref().and_then(|m| m.get(name).cloned()))
71            {
72                return Ok(Value::String(html));
73            }
74            let html = args
75                .get("_stream_html")
76                .and_then(Value::as_object)
77                .and_then(|m| m.get(name))
78                .and_then(Value::as_str)
79                .unwrap_or("")
80                .to_owned();
81            Ok(Value::String(html))
82        },
83    );
84}
85
86/// Parse the canonical stream JSON for a field. Accepts both the
87/// stringified-JSON storage shape (the usual extension-column form)
88/// and an already-parsed array; an absent or garbled value yields an
89/// empty array (renders nothing).
90pub(crate) fn canonical_parsed(raw: Option<&serde_json::Value>) -> serde_json::Value {
91    match raw {
92        Some(serde_json::Value::String(s)) => {
93            serde_json::from_str(s).unwrap_or(serde_json::Value::Array(Vec::new()))
94        }
95        Some(other) => other.clone(),
96        None => serde_json::Value::Array(Vec::new()),
97    }
98}
99
100/// Resolve which stream JSON to render for `field`, honoring a
101/// per-locale translation override (#i18n body translation).
102///
103/// `translations` maps `field_path → localized value` for the active
104/// locale (the same map the `t` filter reads; empty on the default
105/// locale). When it carries a non-empty, JSON-**array** override for
106/// this stream field, that localized body wins; otherwise the
107/// canonical extension body is used. A malformed override (invalid
108/// JSON, or valid-but-not-an-array) logs a warning and falls back to
109/// canonical — it never panics, so a bad translation row can only
110/// degrade to the source-language body, never break the page.
111fn localized_or_canonical(
112    field: &str,
113    raw: Option<&serde_json::Value>,
114    translations: &std::collections::HashMap<String, String>,
115) -> serde_json::Value {
116    match translations
117        .get(field)
118        .map(String::as_str)
119        .filter(|s| !s.trim().is_empty())
120    {
121        Some(s) => match serde_json::from_str::<serde_json::Value>(s) {
122            Ok(v) if v.is_array() => v,
123            Ok(_) => {
124                tracing::warn!(
125                    target: "rustango_cms::block",
126                    field = %field,
127                    "stream translation override is not a JSON array; using canonical body",
128                );
129                canonical_parsed(raw)
130            }
131            Err(e) => {
132                tracing::warn!(
133                    target: "rustango_cms::block",
134                    field = %field,
135                    error = %e,
136                    "stream translation override is not valid JSON; using canonical body",
137                );
138                canonical_parsed(raw)
139            }
140        },
141        None => canonical_parsed(raw),
142    }
143}
144
145/// Walk the handler-provided list of widgets, find every
146/// [`crate::widget::WidgetKind::Stream`], pre-render its JSON value
147/// to HTML, and return a `name → html` map ready to stamp on the
148/// Tera context as `_stream_html`.
149///
150/// `extension` is the serialized extension JSON (the same value
151/// `handler.load_extension` produces). Stream values can sit anywhere
152/// under it; we look them up by the widget's `name`. `translations`
153/// carries the active locale's per-field overrides — a stream field
154/// with a localized body in that map renders the translated blocks
155/// (see `localized_or_canonical`); pass an empty map for the
156/// canonical (default-locale) render.
157///
158/// # Errors
159/// Tera failures during nested block rendering bubble up. Unknown
160/// block types do NOT short-circuit — they render as a yellow drift
161/// banner inline (see [`super::render::prerender_stream`]).
162pub fn prerender_extension_streams(
163    widgets: &[crate::widget::Widget],
164    extension: &serde_json::Value,
165    tera: &Tera,
166    translations: &std::collections::HashMap<String, String>,
167) -> Result<std::collections::HashMap<String, String>, super::BlockError> {
168    let mut out = std::collections::HashMap::new();
169    let ctx = BlockRenderCtx::new(tera);
170    for w in widgets {
171        if !matches!(w.kind, crate::widget::WidgetKind::Stream) {
172            continue;
173        }
174        // Base array = canonical, or a legacy whole-body blob override
175        // (#i18n back-compat); then layer per-leaf overrides on top so
176        // individual block fields — including nested ones — localize.
177        let base = localized_or_canonical(&w.name, extension.get(&w.name), translations);
178        let parsed = super::translate::apply_translatable_overrides(&w.name, &base, translations);
179        let html = render::prerender_stream(&parsed, &ctx)?;
180        out.insert(w.name.clone(), html);
181    }
182    Ok(out)
183}
184
185/// Async variant — preferred when the caller is already in an
186/// `async fn`. Pre-fetches every chooser reference inside the stream
187/// trees and stamps the resolved fields (`_url`, `_title`, etc.) onto
188/// the block values before kicking the sync render walker.
189///
190/// # Errors
191/// Same as the sync variant.
192pub async fn prerender_extension_streams_async(
193    widgets: &[crate::widget::Widget],
194    extension: &serde_json::Value,
195    tera: &Tera,
196    pool: &rustango::sql::Pool,
197    translations: &std::collections::HashMap<String, String>,
198    // #550 FB-17 — active non-default locale id, used to localize embedded
199    // form blocks (None for the default locale).
200    form_locale_id: Option<i64>,
201) -> Result<std::collections::HashMap<String, String>, super::BlockError> {
202    prerender_extension_streams_async_with(
203        widgets,
204        extension,
205        tera,
206        pool,
207        translations,
208        form_locale_id,
209        None,
210        "",
211    )
212    .await
213}
214
215/// [`prerender_extension_streams_async`], plus the page the stream
216/// belongs to.
217///
218/// The page id reaches host [`enrichers`](super::enrich) as
219/// [`EnrichCtx::page_id`](super::enrich::EnrichCtx::page_id). A block
220/// that inherits something from its page — a reporting period set once
221/// on a section root, a currency, a locale default — cannot look that up
222/// from the pool alone, and a thread-local would not survive the awaits
223/// in this function.
224///
225/// Separate function rather than a changed signature, per the `_with`
226/// convention already used for the dyn-block variants: every existing
227/// caller keeps working and opts in by name.
228///
229/// # Errors
230/// Same as the sync variant.
231#[allow(clippy::too_many_arguments)]
232pub async fn prerender_extension_streams_async_with(
233    widgets: &[crate::widget::Widget],
234    extension: &serde_json::Value,
235    tera: &Tera,
236    pool: &rustango::sql::Pool,
237    translations: &std::collections::HashMap<String, String>,
238    form_locale_id: Option<i64>,
239    page_id: Option<i64>,
240    tenant: &str,
241) -> Result<std::collections::HashMap<String, String>, super::BlockError> {
242    let mut out = std::collections::HashMap::new();
243    let ctx = BlockRenderCtx::new(tera);
244    for w in widgets {
245        if !matches!(w.kind, crate::widget::WidgetKind::Stream) {
246            continue;
247        }
248        // Per-locale resolution, in order: base array = canonical (or a
249        // legacy whole-body blob override for #i18n back-compat), then
250        // per-leaf overrides merged on top (recursively, incl. nested
251        // blocks). Chooser enrichment runs AFTER the merge so it resolves
252        // refs in the localized tree (a translation may reference its own
253        // images/snippets).
254        let base = localized_or_canonical(&w.name, extension.get(&w.name), translations);
255        let mut parsed =
256            super::translate::apply_translatable_overrides(&w.name, &base, translations);
257        enrich_chooser_refs_async(&mut parsed, pool, form_locale_id).await;
258        // Host-registered enrichment, after the built-in chooser pass so
259        // a host sees page/image/snippet refs already resolved. This is
260        // the last moment anything async can touch the stream — the
261        // render below is synchronous.
262        super::enrich::fire(
263            &mut parsed,
264            super::enrich::EnrichCtx {
265                pool,
266                tenant,
267                page_id,
268            },
269        )
270        .await;
271        let html = render::prerender_stream(&parsed, &ctx)?;
272        out.insert(w.name.clone(), html);
273    }
274    Ok(out)
275}
276
277/// Recursive enrichment. For each block in the stream array, looks
278/// at its `type`:
279///
280/// - `page_chooser`: looks up `cms_page` by `value.page_id`, adds
281///   `value._url`, `value._title`, `value._slug`.
282/// - `snippet_chooser`: looks up `cms_snippet` by `value.snippet_id`,
283///   adds `value._title`, `value._slug`, `value._html` (rendered
284///   markdown body).
285/// - `document_chooser`: looks up `cms_media` by `value.document_id`,
286///   adds `value._url`, `value._title`, `value._filename`,
287///   `value._mime`, `value._size`.
288/// - `image`: looks up `cms_media` by `value.media_id`, adds
289///   `value._url`, `value._title`, `value._alt_text`, `value._width`,
290///   `value._height`.
291/// - `nested_stream`-style fields (`Stream` BlockFields whose value is
292///   an array under any key): recurse.
293/// - `typed_table`-style fields (`Repeat` BlockFields whose value is
294///   an array): recurse.
295///
296/// All lookups are best-effort. A missing row leaves the value
297/// un-augmented so templates can fall back to their existing
298/// placeholder shapes. Resolved fields use the `_` prefix so they
299/// never collide with author-defined keys.
300pub async fn enrich_chooser_refs_async(
301    stream: &mut serde_json::Value,
302    pool: &rustango::sql::Pool,
303    form_locale_id: Option<i64>,
304) {
305    // #648 — two passes: collect every referenced id in the (nested)
306    // stream, resolve them with one query per table, then stamp the rows
307    // in. Per-block lookups made the query count the author's block count:
308    // a 40-image gallery was 40 sequential round trips on every render.
309    let mut refs = ChooserRefs::default();
310    collect_chooser_refs(stream, &mut refs);
311    if refs.is_empty() {
312        return;
313    }
314    let rows = ChooserRows::fetch(pool, &refs, form_locale_id).await;
315    apply_chooser_refs(stream, &rows);
316}
317
318/// Ids and form slugs a stream's chooser blocks reference.
319#[derive(Default)]
320struct ChooserRefs {
321    pages: std::collections::BTreeSet<i64>,
322    snippets: std::collections::BTreeSet<i64>,
323    media: std::collections::BTreeSet<i64>,
324    forms: std::collections::BTreeSet<String>,
325}
326
327impl ChooserRefs {
328    fn is_empty(&self) -> bool {
329        self.pages.is_empty() && self.snippets.is_empty() && self.media.is_empty() && self.forms.is_empty()
330    }
331}
332
333/// The rows [`ChooserRefs`] resolve to. A missing row simply has no entry,
334/// so its block stays un-augmented, as before.
335struct ChooserRows {
336    pages: std::collections::HashMap<i64, crate::page::Page>,
337    snippets: std::collections::HashMap<i64, crate::snippet::Snippet>,
338    media: std::collections::HashMap<i64, crate::media::Media>,
339    /// Form reference (slug or id) → (snippet id, schema localized for the
340    /// render locale).
341    forms: std::collections::HashMap<String, (Option<i64>, serde_json::Value)>,
342}
343
344/// Ids per `IN (…)` list, well under every backend's bind limit.
345const REF_CHUNK: usize = 1_000;
346
347impl ChooserRows {
348    async fn fetch(
349        pool: &rustango::sql::Pool,
350        refs: &ChooserRefs,
351        form_locale_id: Option<i64>,
352    ) -> Self {
353        use rustango::core::Column as _;
354        use rustango::sql::FetcherPool as _;
355        let ids = |set: &std::collections::BTreeSet<i64>| set.iter().copied().collect::<Vec<_>>();
356
357        let mut pages = std::collections::HashMap::new();
358        for chunk in ids(&refs.pages).chunks(REF_CHUNK) {
359            let found = crate::page::Page::objects()
360                .where_(crate::page::Page::id.is_in(chunk.iter().copied()))
361                .fetch(pool)
362                .await
363                .unwrap_or_default();
364            pages.extend(found.into_iter().filter_map(|p| p.id.get().copied().map(|id| (id, p))));
365        }
366        let mut snippets = std::collections::HashMap::new();
367        for chunk in ids(&refs.snippets).chunks(REF_CHUNK) {
368            let found = crate::snippet::Snippet::objects()
369                .where_(crate::snippet::Snippet::id.is_in(chunk.iter().copied()))
370                .fetch(pool)
371                .await
372                .unwrap_or_default();
373            snippets.extend(found.into_iter().filter_map(|s| s.id.get().copied().map(|id| (id, s))));
374        }
375        let mut media = std::collections::HashMap::new();
376        for chunk in ids(&refs.media).chunks(REF_CHUNK) {
377            let found = crate::media::Media::objects()
378                .where_(crate::media::Media::id.is_in(chunk.iter().copied()))
379                .fetch(pool)
380                .await
381                .unwrap_or_default();
382            media.extend(found.into_iter().filter_map(|m| m.id.get().copied().map(|id| (id, m))));
383        }
384        // Keyed by the block's reference: a slug (typed in older pages) or
385        // the form's id (the chooser). Slugs are looked up first.
386        let mut forms = std::collections::HashMap::new();
387        if !refs.forms.is_empty() {
388            let found = crate::snippet::Snippet::objects()
389                .where_(crate::snippet::Snippet::type_name.eq("form".to_owned()))
390                .where_(crate::snippet::Snippet::slug.is_in(refs.forms.iter().cloned()))
391                .fetch(pool)
392                .await
393                .unwrap_or_default();
394            for s in found {
395                if forms.contains_key(&s.slug) {
396                    continue; // first match wins, as the per-block lookup did
397                }
398                let entry = localized_form(pool, &s, form_locale_id).await;
399                forms.insert(s.slug.clone(), entry);
400            }
401            let ids: Vec<i64> = refs
402                .forms
403                .iter()
404                .filter(|r| !forms.contains_key(*r))
405                .filter_map(|r| r.parse::<i64>().ok())
406                .collect();
407            if !ids.is_empty() {
408                let found = crate::snippet::Snippet::objects()
409                    .where_(crate::snippet::Snippet::type_name.eq("form".to_owned()))
410                    .where_(crate::snippet::Snippet::id.is_in(ids))
411                    .fetch(pool)
412                    .await
413                    .unwrap_or_default();
414                for s in found {
415                    let Some(id) = s.id.get().copied() else { continue };
416                    let entry = localized_form(pool, &s, form_locale_id).await;
417                    forms.insert(id.to_string(), entry);
418                }
419            }
420        }
421        Self { pages, snippets, media, forms }
422    }
423}
424
425/// A form's (snippet id, schema) — the schema localized for the render
426/// locale.
427async fn localized_form(
428    pool: &rustango::sql::Pool,
429    form: &crate::snippet::Snippet,
430    form_locale_id: Option<i64>,
431) -> (Option<i64>, serde_json::Value) {
432    let sid = form.id.get().copied();
433    let mut data = form.data.clone();
434    if let (Some(lid), Some(sid_)) = (form_locale_id, sid) {
435        if let Ok(over) = crate::snippet_translation::fetch_for(pool, sid_, lid).await {
436            if !over.is_empty() {
437                if let Ok(mut sch) = crate::forms::schema::parse(&data) {
438                    crate::forms::schema::apply_translations(&mut sch, &over);
439                    data = crate::forms::schema::to_value(&sch);
440                }
441            }
442        }
443    }
444    (sid, data)
445}
446
447/// A `form` block's reference to its form: the slug typed into older pages,
448/// or the id the chooser stores (a string, or a number from the API).
449fn form_ref(value: Option<&serde_json::Value>) -> Option<String> {
450    match value? {
451        serde_json::Value::String(s) => Some(s.trim()).filter(|s| !s.is_empty()).map(str::to_owned),
452        serde_json::Value::Number(n) => n.as_i64().map(|id| id.to_string()),
453        _ => None,
454    }
455}
456
457/// The blocks of `stream` and of every array nested in a block's value
458/// (Stream-in-Stream, Repeat-in-Stream, any container), with their type.
459fn for_each_block(
460    stream: &mut serde_json::Value,
461    f: &mut dyn FnMut(&str, &str, &mut serde_json::Map<String, serde_json::Value>),
462) {
463    let serde_json::Value::Array(items) = stream else {
464        return;
465    };
466    for entry in items.iter_mut() {
467        let serde_json::Value::Object(envelope) = entry else {
468            continue;
469        };
470        let type_name = envelope.get("type").and_then(|v| v.as_str()).unwrap_or("").to_owned();
471        let block_id = envelope.get("id").and_then(|v| v.as_str()).unwrap_or("").to_owned();
472        let Some(serde_json::Value::Object(value_obj)) = envelope.get_mut("value") else {
473            continue;
474        };
475        f(&type_name, &block_id, value_obj);
476        for v in value_obj.values_mut() {
477            if matches!(v, serde_json::Value::Array(_)) {
478                for_each_block(v, f);
479            }
480        }
481    }
482}
483
484fn collect_chooser_refs(stream: &mut serde_json::Value, refs: &mut ChooserRefs) {
485    for_each_block(stream, &mut |type_name, _id, value| match type_name {
486        "form" => {
487            if let Some(r) = form_ref(value.get("form")) {
488                refs.forms.insert(r);
489            }
490        }
491        "page_chooser" => refs.pages.extend(read_id(value.get("page_id"))),
492        "snippet_chooser" => refs.snippets.extend(read_id(value.get("snippet_id"))),
493        "document_chooser" => refs.media.extend(read_id(value.get("document_id"))),
494        "image" => refs.media.extend(read_id(value.get("media_id"))),
495        _ => {}
496    });
497}
498
499fn apply_chooser_refs(stream: &mut serde_json::Value, rows: &ChooserRows) {
500    use serde_json::Value;
501    for_each_block(stream, &mut |type_name, block_id, value| match type_name {
502        "form" => {
503            // #542 FB-09 — the keys the `form` block's render reads.
504            let key = form_ref(value.get("form")).unwrap_or_default();
505            if let Some((sid, data)) = rows.forms.get(&key) {
506                value.insert("_schema".into(), data.clone());
507                if let Some(sid) = sid {
508                    value.insert("_form_id".into(), serde_json::json!(sid));
509                }
510            }
511            value.insert("_embed".into(), Value::String(block_id.to_owned()));
512        }
513        "page_chooser" => {
514            if let Some(p) = read_id(value.get("page_id")).and_then(|id| rows.pages.get(&id)) {
515                value.insert("_url".into(), Value::String(p.url_path.clone()));
516                value.insert("_title".into(), Value::String(p.title.clone()));
517                value.insert("_slug".into(), Value::String(p.slug.clone()));
518            }
519        }
520        "snippet_chooser" => {
521            if let Some(s) = read_id(value.get("snippet_id")).and_then(|id| rows.snippets.get(&id)) {
522                value.insert("_title".into(), Value::String(s.title.clone()));
523                value.insert("_slug".into(), Value::String(s.slug.clone()));
524                value.insert("_html".into(), Value::String(crate::markdown::render(&s.body_markdown)));
525            }
526        }
527        "document_chooser" => {
528            if let Some(m) = read_id(value.get("document_id")).and_then(|id| rows.media.get(&id)) {
529                value.insert("_url".into(), Value::String(m.public_url()));
530                value.insert("_title".into(), Value::String(m.title.clone()));
531                value.insert("_filename".into(), Value::String(m.filename.clone()));
532                value.insert("_mime".into(), Value::String(m.mime.clone()));
533                value.insert("_size".into(), serde_json::json!(m.size));
534            }
535        }
536        "image" => {
537            if let Some(m) = read_id(value.get("media_id")).and_then(|id| rows.media.get(&id)) {
538                value.insert("_url".into(), Value::String(m.public_url()));
539                value.insert("_title".into(), Value::String(m.title.clone()));
540                value.insert("_alt_text".into(), Value::String(m.alt_text.clone()));
541                if let Some(w) = m.width {
542                    value.insert("_width".into(), serde_json::json!(w));
543                }
544                if let Some(h) = m.height {
545                    value.insert("_height".into(), serde_json::json!(h));
546                }
547            }
548        }
549        _ => {}
550    });
551}
552
553/// Accepts both stringified ints (the stream-block storage shape) and
554/// raw i64s (when the row was loaded from a typed column).
555fn read_id(v: Option<&serde_json::Value>) -> Option<i64> {
556    let v = v?;
557    if let Some(n) = v.as_i64() {
558        return Some(n);
559    }
560    v.as_str().and_then(|s| s.trim().parse::<i64>().ok())
561}
562
563#[cfg(test)]
564mod tests {
565    //! Per-locale StreamField body translation — the substitution
566    //! logic (`localized_or_canonical`) is pure, so it's covered here
567    //! without a DB or Tera. Confirms: canonical fallback is exact,
568    //! a valid array override wins, and every malformed override
569    //! degrades to canonical (never panics).
570    use super::{canonical_parsed, localized_or_canonical};
571    use std::collections::HashMap;
572
573    const CANONICAL: &str = r#"[{"type":"heading","value":{"text":"Hello","level":"2"}}]"#;
574
575    fn raw() -> serde_json::Value {
576        serde_json::Value::String(CANONICAL.to_owned())
577    }
578    fn first_text(v: &serde_json::Value) -> &str {
579        v.as_array().unwrap()[0]["value"]["text"].as_str().unwrap()
580    }
581
582    #[test]
583    fn canonical_parsed_handles_every_shape() {
584        // stringified JSON array (the storage shape)
585        assert_eq!(first_text(&canonical_parsed(Some(&raw()))), "Hello");
586        // already-parsed array passes through unchanged
587        let arr = serde_json::json!([{"type":"x","value":{}}]);
588        assert_eq!(canonical_parsed(Some(&arr)), arr);
589        // absent -> empty array
590        assert_eq!(canonical_parsed(None), serde_json::Value::Array(vec![]));
591        // garbled string -> empty array, no panic
592        let bad = serde_json::Value::String("{not json".to_owned());
593        assert_eq!(
594            canonical_parsed(Some(&bad)),
595            serde_json::Value::Array(vec![])
596        );
597    }
598
599    #[test]
600    fn no_override_uses_canonical() {
601        let out = localized_or_canonical("body", Some(&raw()), &HashMap::new());
602        assert_eq!(out, canonical_parsed(Some(&raw())));
603        assert_eq!(first_text(&out), "Hello");
604    }
605
606    #[test]
607    fn valid_array_override_wins() {
608        let fr = r#"[{"type":"heading","value":{"text":"Bonjour","level":"2"}}]"#;
609        let t = HashMap::from([("body".to_owned(), fr.to_owned())]);
610        assert_eq!(
611            first_text(&localized_or_canonical("body", Some(&raw()), &t)),
612            "Bonjour"
613        );
614    }
615
616    #[test]
617    fn empty_or_whitespace_override_falls_back() {
618        for v in ["", "   ", "\n\t"] {
619            let t = HashMap::from([("body".to_owned(), v.to_owned())]);
620            assert_eq!(
621                first_text(&localized_or_canonical("body", Some(&raw()), &t)),
622                "Hello"
623            );
624        }
625    }
626
627    #[test]
628    fn invalid_json_override_falls_back() {
629        let t = HashMap::from([("body".to_owned(), "{not valid json".to_owned())]);
630        assert_eq!(
631            first_text(&localized_or_canonical("body", Some(&raw()), &t)),
632            "Hello"
633        );
634    }
635
636    #[test]
637    fn non_array_override_falls_back() {
638        let t = HashMap::from([("body".to_owned(), r#"{"text":"oops"}"#.to_owned())]);
639        assert_eq!(
640            first_text(&localized_or_canonical("body", Some(&raw()), &t)),
641            "Hello"
642        );
643    }
644
645    #[test]
646    fn override_keyed_to_other_field_is_ignored() {
647        let t = HashMap::from([(
648            "some_other_field".to_owned(),
649            r#"[{"type":"x","value":{}}]"#.to_owned(),
650        )]);
651        assert_eq!(
652            first_text(&localized_or_canonical("body", Some(&raw()), &t)),
653            "Hello"
654        );
655    }
656}