mod pl; use std::collections::HashMap; pub struct I18n { store: HashMap>, 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 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 } }