Skip to main content

rustango_cms/
locale.rs

1//! `Locale` — per-tenant locale registry.
2//!
3//! Drives the language picker on every page edit form and the
4//! locale FK on `cms_translation`.
5//! Exactly one row carries `is_default = true`; the admin form
6//! enforces that invariant when toggling.
7
8use chrono::{DateTime, Utc};
9use rustango::sql::Auto;
10use rustango::Model;
11use serde::{Deserialize, Serialize};
12
13/// One row per active locale on the tenant. `code` follows
14/// BCP-47 (e.g. `en`, `fr-CA`, `pt-BR`).
15#[derive(Model, Debug, Clone, Serialize, Deserialize)]
16#[rustango(
17    table = "cms_locale",
18    app = "cms",
19    display = "name",
20    admin(
21        list_display = "code, name, is_default, active, sort_order",
22        ordering = "sort_order, code",
23        list_filter = "is_default, active",
24    )
25)]
26pub struct Locale {
27    #[rustango(primary_key)]
28    pub id: Auto<i64>,
29
30    /// BCP-47 tag — `en`, `fr-CA`, `pt-BR`, …
31    #[rustango(max_length = 16, index)]
32    pub code: String,
33
34    /// Display name shown in the admin picker (e.g. `English`,
35    /// `Français (Canada)`).
36    #[rustango(max_length = 64)]
37    pub name: String,
38
39    /// Exactly one row should carry `is_default = true` per tenant —
40    /// the admin form enforces this on save.
41    pub is_default: bool,
42
43    /// Active locales appear in the public-side picker and in the
44    /// page-form sidebar. Setting `active = false` keeps existing
45    /// translations addressable via direct URL but removes the
46    /// locale from authoring surfaces.
47    pub active: bool,
48
49    /// Sort order in the admin picker (low first). Defaults set the
50    /// default locale to 0 and other rows to 100+ when seeded.
51    pub sort_order: i32,
52
53    #[rustango(auto_now_add)]
54    pub created_at: Auto<DateTime<Utc>>,
55}
56
57/// Validate + normalize a BCP-47-ish locale `code` for the `cms_locale`
58/// registry. Content locales may be any well-formed tag — core provides
59/// metadata + graceful fallback via [`rustango::i18n::locale_info`] — but
60/// the tag must be structurally sane so it matches `Accept-Language`, keys
61/// translations predictably, and fits the 16-char column. Normalizes
62/// `_`→`-`, language→lowercase, script→`Titlecase`, region→`UPPERCASE`.
63/// Returns the normalized code, or a human-readable error message.
64///
65/// Mirrors [`rustango_cms::translation::validate_field_path`](crate::translation::validate_field_path).
66/// Pure; unit-tested.
67///
68/// # Errors
69/// When the code is empty, over 16 chars, has an empty segment, or a
70/// segment isn't a valid BCP-47 subtag.
71pub fn validate_code(raw: &str) -> Result<String, String> {
72    let s = raw.trim().replace('_', "-");
73    if s.is_empty() {
74        return Err("Locale code is required.".to_owned());
75    }
76    if s.chars().count() > 16 {
77        return Err("Locale code is too long (max 16 characters).".to_owned());
78    }
79    let mut out: Vec<String> = Vec::new();
80    for (i, sub) in s.split('-').enumerate() {
81        if sub.is_empty() {
82            return Err("Locale code has an empty segment (check the hyphens).".to_owned());
83        }
84        if i == 0 {
85            // Language: 2–3 ASCII letters (`en`, `zh`, `ckb`).
86            if (2..=3).contains(&sub.len()) && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
87                out.push(sub.to_ascii_lowercase());
88            } else {
89                return Err(format!(
90                    "`{sub}` is not a valid language subtag (2–3 letters, e.g. `en`, `zh`)."
91                ));
92            }
93        } else if sub.len() == 4 && sub.bytes().all(|b| b.is_ascii_alphabetic()) {
94            // Script: 4 letters, Titlecase (`Hans`, `Cyrl`).
95            let mut chars = sub.chars();
96            let first = chars.next().unwrap_or_default().to_ascii_uppercase();
97            out.push(format!("{first}{}", chars.as_str().to_ascii_lowercase()));
98        } else if (sub.len() == 2 && sub.bytes().all(|b| b.is_ascii_alphabetic()))
99            || (sub.len() == 3 && sub.bytes().all(|b| b.is_ascii_digit()))
100        {
101            // Region: 2 letters (`US`) or 3 digits (`419`), UPPERCASE.
102            out.push(sub.to_ascii_uppercase());
103        } else if sub.len() <= 8 && sub.bytes().all(|b| b.is_ascii_alphanumeric()) {
104            // Variant: up to 8 alphanumerics, lowercase.
105            out.push(sub.to_ascii_lowercase());
106        } else {
107            return Err(format!("`{sub}` is not a valid locale subtag."));
108        }
109    }
110    Ok(out.join("-"))
111}
112
113#[cfg(test)]
114mod tests {
115    use super::validate_code;
116
117    #[test]
118    fn accepts_and_normalizes_well_formed_tags() {
119        assert_eq!(validate_code("en").unwrap(), "en");
120        assert_eq!(validate_code(" fr-CA ").unwrap(), "fr-CA");
121        assert_eq!(validate_code("zh-Hans").unwrap(), "zh-Hans");
122        assert_eq!(validate_code("pt-BR").unwrap(), "pt-BR");
123        assert_eq!(validate_code("ckb").unwrap(), "ckb");
124        // Case + underscore normalization.
125        assert_eq!(validate_code("EN_us").unwrap(), "en-US");
126        assert_eq!(validate_code("ZH-hans").unwrap(), "zh-Hans");
127        assert_eq!(validate_code("es-419").unwrap(), "es-419");
128    }
129
130    #[test]
131    fn rejects_malformed_tags() {
132        assert!(validate_code("").is_err());
133        assert!(validate_code("   ").is_err());
134        assert!(validate_code("has space").is_err());
135        assert!(validate_code("123").is_err()); // language must be letters
136        assert!(validate_code("e").is_err()); // too short
137        assert!(validate_code("en-").is_err()); // empty segment
138        assert!(validate_code("en--US").is_err());
139        assert!(validate_code(&"a".repeat(17)).is_err()); // over the 16-char column
140    }
141}