Skip to main content

rustango_cms/
snippet.rs

1//! Library snippets — reusable, non-page content addressable by slug.
2//!
3//! Snippets are the bridge between Library *types* (the trait-shape
4//! registrations from [`crate::library`]) and live pages: editors
5//! create a snippet under a given type, give it a slug, and any
6//! template can pull it back via `{{ cms_snippet(slug="hero-cta") }}`.
7//!
8//! Storage uses one generic `cms_snippet` table (rather than per-type
9//! extension tables) so adding a new `LibraryTypeHandler` doesn't
10//! require migrating tables — typed fields go in the `data` JSON
11//! column when the registered type wants more than title + body.
12//!
13//! The slug is unique tenant-wide so `cms_snippet(slug="hero-cta")`
14//! resolves without needing the caller to know the type. Pass
15//! `type_name=` when slugs collide across types.
16
17use chrono::{DateTime, Utc};
18use rustango::sql::Auto;
19use rustango::Model;
20use serde::{Deserialize, Serialize};
21
22/// A single reusable content block. One row per snippet instance.
23#[derive(Model, Debug, Clone, Serialize, Deserialize)]
24#[rustango(
25    table = "cms_snippet",
26    app = "cms",
27    display = "title",
28    admin(
29        list_display = "type_name, slug, title, word_count, updated_at",
30        ordering = "type_name, slug",
31        list_filter = "type_name",
32    )
33)]
34pub struct Snippet {
35    #[rustango(primary_key)]
36    pub id: Auto<i64>,
37
38    /// Which `LibraryTypeHandler::type_name()` this row belongs to.
39    /// Indexed for the "list snippets of type X" admin view.
40    #[rustango(max_length = 64, index)]
41    pub type_name: String,
42
43    /// Folder path — slash-separated, no leading slash, trailing
44    /// slash optional. Empty string = root. Used purely for the
45    /// admin's tree organization; doesn't affect template lookups
46    /// (slug remains the unique key).
47    #[rustango(max_length = 255, index, default = "''")]
48    pub folder_path: String,
49
50    /// Stable URL-friendly identifier authors reference from
51    /// templates: `{{ cms_snippet(slug="hero-cta") }}`. Unique
52    /// across the tenant so a slug alone is enough to resolve.
53    #[rustango(max_length = 128, unique)]
54    pub slug: String,
55
56    /// Human display title for the admin list view.
57    #[rustango(max_length = 200)]
58    pub title: String,
59
60    /// Markdown body — rendered through the same sanitizing
61    /// pipeline as page bodies. Most snippet types only need this.
62    pub body_markdown: String,
63
64    /// Extra typed fields (CTA button label + URL, author email,
65    /// FAQ answer link, etc.) the registered handler knows how to
66    /// interpret. JSON object; empty `{}` when unused.
67    #[rustango(default = "'{}'::jsonb")]
68    pub data: serde_json::Value,
69
70    #[rustango(auto_now_add)]
71    pub created_at: Auto<DateTime<Utc>>,
72    #[rustango(auto_now)]
73    pub updated_at: Auto<DateTime<Utc>>,
74}
75
76// =====================================================================
77// #123 — opt-in versioned snapshots for library snippets.
78// Mirrors the page-revision shape: full-row JSON, per-snippet
79// monotonic `sequence`. Only captured for types whose handler
80// returns `revisions_enabled() == true`.
81// =====================================================================
82
83#[derive(rustango::Model, Debug, Clone, Serialize, Deserialize)]
84#[rustango(
85    table = "cms_snippet_revision",
86    app = "cms",
87    admin(
88        list_display = "snippet_id, sequence, captured_by, captured_at",
89        ordering = "-captured_at",
90        list_filter = "snippet_id",
91    )
92)]
93pub struct SnippetRevision {
94    #[rustango(primary_key)]
95    pub id: Auto<i64>,
96
97    #[rustango(fk = "cms_snippet", on = "id", index)]
98    pub snippet_id: i64,
99
100    /// Per-snippet monotonic counter starting at 1.
101    pub sequence: i32,
102
103    /// Full snapshot of the snippet row at the time of save.
104    pub snapshot: serde_json::Value,
105
106    /// `rustango_users.id` of the editor who triggered the save.
107    pub captured_by: Option<i64>,
108
109    #[rustango(auto_now_add)]
110    pub captured_at: Auto<DateTime<Utc>>,
111}
112
113impl SnippetRevision {
114    /// Short label used in the admin's revisions card.
115    #[must_use]
116    pub fn label(&self) -> String {
117        let when = self
118            .captured_at
119            .get()
120            .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string())
121            .unwrap_or_default();
122        format!("#{} · {}", self.sequence, when)
123    }
124}
125
126/// Capture one revision row for `snippet`. Bumps `sequence` off the
127/// current max for that snippet id. Idempotent in the sense that
128/// repeated calls produce one row per call — callers should only
129/// invoke after a successful save.
130///
131/// # Errors
132/// Driver / query failures or serialization errors.
133pub async fn capture_revision(
134    pool: &rustango::sql::Pool,
135    snippet: &Snippet,
136    captured_by: Option<i64>,
137) -> Result<SnippetRevision, rustango::sql::ExecError> {
138    use rustango::core::Column as _;
139    use rustango::sql::{sqlx, FetcherPool as _};
140    let snippet_id = snippet.id.get().copied().unwrap_or_default();
141    let recent: Vec<SnippetRevision> = SnippetRevision::objects()
142        .where_(SnippetRevision::snippet_id.eq(snippet_id))
143        .order_by(&[("sequence", true)])
144        .fetch(pool)
145        .await?;
146    let next_seq = recent.first().map_or(1, |r| r.sequence + 1);
147    let snapshot = serde_json::to_value(snippet)
148        .map_err(|e| rustango::sql::ExecError::Driver(sqlx::Error::Decode(Box::new(e))))?;
149    let mut row = SnippetRevision {
150        id: Auto::Unset,
151        snippet_id,
152        sequence: next_seq,
153        snapshot,
154        captured_by,
155        captured_at: Auto::Unset,
156    };
157    row.insert(pool).await?;
158    Ok(row)
159}
160
161/// Every revision row for `snippet_id`, newest first.
162///
163/// # Errors
164/// Driver / query failures.
165pub async fn revisions_for(
166    pool: &rustango::sql::Pool,
167    snippet_id: i64,
168) -> Result<Vec<SnippetRevision>, rustango::sql::ExecError> {
169    use rustango::core::Column as _;
170    use rustango::sql::FetcherPool as _;
171    SnippetRevision::objects()
172        .where_(SnippetRevision::snippet_id.eq(snippet_id))
173        .order_by(&[("sequence", true)])
174        .fetch(pool)
175        .await
176}
177
178/// Fetch one revision by `(snippet_id, sequence)`. Returns `None`
179/// when no matching row exists.
180///
181/// # Errors
182/// Driver / query failures.
183pub async fn revision_by_sequence(
184    pool: &rustango::sql::Pool,
185    snippet_id: i64,
186    sequence: i32,
187) -> Result<Option<SnippetRevision>, rustango::sql::ExecError> {
188    use rustango::core::Column as _;
189    use rustango::sql::FetcherPool as _;
190    let mut rows: Vec<SnippetRevision> = SnippetRevision::objects()
191        .where_(SnippetRevision::snippet_id.eq(snippet_id))
192        .where_(SnippetRevision::sequence.eq(sequence))
193        .fetch(pool)
194        .await?;
195    Ok(rows.pop())
196}
197
198// =====================================================================
199// Tera function — `{{ cms_snippet(slug=...) }}` resolves to rendered
200// HTML inside any template the host app registered the function with.
201// =====================================================================
202
203/// Write (or clear) an element's own template name in its `data`.
204///
205/// An empty `name` removes the key rather than storing `""`, so the
206/// element falls back to its type's template — "clear the box to go
207/// back to the default" is what an editor expects, and an empty
208/// string would otherwise be a name that renders nothing.
209///
210/// A `data` that is not a JSON object (null on a fresh row, or a row
211/// written by something else) is replaced with one; the alternative
212/// is silently dropping the edit.
213pub fn set_element_template(data: &mut serde_json::Value, name: &str) {
214    if !data.is_object() {
215        if name.is_empty() {
216            return;
217        }
218        *data = serde_json::Value::Object(serde_json::Map::new());
219    }
220    let Some(obj) = data.as_object_mut() else {
221        return;
222    };
223    if name.is_empty() {
224        obj.remove("template");
225    } else {
226        obj.insert(
227            "template".to_owned(),
228            serde_json::Value::String(name.to_owned()),
229        );
230    }
231}
232
233/// Normalize a user-typed folder path into the storage form:
234/// no leading slash, single trailing slash on non-empty paths,
235/// collapsed runs of slashes, and segment trim. Empty input
236/// (or `/`) → root (`""`).
237///
238/// Examples:
239/// - `"  /marketing/cta/  "` → `"marketing/cta/"`
240/// - `"//foo///bar"` → `"foo/bar/"`
241/// - `""` / `"/"` → `""`
242#[must_use]
243pub fn normalize_folder(raw: &str) -> String {
244    let trimmed = raw.trim();
245    let segs: Vec<&str> = trimmed
246        .split('/')
247        .map(str::trim)
248        .filter(|s| !s.is_empty())
249        .collect();
250    if segs.is_empty() {
251        return String::new();
252    }
253    let mut out = segs.join("/");
254    out.push('/');
255    out
256}
257
258/// All direct child folders of `parent` — walks every snippet's
259/// `folder_path`, keeps only the segment immediately under `parent`,
260/// dedupes + sorts. Empty `parent` means root.
261///
262/// Cheap for the typical Library size (tens to low hundreds of
263/// snippets); upgrade to a recursive CTE only if profiling demands.
264///
265/// # Errors
266/// Driver / query failures from the snippet lookup.
267pub async fn child_folders(
268    pool: &rustango::sql::Pool,
269    parent: &str,
270) -> Result<Vec<String>, rustango::sql::ExecError> {
271    use rustango::sql::FetcherPool as _;
272    let rows: Vec<Snippet> = Snippet::objects().fetch(pool).await?;
273    let mut out: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
274    let parent_norm = normalize_folder(parent);
275    for r in rows {
276        if !r.folder_path.starts_with(&parent_norm) {
277            continue;
278        }
279        let rest = &r.folder_path[parent_norm.len()..];
280        let Some((head, _)) = rest.split_once('/') else {
281            continue;
282        };
283        if head.is_empty() {
284            continue;
285        }
286        out.insert(head.to_owned());
287    }
288    Ok(out.into_iter().collect())
289}
290
291/// Every folder path used by snippets of `type_name`, plus every
292/// intermediate folder derived from the leaf paths. Result is sorted
293/// and includes the empty (root) folder.
294///
295/// Example: snippets at `marketing/cta/` and `marketing/banner/`
296/// produce `["", "marketing/", "marketing/banner/", "marketing/cta/"]`.
297///
298/// # Errors
299/// Driver / query failures.
300pub async fn folder_tree_for_type(
301    pool: &rustango::sql::Pool,
302    type_name: &str,
303) -> Result<Vec<String>, rustango::sql::ExecError> {
304    use rustango::core::Column as _;
305    use rustango::sql::FetcherPool as _;
306    let rows: Vec<Snippet> = Snippet::objects()
307        .where_(Snippet::type_name.eq(type_name.to_owned()))
308        .fetch(pool)
309        .await?;
310    let mut out: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
311    out.insert(String::new());
312    for r in rows {
313        if r.folder_path.is_empty() {
314            continue;
315        }
316        let mut acc = String::new();
317        for seg in r.folder_path.split('/').filter(|s| !s.is_empty()) {
318            acc.push_str(seg);
319            acc.push('/');
320            out.insert(acc.clone());
321        }
322    }
323    Ok(out.into_iter().collect())
324}
325
326thread_local! {
327    /// The render's `slug → html` maps (wrapped, body-only), installed by
328    /// [`install`] for the duration of `tera.render`.
329    static CURRENT_SNIPPETS: std::cell::RefCell<Option<SnippetMaps>> =
330        const { std::cell::RefCell::new(None) };
331}
332
333type SnippetMaps = (
334    std::collections::HashMap<String, String>,
335    std::collections::HashMap<String, String>,
336);
337
338/// Clears the installed snippet maps on drop. Returned by [`install`].
339#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
340pub struct SnippetsGuard {
341    _priv: (),
342}
343
344impl Drop for SnippetsGuard {
345    fn drop(&mut self) {
346        CURRENT_SNIPPETS.with(|cell| *cell.borrow_mut() = None);
347    }
348}
349
350/// Install the render's prefetched snippets (from [`prefetch_all`]) for
351/// `cms_snippet(slug=…)`, until the guard drops.
352pub fn install(
353    wrapped: std::collections::HashMap<String, String>,
354    inline: std::collections::HashMap<String, String>,
355) -> SnippetsGuard {
356    CURRENT_SNIPPETS.with(|cell| *cell.borrow_mut() = Some((wrapped, inline)));
357    SnippetsGuard { _priv: () }
358}
359
360/// Register the `cms_snippet` Tera function. Wired from
361/// [`crate::urls::register_tera_helpers`].
362///
363/// `{{ cms_snippet(slug="hero-cta") }}` is the snippet's rendered body in
364/// its wrapper; `body=true` gives the body alone. An unknown slug is an
365/// empty string. Tera functions can't read the context, so the maps come
366/// from the thread-local the public render installs.
367pub fn register_tera_function(tera: &mut tera::Tera) {
368    tera.register_function("cms_snippet", CmsSnippetFn);
369}
370
371struct CmsSnippetFn;
372
373impl tera::Function for CmsSnippetFn {
374    fn call(&self, args: &std::collections::HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
375        let slug = args
376            .get("slug")
377            .and_then(tera::Value::as_str)
378            .ok_or_else(|| tera::Error::msg("cms_snippet: `slug` is required"))?;
379        let body_only = args.get("body").and_then(tera::Value::as_bool).unwrap_or(false);
380        let html = CURRENT_SNIPPETS.with(|cell| {
381            cell.borrow()
382                .as_ref()
383                .and_then(|(wrapped, inline)| if body_only { inline.get(slug) } else { wrapped.get(slug) })
384                .cloned()
385                .unwrap_or_default()
386        });
387        Ok(tera::Value::String(html))
388    }
389
390    fn is_safe(&self) -> bool {
391        true
392    }
393}
394
395/// Prefetch every snippet for the current tenant and return two
396/// `slug → html` maps (wrapped + inline). The public-render flow
397/// inserts them into the Tera context so `{{ cms_snippet(slug=…) }}`
398/// resolves without re-entering the DB.
399///
400/// Cheap for typical sites — bounded by `cms_snippet` cardinality
401/// (callouts, authors, FAQ entries; tens at most). When sites grow
402/// past that, swap this for selective prefetch keyed on the slugs
403/// the template actually references.
404///
405/// # Errors
406/// Driver / query failures from the snippet lookup.
407pub async fn prefetch_all(
408    pool: &rustango::sql::Pool,
409    locale_id: Option<i64>,
410) -> Result<
411    (
412        std::collections::HashMap<String, String>,
413        std::collections::HashMap<String, String>,
414    ),
415    rustango::sql::ExecError,
416> {
417    use rustango::sql::FetcherPool as _;
418    let rows: Vec<Snippet> = Snippet::objects().fetch(pool).await?;
419    // #409 — per-locale `body_markdown` overrides for the active
420    // non-default locale (one batched fetch). Empty on the default
421    // locale (`locale_id` None) so the canonical text renders.
422    let translations = match locale_id {
423        Some(lid) => {
424            let ids: Vec<i64> = rows.iter().filter_map(|s| s.id.get().copied()).collect();
425            crate::snippet_translation::fetch_for_snippets(pool, &ids, lid)
426                .await
427                .unwrap_or_default()
428        }
429        None => std::collections::HashMap::new(),
430    };
431    let mut wrapped: std::collections::HashMap<String, String> =
432        std::collections::HashMap::with_capacity(rows.len());
433    let mut inline: std::collections::HashMap<String, String> =
434        std::collections::HashMap::with_capacity(rows.len());
435    for s in rows {
436        let body =
437            s.id.get()
438                .copied()
439                .and_then(|id| translations.get(&id))
440                .and_then(|m| m.get("body_markdown"))
441                .map_or(s.body_markdown.as_str(), String::as_str);
442        inline.insert(s.slug.clone(), crate::markdown::render(body));
443        wrapped.insert(s.slug.clone(), render_with_wrapper(&s, body));
444    }
445    Ok((wrapped, inline))
446}
447
448/// Wrap rendered markdown in a class-bearing `<div>` so theme CSS
449/// can target `.cms-snippet[data-type="callout"]` etc. `body_markdown`
450/// is passed in (rather than read off `s`) so the caller can supply a
451/// per-locale translation override.
452fn render_with_wrapper(s: &Snippet, body_markdown: &str) -> String {
453    let html = crate::markdown::render(body_markdown);
454    format!(
455        r#"<div class="cms-snippet" data-snippet-slug="{slug}" data-snippet-type="{ty}">{html}</div>"#,
456        slug = html_escape(&s.slug),
457        ty = html_escape(&s.type_name),
458    )
459}
460
461fn html_escape(s: &str) -> String {
462    s.replace('&', "&amp;")
463        .replace('<', "&lt;")
464        .replace('>', "&gt;")
465        .replace('"', "&quot;")
466}
467
468#[cfg(test)]
469mod cms_snippet_fn_tests {
470    use super::*;
471    use std::collections::HashMap;
472
473    fn render(src: &str) -> String {
474        let mut tera = tera::Tera::default();
475        register_tera_function(&mut tera);
476        tera.add_raw_template("t.html", src).unwrap();
477        tera.render("t.html", &tera::Context::new()).unwrap()
478    }
479
480    /// `cms_snippet` reads the snippets the render installed.
481    #[test]
482    fn cms_snippet_returns_the_installed_snippet() {
483        let _g = install(
484            HashMap::from([("care".to_owned(), r#"<div class="cms-snippet"><p>Hand wash</p></div>"#.to_owned())]),
485            HashMap::from([("care".to_owned(), "<p>Hand wash</p>".to_owned())]),
486        );
487        assert_eq!(
488            render(r#"{{ cms_snippet(slug="care") }}"#),
489            r#"<div class="cms-snippet"><p>Hand wash</p></div>"#,
490            "safe: not escaped"
491        );
492        assert_eq!(render(r#"{{ cms_snippet(slug="care", body=true) }}"#), "<p>Hand wash</p>");
493        assert_eq!(render(r#"[{{ cms_snippet(slug="nope") }}]"#), "[]");
494    }
495
496    #[test]
497    fn the_guard_clears_the_snippets() {
498        drop(install(HashMap::new(), HashMap::new()));
499        CURRENT_SNIPPETS.with(|c| assert!(c.borrow().is_none()));
500    }
501}