add I18nExt trait

This commit is contained in:
llama 2025-10-24 19:27:35 +08:00
parent fcc0ee3cb7
commit 316e176d64
No known key found for this signature in database
GPG key ID: 0B7543854B9413C3

View file

@ -8,24 +8,30 @@ use anyhow::Result;
use phf::phf_map; use phf::phf_map;
use phf::phf_ordered_map; use phf::phf_ordered_map;
use phf::phf_set; use phf::phf_set;
use tauri::AppHandle;
use tauri::Manager; use tauri::Manager;
use tauri::Runtime; use tauri::Runtime;
pub type I18n = anki_i18n::I18n<anki_i18n::Launcher>; pub type I18n = anki_i18n::I18n<anki_i18n::Launcher>;
pub type Tr = RwLock<Option<I18n>>; pub type Tr = RwLock<Option<I18n>>;
pub fn setup_i18n<R: Runtime>(app: &AppHandle<R>, locales: &[&str]) { pub trait I18nExt<R: Runtime> {
*app.state::<Tr>().write().expect("tr lock was poisoned!") = Some(I18n::new(locales)); fn setup_tr(&self, locales: &[&str]);
fn tr(&self) -> Result<I18n>;
} }
pub fn get_tr<R: Runtime>(app: &AppHandle<R>) -> Result<I18n> { impl<R: Runtime, T: Manager<R>> I18nExt<R> for T {
let tr_state = app.state::<Tr>(); fn setup_tr(&self, locales: &[&str]) {
*self.state::<Tr>().write().expect("tr lock was poisoned!") = Some(I18n::new(locales));
}
fn tr(&self) -> Result<I18n> {
let tr_state = self.state::<Tr>();
let guard = tr_state.read().expect("tr lock was poisoned!"); let guard = tr_state.read().expect("tr lock was poisoned!");
guard guard
.clone() .clone()
.ok_or_else(|| anyhow!("tr was not initialised!")) .ok_or_else(|| anyhow!("tr was not initialised!"))
} }
}
pub const LANGS: phf::OrderedMap<&'static str, &'static str> = phf_ordered_map! { pub const LANGS: phf::OrderedMap<&'static str, &'static str> = phf_ordered_map! {
// "af-ZA" => "Afrikaans", // "af-ZA" => "Afrikaans",