Skip to main content

rustango_cms/
language_switcher.rs

1//! Public language-switcher data for templates.
2//!
3//! The admin has a locale picker, but visitors had no built-in way to
4//! switch language. This exposes a `language_switcher()` Tera function
5//! returning the active locales — each with the URL to view the
6//! *current* page in that locale, built per the configured
7//! [`crate::locale_mode::LocaleMode`]:
8//!
9//! ```html
10//! <nav aria-label="Language">
11//!   {% for loc in language_switcher() %}
12//!     <a href="{{ loc.url }}"{% if loc.is_current %} aria-current="page"{% endif %}>
13//!       {{ loc.name }}</a>
14//!   {% endfor %}
15//! </nav>
16//! ```
17//!
18//! Like [`crate::page_url`], the per-request data is stashed in a
19//! thread-local installed by the public render handler (it owns the
20//! pool + the resolved locale + the mount prefix) and cleared by the
21//! returned guard when `tera.render` finishes.
22
23use std::cell::RefCell;
24use std::collections::HashMap;
25use std::sync::Arc;
26
27use serde::Serialize;
28
29use crate::locale::Locale;
30use crate::locale_mode::LocaleMode;
31
32/// One entry in the switcher: a locale + the URL to the current page in
33/// it, and whether it's the locale the request resolved to.
34#[derive(Debug, Clone, Serialize)]
35pub struct SwitcherEntry {
36    pub code: String,
37    pub name: String,
38    pub url: String,
39    pub is_current: bool,
40    /// This locale is the tenant default (its switcher URL carries a
41    /// `?lang=` cookie-reset query; hreflang uses the clean path instead).
42    pub is_default: bool,
43}
44
45thread_local! {
46    static CURRENT_SWITCHER: RefCell<Option<Arc<Vec<SwitcherEntry>>>> = const { RefCell::new(None) };
47    /// Entries handed off by the router *before* the render future is
48    /// polled. Read synchronously at the top of `render::render_inner`
49    /// (same thread as the caller, before its first `.await`) into a
50    /// local, then re-`install`ed inside render's await-free block so
51    /// the thread-local is set on the *same* thread that runs
52    /// `tera.render` — surviving tokio's thread-hops. See the
53    /// [`stash_pending`] / [`take_pending`] pair.
54    static PENDING_SWITCHER: RefCell<Option<Vec<SwitcherEntry>>> = const { RefCell::new(None) };
55}
56
57/// RAII guard — clears the thread-local on drop. Returned by [`install`].
58pub struct SwitcherGuard {
59    _priv: (),
60}
61
62impl Drop for SwitcherGuard {
63    fn drop(&mut self) {
64        CURRENT_SWITCHER.with(|cell| {
65            *cell.borrow_mut() = None;
66        });
67    }
68}
69
70/// Install the switcher entries for the duration of the returned guard.
71#[must_use]
72pub fn install(entries: Vec<SwitcherEntry>) -> SwitcherGuard {
73    CURRENT_SWITCHER.with(|cell| {
74        *cell.borrow_mut() = Some(Arc::new(entries));
75    });
76    SwitcherGuard { _priv: () }
77}
78
79/// RAII guard clearing `PENDING_SWITCHER` on drop — the router holds
80/// it across the render future so a stashed hand-off never leaks onto a
81/// pooled worker thread if the render short-circuits before consuming it.
82pub struct PendingGuard {
83    _priv: (),
84}
85
86impl Drop for PendingGuard {
87    fn drop(&mut self) {
88        PENDING_SWITCHER.with(|cell| {
89            *cell.borrow_mut() = None;
90        });
91    }
92}
93
94/// Stash entries for the *upcoming* render on this thread and return a
95/// guard that clears them on drop. Called by the public render handler
96/// immediately before it polls the render future (no `.await` in
97/// between), so the future's first synchronous slice — the top of
98/// [`crate::render`](mod@crate::render)'s `render_inner`, which calls [`take_pending`] —
99/// runs on this same thread and sees them.
100#[must_use]
101pub fn stash_pending(entries: Vec<SwitcherEntry>) -> PendingGuard {
102    PENDING_SWITCHER.with(|cell| {
103        *cell.borrow_mut() = Some(entries);
104    });
105    PendingGuard { _priv: () }
106}
107
108/// Take (and clear) any entries [`stash_pending`]'d for this render.
109/// Called at the very top of `render_inner`, before its first `.await`,
110/// so the returned `Vec` becomes a plain local that travels with the
111/// future across tokio thread-hops and can be [`install`]ed in render's
112/// await-free block right before `tera.render`.
113#[must_use]
114pub fn take_pending() -> Option<Vec<SwitcherEntry>> {
115    PENDING_SWITCHER.with(|cell| cell.borrow_mut().take())
116}
117
118/// Register the `language_switcher()` Tera function.
119pub fn register_tera_function(tera: &mut tera::Tera) {
120    tera.register_function("language_switcher", switcher_fn);
121}
122
123fn switcher_fn(_args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
124    let entries = CURRENT_SWITCHER.with(|cell| cell.borrow().clone());
125    match entries {
126        Some(list) => tera::to_value(&*list).map_err(tera::Error::json),
127        None => Ok(tera::Value::Array(Vec::new())),
128    }
129}
130
131/// Register the `rcms_hreflang_tags(origin=…)` Tera function.
132pub fn register_hreflang_function(tera: &mut tera::Tera) {
133    tera.register_function("rcms_hreflang_tags", hreflang_fn);
134}
135
136/// `rcms_hreflang_tags(origin="https://site.tld")` → the `<head>`
137/// `<link rel="alternate" hreflang=…>` cluster for the current page across
138/// every active locale, plus `x-default` → the default locale. Emitted so
139/// SEO crawlers / audit tools that read the rendered page head (not just
140/// the sitemap) discover + bidirectionally link the language versions.
141///
142/// Uses the same per-request switcher entries the render handler installs
143/// (built per the configured [`crate::locale_mode::LocaleMode`]); the
144/// default-locale entry's `?lang=` cookie-reset query is stripped so the
145/// hreflang URL matches the clean canonical. Returns an empty string when
146/// fewer than two locales are active (single-language site → no hreflang).
147/// `href`s are absolute when `origin` is a non-empty absolute URL.
148fn hreflang_fn(args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
149    let origin = args
150        .get("origin")
151        .and_then(tera::Value::as_str)
152        .unwrap_or("")
153        .trim_end_matches('/');
154    let entries = CURRENT_SWITCHER.with(|cell| cell.borrow().clone());
155    let Some(entries) = entries else {
156        return Ok(tera::Value::String(String::new()));
157    };
158    if entries.len() < 2 {
159        return Ok(tera::Value::String(String::new()));
160    }
161    let href_for = |e: &SwitcherEntry| -> String {
162        let path = if e.is_default {
163            e.url.split('?').next().unwrap_or(e.url.as_str())
164        } else {
165            e.url.as_str()
166        };
167        format!("{origin}{path}")
168    };
169    let mut out = String::with_capacity(entries.len() * 96);
170    let mut x_default: Option<String> = None;
171    for e in entries.iter() {
172        let href = href_for(e);
173        out.push_str(&format!(
174            "<link rel=\"alternate\" hreflang=\"{}\" href=\"{}\"/>\n",
175            attr_escape(&e.code),
176            attr_escape(&href)
177        ));
178        if e.is_default {
179            x_default = Some(href);
180        }
181    }
182    if let Some(href) = x_default {
183        out.push_str(&format!(
184            "<link rel=\"alternate\" hreflang=\"x-default\" href=\"{}\"/>\n",
185            attr_escape(&href)
186        ));
187    }
188    Ok(tera::Value::String(out))
189}
190
191/// Minimal HTML-attribute escape (output is consumed via `| safe`).
192fn attr_escape(s: &str) -> String {
193    s.replace('&', "&amp;")
194        .replace('<', "&lt;")
195        .replace('>', "&gt;")
196        .replace('"', "&quot;")
197}
198
199/// Build switcher entries for `url_path` across the given active
200/// `locales`. The URL shape follows `mode`:
201/// - default locale → `{url_prefix}{url_path}?lang={code}` (explicit so a
202///   click resets the persistence cookie — see `locale_mode::LOCALE_COOKIE`),
203/// - path modes → `{url_prefix}/{code}{url_path}`,
204/// - query mode → `{url_prefix}{url_path}?lang={code}`.
205///
206/// `current_code` is the locale the request resolved to (`None` = the
207/// default); the matching entry is flagged `is_current`.
208#[must_use]
209pub fn build(
210    locales: &[Locale],
211    url_prefix: &str,
212    url_path: &str,
213    mode: LocaleMode,
214    current_code: Option<&str>,
215) -> Vec<SwitcherEntry> {
216    let default_code = locales
217        .iter()
218        .find(|l| l.is_default)
219        .map(|l| l.code.as_str());
220    let current = current_code.or(default_code);
221    locales
222        .iter()
223        .map(|l| {
224            // The default-locale link carries an explicit `?lang=` so
225            // clicking it overrides a stale `rcms_locale` cookie and
226            // returns the visitor to the default language. Non-default
227            // path-mode links use the `/<code>/` prefix (also explicit).
228            let url = if l.is_default {
229                format!("{url_prefix}{url_path}?lang={}", l.code)
230            } else if mode.reads_path() {
231                format!("{url_prefix}/{}{url_path}", l.code)
232            } else {
233                format!("{url_prefix}{url_path}?lang={}", l.code)
234            };
235            SwitcherEntry {
236                code: l.code.clone(),
237                name: l.name.clone(),
238                url,
239                is_current: Some(l.code.as_str()) == current,
240                is_default: l.is_default,
241            }
242        })
243        .collect()
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use rustango::sql::Auto;
250
251    fn loc(code: &str, name: &str, is_default: bool) -> Locale {
252        Locale {
253            id: Auto::Unset,
254            code: code.to_owned(),
255            name: name.to_owned(),
256            is_default,
257            active: true,
258            sort_order: 0,
259            created_at: Auto::Unset,
260        }
261    }
262
263    #[test]
264    fn query_mode_urls() {
265        let locales = [loc("en", "English", true), loc("es", "Español", false)];
266        let out = build(&locales, "", "/about", LocaleMode::Query, Some("es"));
267        assert_eq!(out[0].url, "/about?lang=en"); // default — explicit (cookie reset)
268        assert!(!out[0].is_current);
269        assert_eq!(out[1].url, "/about?lang=es");
270        assert!(out[1].is_current);
271    }
272
273    #[test]
274    fn path_mode_urls_and_prefix() {
275        let locales = [loc("en", "English", true), loc("fr", "Français", false)];
276        let out = build(&locales, "/p", "/blog", LocaleMode::Path, None);
277        assert_eq!(out[0].url, "/p/blog?lang=en");
278        assert!(out[0].is_current); // None → default is current
279        assert_eq!(out[1].url, "/p/fr/blog");
280        assert!(!out[1].is_current);
281    }
282
283    #[test]
284    fn pathorquery_prefers_path_shape() {
285        let locales = [loc("en", "English", true), loc("de", "Deutsch", false)];
286        let out = build(&locales, "", "/x", LocaleMode::PathOrQuery, Some("de"));
287        assert_eq!(out[1].url, "/de/x");
288    }
289}