Skip to main content

rustango_cms/
breadcrumbs.rs

1//! Breadcrumb engine — walks the page tree once and returns an
2//! ordered list of `(title, url, is_current)` crumbs.
3//!
4//! Powers both public templates (via [`to_context_value`]) and
5//! the admin chrome (admin handlers can call [`resolve_breadcrumbs`]
6//! directly and stuff the result into Tera context). The shared
7//! `_breadcrumbs.html` macro in [`crate::admin::register_templates`]
8//! renders the standard `<nav aria-label="Breadcrumb">` shape plus a
9//! parallel JSON-LD `BreadcrumbList` block for SEO.
10//!
11//! ## Public-side example
12//!
13//! ```text
14//! {# In a Tera template: #}
15//! {% set crumbs = breadcrumbs(page_id=page.id) %}
16//! {% import "_breadcrumbs.html" as bc %}
17//! {{ bc::render(crumbs=crumbs) | safe }}
18//! ```
19//!
20//! ## Options
21//!
22//! - `include_root` — keep the tenant root crumb (defaults `true`).
23//! - `include_current` — keep the leaf crumb (defaults `true`;
24//!   public templates usually want this off when the breadcrumb sits
25//!   right above the page's `<h1>`).
26//! - `max_depth` — cap the walk to N ancestors; oversized trees
27//!   degrade gracefully.
28
29use rustango::core::Column as _;
30
31use crate::page::Page;
32
33/// One link in the breadcrumb trail.
34#[derive(Debug, Clone, serde::Serialize)]
35pub struct Crumb {
36    pub title: String,
37    /// Tenant-absolute, like `url_path`. On a hostname-mapped site, pass it
38    /// through [`crate::site::to_public_path`] with the site's prefix.
39    pub url: String,
40    pub is_current: bool,
41    pub page_id: Option<i64>,
42}
43
44/// Options controlling [`resolve_breadcrumbs`].
45#[derive(Debug, Clone, Copy)]
46pub struct BreadcrumbsOptions {
47    /// Keep the root-most ancestor in the trail. Defaults `true`.
48    pub include_root: bool,
49    /// Keep the leaf (the page passed to `resolve_breadcrumbs`).
50    /// Defaults `true`; flip off when the breadcrumb is rendered
51    /// next to the page's `<h1>` to avoid duplication.
52    pub include_current: bool,
53    /// Hard cap on ancestor walks. Defaults 32 — guards against
54    /// pathological tree depths.
55    pub max_depth: usize,
56}
57
58impl Default for BreadcrumbsOptions {
59    fn default() -> Self {
60        Self {
61            include_root: true,
62            include_current: true,
63            max_depth: 32,
64        }
65    }
66}
67
68/// Walk the page's ancestor chain and return an ordered crumb list
69/// from root to leaf.
70///
71/// # Errors
72/// Propagates driver / query failures from the page lookups.
73pub async fn resolve_breadcrumbs(
74    pool: &rustango::sql::Pool,
75    page_id: i64,
76    options: BreadcrumbsOptions,
77) -> Result<Vec<Crumb>, rustango::sql::ExecError> {
78    let target = Page::objects()
79        .where_(Page::id.eq(page_id))
80        .first(pool)
81        .await?;
82    let Some(leaf) = target else {
83        return Ok(Vec::new());
84    };
85
86    // Every ancestor in one query from the materialized path (#747) — the
87    // walk it replaces cost one round trip per level. Root first; keep the
88    // `max_depth` nearest the leaf.
89    let paths = crate::tree::MaterializedPath::ancestors_of(&leaf.path);
90    let mut chain: Vec<Page> = if paths.is_empty() {
91        Vec::new()
92    } else {
93        use rustango::sql::FetcherPool as _;
94        Page::objects()
95            .where_(Page::path.is_in(paths))
96            .order_by(&[("path", false)])
97            .fetch(pool)
98            .await?
99    };
100    // Byte order, not the collation's: a path's prefixes sort first then.
101    chain.sort_by(|a, b| a.path.cmp(&b.path));
102    let excess = chain.len().saturating_sub(options.max_depth);
103    chain.drain(..excess);
104    chain.push(leaf);
105
106    if !options.include_root && !chain.is_empty() {
107        chain.remove(0);
108    }
109    if !options.include_current && !chain.is_empty() {
110        chain.pop();
111    }
112
113    let last_index = chain.len().saturating_sub(1);
114    Ok(chain
115        .into_iter()
116        .enumerate()
117        .map(|(i, page)| Crumb {
118            title: page.title.clone(),
119            url: if page.url_path.is_empty() {
120                "/".to_owned()
121            } else {
122                page.url_path.clone()
123            },
124            is_current: i == last_index,
125            page_id: page.id.get().copied(),
126        })
127        .collect())
128}
129
130/// Convenience: render the breadcrumb crumb list as a JSON value
131/// suitable for stuffing into a Tera context. Use this in admin or
132/// public-render handlers right before calling `tera.render(...)`:
133///
134/// ```ignore
135/// let crumbs = breadcrumbs::resolve_breadcrumbs(pool, page_id, opts).await?;
136/// ctx.insert("breadcrumbs", &breadcrumbs::to_context_value(&crumbs));
137/// ```
138///
139/// Tera's sync function signature can't host the async DB walk
140/// directly without a tokio runtime handle, so we keep the API on
141/// the handler side — every chrome'd handler already has the pool
142/// in scope, so pre-fetching is free.
143#[must_use]
144pub fn to_context_value(crumbs: &[Crumb]) -> serde_json::Value {
145    serde_json::to_value(crumbs).unwrap_or(serde_json::Value::Array(Vec::new()))
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn options_defaults() {
154        let o = BreadcrumbsOptions::default();
155        assert!(o.include_root);
156        assert!(o.include_current);
157        assert_eq!(o.max_depth, 32);
158    }
159}