const SUPPORTED_LOCALES: &[&str] = &["en", "zh-CN", "de", "ja", "ko", "hi", "es"];
fn normalize_locale(raw: &str) -> &'static str {
let lower = raw.to_lowercase();
for &loc in SUPPORTED_LOCALES {
if lower == loc.to_lowercase() {
return loc;
}
}
let normalized = lower.replace('_', "-").replace(".utf-8", "");
for &loc in SUPPORTED_LOCALES {
if normalized.starts_with(&loc.to_lowercase()) {
return loc;
}
}
let lang = normalized.split('-').next().unwrap_or("");
match lang {
"zh" => "zh-CN",
"de" => "de",
"ja" => "ja",
"ko" => "ko",
"hi" => "hi",
"es" => "es",
_ => "en",
}
}
pub fn init_locale(lang_override: Option<&str>) {
let locale = match lang_override {
Some(lang) => normalize_locale(lang),
None => {
let sys = sys_locale::get_locale().unwrap_or_else(|| "en".to_string());
normalize_locale(&sys)
}
};
rust_i18n::set_locale(locale);
}
pub fn t(key: &str, params: &[(&str, &str)]) -> String {
let mut msg = rust_i18n::t!(key).to_string();
for &(name, value) in params {
msg = msg.replace(&format!("%{{{}}}", name), value);
}
msg
}
pub fn t_en(key: &str, params: &[(&str, &str)]) -> String {
let mut msg = rust_i18n::t!(key, locale = "en").to_string();
for &(name, value) in params {
msg = msg.replace(&format!("%{{{}}}", name), value);
}
msg
}