Skip to main content

rustango_cms/
auto_menu.rs

1//! `auto_menu(parent_id=…, depth=…)` Tera function — an automatic
2//! menu built from the page tree.
3//!
4//! The function walks the page tree at render time,
5//! filters by `show_in_menus = True` + `status = "published"`, and
6//! returns a nested list a host template can iterate to emit nav
7//! chrome. Hosts don't have
8//! to hand-roll the SQL or maintain a `cms_navigation` row when the
9//! menu IS the published tree.
10//!
11//! ## Usage
12//!
13//! ```text
14//! {% set items = auto_menu(parent_id=1, depth=2) %}
15//! <nav>
16//!   {% for it in items %}
17//!     <a href="{{ it.url_path }}">{{ it.title }}</a>
18//!     {% if it.children | length > 0 %}
19//!       <ul>
20//!         {% for c in it.children %}
21//!           <li><a href="{{ c.url_path }}">{{ c.title }}</a></li>
22//!         {% endfor %}
23//!       </ul>
24//!     {% endif %}
25//!   {% endfor %}
26//! </nav>
27//! ```
28//!
29//! ## Arguments
30//!
31//! - `parent_id` — id of the page whose immediate children seed the
32//!   menu. Omit / `0` / `null` for tree roots (`parent_id IS NULL`).
33//! - `depth` — how many levels of children to expand. `1` = direct
34//!   children only (each `children` list empty). `2` = include
35//!   grandchildren. Default `1`.
36//!
37//! Each emitted item has `page_id`, `title`, `url_path`, and a
38//! `children` list of the same shape.
39//!
40//! ## Implementation
41//!
42//! Same thread-local install pattern as [`crate::page_url`] /
43//! [`crate::children_filtered`] — the public-render handler
44//! pre-fetches every `show_in_menus = true` page the resolver would
45//! serve (published, archived, or scheduled and past go-live) in one
46//! query, installs a slim projection in a thread-local,
47//! the function builds the nested tree from the in-memory list at
48//! call time. The set is bounded (typically tens; full sites a few
49//! hundred), so one fetch per render amortizes across N
50//! `auto_menu()` calls in the same template.
51
52use 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
63/// Default depth when the template omits the kwarg — direct children
64/// only.
65pub const DEFAULT_DEPTH: i64 = 1;
66
67/// Slim projection of a [`Page`] row carrying just the columns the
68/// menu builder needs. Drops everything else (theme, og_*, SEO body,
69/// etc.) so the per-render thread-local stays small.
70#[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    /// Materialized tree path — carried so viewer-aware menu filtering
78    /// can resolve inherited (subtree) view restrictions in-memory
79    /// (#members). Not used by the item tree itself.
80    #[serde(default)]
81    pub path: String,
82    /// Page-type id — carried so viewer-aware filtering can consult a
83    /// per-type view restriction (#members).
84    #[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    /// Per-thread, per-render menu pool. Holds every published page
105    /// flagged `show_in_menus = true`. Cleared by [`AutoMenuGuard`]
106    /// when the render returns.
107    static CURRENT_MENU_ROWS: RefCell<Option<Arc<Vec<MenuRow>>>>
108        = const { RefCell::new(None) };
109}
110
111/// RAII guard. While in scope `auto_menu(...)` resolves against the
112/// installed rows; on drop the thread-local clears so a follow-up
113/// render on the same tokio worker doesn't inherit stale data.
114#[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
127/// Install the menu row pool for the duration of the returned guard.
128pub 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
135/// Fetch every published page with `show_in_menus = true`, project to
136/// [`MenuRow`], and return the pool. Bounded by the tenant's
137/// menu-eligible cardinality (typically tens; a large site a few
138/// hundred). Failures degrade to an empty pool — the menu just
139/// renders empty rather than 500'ing the page.
140///
141/// Built-in Error pages (404/500 …) are excluded regardless of their
142/// `show_in_menus` flag — they're failure substitutes, not navigation
143/// destinations, and a root-level error page would otherwise duplicate
144/// the host chrome's per-root nav blocks (same rationale as the
145/// sitemap exclusion).
146///
147/// # Errors
148/// None — driver / query failures are logged and yield an empty
149/// pool.
150pub 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        // Served pages, as the resolver judges them — archived ones too,
156        // which explicit menus already keep (#763).
157        .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
179/// Cached variant of [`prefetch`]. Serves the menu pool from
180/// `cache` under `key`, recomputing + storing on miss via
181/// [`rustango::cache_fragment::cached_render`]. The pool is a slim
182/// projection of the published, menu-eligible tree; it changes only
183/// when a page's `show_in_menus` / title / slug / order changes, so a
184/// short `ttl` bounds staleness exactly like the public page cache.
185///
186/// The fragment is stored as the JSON of `Vec<MenuRow>` (the
187/// framework cache is string-valued). Cache backend errors degrade to
188/// a live query — `cached_render` swallows them and runs the closure.
189///
190/// # Errors
191/// None — query + cache failures both fall back to a (possibly empty)
192/// live pool.
193pub 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
206/// Register the `auto_menu` Tera function. Wired from
207/// [`crate::urls::register_tera_helpers`].
208pub 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        // `parent_id` omitted / 0 / null → root menu (parent_id IS NULL).
221        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/// JSON-friendly shape templates iterate over.
241#[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
249/// Group rows by `parent_id`. Rows arrive sort_order-then-id sorted
250/// (per [`prefetch`]); the index preserves that order inside each
251/// bucket, so the emitted menu is stable.
252fn index_by_parent(rows: &[MenuRow]) -> HashMap<Option<i64>, Vec<&MenuRow>> {
253    crate::tree_build::index_by_parent(rows, |r| r.parent_id)
254}
255
256/// Recursively materialize the items under `parent` down to `depth`
257/// levels. `depth = 1` returns immediate children with empty
258/// `children` arrays.
259fn 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    /// Tree:
308    ///   1 Home (root)
309    ///   2 About (root)
310    ///     3 Team (child of About)
311    ///     4 Careers (child of About)
312    ///       5 Engineering (child of Careers)
313    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    /// `prefetch_cached` stores the menu pool as JSON of
331    /// `Vec<MenuRow>` (the framework cache is string-valued). Guard the
332    /// round-trip so a field rename / drop that would silently corrupt
333    /// cached menus fails loudly here instead of in production.
334    #[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        // MenuRow has no PartialEq — canonical JSON is the equality proxy.
340        assert_eq!(serde_json::to_string(&back).unwrap(), json);
341        assert_eq!(back.len(), 5);
342        // Option<i64> parent_id (both None and Some) must survive.
343        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        // Home has no children; About → Team[], Careers[Engineering,]
407        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        // Input order is `sort_order, id` per `prefetch`; the in-
432        // memory tree builder must preserve that.
433        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        // Items emit in the order they were installed (the prefetch
445        // sort is what gives them sort_order semantics).
446        assert_eq!(out, "Z-late A-early M-mid ");
447    }
448
449    #[test]
450    fn json_shape_matches_issue_spec() {
451        // The issue specifies the per-item shape: page_id, title,
452        // url_path, children. Pin against the literal output.
453        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|&#x2F;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        // depth = 0 isn't useful (would emit nothing). The function
478        // floors to the default so a typo doesn't silently break
479        // navigation.
480        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}