Skip to main content

rustango_cms/
navigation.rs

1//! `Navigation` — tenant-managed named menus with nested items.
2//!
3//! Two tables:
4//! - `cms_menu` — one row per editor-curated menu (`main_nav`,
5//!   `footer`, etc.). Per-tenant scoped via the tenancy machinery.
6//! - `cms_menu_item` — tree-shaped nodes inside a menu. Each item
7//!   either links to a page (`page_id` FK) OR carries a custom URL
8//!   (`external_url`) — the form enforces exactly one.
9//!
10//! The `menu(slug="...")` Tera helper exposes the nested tree to
11//! templates; themes render their own markup, so the helper carries
12//! no opinions about classes / icons / hover state.
13
14use chrono::{DateTime, Utc};
15use rustango::sql::Auto;
16use rustango::Model;
17use serde::{Deserialize, Serialize};
18
19/// Named menu container — slug is the stable handle templates pass
20/// to the `menu(slug="...")` Tera helper. Unique within a tenant.
21#[derive(Model, Debug, Clone, Serialize, Deserialize)]
22#[rustango(
23    table = "cms_menu",
24    app = "cms",
25    display = "name",
26    admin(list_display = "slug, name, created_at", ordering = "name",)
27)]
28pub struct Menu {
29    #[rustango(primary_key)]
30    pub id: Auto<i64>,
31
32    /// Stable handle (kebab-case). Templates pass this to the
33    /// `menu()` Tera helper.
34    #[rustango(max_length = 64, unique)]
35    pub slug: String,
36
37    /// Display name shown in the admin list.
38    #[rustango(max_length = 100)]
39    pub name: String,
40
41    #[rustango(auto_now_add)]
42    pub created_at: Auto<DateTime<Utc>>,
43}
44
45/// One node inside a menu. Tree-shaped via `parent_id` self-FK. The
46/// link target is exactly one of `page_id` (internal) or
47/// `external_url` (custom URL); the admin form enforces this, and
48/// the public render resolver picks the live URL from the chosen
49/// side at request time so slug renames stay reflected.
50#[derive(Model, Debug, Clone, Serialize, Deserialize)]
51#[rustango(
52    table = "cms_menu_item",
53    app = "cms",
54    display = "label",
55    admin(
56        list_display = "menu_id, label, parent_id, sort_order",
57        ordering = "menu_id, parent_id, sort_order",
58    )
59)]
60pub struct MenuItem {
61    #[rustango(primary_key)]
62    pub id: Auto<i64>,
63
64    #[rustango(fk = "cms_menu", on = "id", index)]
65    pub menu_id: i64,
66
67    /// Tree parent — None for top-level items.
68    #[rustango(fk = "cms_menu_item", on = "id", index)]
69    pub parent_id: Option<i64>,
70
71    /// Sibling order — ascending.
72    pub sort_order: i32,
73
74    /// Link text rendered to readers. May be empty when linked to a
75    /// page; templates fall back to the page title in that case.
76    #[rustango(max_length = 200)]
77    pub label: String,
78
79    /// Internal page link. Mutually exclusive with `external_url`.
80    /// Nulled (rather than cascade-deleted) when the page is
81    /// deleted, so the menu item stays visible for the editor to
82    /// re-target.
83    #[rustango(fk = "cms_page", on = "id")]
84    pub page_id: Option<i64>,
85
86    /// Custom external URL. Mutually exclusive with `page_id`.
87    #[rustango(max_length = 500)]
88    pub external_url: Option<String>,
89
90    /// Open the link in a new tab (target="_blank" rel="noopener").
91    pub open_in_new_tab: bool,
92}
93
94// ----------------------------------------------------------------
95// Resolution — one core, four thin wrappers.
96//
97// `{% set nav = menu(slug="main") %}` in a theme, `GET /api/v2/menus/`
98// for a headless client, and the public render's whole-menu injection
99// all land in [`resolve_menus_with`]. They previously had three
100// separate implementations, of which `resolve_all_menus` was `1 + 3N`
101// queries — it resolved every menu's full tree and then discarded
102// everything but the slug and the name.
103//
104// The core is a **fixed handful of queries whatever the menu size**:
105// menus, items, target pages, then at most two batched translation
106// lookups. Nothing in here may query per item; that is the regression
107// this shape exists to prevent.
108// ----------------------------------------------------------------
109
110/// One node in the resolved menu tree. Themes iterate this shape.
111#[derive(Debug, Clone, Serialize)]
112pub struct ResolvedMenuItem {
113    /// `cms_menu_item.id` — lets a headless client correlate a rendered
114    /// node with the row an editor edits.
115    pub id: Option<i64>,
116    pub label: String,
117    /// Where the item points. `null` for a grouping header — an item with
118    /// neither a page nor an external URL, which is a label, not a link.
119    pub url: Option<String>,
120    /// `true` when this item targets a CMS page (vs. an external URL).
121    pub is_page: bool,
122    pub page_id: Option<i64>,
123    pub open_in_new_tab: bool,
124    /// This item targets the page currently being viewed.
125    pub is_active: bool,
126    /// This item lies on the path to the current page — it targets an
127    /// ancestor of it, or it parents a subtree containing the active
128    /// item. The second case is what highlights a top-level section
129    /// whose own link is a grouping label or an external URL.
130    pub in_active_trail: bool,
131    pub children: Vec<ResolvedMenuItem>,
132}
133
134/// Resolved menu shape returned by `menu(slug=...)`.
135#[derive(Debug, Clone, Serialize)]
136pub struct ResolvedMenu {
137    pub slug: String,
138    pub name: String,
139    pub items: Vec<ResolvedMenuItem>,
140}
141
142/// Everything the resolver needs beyond the menu itself.
143///
144/// A struct rather than three positional `Option`s because every one of
145/// them is optional and independently useful, and three bare `None`s at
146/// a call site say nothing about which is which.
147#[derive(Debug, Clone, Copy, Default)]
148pub struct MenuOptions<'a> {
149    /// #members — hide items whose target page this viewer may not see.
150    /// `None` is an anonymous viewer, which is the safe default: it
151    /// hides everything gated rather than revealing it.
152    pub viewer: Option<&'a rustango::tenancy::auth::User>,
153    /// Localize labels. `None` or the default locale returns canonical
154    /// content without issuing the translation queries at all.
155    pub locale: Option<&'a crate::locale::Locale>,
156    /// The page being rendered, for `is_active` / `in_active_trail`.
157    /// Passed as the row rather than an id because the trail test is a
158    /// `path` prefix comparison, and the caller already holds it.
159    pub current: Option<&'a crate::page::Page>,
160}
161
162/// Resolve a menu by slug. Returns `None` when no menu with that
163/// slug exists in the tenant.
164///
165/// # Errors
166/// Driver / query failures from any of the lookups.
167pub async fn resolve_menu(
168    pool: &rustango::sql::Pool,
169    slug: &str,
170) -> Result<Option<ResolvedMenu>, rustango::sql::ExecError> {
171    resolve_menu_with(pool, slug, MenuOptions::default()).await
172}
173
174/// Like [`resolve_menu`] but hides items whose target page the
175/// `viewer` can't access (#members) — login / groups / permission
176/// restrictions, page/subtree or per-type. Anonymous viewers see only
177/// public + password-gated items. An item pointing at a denied page is
178/// dropped (with any submenu it parents), exactly like a draft target.
179///
180/// # Errors
181/// Driver / query failures from any of the lookups.
182pub async fn resolve_menu_for_viewer(
183    pool: &rustango::sql::Pool,
184    slug: &str,
185    viewer: Option<&rustango::tenancy::auth::User>,
186) -> Result<Option<ResolvedMenu>, rustango::sql::ExecError> {
187    resolve_menu_with(
188        pool,
189        slug,
190        MenuOptions {
191            viewer,
192            ..Default::default()
193        },
194    )
195    .await
196}
197
198/// Resolve one menu with the full option set.
199///
200/// # Errors
201/// Driver / query failures from any of the lookups.
202pub async fn resolve_menu_with(
203    pool: &rustango::sql::Pool,
204    slug: &str,
205    opts: MenuOptions<'_>,
206) -> Result<Option<ResolvedMenu>, rustango::sql::ExecError> {
207    let mut all = resolve_menus_with(pool, Some(&[slug.to_owned()]), opts).await?;
208    Ok(all.remove(slug))
209}
210
211/// Resolve every menu in the tenant into a `slug → ResolvedMenu`
212/// map, with no viewer, locale or current page.
213///
214/// # Errors
215/// Driver / query failures from any underlying fetch.
216pub async fn resolve_all_menus(
217    pool: &rustango::sql::Pool,
218) -> Result<std::collections::HashMap<String, ResolvedMenu>, rustango::sql::ExecError> {
219    resolve_menus_with(pool, None, MenuOptions::default()).await
220}
221
222/// The resolver. `slugs = None` resolves every menu in the tenant;
223/// `Some(&[…])` restricts to those slugs.
224///
225/// Query budget, and it does not grow with the number of menus or
226/// items: menus · items · target pages · (viewer restrictions) ·
227/// (item translations) · (page-title translations). The last two are
228/// skipped entirely for the default locale.
229///
230/// # Errors
231/// Driver / query failures from any of the lookups.
232pub async fn resolve_menus_with(
233    pool: &rustango::sql::Pool,
234    slugs: Option<&[String]>,
235    opts: MenuOptions<'_>,
236) -> Result<std::collections::HashMap<String, ResolvedMenu>, rustango::sql::ExecError> {
237    use rustango::core::Column as _;
238    use rustango::sql::FetcherPool as _;
239
240    let mut menu_q = Menu::objects();
241    if let Some(list) = slugs {
242        if list.is_empty() {
243            return Ok(std::collections::HashMap::new());
244        }
245        menu_q = menu_q.where_(Menu::slug.is_in(list.iter().cloned()));
246    }
247    let menus: Vec<Menu> = menu_q.fetch(pool).await?;
248    if menus.is_empty() {
249        return Ok(std::collections::HashMap::new());
250    }
251    let menu_ids: Vec<i64> = menus.iter().filter_map(|m| m.id.get().copied()).collect();
252
253    // Every menu's items in one query, then split by `menu_id` in
254    // memory — the whole reason `resolve_all_menus` is no longer N+1.
255    let items: Vec<MenuItem> = MenuItem::objects()
256        .where_(MenuItem::menu_id.is_in(menu_ids.iter().copied()))
257        .order_by(&[("sort_order", false), ("id", false)])
258        .fetch(pool)
259        .await?;
260
261    // One bulk page lookup for every internal-link item — avoids N+1.
262    // #585 — only **public** targets resolve; an item pointing at a
263    // draft, scheduled, expired or deleted page is dropped below rather
264    // than rendered as a dead link.
265    let referenced_page_ids: std::collections::BTreeSet<i64> =
266        items.iter().filter_map(|i| i.page_id).collect();
267    let pages: Vec<crate::page::Page> = if referenced_page_ids.is_empty() {
268        Vec::new()
269    } else {
270        crate::page::Page::objects()
271            .where_(crate::page::Page::id.is_in(referenced_page_ids.iter().copied()))
272            // `published` **and** `archived` — `PageStatus::is_public`.
273            // Filtering to published alone meant a menu silently lost an
274            // item whose target had been archived, while the tree, the
275            // sitemap and the renderer all still served that page. A SPA
276            // drawing nav from menus and content from the tree then
277            // disagreed with itself.
278            .where_(crate::page::Page::status.is_in(crate::page::PageStatus::public_strings()))
279            .fetch(pool)
280            .await?
281    };
282    let pages_by_id: std::collections::HashMap<i64, &crate::page::Page> = pages
283        .iter()
284        .filter_map(|p| p.id.get().copied().map(|id| (id, p)))
285        .collect();
286
287    // #members — resolve which referenced pages this viewer may not see
288    // (login / groups / permission, page/subtree or per-type). Denied
289    // targets are dropped alongside draft ones below.
290    let page_triples: Vec<(i64, String, i64)> = pages
291        .iter()
292        .filter_map(|p| {
293            p.id.get()
294                .copied()
295                .map(|id| (id, p.path.clone(), p.page_type_id))
296        })
297        .collect();
298    let denied = crate::view_restriction::denied_page_ids(pool, opts.viewer, &page_triples).await;
299
300    // Two translation sources, both batched, both skipped on the default
301    // locale — canonical content already *is* the default-locale content.
302    //
303    // 1. authored labels (and per-locale external URLs) on the item;
304    // 2. the page-title fallback an item with an empty label uses, which
305    //    lives in `cms_translation` where the renderer already keeps it.
306    let (item_tr, page_tr) = match opts.locale.filter(|l| !l.is_default) {
307        Some(loc) => {
308            let lid = loc.id.get().copied().unwrap_or_default();
309            let item_ids: Vec<i64> = items.iter().filter_map(|i| i.id.get().copied()).collect();
310            let page_ids: Vec<i64> = referenced_page_ids.iter().copied().collect();
311            (
312                crate::menu_item_translation::fetch_for_items(pool, &item_ids, lid)
313                    .await
314                    .unwrap_or_default(),
315                crate::translation::fetch_for_pages(pool, &page_ids, lid)
316                    .await
317                    .unwrap_or_default(),
318            )
319        }
320        None => Default::default(),
321    };
322
323    let ctx = ResolveCtx {
324        pages_by_id: &pages_by_id,
325        denied: &denied,
326        item_tr: &item_tr,
327        page_tr: &page_tr,
328        current: opts.current,
329    };
330
331    let mut out = std::collections::HashMap::new();
332    for menu in menus {
333        let menu_id = menu.id.get().copied().unwrap_or_default();
334        let mut children_of: std::collections::HashMap<Option<i64>, Vec<&MenuItem>> =
335            std::collections::HashMap::new();
336        for item in items.iter().filter(|i| i.menu_id == menu_id) {
337            children_of.entry(item.parent_id).or_default().push(item);
338        }
339        let tree = build(None, &children_of, &ctx);
340
341        // A `parent_id` cycle, or a parent that lives in a different
342        // menu, makes an item unreachable from the root bucket — so it
343        // renders nowhere, with no error, while the admin's item count
344        // still includes it. Say so: silence here means an editor sees
345        // "5 items" and a navbar with 2, and nothing explains the gap.
346        //
347        // Items legitimately dropped for access or publication reasons
348        // are subtracted first, so this only fires on structural damage.
349        let rendered = count_nodes(&tree);
350        let droppable = items
351            .iter()
352            .filter(|i| i.menu_id == menu_id)
353            .filter(|i| {
354                i.page_id
355                    .is_some_and(|pid| denied.contains(&pid) || !pages_by_id.contains_key(&pid))
356            })
357            .count();
358        let expected = items.iter().filter(|i| i.menu_id == menu_id).count() - droppable;
359        if rendered < expected {
360            tracing::warn!(
361                target: "rustango_cms::navigation",
362                menu = %menu.slug,
363                rendered,
364                expected,
365                "menu items unreachable from the root — a parent_id cycle, \
366                 or a parent belonging to another menu",
367            );
368        }
369
370        out.insert(
371            menu.slug.clone(),
372            ResolvedMenu {
373                slug: menu.slug,
374                name: menu.name,
375                items: tree,
376            },
377        );
378    }
379    Ok(out)
380}
381
382/// Total nodes in a resolved tree, used to detect items the walk could
383/// not reach.
384fn count_nodes(items: &[ResolvedMenuItem]) -> usize {
385    items.len() + items.iter().map(|i| count_nodes(&i.children)).sum::<usize>()
386}
387
388/// The read-only lookups `build` needs, bundled so the recursion
389/// carries one reference instead of five.
390struct ResolveCtx<'a> {
391    pages_by_id: &'a std::collections::HashMap<i64, &'a crate::page::Page>,
392    denied: &'a std::collections::HashSet<i64>,
393    item_tr: &'a std::collections::HashMap<i64, std::collections::HashMap<String, String>>,
394    page_tr: &'a std::collections::HashMap<i64, std::collections::HashMap<String, String>>,
395    current: Option<&'a crate::page::Page>,
396}
397
398impl ResolveCtx<'_> {
399    /// A localized field on an item, if an editor set one for this locale.
400    fn item_override(&self, item_id: Option<i64>, field: &str) -> Option<String> {
401        self.item_tr
402            .get(&item_id?)?
403            .get(field)
404            .filter(|s| !s.is_empty())
405            .cloned()
406    }
407
408    /// A target page's localized title, falling back to its canonical one.
409    fn page_title(&self, page_id: i64, page: &crate::page::Page) -> String {
410        self.page_tr
411            .get(&page_id)
412            .and_then(|m| m.get("title"))
413            .filter(|s| !s.is_empty())
414            .cloned()
415            .unwrap_or_else(|| page.title.clone())
416    }
417
418    /// Does this item's target page sit above the page being viewed?
419    /// A `path` prefix test, so it costs no query — the materialized
420    /// path already encodes ancestry.
421    fn is_ancestor_of_current(&self, target: &crate::page::Page) -> bool {
422        let Some(cur) = self.current else {
423            return false;
424        };
425        cur.path.starts_with(&target.path) && cur.path != target.path
426    }
427
428    /// Is `page_id` the page currently being viewed?
429    ///
430    /// An alias counts as its source: the two are different rows with
431    /// different ids, so a nav item pointing at the canonical page would
432    /// otherwise never highlight while a reader is on the alias's URL.
433    fn is_current_page(&self, page_id: i64) -> bool {
434        let Some(cur) = self.current else {
435            return false;
436        };
437        cur.id.get().copied() == Some(page_id) || cur.alias_of == Some(page_id)
438    }
439
440    /// Does this custom-link URL point at the page being viewed?
441    ///
442    /// `is_active` used to be page-id equality set only in the page
443    /// branch, so an editor who added "Blog" as a custom link to `/blog`
444    /// rather than a page link lost highlighting entirely — and the
445    /// client had to re-derive it from URLs, which is exactly what this
446    /// endpoint exists to avoid. Compared slash-insensitively, since a
447    /// hand-typed URL may or may not carry a trailing one.
448    fn external_matches_current(&self, url: &str) -> bool {
449        let Some(cur) = self.current else {
450            return false;
451        };
452        // Only same-origin paths can name a page here; an absolute URL to
453        // another host never matches.
454        if !url.starts_with('/') {
455            return false;
456        }
457        let trim = |s: &str| s.trim_end_matches('/').to_owned();
458        !cur.url_path.is_empty() && trim(url) == trim(&cur.url_path)
459    }
460}
461
462fn build(
463    parent: Option<i64>,
464    children_of: &std::collections::HashMap<Option<i64>, Vec<&MenuItem>>,
465    ctx: &ResolveCtx<'_>,
466) -> Vec<ResolvedMenuItem> {
467    children_of
468        .get(&parent)
469        .map(|group| {
470            group
471                .iter()
472                .filter_map(|it| {
473                    let id = it.id.get().copied();
474                    let mut is_active = false;
475                    let mut in_active_trail = false;
476                    let (url, resolved_label, is_page) = if let Some(pid) = it.page_id {
477                        // #members — hide items the viewer can't access.
478                        if ctx.denied.contains(&pid) {
479                            return None;
480                        }
481                        // #585 — internal link resolves only if the target
482                        // page is published; otherwise drop the item (and,
483                        // with it, any submenu it parents). No dead links.
484                        let p = ctx.pages_by_id.get(&pid)?;
485                        let url = if p.url_path.is_empty() {
486                            "/".to_owned()
487                        } else {
488                            p.url_path.clone()
489                        };
490                        // An authored label wins, then its translation;
491                        // only an *empty* label falls through to the page
492                        // title — and that title is localized too, which
493                        // it never used to be.
494                        let label = match ctx.item_override(id, "label") {
495                            Some(t) => t,
496                            None if !it.label.trim().is_empty() => it.label.clone(),
497                            None => ctx.page_title(pid, p),
498                        };
499                        is_active = ctx.is_current_page(pid);
500                        in_active_trail = ctx.is_ancestor_of_current(p);
501                        (url, label, true)
502                    } else if let Some(ext) = it.external_url.clone() {
503                        let url = ctx.item_override(id, "external_url").unwrap_or(ext);
504                        is_active = ctx.external_matches_current(&url);
505                        (
506                            url,
507                            ctx.item_override(id, "label").unwrap_or_else(|| it.label.clone()),
508                            false,
509                        )
510                    } else {
511                        // Neither target: a grouping header. It used to
512                        // render `url: "/"`, which a client cannot
513                        // distinguish from a deliberate link to the
514                        // homepage — so every dropdown label became a
515                        // link. `save-tree` now rejects creating these,
516                        // but rows already in the database still render.
517                        (
518                            String::new(),
519                            ctx.item_override(id, "label").unwrap_or_else(|| it.label.clone()),
520                            false,
521                        )
522                    };
523                    let children = build(id, children_of, ctx);
524                    // A grouping item — a label with no link, or an
525                    // external one — is on the trail when something under
526                    // it is. Without this, nothing highlights the open
527                    // section in the common "dropdown header" nav.
528                    in_active_trail |= children.iter().any(|c| c.is_active || c.in_active_trail);
529                    Some(ResolvedMenuItem {
530                        id,
531                        label: resolved_label,
532                        url: (!url.is_empty()).then_some(url),
533                        is_page,
534                        page_id: it.page_id,
535                        open_in_new_tab: it.open_in_new_tab,
536                        is_active,
537                        in_active_trail,
538                        children,
539                    })
540                })
541                .collect()
542        })
543        .unwrap_or_default()
544}
545
546/// Order menu items so a child is always deleted before its parent.
547///
548/// `cms_menu_item.parent_id` is a self-FK with no `ON DELETE`, so removing
549/// a parent while a child still points at it trips the constraint. Sorting
550/// on `parent_id.is_none()` is not enough: it puts every non-root in one
551/// bucket, so a grandchild and its parent tie and their relative order
552/// comes from `HashMap` iteration — the delete then fails, or doesn't,
553/// depending on hashing.
554///
555/// Peels leaves off the set: on each pass, emit every item that nothing
556/// *remaining* claims as a parent. Items whose parent lies outside the set
557/// are leaves for this purpose, which is what makes partial deletes work.
558///
559/// A `parent_id` cycle can't be peeled; rather than loop forever, the
560/// remainder is emitted as-is and the database rejects it — a loud failure
561/// beats a hang.
562#[must_use]
563pub fn order_deepest_first(items: Vec<MenuItem>) -> Vec<MenuItem> {
564    let mut remaining = items;
565    let mut out = Vec::with_capacity(remaining.len());
566    while !remaining.is_empty() {
567        let claimed: std::collections::HashSet<i64> =
568            remaining.iter().filter_map(|it| it.parent_id).collect();
569        let (leaves, rest): (Vec<MenuItem>, Vec<MenuItem>) = remaining
570            .into_iter()
571            .partition(|it| !it.id.get().copied().is_some_and(|id| claimed.contains(&id)));
572        if leaves.is_empty() {
573            // Every survivor is claimed by another survivor — a cycle.
574            out.extend(rest);
575            return out;
576        }
577        out.extend(leaves);
578        remaining = rest;
579    }
580    out
581}
582
583/// Rewrite the page links in a resolved menu tree to a hostname-mapped
584/// site's public paths. External URLs are left alone.
585pub fn rebase_page_urls(items: &mut [ResolvedMenuItem], site_prefix: &str) {
586    for item in items {
587        if item.is_page {
588            if let Some(url) = item.url.as_mut() {
589                *url = crate::site::to_public_path(site_prefix, url);
590            }
591        }
592        rebase_page_urls(&mut item.children, site_prefix);
593    }
594}
595
596// ----------------------------------------------------------------
597// `menu(slug="…")` Tera function (#639). Tera functions can't reach the
598// database, so the public render resolves every menu up front and
599// installs the map here for the duration of `tera.render`.
600// ----------------------------------------------------------------
601
602thread_local! {
603    static CURRENT_MENUS: std::cell::RefCell<Option<std::collections::HashMap<String, ResolvedMenu>>> =
604        const { std::cell::RefCell::new(None) };
605}
606
607/// Clears the installed menus on drop. Returned by [`install`].
608#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
609pub struct MenusGuard {
610    _priv: (),
611}
612
613impl Drop for MenusGuard {
614    fn drop(&mut self) {
615        CURRENT_MENUS.with(|cell| *cell.borrow_mut() = None);
616    }
617}
618
619/// Install the resolved `slug → menu` map `menu(slug=…)` reads, until
620/// the guard drops.
621pub fn install(menus: std::collections::HashMap<String, ResolvedMenu>) -> MenusGuard {
622    CURRENT_MENUS.with(|cell| *cell.borrow_mut() = Some(menus));
623    MenusGuard { _priv: () }
624}
625
626/// Register `menu(slug="…")`: the resolved menu (`slug`, `name`, nested
627/// `items`), or null when no menu has that slug. Wired from
628/// [`crate::urls::register_tera_helpers`].
629pub fn register_tera_function(tera: &mut tera::Tera) {
630    tera.register_function("menu", MenuFn);
631}
632
633struct MenuFn;
634
635impl tera::Function for MenuFn {
636    fn call(&self, args: &std::collections::HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
637        let Some(slug) = args.get("slug").and_then(tera::Value::as_str) else {
638            return Err(tera::Error::msg("menu() needs a `slug` argument"));
639        };
640        CURRENT_MENUS.with(|cell| match cell.borrow().as_ref().and_then(|m| m.get(slug)) {
641            Some(menu) => tera::to_value(menu).map_err(tera::Error::json),
642            None => Ok(tera::Value::Null),
643        })
644    }
645}
646
647#[cfg(test)]
648mod delete_order_tests {
649    use super::*;
650
651    fn item(id: i64, parent: Option<i64>) -> MenuItem {
652        MenuItem {
653            id: rustango::sql::Auto::Set(id),
654            menu_id: 1,
655            parent_id: parent,
656            sort_order: 0,
657            label: String::new(),
658            page_id: None,
659            external_url: None,
660            open_in_new_tab: false,
661        }
662    }
663
664    fn ids(items: &[MenuItem]) -> Vec<i64> {
665        items.iter().filter_map(|i| i.id.get().copied()).collect()
666    }
667
668    /// A child must never be emitted after its parent.
669    fn assert_children_first(ordered: &[MenuItem]) {
670        let order = ids(ordered);
671        for it in ordered {
672            let Some(parent) = it.parent_id else { continue };
673            let Some(id) = it.id.get().copied() else {
674                continue;
675            };
676            let (Some(ci), Some(pi)) = (
677                order.iter().position(|&x| x == id),
678                order.iter().position(|&x| x == parent),
679            ) else {
680                continue; // parent outside the set — nothing to order against
681            };
682            assert!(ci < pi, "child {id} deleted after parent {parent}: {order:?}");
683        }
684    }
685
686    #[test]
687    fn a_three_level_subtree_deletes_leaves_first() {
688        // The case that failed nondeterministically: A → B → C all tied
689        // under the old `parent_id.is_none()` key.
690        let ordered = order_deepest_first(vec![
691            item(1, None),
692            item(2, Some(1)),
693            item(3, Some(2)),
694        ]);
695        assert_eq!(ids(&ordered), vec![3, 2, 1]);
696        assert_children_first(&ordered);
697    }
698
699    #[test]
700    fn input_order_does_not_matter() {
701        for input in [
702            vec![item(1, None), item(2, Some(1)), item(3, Some(2))],
703            vec![item(3, Some(2)), item(1, None), item(2, Some(1))],
704            vec![item(2, Some(1)), item(3, Some(2)), item(1, None)],
705        ] {
706            assert_children_first(&order_deepest_first(input));
707        }
708    }
709
710    #[test]
711    fn siblings_and_several_roots_are_all_ordered() {
712        let ordered = order_deepest_first(vec![
713            item(1, None),
714            item(2, Some(1)),
715            item(3, Some(1)),
716            item(4, Some(3)),
717            item(5, None),
718        ]);
719        assert_eq!(ordered.len(), 5);
720        assert_children_first(&ordered);
721    }
722
723    #[test]
724    fn an_item_whose_parent_is_kept_is_a_leaf_here() {
725        // Partial delete: 9's parent (7) survives the save, so 9 has
726        // nothing to wait for.
727        let ordered = order_deepest_first(vec![item(9, Some(7))]);
728        assert_eq!(ids(&ordered), vec![9]);
729    }
730
731    #[test]
732    fn a_cycle_terminates_instead_of_hanging() {
733        // Corrupt data must not spin the request forever; the DB rejects
734        // the delete instead.
735        let ordered = order_deepest_first(vec![item(1, Some(2)), item(2, Some(1))]);
736        assert_eq!(ordered.len(), 2);
737    }
738
739    #[test]
740    fn an_empty_set_is_empty() {
741        assert!(order_deepest_first(Vec::new()).is_empty());
742    }
743}
744
745/// Order menu items in **tree pre-order**: each item immediately
746/// followed by its own subtree, siblings by `(sort_order, id)`.
747///
748/// The menu builder's save reconstructs each item's parent from DOM
749/// adjacency — "the most recent card one level shallower" — which is how
750/// dragging expresses intent. That contract only holds if the DOM starts
751/// in pre-order. The editor loaded items `ORDER BY parent_id, sort_order`
752/// instead, which is not pre-order in any dialect, so simply opening a
753/// menu and pressing Save rewrote it: on Postgres (NULLs last) a child
754/// became a root; on sqlite (NULLs first) it was re-parented to whichever
755/// root happened to precede it.
756///
757/// Items unreachable from the root — an orphan whose parent was deleted,
758/// or a `parent_id` cycle — are appended at the end rather than dropped.
759/// Dropping them would hide them from the editor *and* delete them on the
760/// next save, turning a display bug into data loss.
761#[must_use]
762pub fn order_pre_order(items: Vec<MenuItem>) -> Vec<MenuItem> {
763    use std::collections::{HashMap, HashSet};
764
765    let mut children_of: HashMap<Option<i64>, Vec<usize>> = HashMap::new();
766    for (i, it) in items.iter().enumerate() {
767        children_of.entry(it.parent_id).or_default().push(i);
768    }
769    for group in children_of.values_mut() {
770        group.sort_by_key(|&i| (items[i].sort_order, items[i].id.get().copied().unwrap_or(0)));
771    }
772
773    let mut out: Vec<usize> = Vec::with_capacity(items.len());
774    let mut seen: HashSet<usize> = HashSet::new();
775    // Explicit stack rather than recursion: a corrupt `parent_id` cycle
776    // must not blow the stack, and `seen` makes re-entry impossible.
777    let mut stack: Vec<usize> = children_of
778        .get(&None)
779        .cloned()
780        .unwrap_or_default()
781        .into_iter()
782        .rev()
783        .collect();
784    while let Some(i) = stack.pop() {
785        if !seen.insert(i) {
786            continue;
787        }
788        out.push(i);
789        if let Some(kids) = items[i]
790            .id
791            .get()
792            .copied()
793            .and_then(|id| children_of.get(&Some(id)))
794        {
795            for &k in kids.iter().rev() {
796                stack.push(k);
797            }
798        }
799    }
800    // Whatever the walk could not reach.
801    for i in 0..items.len() {
802        if !seen.contains(&i) {
803            out.push(i);
804        }
805    }
806
807    let mut slots: Vec<Option<MenuItem>> = items.into_iter().map(Some).collect();
808    out.into_iter()
809        .filter_map(|i| slots[i].take())
810        .collect()
811}
812
813#[cfg(test)]
814mod pre_order_tests {
815    use super::*;
816
817    fn item(id: i64, parent: Option<i64>, sort_order: i32) -> MenuItem {
818        MenuItem {
819            id: rustango::sql::Auto::Set(id),
820            menu_id: 1,
821            parent_id: parent,
822            sort_order,
823            label: format!("item-{id}"),
824            page_id: None,
825            external_url: None,
826            open_in_new_tab: false,
827        }
828    }
829
830    fn ids(items: &[MenuItem]) -> Vec<i64> {
831        items.iter().filter_map(|i| i.id.get().copied()).collect()
832    }
833
834    #[test]
835    fn a_child_immediately_follows_its_parent() {
836        // The property the builder's save depends on.
837        let ordered = order_pre_order(vec![
838            item(3, Some(1), 0),
839            item(1, None, 0),
840            item(2, None, 10),
841        ]);
842        assert_eq!(ids(&ordered), vec![1, 3, 2]);
843    }
844
845    #[test]
846    fn siblings_come_back_in_sort_order() {
847        let ordered = order_pre_order(vec![
848            item(1, None, 0),
849            item(2, Some(1), 20),
850            item(3, Some(1), 10),
851        ]);
852        assert_eq!(ids(&ordered), vec![1, 3, 2]);
853    }
854
855    #[test]
856    fn a_deep_subtree_stays_contiguous() {
857        let ordered = order_pre_order(vec![
858            item(1, None, 0),
859            item(2, Some(1), 0),
860            item(3, Some(2), 0),
861            item(4, None, 10),
862        ]);
863        assert_eq!(ids(&ordered), vec![1, 2, 3, 4]);
864    }
865
866    #[test]
867    fn the_result_never_loses_an_item() {
868        // The regression that would turn a display bug into data loss:
869        // anything missing here is invisible in the editor and deleted by
870        // the next save.
871        let input = vec![
872            item(1, None, 0),
873            item(2, Some(1), 0),
874            item(9, Some(404), 0), // orphan — parent not in this menu
875        ];
876        let ordered = order_pre_order(input);
877        assert_eq!(ordered.len(), 3);
878        assert!(ids(&ordered).contains(&9));
879    }
880
881    #[test]
882    fn a_cycle_terminates_and_keeps_both_items() {
883        let ordered = order_pre_order(vec![
884            item(1, None, 0),
885            item(2, Some(3), 0),
886            item(3, Some(2), 0),
887        ]);
888        assert_eq!(ordered.len(), 3);
889        assert_eq!(ids(&ordered)[0], 1, "the reachable root still comes first");
890    }
891
892    #[test]
893    fn an_empty_menu_is_empty() {
894        assert!(order_pre_order(Vec::new()).is_empty());
895    }
896
897    #[test]
898    fn input_order_does_not_change_the_result() {
899        // The editor previously fed this in `ORDER BY parent_id` order,
900        // which differs per dialect on NULL placement.
901        let a = order_pre_order(vec![
902            item(1, None, 0),
903            item(2, Some(1), 0),
904            item(3, None, 10),
905        ]);
906        let b = order_pre_order(vec![
907            item(2, Some(1), 0),
908            item(3, None, 10),
909            item(1, None, 0),
910        ]);
911        assert_eq!(ids(&a), ids(&b));
912    }
913}
914
915#[cfg(test)]
916mod menu_fn_tests {
917    use super::*;
918
919    fn render(src: &str) -> tera::Result<String> {
920        let mut tera = tera::Tera::default();
921        register_tera_function(&mut tera);
922        tera.add_raw_template("t.html", src).unwrap();
923        tera.render("t.html", &tera::Context::new())
924    }
925
926    /// `menu(slug=…)` reads the menus the render installed.
927    #[test]
928    fn menu_returns_the_installed_menu_or_null() {
929        let item = ResolvedMenuItem {
930            id: Some(1),
931            label: "About".into(),
932            url: Some("/about".into()),
933            is_page: true,
934            page_id: Some(7),
935            open_in_new_tab: false,
936            is_active: false,
937            in_active_trail: false,
938            children: Vec::new(),
939        };
940        let menu = ResolvedMenu {
941            slug: "main".into(),
942            name: "Main".into(),
943            items: vec![item],
944        };
945        let _g = install(std::collections::HashMap::from([("main".to_owned(), menu)]));
946        let out = render(
947            r#"{% set nav = menu(slug="main") %}{{ nav.name }}:{% for i in nav.items %}{{ i.label }}={{ i.url }}{% endfor %}|{% set gone = menu(slug="nope") %}{% if gone %}x{% else %}none{% endif %}"#,
948        )
949        .unwrap();
950        assert_eq!(out, "Main:About=&#x2F;about|none", "autoescaped like any .html template");
951        assert!(render("{{ menu() }}").is_err(), "a missing slug is a template error");
952    }
953
954    #[test]
955    fn guard_clears_the_menus() {
956        drop(install(std::collections::HashMap::new()));
957        CURRENT_MENUS.with(|c| assert!(c.borrow().is_none()));
958    }
959
960    /// Page links move to the site's public path; external ones stay.
961    #[test]
962    fn rebase_rewrites_page_links_at_every_depth() {
963        let item = |label: &str, url: &str, is_page: bool, children| ResolvedMenuItem {
964            id: None,
965            label: label.into(),
966            url: Some(url.into()),
967            is_page,
968            page_id: None,
969            open_in_new_tab: false,
970            is_active: false,
971            in_active_trail: false,
972            children,
973        };
974        let mut items = vec![item(
975            "Shop",
976            "/shop",
977            true,
978            vec![item("Catalog", "/shop/catalog", true, vec![]), item("Docs", "https://x.test/shop/a", false, vec![])],
979        )];
980        rebase_page_urls(&mut items, "/shop");
981        assert_eq!(items[0].url.as_deref(), Some("/"));
982        assert_eq!(items[0].children[0].url.as_deref(), Some("/catalog"));
983        assert_eq!(items[0].children[1].url.as_deref(), Some("https://x.test/shop/a"));
984    }
985}