diff --git a/src/base/component/poweredby.rs b/src/base/component/poweredby.rs
index c85e632c..cb02726f 100644
--- a/src/base/component/poweredby.rs
+++ b/src/base/component/poweredby.rs
@@ -1,5 +1,15 @@
use crate::prelude::*;
+// Enlace a la página oficial de PageTop.
+const PAGETOP_LINK: &str = concat!(
+ "",
+ "PageTop",
+ "",
+);
+
/// 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.
@@ -24,18 +34,13 @@ impl Component for PoweredBy {
}
async fn prepare(&self, cx: &mut Context) -> Result {
- let pagetop_link = html! {
- a href="https://pagetop.cillero.es" target="_blank" rel="noopener noreferrer" {
- "PageTop"
- }
- };
Ok(html! {
div id=[self.id()] class="poweredby" {
@if let Some(c) = self.copyright() {
span class="poweredby__copyright" { (c) "." } " "
}
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))
}
}
})
diff --git a/src/locale/lc.rs b/src/locale/lc.rs
index 59e3fa46..e7d51b48 100644
--- a/src/locale/lc.rs
+++ b/src/locale/lc.rs
@@ -7,7 +7,6 @@ include_locales!(LOCALES_PAGETOP);
use fluent_templates::Loader;
use fluent_templates::StaticLoader as Locales;
-use fluent_templates::fluent_bundle::FluentValue;
use std::collections::HashMap;
@@ -35,32 +34,22 @@ enum LcKind {
// `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
// 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)]
enum LcArg {
Text(CowStr),
Number(u32),
- Markup(String),
}
-impl LcArg {
- // Valor para Fluent. Con `escape`, el texto se escapa para insertarse en marcado HTML.
- fn to_fluent(&self, escape: bool) -> FluentValue<'_> {
- match self {
- LcArg::Text(s) if escape && needs_escape(s) => s.as_ref().render().into_string().into(),
+impl<'a> From<&'a LcArg> for fluent_templates::fluent_bundle::FluentValue<'a> {
+ fn from(arg: &'a LcArg) -> Self {
+ match arg {
LcArg::Text(s) => s.as_ref().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 >*****************************************************************************************
/// 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
/// 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.
-/// Para `n()` se escapa el texto, y también los argumentos de texto de `l()`/`t()`, para evitar
-/// HTML no controlado. Para valores de atributo, usa siempre [`lookup()`](Self::lookup).
+/// Para `n()` se escapa el texto para evitar HTML no controlado. Para valores de atributo, usa
+/// siempre [`lookup()`](Self::lookup).
///
/// # Ejemplo
///
@@ -180,11 +169,9 @@ impl Lc {
/// Añade un argumento `{$arg}` => `value` a la traducción.
///
- /// `value` se interpreta siempre como texto: [`using()`](Self::using) lo escapa, así que puede
- /// venir de datos de usuario sin riesgo de inyectar marcado. Para insertar marcado HTML de
- /// confianza hay que utilizar [`with_markup()`](Self::with_markup). Si se necesita un argumento
- /// numérico que además deba seleccionar plural (`{ $n -> [one] ... *[other] ... }`), hay que
- /// utilizar [`with_number()`](Self::with_number).
+ /// `value` se interpreta siempre como texto. Si se necesita un argumento numérico que además
+ /// deba seleccionar plural (`{ $n -> [one] ... *[other] ... }`), hay que utilizar en su lugar
+ /// [`with_number()`](Self::with_number).
pub fn with_arg(mut self, arg: impl Into, value: impl Into) -> Self {
self.args.push((arg.into(), LcArg::Text(value.into())));
self
@@ -224,30 +211,6 @@ impl Lc {
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, markup: Markup) -> Self {
- self.args
- .push((arg.into(), LcArg::Markup(markup.into_string())));
- self
- }
-
// **< Lc GETTERS >*****************************************************************************
/// 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);
/// ```
pub fn lookup(&self, language: &impl LangId) -> Option {
- 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.
@@ -313,11 +291,9 @@ impl Lc {
///
/// Las claves de traducción (`l()`/`t()`) son texto de confianza, con traducciones en ficheros
/// `.ftl` que pueden incluir marcado HTML (p. ej. ``, enlaces, etc.) que se insertan
- /// tal cual. El texto literal (`n()`) y los argumentos de texto
- /// ([`with_arg()`](Self::with_arg)), en cambio, suelen venir de datos en tiempo de ejecución
- /// que no deben interpretarse como marcado, por lo que se escapan igual que cualquier otro
- /// 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.
+ /// tal cual. El texto literal (`n()`), en cambio, suele venir de datos en tiempo de ejecución
+ /// que no debe interpretarse como marcado, por lo que se escapa igual que cualquier otro valor
+ /// interpolado con [`html!`](crate::html::html).
///
/// 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
@@ -333,36 +309,7 @@ impl Lc {
pub fn using(&self, language: &impl LangId) -> Markup {
match &self.op {
LcKind::Text(text) => text.render(),
- _ => PreEscaped(self.resolve(language, true).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 {
- 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())
- })
- }
+ _ => PreEscaped(self.lookup(language).unwrap_or_default()),
}
}
@@ -418,19 +365,3 @@ impl Lc {
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:?}");
- }
- }
-}
diff --git a/tests/locale.rs b/tests/locale.rs
index 5dd93524..ca55fd92 100644
--- a/tests/locale.rs
+++ b/tests/locale.rs
@@ -30,42 +30,6 @@ async fn translation_with_args() {
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#"Ana & "Luis""#);
- 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 & ");
- assert_eq!(
- lc.lookup(&Locale::resolve("es-ES")),
- Some("¡Hola, Ana & !".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, Ana & Luis!"
- );
-}
-
#[pagetop::test]
async fn translation_with_plural_and_select() {
setup().await;