Compare commits
No commits in common. "b3a7d409301be54c64d572450c9bbe14f69336cb" and "3170f9a4d0a51d38ee48039099bbbe4ed78d45bc" have entirely different histories.
b3a7d40930
...
3170f9a4d0
3 changed files with 40 additions and 140 deletions
|
|
@ -1,5 +1,15 @@
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
|
||||||
|
// Enlace a la página oficial de PageTop.
|
||||||
|
const PAGETOP_LINK: &str = concat!(
|
||||||
|
"<a ",
|
||||||
|
"href=\"https://pagetop.cillero.es\" ",
|
||||||
|
"target=\"_blank\" ",
|
||||||
|
"rel=\"noopener noreferrer\">",
|
||||||
|
"PageTop",
|
||||||
|
"</a>",
|
||||||
|
);
|
||||||
|
|
||||||
/// Componente que muestra el típico mensaje *Powered by* (*Funciona con*) en el pie de página.
|
/// Componente que muestra el típico mensaje *Powered by* (*Funciona con*) en el pie de página.
|
||||||
///
|
///
|
||||||
/// Por defecto, usando [`default()`](Self::default) sólo se muestra un reconocimiento a PageTop.
|
/// Por defecto, usando [`default()`](Self::default) sólo se muestra un reconocimiento a PageTop.
|
||||||
|
|
@ -24,18 +34,13 @@ impl Component for PoweredBy {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let pagetop_link = html! {
|
|
||||||
a href="https://pagetop.cillero.es" target="_blank" rel="noopener noreferrer" {
|
|
||||||
"PageTop"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(html! {
|
Ok(html! {
|
||||||
div id=[self.id()] class="poweredby" {
|
div id=[self.id()] class="poweredby" {
|
||||||
@if let Some(c) = self.copyright() {
|
@if let Some(c) = self.copyright() {
|
||||||
span class="poweredby__copyright" { (c) "." } " "
|
span class="poweredby__copyright" { (c) "." } " "
|
||||||
}
|
}
|
||||||
span class="poweredby__pagetop" {
|
span class="poweredby__pagetop" {
|
||||||
(Lc::l("poweredby_pagetop").with_markup("pagetop_link", pagetop_link).using(cx))
|
(Lc::l("poweredby_pagetop").with_arg("pagetop_link", PAGETOP_LINK).using(cx))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
127
src/locale/lc.rs
127
src/locale/lc.rs
|
|
@ -7,7 +7,6 @@ include_locales!(LOCALES_PAGETOP);
|
||||||
|
|
||||||
use fluent_templates::Loader;
|
use fluent_templates::Loader;
|
||||||
use fluent_templates::StaticLoader as Locales;
|
use fluent_templates::StaticLoader as Locales;
|
||||||
use fluent_templates::fluent_bundle::FluentValue;
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
|
@ -35,32 +34,22 @@ enum LcKind {
|
||||||
// `Text` resuelve a `FluentValue::String` para interpolar cualquier texto; pero no aplica el
|
// `Text` resuelve a `FluentValue::String` para interpolar cualquier texto; pero no aplica el
|
||||||
// selector de plural de Fluent (`{ $n -> [one] ... *[other] ... }`). Para eso está `Number`, que
|
// selector de plural de Fluent (`{ $n -> [one] ... *[other] ... }`). Para eso está `Number`, que
|
||||||
// resuelve a `FluentValue::Number` y es el único tipo con el que Fluent consulta las reglas de
|
// resuelve a `FluentValue::Number` y es el único tipo con el que Fluent consulta las reglas de
|
||||||
// plural del idioma. `Markup` es marcado HTML de confianza, que `using()` no escapa.
|
// plural del idioma.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
enum LcArg {
|
enum LcArg {
|
||||||
Text(CowStr),
|
Text(CowStr),
|
||||||
Number(u32),
|
Number(u32),
|
||||||
Markup(String),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LcArg {
|
impl<'a> From<&'a LcArg> for fluent_templates::fluent_bundle::FluentValue<'a> {
|
||||||
// Valor para Fluent. Con `escape`, el texto se escapa para insertarse en marcado HTML.
|
fn from(arg: &'a LcArg) -> Self {
|
||||||
fn to_fluent(&self, escape: bool) -> FluentValue<'_> {
|
match arg {
|
||||||
match self {
|
|
||||||
LcArg::Text(s) if escape && needs_escape(s) => s.as_ref().render().into_string().into(),
|
|
||||||
LcArg::Text(s) => s.as_ref().into(),
|
LcArg::Text(s) => s.as_ref().into(),
|
||||||
LcArg::Number(n) => (*n).into(),
|
LcArg::Number(n) => (*n).into(),
|
||||||
LcArg::Markup(s) => s.as_str().into(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Indica si el texto contiene algún carácter que Maud escapa. Sin ninguno, el texto escapado es
|
|
||||||
// idéntico al original y se interpola prestado, sin reservar memoria para una copia.
|
|
||||||
fn needs_escape(text: &str) -> bool {
|
|
||||||
text.bytes().any(|b| matches!(b, b'&' | b'<' | b'>' | b'"'))
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< Lc >*****************************************************************************************
|
// **< Lc >*****************************************************************************************
|
||||||
|
|
||||||
/// Crea instancias para traducir *textos localizados*.
|
/// Crea instancias para traducir *textos localizados*.
|
||||||
|
|
@ -90,8 +79,8 @@ fn needs_escape(text: &str) -> bool {
|
||||||
/// - [`using()`](Self::using) devuelve [`Markup`] para presentar al usuario, listo para insertarse
|
/// - [`using()`](Self::using) devuelve [`Markup`] para presentar al usuario, listo para insertarse
|
||||||
/// en el contenido de una plantilla (`(x.using(cx))` dentro de [`html!`](crate::html::html)).
|
/// en el contenido de una plantilla (`(x.using(cx))` dentro de [`html!`](crate::html::html)).
|
||||||
/// Nunca devuelve `None`, por lo que una traducción no encontrada se convierte en marcado vacío.
|
/// Nunca devuelve `None`, por lo que una traducción no encontrada se convierte en marcado vacío.
|
||||||
/// Para `n()` se escapa el texto, y también los argumentos de texto de `l()`/`t()`, para evitar
|
/// Para `n()` se escapa el texto para evitar HTML no controlado. Para valores de atributo, usa
|
||||||
/// HTML no controlado. Para valores de atributo, usa siempre [`lookup()`](Self::lookup).
|
/// siempre [`lookup()`](Self::lookup).
|
||||||
///
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
|
|
@ -180,11 +169,9 @@ impl Lc {
|
||||||
|
|
||||||
/// Añade un argumento `{$arg}` => `value` a la traducción.
|
/// Añade un argumento `{$arg}` => `value` a la traducción.
|
||||||
///
|
///
|
||||||
/// `value` se interpreta siempre como texto: [`using()`](Self::using) lo escapa, así que puede
|
/// `value` se interpreta siempre como texto. Si se necesita un argumento numérico que además
|
||||||
/// venir de datos de usuario sin riesgo de inyectar marcado. Para insertar marcado HTML de
|
/// deba seleccionar plural (`{ $n -> [one] ... *[other] ... }`), hay que utilizar en su lugar
|
||||||
/// confianza hay que utilizar [`with_markup()`](Self::with_markup). Si se necesita un argumento
|
/// [`with_number()`](Self::with_number).
|
||||||
/// numérico que además deba seleccionar plural (`{ $n -> [one] ... *[other] ... }`), hay que
|
|
||||||
/// utilizar [`with_number()`](Self::with_number).
|
|
||||||
pub fn with_arg(mut self, arg: impl Into<CowStr>, value: impl Into<CowStr>) -> Self {
|
pub fn with_arg(mut self, arg: impl Into<CowStr>, value: impl Into<CowStr>) -> Self {
|
||||||
self.args.push((arg.into(), LcArg::Text(value.into())));
|
self.args.push((arg.into(), LcArg::Text(value.into())));
|
||||||
self
|
self
|
||||||
|
|
@ -224,30 +211,6 @@ impl Lc {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Añade un argumento `{$arg}` => `markup` con marcado HTML de confianza, que
|
|
||||||
/// [`using()`](Self::using) inserta sin escapar.
|
|
||||||
///
|
|
||||||
/// A diferencia de [`with_arg()`](Self::with_arg), sirve para incluir en la traducción un
|
|
||||||
/// fragmento HTML generado por la aplicación, como un enlace. No debe contener datos de usuario
|
|
||||||
/// sin escapar (construirlo con [`html!`](crate::html::html) los escapa): permitirían inyectar
|
|
||||||
/// marcado, p. ej. un enlace fraudulento en un correo legítimo de la aplicación. Con
|
|
||||||
/// [`get()`](Self::get) y [`lookup()`](Self::lookup) el marcado se interpola como texto.
|
|
||||||
///
|
|
||||||
/// # Ejemplo
|
|
||||||
///
|
|
||||||
/// ```rust,no_run
|
|
||||||
/// # use pagetop::prelude::*;
|
|
||||||
/// let link = html! { a href="https://pagetop.cillero.es" { "PageTop" } };
|
|
||||||
/// let text = Lc::l("poweredby_pagetop")
|
|
||||||
/// .with_markup("pagetop_link", link)
|
|
||||||
/// .using(&Locale::resolve("es"));
|
|
||||||
/// ```
|
|
||||||
pub fn with_markup(mut self, arg: impl Into<CowStr>, markup: Markup) -> Self {
|
|
||||||
self.args
|
|
||||||
.push((arg.into(), LcArg::Markup(markup.into_string())));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< Lc GETTERS >*****************************************************************************
|
// **< Lc GETTERS >*****************************************************************************
|
||||||
|
|
||||||
/// Indica si la instancia está **sin contenido** ([`Lc::none()`]).
|
/// Indica si la instancia está **sin contenido** ([`Lc::none()`]).
|
||||||
|
|
@ -304,7 +267,22 @@ impl Lc {
|
||||||
/// let text = Lc::l("greeting").with_arg("name", "Usuario").lookup(&r);
|
/// let text = Lc::l("greeting").with_arg("name", "Usuario").lookup(&r);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn lookup(&self, language: &impl LangId) -> Option<String> {
|
pub fn lookup(&self, language: &impl LangId) -> Option<String> {
|
||||||
self.resolve(language, false)
|
match &self.op {
|
||||||
|
LcKind::None => None,
|
||||||
|
LcKind::Text(text) => Some(text.clone().into_owned()),
|
||||||
|
LcKind::Translate(key) => {
|
||||||
|
if self.args.is_empty() {
|
||||||
|
self.locales.try_lookup(language.langid(), key.as_ref())
|
||||||
|
} else {
|
||||||
|
let mut args = HashMap::with_capacity(self.args.len());
|
||||||
|
for (k, v) in self.args.iter() {
|
||||||
|
args.insert(k.clone(), v.into());
|
||||||
|
}
|
||||||
|
self.locales
|
||||||
|
.try_lookup_with_args(language.langid(), key.as_ref(), &args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Traduce el texto y lo devuelve como [`Markup`] usando la fuente de idioma proporcionada.
|
/// Traduce el texto y lo devuelve como [`Markup`] usando la fuente de idioma proporcionada.
|
||||||
|
|
@ -313,11 +291,9 @@ impl Lc {
|
||||||
///
|
///
|
||||||
/// Las claves de traducción (`l()`/`t()`) son texto de confianza, con traducciones en ficheros
|
/// Las claves de traducción (`l()`/`t()`) son texto de confianza, con traducciones en ficheros
|
||||||
/// `.ftl` que pueden incluir marcado HTML (p. ej. `<strong>`, enlaces, etc.) que se insertan
|
/// `.ftl` que pueden incluir marcado HTML (p. ej. `<strong>`, enlaces, etc.) que se insertan
|
||||||
/// tal cual. El texto literal (`n()`) y los argumentos de texto
|
/// tal cual. El texto literal (`n()`), en cambio, suele venir de datos en tiempo de ejecución
|
||||||
/// ([`with_arg()`](Self::with_arg)), en cambio, suelen venir de datos en tiempo de ejecución
|
/// que no debe interpretarse como marcado, por lo que se escapa igual que cualquier otro valor
|
||||||
/// que no deben interpretarse como marcado, por lo que se escapan igual que cualquier otro
|
/// interpolado con [`html!`](crate::html::html).
|
||||||
/// valor interpolado con [`html!`](crate::html::html). El marcado de confianza que se pasa como
|
|
||||||
/// argumento con [`with_markup()`](Self::with_markup) se inserta sin escapar.
|
|
||||||
///
|
///
|
||||||
/// No debe usarse para un valor de atributo (`attr=[...]` en [`html!`](crate::html::html)): el
|
/// No debe usarse para un valor de atributo (`attr=[...]` en [`html!`](crate::html::html)): el
|
||||||
/// marcado de confianza que se aplica en `l()`/`t()` no tiene sentido ahí, y podría romper el
|
/// marcado de confianza que se aplica en `l()`/`t()` no tiene sentido ahí, y podría romper el
|
||||||
|
|
@ -333,36 +309,7 @@ impl Lc {
|
||||||
pub fn using(&self, language: &impl LangId) -> Markup {
|
pub fn using(&self, language: &impl LangId) -> Markup {
|
||||||
match &self.op {
|
match &self.op {
|
||||||
LcKind::Text(text) => text.render(),
|
LcKind::Text(text) => text.render(),
|
||||||
_ => PreEscaped(self.resolve(language, true).unwrap_or_default()),
|
_ => PreEscaped(self.lookup(language).unwrap_or_default()),
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resuelve la traducción. Con `escape`, los argumentos de texto se escapan para `using()`.
|
|
||||||
fn resolve(&self, language: &impl LangId, escape: bool) -> Option<String> {
|
|
||||||
match &self.op {
|
|
||||||
LcKind::None => None,
|
|
||||||
LcKind::Text(text) => Some(text.clone().into_owned()),
|
|
||||||
LcKind::Translate(key) => {
|
|
||||||
let langid = language.langid();
|
|
||||||
let args = (!self.args.is_empty()).then(|| {
|
|
||||||
let mut args = HashMap::with_capacity(self.args.len());
|
|
||||||
for (k, v) in self.args.iter() {
|
|
||||||
args.insert(k.clone(), v.to_fluent(escape));
|
|
||||||
}
|
|
||||||
args
|
|
||||||
});
|
|
||||||
// `try_lookup_complete()` negocia el idioma en cada llamada, con varias reservas de
|
|
||||||
// memoria, aunque `langid` sea casi siempre un idioma disponible. Se prueba antes
|
|
||||||
// el idioma exacto, que es lo primero que elige la negociación, por lo que el
|
|
||||||
// resultado no cambia; sólo si falla se recorre la cadena de idiomas de respaldo.
|
|
||||||
self.locales
|
|
||||||
.lookup_single_language(langid, key.as_ref(), args.as_ref())
|
|
||||||
.ok()
|
|
||||||
.or_else(|| {
|
|
||||||
self.locales
|
|
||||||
.try_lookup_complete(langid, key.as_ref(), args.as_ref())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -418,19 +365,3 @@ impl Lc {
|
||||||
key
|
key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
// `needs_escape()` must flag every character that Maud escapes; otherwise `using()` would
|
|
||||||
// interpolate it unescaped. Compares every character up to U+02FF with Maud's own escaping.
|
|
||||||
#[test]
|
|
||||||
fn needs_escape_matches_maud() {
|
|
||||||
for c in (0..=0x2ffu32).filter_map(char::from_u32) {
|
|
||||||
let text = c.to_string();
|
|
||||||
let escaped = text.as_str().render().into_string();
|
|
||||||
assert_eq!(needs_escape(&text), escaped != text, "mismatch for {c:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -30,42 +30,6 @@ async fn translation_with_args() {
|
||||||
assert_eq!(translation, Some("¡Hola, Manuel!".to_string()));
|
assert_eq!(translation, Some("¡Hola, Manuel!".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Text arguments may come from user data: `using()` must not let them inject markup.
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn using_escapes_text_args() {
|
|
||||||
setup().await;
|
|
||||||
|
|
||||||
let lc = Lc::l("test_hello_user").with_arg("userName", r#"<a href="x">Ana & "Luis"</a>"#);
|
|
||||||
assert_eq!(
|
|
||||||
lc.using(&Locale::resolve("es-ES")).into_string(),
|
|
||||||
"¡Hola, <a href="x">Ana & "Luis"</a>!"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// `lookup()` returns plain text, escaped later where it is used (e.g. in an attribute).
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn lookup_does_not_escape_text_args() {
|
|
||||||
setup().await;
|
|
||||||
|
|
||||||
let lc = Lc::l("test_hello_user").with_arg("userName", "Ana & <Luis>");
|
|
||||||
assert_eq!(
|
|
||||||
lc.lookup(&Locale::resolve("es-ES")),
|
|
||||||
Some("¡Hola, Ana & <Luis>!".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn using_keeps_markup_args() {
|
|
||||||
setup().await;
|
|
||||||
|
|
||||||
let name = "Ana & Luis";
|
|
||||||
let lc = Lc::l("test_hello_user").with_markup("userName", html! { strong { (name) } });
|
|
||||||
assert_eq!(
|
|
||||||
lc.using(&Locale::resolve("es-ES")).into_string(),
|
|
||||||
"¡Hola, <strong>Ana & Luis</strong>!"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
async fn translation_with_plural_and_select() {
|
async fn translation_with_plural_and_select() {
|
||||||
setup().await;
|
setup().await;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue