use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use serde::Serialize;
use crate::locale::Locale;
use crate::locale_mode::LocaleMode;
#[derive(Debug, Clone, Serialize)]
pub struct SwitcherEntry {
pub code: String,
pub name: String,
pub url: String,
pub is_current: bool,
pub is_default: bool,
}
thread_local! {
static CURRENT_SWITCHER: RefCell<Option<Arc<Vec<SwitcherEntry>>>> = const { RefCell::new(None) };
static PENDING_SWITCHER: RefCell<Option<Vec<SwitcherEntry>>> = const { RefCell::new(None) };
}
pub struct SwitcherGuard {
_priv: (),
}
impl Drop for SwitcherGuard {
fn drop(&mut self) {
CURRENT_SWITCHER.with(|cell| {
*cell.borrow_mut() = None;
});
}
}
#[must_use]
pub fn install(entries: Vec<SwitcherEntry>) -> SwitcherGuard {
CURRENT_SWITCHER.with(|cell| {
*cell.borrow_mut() = Some(Arc::new(entries));
});
SwitcherGuard { _priv: () }
}
pub struct PendingGuard {
_priv: (),
}
impl Drop for PendingGuard {
fn drop(&mut self) {
PENDING_SWITCHER.with(|cell| {
*cell.borrow_mut() = None;
});
}
}
#[must_use]
pub fn stash_pending(entries: Vec<SwitcherEntry>) -> PendingGuard {
PENDING_SWITCHER.with(|cell| {
*cell.borrow_mut() = Some(entries);
});
PendingGuard { _priv: () }
}
#[must_use]
pub fn take_pending() -> Option<Vec<SwitcherEntry>> {
PENDING_SWITCHER.with(|cell| cell.borrow_mut().take())
}
pub fn register_tera_function(tera: &mut tera::Tera) {
tera.register_function("language_switcher", switcher_fn);
}
fn switcher_fn(_args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
let entries = CURRENT_SWITCHER.with(|cell| cell.borrow().clone());
match entries {
Some(list) => tera::to_value(&*list).map_err(tera::Error::json),
None => Ok(tera::Value::Array(Vec::new())),
}
}
pub fn register_hreflang_function(tera: &mut tera::Tera) {
tera.register_function("rcms_hreflang_tags", hreflang_fn);
}
fn hreflang_fn(args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
let origin = args
.get("origin")
.and_then(tera::Value::as_str)
.unwrap_or("")
.trim_end_matches('/');
let entries = CURRENT_SWITCHER.with(|cell| cell.borrow().clone());
let Some(entries) = entries else {
return Ok(tera::Value::String(String::new()));
};
if entries.len() < 2 {
return Ok(tera::Value::String(String::new()));
}
let href_for = |e: &SwitcherEntry| -> String {
let path = if e.is_default {
e.url.split('?').next().unwrap_or(e.url.as_str())
} else {
e.url.as_str()
};
format!("{origin}{path}")
};
let mut out = String::with_capacity(entries.len() * 96);
let mut x_default: Option<String> = None;
for e in entries.iter() {
let href = href_for(e);
out.push_str(&format!(
"<link rel=\"alternate\" hreflang=\"{}\" href=\"{}\"/>\n",
attr_escape(&e.code),
attr_escape(&href)
));
if e.is_default {
x_default = Some(href);
}
}
if let Some(href) = x_default {
out.push_str(&format!(
"<link rel=\"alternate\" hreflang=\"x-default\" href=\"{}\"/>\n",
attr_escape(&href)
));
}
Ok(tera::Value::String(out))
}
fn attr_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
#[must_use]
pub fn build(
locales: &[Locale],
url_prefix: &str,
url_path: &str,
mode: LocaleMode,
current_code: Option<&str>,
) -> Vec<SwitcherEntry> {
let default_code = locales
.iter()
.find(|l| l.is_default)
.map(|l| l.code.as_str());
let current = current_code.or(default_code);
locales
.iter()
.map(|l| {
let url = if l.is_default {
format!("{url_prefix}{url_path}?lang={}", l.code)
} else if mode.reads_path() {
format!("{url_prefix}/{}{url_path}", l.code)
} else {
format!("{url_prefix}{url_path}?lang={}", l.code)
};
SwitcherEntry {
code: l.code.clone(),
name: l.name.clone(),
url,
is_current: Some(l.code.as_str()) == current,
is_default: l.is_default,
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use rustango::sql::Auto;
fn loc(code: &str, name: &str, is_default: bool) -> Locale {
Locale {
id: Auto::Unset,
code: code.to_owned(),
name: name.to_owned(),
is_default,
active: true,
sort_order: 0,
created_at: Auto::Unset,
}
}
#[test]
fn query_mode_urls() {
let locales = [loc("en", "English", true), loc("es", "Español", false)];
let out = build(&locales, "", "/about", LocaleMode::Query, Some("es"));
assert_eq!(out[0].url, "/about?lang=en"); assert!(!out[0].is_current);
assert_eq!(out[1].url, "/about?lang=es");
assert!(out[1].is_current);
}
#[test]
fn path_mode_urls_and_prefix() {
let locales = [loc("en", "English", true), loc("fr", "Français", false)];
let out = build(&locales, "/p", "/blog", LocaleMode::Path, None);
assert_eq!(out[0].url, "/p/blog?lang=en");
assert!(out[0].is_current); assert_eq!(out[1].url, "/p/fr/blog");
assert!(!out[1].is_current);
}
#[test]
fn pathorquery_prefers_path_shape() {
let locales = [loc("en", "English", true), loc("de", "Deutsch", false)];
let out = build(&locales, "", "/x", LocaleMode::PathOrQuery, Some("de"));
assert_eq!(out[1].url, "/de/x");
}
}