use std::collections::HashMap;
pub type TranslationMap = HashMap<String, String>;
#[must_use]
pub fn translate(key: &str, translations: &TranslationMap) -> Option<String> {
translations.get(key).cloned()
}
pub fn translate_with_fallback(
key: &str,
translations: &TranslationMap,
fallback_translations: &TranslationMap,
) -> String {
if let Some(translation) = translations.get(key) {
return translation.clone();
}
if let Some(translation) = fallback_translations.get(key) {
tracing::debug!(
"Translation key '{}' not found in primary locale, using fallback",
key
);
return translation.clone();
}
tracing::debug!(
"Missing translation key: '{}'. Returning key as-is. Please add this key to locale files.",
key
);
key.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_translate() {
let mut translations = HashMap::new();
translations.insert("app.titles.search".to_string(), "Suche".to_string());
assert_eq!(
translate("app.titles.search", &translations),
Some("Suche".to_string())
);
assert_eq!(translate("app.titles.help", &translations), None);
}
#[test]
fn test_translate_with_fallback() {
let mut primary = HashMap::new();
primary.insert("app.titles.search".to_string(), "Suche".to_string());
let mut fallback = HashMap::new();
fallback.insert("app.titles.search".to_string(), "Search".to_string());
fallback.insert("app.titles.help".to_string(), "Help".to_string());
assert_eq!(
translate_with_fallback("app.titles.search", &primary, &fallback),
"Suche"
);
assert_eq!(
translate_with_fallback("app.titles.help", &primary, &fallback),
"Help"
);
assert_eq!(
translate_with_fallback("app.titles.missing", &primary, &fallback),
"app.titles.missing"
);
}
}