From 7c176ddafe80214b80bc859728c5e16a3ec8d4df Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sat, 21 Oct 2023 20:01:44 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20new=20translation=20handling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pagetop/src/locale.rs | 76 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/pagetop/src/locale.rs b/pagetop/src/locale.rs index f06b37fe..75ae5109 100644 --- a/pagetop/src/locale.rs +++ b/pagetop/src/locale.rs @@ -86,11 +86,9 @@ //! //! static_locales!(LOCALES_SAMPLE in "path/to/locale"); //! ``` -//! -//! Usa el componente [L10n](crate::core::component::L10n) para incluir textos y contenidos -//! opcionalmente traducibles segĂșn el contexto de renderizado. -use crate::{config, kv, trace, LazyStatic}; +use crate::html::{Markup, PreEscaped}; +use crate::{config, kv, trace, LazyStatic, LOCALES_PAGETOP}; pub use fluent_templates; @@ -161,3 +159,73 @@ macro_rules! static_locales { } }; } + +#[derive(Default)] +enum L10nOp { + #[default] + None, + Text(String), + Translate(String), +} + +#[derive(Default)] +pub struct L10n { + op: L10nOp, + locales: Option<&'static Locales>, + args: HashMap, +} + +impl L10n { + pub fn n(text: impl Into) -> Self { + L10n { + op: L10nOp::Text(text.into()), + ..Default::default() + } + } + + pub fn l(key: impl Into) -> Self { + L10n { + op: L10nOp::Translate(key.into()), + locales: Some(&LOCALES_PAGETOP), + ..Default::default() + } + } + + pub fn t(key: impl Into, locales: &'static Locales) -> Self { + L10n { + op: L10nOp::Translate(key.into()), + locales: Some(locales), + ..Default::default() + } + } + + pub fn with_arg(mut self, arg: impl Into, value: impl Into) -> Self { + self.args.insert(arg.into(), value.into()); + self + } + + pub fn using(&self, langid: &LanguageIdentifier) -> Option { + match &self.op { + L10nOp::None => None, + L10nOp::Text(text) => Some(text.to_owned()), + L10nOp::Translate(key) => match self.locales { + Some(locales) => locales.lookup_with_args( + langid, + key, + &self + .args + .iter() + .fold(HashMap::new(), |mut args, (key, value)| { + args.insert(key.to_string(), value.to_owned().into()); + args + }), + ), + None => None, + }, + } + } + + pub fn escaped(&self, langid: &LanguageIdentifier) -> Markup { + PreEscaped(self.using(langid).unwrap_or_default()) + } +}