bazzar/crates/web/src/i18n.rs

75 lines
1.8 KiB
Rust

mod pl;
use std::collections::HashMap;
#[derive(Debug)]
pub struct I18n {
store: HashMap<String, HashMap<String, &'static str>>,
lang: String,
}
impl I18n {
pub fn load() -> Self {
let mut i18n = Self {
store: HashMap::with_capacity(1_000),
lang: "".into(),
};
pl::define(&mut i18n);
let languages: js_sys::Array = seed::window().navigator().languages();
languages.find(&mut |lang, _idx, _array| {
let l: wasm_bindgen::JsValue = lang;
if let Some(s) = l.as_string() {
if i18n.store.contains_key(&s) {
i18n.lang = s;
true
} else {
false
}
} else {
false
}
});
i18n
}
fn scope(&mut self, lang: &'static str) -> Scope {
Scope { store: self, lang }
}
pub fn t(&self, key: &'static str) -> &'static str {
self.store
.get(self.lang.as_str())
.and_then(|s| s.get(key))
.copied()
.unwrap_or(key)
}
pub fn l(&self, key: &String) -> String {
self.store
.get(self.lang.as_str())
.and_then(|s| s.get(key))
.copied()
.map(Into::into)
.unwrap_or_else(|| key.clone())
}
pub fn current_language(&self) -> &str {
self.lang.as_str()
}
}
pub struct Scope<'store, 'lang> {
lang: &'lang str,
store: &'store mut I18n,
}
impl<'store, 'lang> Scope<'store, 'lang> {
fn define(&mut self, key: &str, value: &'static str) -> &mut Self {
self.store
.store
.entry(self.lang.into())
.or_insert_with(|| HashMap::with_capacity(1_000))
.insert(key.into(), value);
self
}
}