2022-05-12 16:05:58 +02:00
|
|
|
mod pl;
|
|
|
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
2022-05-15 13:08:42 +02:00
|
|
|
#[derive(Debug)]
|
2022-05-12 16:05:58 +02:00
|
|
|
pub struct I18n {
|
|
|
|
store: HashMap<String, HashMap<String, &'static str>>,
|
|
|
|
lang: String,
|
|
|
|
}
|
2022-05-10 08:23:35 +02:00
|
|
|
|
|
|
|
impl I18n {
|
|
|
|
pub fn load() -> Self {
|
2022-05-12 16:05:58 +02:00
|
|
|
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 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
|
2022-05-10 08:23:35 +02:00
|
|
|
}
|
|
|
|
}
|