1use chrono::{DateTime, Utc};
18use rustango::sql::Auto;
19use rustango::Model;
20use serde::{Deserialize, Serialize};
21
22#[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 #[rustango(max_length = 64, index)]
41 pub type_name: String,
42
43 #[rustango(max_length = 255, index, default = "''")]
48 pub folder_path: String,
49
50 #[rustango(max_length = 128, unique)]
54 pub slug: String,
55
56 #[rustango(max_length = 200)]
58 pub title: String,
59
60 pub body_markdown: String,
63
64 #[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#[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 pub sequence: i32,
102
103 pub snapshot: serde_json::Value,
105
106 pub captured_by: Option<i64>,
108
109 #[rustango(auto_now_add)]
110 pub captured_at: Auto<DateTime<Utc>>,
111}
112
113impl SnippetRevision {
114 #[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
126pub 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
161pub 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
178pub 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
198pub 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#[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
258pub 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
291pub 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 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#[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
350pub 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
360pub 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
395pub 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 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
448fn 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('&', "&")
463 .replace('<', "<")
464 .replace('>', ">")
465 .replace('"', """)
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 #[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}