Skip to main content

rustango_cms/
theme_resolve.rs

1//! Per-request theme resolution.
2//!
3//! Walks this chain for each public page request, returning the first
4//! hit (or `None` if nothing's configured):
5//!
6//! 1. `page.theme_id` — explicit theme on the rendered page itself.
7//! 2. Each ancestor's `theme_id`, climbing toward the root.
8//! 3. The `cms_theme` row with `is_default = true` (site default).
9//! 4. The `cms_theme` row with `is_admin_default = true` (last resort,
10//!    so the public site doesn't render naked when the operator only
11//!    set the admin theme).
12//!
13//! The walk uses the page's materialized `path` to fetch every
14//! ancestor in one indexed SELECT — no recursive query, no
15//! per-segment round-trip.
16
17use rustango::core::Column as _;
18use rustango::sql::{ExecError, FetcherPool as _, Pool};
19
20use crate::page::Page;
21use crate::theme::{BrandColor, Theme};
22
23/// What [`resolve_for_page`] returns: the matched theme + its brand
24/// colors, ready to feed into [`crate::theme::emit_css`].
25pub struct ResolvedTheme {
26    pub theme: Theme,
27    pub brand_colors: Vec<BrandColor>,
28}
29
30/// Walk the resolution chain and return the active theme for `page`.
31/// `None` means "no theme configured anywhere"; the caller should
32/// skip emitting the `<style>` block and let the public template
33/// fall back to its own defaults.
34pub async fn resolve_for_page(
35    pool: &Pool,
36    page: &Page,
37) -> Result<Option<ResolvedTheme>, ExecError> {
38    // 1. The page itself.
39    if let Some(tid) = page.theme_id {
40        if let Some(rt) = load_by_id(pool, tid).await? {
41            return Ok(Some(rt));
42        }
43    }
44    // 2. Ancestors. Materialized-path lookup → one indexed SELECT.
45    // tree::MaterializedPath stores `0001/0005/0007/` shape — split
46    // on `/`, drop the trailing empty, drop the self segment, then
47    // rebuild each prefix into the canonical "with trailing slash"
48    // form so the `IN (…)` query lands on the index.
49    if !page.path.is_empty() {
50        let segs: Vec<&str> = page.path.split('/').filter(|s| !s.is_empty()).collect();
51        // Drop the self segment (last one).
52        let ancestor_segs = if segs.len() > 1 {
53            &segs[..segs.len() - 1]
54        } else {
55            &[][..]
56        };
57        if !ancestor_segs.is_empty() {
58            let mut prefixes: Vec<String> = Vec::with_capacity(ancestor_segs.len());
59            let mut accum = String::new();
60            for seg in ancestor_segs {
61                accum.push_str(seg);
62                accum.push('/');
63                prefixes.push(accum.clone());
64            }
65            let mut ancestors: Vec<Page> = Page::objects()
66                .where_(Page::path.is_in(prefixes))
67                .fetch(pool)
68                .await
69                .unwrap_or_default();
70            // Closest first (deepest).
71            ancestors.sort_by_key(|p| std::cmp::Reverse(p.depth));
72            for a in ancestors {
73                if let Some(tid) = a.theme_id {
74                    if let Some(rt) = load_by_id(pool, tid).await? {
75                        return Ok(Some(rt));
76                    }
77                }
78            }
79        }
80    }
81    // 3. Site default.
82    if let Some(rt) = load_by_flag(pool, "is_default").await? {
83        return Ok(Some(rt));
84    }
85    // 4. Admin default (last resort).
86    if let Some(rt) = load_by_flag(pool, "is_admin_default").await? {
87        return Ok(Some(rt));
88    }
89    Ok(None)
90}
91
92async fn load_by_id(pool: &Pool, theme_id: i64) -> Result<Option<ResolvedTheme>, ExecError> {
93    let theme = Theme::objects()
94        .where_(Theme::id.eq(theme_id))
95        .first(pool)
96        .await?;
97    let Some(theme) = theme else { return Ok(None) };
98    let brand_colors = BrandColor::objects()
99        .where_(BrandColor::theme_id.eq(theme_id))
100        .order_by(&[("sort_order", false)])
101        .fetch(pool)
102        .await?;
103    Ok(Some(ResolvedTheme {
104        theme,
105        brand_colors,
106    }))
107}
108
109async fn load_by_flag(pool: &Pool, flag: &str) -> Result<Option<ResolvedTheme>, ExecError> {
110    let theme = if flag == "is_admin_default" {
111        Theme::objects()
112            .where_(Theme::is_admin_default.eq(true))
113            .fetch(pool)
114            .await?
115    } else {
116        Theme::objects()
117            .where_(Theme::is_default.eq(true))
118            .fetch(pool)
119            .await?
120    };
121    let Some(theme) = theme.into_iter().next() else {
122        return Ok(None);
123    };
124    let theme_id = theme.id.get().copied().unwrap_or_default();
125    let brand_colors = BrandColor::objects()
126        .where_(BrandColor::theme_id.eq(theme_id))
127        .order_by(&[("sort_order", false)])
128        .fetch(pool)
129        .await?;
130    Ok(Some(ResolvedTheme {
131        theme,
132        brand_colors,
133    }))
134}