1use std::cell::RefCell;
53use std::collections::HashMap;
54use std::sync::Arc;
55
56use rustango::core::Column as _;
57use rustango::sql::FetcherPool as _;
58use serde::{Deserialize, Serialize};
59use tera::{Function, Tera, Value};
60
61use crate::page::Page;
62
63pub const DEFAULT_DEPTH: i64 = 1;
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct MenuRow {
72 pub id: i64,
73 pub parent_id: Option<i64>,
74 pub title: String,
75 pub url_path: String,
76 pub sort_order: i32,
77 #[serde(default)]
81 pub path: String,
82 #[serde(default)]
85 pub page_type_id: i64,
86}
87
88impl MenuRow {
89 fn from_page(p: Page) -> Option<Self> {
90 let id = p.id.get().copied()?;
91 Some(Self {
92 id,
93 parent_id: p.parent_id,
94 title: p.title,
95 url_path: p.url_path,
96 sort_order: p.sort_order,
97 path: p.path,
98 page_type_id: p.page_type_id,
99 })
100 }
101}
102
103thread_local! {
104 static CURRENT_MENU_ROWS: RefCell<Option<Arc<Vec<MenuRow>>>>
108 = const { RefCell::new(None) };
109}
110
111#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
115pub struct AutoMenuGuard {
116 _priv: (),
117}
118
119impl Drop for AutoMenuGuard {
120 fn drop(&mut self) {
121 CURRENT_MENU_ROWS.with(|cell| {
122 *cell.borrow_mut() = None;
123 });
124 }
125}
126
127pub fn install(rows: Vec<MenuRow>) -> AutoMenuGuard {
129 CURRENT_MENU_ROWS.with(|cell| {
130 *cell.borrow_mut() = Some(Arc::new(rows));
131 });
132 AutoMenuGuard { _priv: () }
133}
134
135pub async fn prefetch(pool: &rustango::sql::Pool) -> Vec<MenuRow> {
151 let error_tid = crate::error_pages::error_page_type_id(pool).await;
152 let now = chrono::Utc::now();
153 let rows = Page::objects()
154 .where_(Page::show_in_menus.eq(true))
155 .where_(Page::status.is_in(crate::resolver::served_statuses()))
158 .order_by(&[("sort_order", false), ("id", false)])
159 .fetch(pool)
160 .await;
161 match rows {
162 Ok(rows) => rows
163 .into_iter()
164 .filter(|p| error_tid.map_or(true, |tid| p.page_type_id != tid))
165 .filter(|p| crate::resolver::visible_now(p, now))
166 .filter_map(MenuRow::from_page)
167 .collect(),
168 Err(e) => {
169 tracing::warn!(
170 target: "rustango_cms::auto_menu",
171 error = %e,
172 "auto_menu prefetch failed; templates will see an empty list",
173 );
174 Vec::new()
175 }
176 }
177}
178
179pub async fn prefetch_cached(
194 pool: &rustango::sql::Pool,
195 cache: &rustango::cache::BoxedCache,
196 key: &str,
197 ttl: Option<std::time::Duration>,
198) -> Vec<MenuRow> {
199 let json = rustango::cache_fragment::cached_render(cache.as_ref(), key, ttl, || async {
200 serde_json::to_string(&prefetch(pool).await).unwrap_or_else(|_| "[]".to_owned())
201 })
202 .await;
203 serde_json::from_str(&json).unwrap_or_default()
204}
205
206pub fn register_tera_function(tera: &mut Tera) {
209 tera.register_function("auto_menu", AutoMenuFn);
210}
211
212struct AutoMenuFn;
213
214impl Function for AutoMenuFn {
215 fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
216 let pool = CURRENT_MENU_ROWS.with(|cell| cell.borrow().clone());
217 let Some(pool) = pool else {
218 return Ok(Value::Array(Vec::new()));
219 };
220 let parent: Option<i64> = args.get("parent_id").and_then(|v| {
222 if v.is_null() {
223 return None;
224 }
225 v.as_i64().filter(|n| *n > 0)
226 });
227 let depth: i64 = args
228 .get("depth")
229 .and_then(Value::as_i64)
230 .filter(|n| *n >= 1)
231 .unwrap_or(DEFAULT_DEPTH);
232
233 let by_parent = index_by_parent(&pool);
234 let items = build_items(&by_parent, parent, depth);
235 serde_json::to_value(&items)
236 .map_err(|e| tera::Error::msg(format!("auto_menu: serializing items failed: {e}")))
237 }
238}
239
240#[derive(Debug, Serialize)]
242pub struct MenuItem {
243 pub page_id: i64,
244 pub title: String,
245 pub url_path: String,
246 pub children: Vec<MenuItem>,
247}
248
249fn index_by_parent(rows: &[MenuRow]) -> HashMap<Option<i64>, Vec<&MenuRow>> {
253 crate::tree_build::index_by_parent(rows, |r| r.parent_id)
254}
255
256fn build_items(
260 by_parent: &HashMap<Option<i64>, Vec<&MenuRow>>,
261 parent: Option<i64>,
262 depth: i64,
263) -> Vec<MenuItem> {
264 crate::tree_build::build(
265 by_parent,
266 parent,
267 depth,
268 &|r: &MenuRow| r.id,
269 &|r: &MenuRow, children| MenuItem {
270 page_id: r.id,
271 title: r.title.clone(),
272 url_path: r.url_path.clone(),
273 children,
274 },
275 )
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use tera::{Context, Tera};
282
283 fn fresh_tera() -> Tera {
284 let mut tera = Tera::default();
285 register_tera_function(&mut tera);
286 tera
287 }
288
289 fn render(tera: &Tera, src: &str) -> String {
290 let mut t = tera.clone();
291 t.add_raw_template("t.html", src).unwrap();
292 t.render("t.html", &Context::new()).unwrap()
293 }
294
295 fn row(id: i64, parent: Option<i64>, title: &str, slug: &str, sort: i32) -> MenuRow {
296 MenuRow {
297 id,
298 parent_id: parent,
299 title: title.to_owned(),
300 url_path: format!("/{slug}"),
301 sort_order: sort,
302 path: String::new(),
303 page_type_id: 0,
304 }
305 }
306
307 fn fixture() -> Vec<MenuRow> {
314 vec![
315 row(1, None, "Home", "", 0),
316 row(2, None, "About", "about", 1),
317 row(3, Some(2), "Team", "about/team", 0),
318 row(4, Some(2), "Careers", "about/careers", 1),
319 row(5, Some(4), "Engineering", "about/careers/eng", 0),
320 ]
321 }
322
323 #[test]
324 fn returns_empty_when_nothing_installed() {
325 let tera = fresh_tera();
326 let out = render(&tera, "{{ auto_menu() | length }}");
327 assert_eq!(out, "0");
328 }
329
330 #[test]
335 fn menu_rows_json_round_trip_is_lossless() {
336 let rows = fixture();
337 let json = serde_json::to_string(&rows).expect("serialize");
338 let back: Vec<MenuRow> = serde_json::from_str(&json).expect("deserialize");
339 assert_eq!(serde_json::to_string(&back).unwrap(), json);
341 assert_eq!(back.len(), 5);
342 assert_eq!(back[0].parent_id, None);
344 assert_eq!(back[4].parent_id, Some(4));
345 assert_eq!(back[3].title, "Careers");
346 assert_eq!(back[2].url_path, "/about/team");
347 }
348
349 #[test]
350 fn root_menu_returns_top_level_items() {
351 let _g = install(fixture());
352 let tera = fresh_tera();
353 let out = render(
354 &tera,
355 "{% for it in auto_menu() %}{{ it.title }} {% endfor %}",
356 );
357 assert_eq!(out, "Home About ");
358 }
359
360 #[test]
361 fn explicit_parent_id_returns_children_of_that_page() {
362 let _g = install(fixture());
363 let tera = fresh_tera();
364 let out = render(
365 &tera,
366 "{% for it in auto_menu(parent_id=2) %}{{ it.title }} {% endfor %}",
367 );
368 assert_eq!(out, "Team Careers ");
369 }
370
371 #[test]
372 fn depth_one_emits_empty_children_arrays() {
373 let _g = install(fixture());
374 let tera = fresh_tera();
375 let out = render(
376 &tera,
377 "{% for it in auto_menu(parent_id=2, depth=1) %}\
378 {{ it.title }}={{ it.children | length }} {% endfor %}",
379 );
380 assert_eq!(out, "Team=0 Careers=0 ");
381 }
382
383 #[test]
384 fn depth_two_expands_one_level_of_nesting() {
385 let _g = install(fixture());
386 let tera = fresh_tera();
387 let src = r#"
388{%- for it in auto_menu(parent_id=2, depth=2) -%}
389{{ it.title }}:{% for c in it.children %}{{ c.title }},{% endfor %};
390{%- endfor -%}
391"#;
392 let out = render(&tera, src);
393 assert_eq!(out, "Team:;Careers:Engineering,;");
394 }
395
396 #[test]
397 fn depth_three_reaches_grandchildren() {
398 let _g = install(fixture());
399 let tera = fresh_tera();
400 let src = r#"
401{%- for it in auto_menu(depth=3) -%}
402{{ it.title }}({% for c in it.children %}{{ c.title }}[{% for g in c.children %}{{ g.title }},{% endfor %}],{% endfor %});
403{%- endfor -%}
404"#;
405 let out = render(&tera, src);
406 assert_eq!(out, "Home();About(Team[],Careers[Engineering,],);");
408 }
409
410 #[test]
411 fn parent_id_zero_treated_as_root() {
412 let _g = install(fixture());
413 let tera = fresh_tera();
414 let out = render(
415 &tera,
416 "{% for it in auto_menu(parent_id=0) %}{{ it.title }} {% endfor %}",
417 );
418 assert_eq!(out, "Home About ");
419 }
420
421 #[test]
422 fn parent_id_unknown_returns_empty() {
423 let _g = install(fixture());
424 let tera = fresh_tera();
425 let out = render(&tera, "{{ auto_menu(parent_id=999) | length }}");
426 assert_eq!(out, "0");
427 }
428
429 #[test]
430 fn items_are_ordered_by_input_order() {
431 let rows = vec![
434 row(10, None, "Z-late", "z", 5),
435 row(11, None, "A-early", "a", 0),
436 row(12, None, "M-mid", "m", 2),
437 ];
438 let _g = install(rows);
439 let tera = fresh_tera();
440 let out = render(
441 &tera,
442 "{% for it in auto_menu() %}{{ it.title }} {% endfor %}",
443 );
444 assert_eq!(out, "Z-late A-early M-mid ");
447 }
448
449 #[test]
450 fn json_shape_matches_issue_spec() {
451 let _g = install(vec![row(7, None, "Solo", "solo", 0)]);
454 let tera = fresh_tera();
455 let out = render(
456 &tera,
457 "{% set m = auto_menu() %}{{ m[0].page_id }}|{{ m[0].title }}|{{ m[0].url_path }}|{{ m[0].children | length }}",
458 );
459 assert_eq!(out, "7|Solo|/solo|0");
460 }
461
462 #[test]
463 fn guard_clears_thread_local() {
464 {
465 let _g = install(fixture());
466 let tera = fresh_tera();
467 assert_eq!(render(&tera, "{{ auto_menu() | length }}"), "2");
468 }
469 let tera = fresh_tera();
470 assert_eq!(render(&tera, "{{ auto_menu() | length }}"), "0");
471 }
472
473 #[test]
474 fn negative_or_zero_depth_normalizes_to_default() {
475 let _g = install(fixture());
476 let tera = fresh_tera();
477 let out0 = render(
481 &tera,
482 "{% for it in auto_menu(parent_id=2, depth=0) %}{{ it.title }} {% endfor %}",
483 );
484 let out1 = render(
485 &tera,
486 "{% for it in auto_menu(parent_id=2, depth=1) %}{{ it.title }} {% endfor %}",
487 );
488 assert_eq!(out0, out1);
489 }
490}