From 126fe3a8ea5d9dbc3b5081739313f488627cbb0e Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Thu, 24 Jul 2025 13:16:39 +0200 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=A7=91=E2=80=8D=F0=9F=92=BB=20Mejora?= =?UTF-8?q?=20las=20operaciones=20de=20cambio=20en=20contexto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/html.rs | 2 +- src/html/context.rs | 165 ++++++++++++++++++++++++++------------------ 2 files changed, 98 insertions(+), 69 deletions(-) diff --git a/src/html.rs b/src/html.rs index 3c9c796..7f18ee8 100644 --- a/src/html.rs +++ b/src/html.rs @@ -10,7 +10,7 @@ pub use assets::stylesheet::{StyleSheet, TargetMedia}; pub(crate) use assets::Assets; mod context; -pub use context::{Context, ErrorParam}; +pub use context::{Context, ContextOp, ErrorParam}; mod opt_id; pub use opt_id::OptionId; diff --git a/src/html/context.rs b/src/html/context.rs index b362250..4374b14 100644 --- a/src/html/context.rs +++ b/src/html/context.rs @@ -13,6 +13,37 @@ use std::str::FromStr; use std::fmt; +/// Operaciones para modificar el contexto ([`Context`]) del documento. +pub enum ContextOp { + /// Modifica el identificador de idioma del documento. + LangId(&'static LanguageIdentifier), + /// Establece el tema que se usará para renderizar el documento. + /// + /// Localiza el tema por su [`short_name`](crate::core::AnyInfo::short_name), y si no aplica + /// ninguno entonces usará el tema por defecto. + Theme(&'static str), + /// Define el tipo de composición usado para renderizar el documento. + Layout(&'static str), + + // Favicon. + /// Define el *favicon* del documento. Sobrescribe cualquier valor anterior. + SetFavicon(Option), + /// Define el *favicon* solo si no se ha establecido previamente. + SetFaviconIfNone(Favicon), + + // Stylesheets. + /// Añade una hoja de estilos CSS al documento. + AddStyleSheet(StyleSheet), + /// Elimina una hoja de estilos por su ruta o identificador. + RemoveStyleSheet(&'static str), + + // JavaScripts. + /// Añade un *script* JavaScript al documento. + AddJavaScript(JavaScript), + /// Elimina un *script* por su ruta o identificador. + RemoveJavaScript(&'static str), +} + /// Errores de lectura o conversión de parámetros almacenados en el contexto. #[derive(Debug)] pub enum ErrorParam { @@ -33,48 +64,52 @@ impl fmt::Display for ErrorParam { impl Error for ErrorParam {} -/// Representa el contexto asociado a un documento HTML. +/// Representa el contexto de un documento HTML. /// -/// Esta estructura se crea internamente para recoger información relativa al documento asociado, -/// como la solicitud HTTP de origen, el idioma, el tema para renderizar ([`ThemeRef`]), y los -/// recursos *favicon* ([`Favicon`]), las hojas de estilo ([`StyleSheet`]) y los *scripts* -/// ([`JavaScript`]). También admite parámetros de contexto definidos en tiempo de ejecución. +/// Se crea internamente para manejar información relevante del documento, como la solicitud HTTP de +/// origen, el idioma, tema y composición para el renderizado, los recursos *favicon* ([`Favicon`]), +/// hojas de estilo ([`StyleSheet`]) y *scripts* ([`JavaScript`]), así como parámetros de contexto +/// definidos en tiempo de ejecución. /// /// # Ejemplo /// /// ```rust /// use pagetop::prelude::*; /// -/// fn configure_context(mut ctx: Context) { +/// fn configure_context(mut cx: Context) { /// // Establece el idioma del documento a español. -/// ctx.set_langid(LangMatch::langid_or_default("es-ES")); -/// +/// cx.alter_assets(ContextOp::LangId( +/// LangMatch::langid_or_default("es-ES") +/// )) /// // Selecciona un tema (por su nombre corto). -/// ctx.set_theme("aliner"); -/// +/// .alter_assets(ContextOp::Theme("aliner")) /// // Asigna un favicon. -/// ctx.set_favicon(Some(Favicon::new().with_icon("/icons/favicon.ico"))); -/// +/// .alter_assets(ContextOp::SetFavicon(Some( +/// Favicon::new().with_icon("/icons/favicon.ico") +/// ))) /// // Añade una hoja de estilo externa. -/// ctx.add_stylesheet(StyleSheet::from("/css/style.css")); -/// +/// .alter_assets(ContextOp::AddStyleSheet( +/// StyleSheet::from("/css/style.css") +/// )) /// // Añade un script JavaScript. -/// ctx.add_javascript(JavaScript::defer("/js/main.js")); +/// .alter_assets(ContextOp::AddJavaScript( +/// JavaScript::defer("/js/main.js") +/// )); /// /// // Añade un parámetro dinámico al contexto. -/// ctx.set_param("usuario_id", 42); +/// cx.set_param("usuario_id", 42); /// /// // Recupera el parámetro y lo convierte a su tipo original. -/// let id: i32 = ctx.get_param("usuario_id").unwrap(); +/// let id: i32 = cx.get_param("usuario_id").unwrap(); /// assert_eq!(id, 42); /// /// // Recupera el tema seleccionado. -/// let active_theme = ctx.theme(); +/// let active_theme = cx.theme(); /// assert_eq!(active_theme.short_name(), "aliner"); /// /// // Genera un identificador único para un componente de tipo `Menu`. /// struct Menu; -/// let unique_id = ctx.required_id::(None); +/// let unique_id = cx.required_id::(None); /// assert_eq!(unique_id, "menu-1"); // Si es el primero generado. /// } /// ``` @@ -83,6 +118,7 @@ pub struct Context { request : HttpRequest, // Solicitud HTTP de origen. langid : &'static LanguageIdentifier, // Identificador del idioma. theme : ThemeRef, // Referencia al tema para renderizar. + layout : &'static str, // Composición del documento para renderizar. favicon : Option, // Favicon, si se ha definido. stylesheets: Assets, // Hojas de estilo CSS. javascripts: Assets, // Scripts JavaScript. @@ -100,6 +136,7 @@ impl Context { request, langid : &DEFAULT_LANGID, theme : *DEFAULT_THEME, + layout : "default", favicon : None, stylesheets: Assets::::new(), javascripts: Assets::::new(), @@ -108,59 +145,45 @@ impl Context { } } - /// Modifica el identificador de idioma del documento. - pub fn set_langid(&mut self, langid: &'static LanguageIdentifier) -> &mut Self { - self.langid = langid; - self - } - - /// Establece el tema que se usará para renderizar el documento. - /// - /// Localiza el tema por su [`short_name`](crate::core::AnyInfo::short_name), y si no aplica - /// ninguno entonces usará el tema por defecto. - pub fn set_theme(&mut self, short_name: impl AsRef) -> &mut Self { - self.theme = theme_by_short_name(short_name).unwrap_or(*DEFAULT_THEME); - self - } - - /// Define el *favicon* del documento. Sobrescribe cualquier valor anterior. - pub fn set_favicon(&mut self, favicon: Option) -> &mut Self { - self.favicon = favicon; - self - } - - /// Define el *favicon* solo si no se ha establecido previamente. - pub fn set_favicon_if_none(&mut self, favicon: Favicon) -> &mut Self { - if self.favicon.is_none() { - self.favicon = Some(favicon); + /// Modifica información o recursos del contexto usando [`ContextOp`]. + pub fn alter_assets(&mut self, op: ContextOp) -> &mut Self { + match op { + ContextOp::LangId(langid) => { + self.langid = langid; + } + ContextOp::Theme(theme_name) => { + self.theme = theme_by_short_name(theme_name).unwrap_or(*DEFAULT_THEME); + } + ContextOp::Layout(layout) => { + self.layout = layout; + } + // Favicon. + ContextOp::SetFavicon(favicon) => { + self.favicon = favicon; + } + ContextOp::SetFaviconIfNone(icon) => { + if self.favicon.is_none() { + self.favicon = Some(icon); + } + } + // Stylesheets. + ContextOp::AddStyleSheet(css) => { + self.stylesheets.add(css); + } + ContextOp::RemoveStyleSheet(path) => { + self.stylesheets.remove(path); + } + // JavaScripts. + ContextOp::AddJavaScript(js) => { + self.javascripts.add(js); + } + ContextOp::RemoveJavaScript(path) => { + self.javascripts.remove(path); + } } self } - /// Añade una hoja de estilos CSS al documento. - pub fn add_stylesheet(&mut self, css: StyleSheet) -> &mut Self { - self.stylesheets.add(css); - self - } - - /// Elimina una hoja de estilos por su ruta o identificador. - pub fn remove_stylesheet(&mut self, name: impl AsRef) -> &mut Self { - self.stylesheets.remove(name); - self - } - - /// Añade un *script* JavaScript al documento. - pub fn add_javascript(&mut self, js: JavaScript) -> &mut Self { - self.javascripts.add(js); - self - } - - /// Elimina un *script* por su ruta o identificador. - pub fn remove_javascript(&mut self, name: impl AsRef) -> &mut Self { - self.javascripts.remove(name); - self - } - /// Añade o modifica un parámetro del contexto almacenando el valor como [`String`]. pub fn set_param(&mut self, key: impl AsRef, value: T) -> &mut Self { self.params @@ -185,6 +208,12 @@ impl Context { self.theme } + /// Devuelve el tipo de composición usado para renderizar el documento. El valor predeterminado + /// es `"default"`. + pub fn layout(&self) -> &str { + self.layout + } + /// Recupera un parámetro del contexto convertido al tipo especificado. /// /// Devuelve un error si el parámetro no existe ([`ErrorParam::NotFound`]) o la conversión falla From 07482616926d6d81e988577a29668311a5aa8624 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Thu, 24 Jul 2025 21:20:35 +0200 Subject: [PATCH 2/2] =?UTF-8?q?=E2=9C=A8=20A=C3=B1ade=20gesti=C3=B3n=20de?= =?UTF-8?q?=20regiones=20en=20temas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/theme.rs | 18 ++++++ src/core/theme/definition.rs | 7 ++- src/core/theme/regions.rs | 111 +++++++++++++++++++++++++++++++++++ src/locale/en-US/theme.ftl | 1 + src/locale/es-ES/theme.ftl | 1 + 5 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 src/core/theme/regions.rs create mode 100644 src/locale/en-US/theme.ftl create mode 100644 src/locale/es-ES/theme.ftl diff --git a/src/core/theme.rs b/src/core/theme.rs index d741cf8..d67a445 100644 --- a/src/core/theme.rs +++ b/src/core/theme.rs @@ -1,6 +1,24 @@ //! API para añadir y gestionar nuevos temas. +//! +//! En `PageTop` un tema es la *piel* de la aplicación, decide cómo se muestra cada documento HTML, +//! especialmente las páginas de contenido ([`Page`](crate::response::page::Page)), sin alterar la +//! lógica interna de sus componentes. +//! +//! Un tema **declara las regiones** (*cabecera*, *barra lateral*, *pie*, etc.) que estarán +//! disponibles para colocar contenido. Los temas son responsables últimos de los estilos, +//! tipografías, espaciados y cualquier otro detalle visual o de comportamiento (como animaciones, +//! *scripts* de interfaz, etc.). +//! +//! Es una extensión más (implementando [`ExtensionTrait`](crate::core::extension::ExtensionTrait)). +//! Se instala, activa y declara dependencias igual que el resto de extensiones; y se señala a sí +//! misma como tema (implementando [`theme()`](crate::core::extension::ExtensionTrait::theme) +//! y [`ThemeTrait`]). mod definition; pub use definition::{ThemeRef, ThemeTrait}; +mod regions; +pub(crate) use regions::ChildrenInRegions; +pub use regions::InRegion; + pub(crate) mod all; diff --git a/src/core/theme/definition.rs b/src/core/theme/definition.rs index e32ac48..6f1e54a 100644 --- a/src/core/theme/definition.rs +++ b/src/core/theme/definition.rs @@ -1,4 +1,5 @@ use crate::core::extension::ExtensionTrait; +use crate::locale::L10n; /// Representa una referencia a un tema. /// @@ -27,4 +28,8 @@ pub type ThemeRef = &'static dyn ThemeTrait; /// /// impl ThemeTrait for MyTheme {} /// ``` -pub trait ThemeTrait: ExtensionTrait + Send + Sync {} +pub trait ThemeTrait: ExtensionTrait + Send + Sync { + fn regions(&self) -> Vec<(&'static str, L10n)> { + vec![("content", L10n::l("content"))] + } +} diff --git a/src/core/theme/regions.rs b/src/core/theme/regions.rs new file mode 100644 index 0000000..5beee25 --- /dev/null +++ b/src/core/theme/regions.rs @@ -0,0 +1,111 @@ +use crate::core::component::{Child, ChildOp, Children}; +use crate::core::theme::ThemeRef; +use crate::{builder_fn, AutoDefault, UniqueId}; + +use parking_lot::RwLock; + +use std::collections::HashMap; +use std::sync::LazyLock; + +static THEME_REGIONS: LazyLock>> = + LazyLock::new(|| RwLock::new(HashMap::new())); + +static COMMON_REGIONS: LazyLock> = + LazyLock::new(|| RwLock::new(ChildrenInRegions::default())); + +// Estructura interna para mantener los componentes de cada región dada. +#[derive(AutoDefault)] +pub struct ChildrenInRegions(HashMap<&'static str, Children>); + +impl ChildrenInRegions { + pub fn new() -> Self { + ChildrenInRegions::default() + } + + pub fn with(region_id: &'static str, child: Child) -> Self { + ChildrenInRegions::default().with_in_region(region_id, ChildOp::Add(child)) + } + + #[builder_fn] + pub fn with_in_region(mut self, region_id: &'static str, op: ChildOp) -> Self { + if let Some(region) = self.0.get_mut(region_id) { + region.alter_child(op); + } else { + self.0.insert(region_id, Children::new().with_child(op)); + } + self + } + + pub fn all_in_region(&self, theme: ThemeRef, region_id: &str) -> Children { + let common = COMMON_REGIONS.read(); + if let Some(r) = THEME_REGIONS.read().get(&theme.type_id()) { + Children::merge(&[ + common.0.get(region_id), + self.0.get(region_id), + r.0.get(region_id), + ]) + } else { + Children::merge(&[common.0.get(region_id), self.0.get(region_id)]) + } + } +} + +/// Permite añadir componentes a regiones globales o regiones de temas concretos. +/// +/// Dada una región, según la variante seleccionada, se le podrán añadir ([`add()`](Self::add)) +/// componentes que se mantendrán durante la ejecución de la aplicación. +/// +/// Estas estructuras de componentes se renderizarán automáticamente al procesar los documentos HTML +/// que las usan, como las páginas de contenido ([`Page`](crate::response::page::Page)), por +/// ejemplo. +pub enum InRegion { + /// Representa la región por defecto en la que se pueden añadir componentes. + Content, + /// Representa la región con el nombre del argumento. + Named(&'static str), + /// Representa la región con el nombre y del tema especificado en los argumentos. + OfTheme(&'static str, ThemeRef), +} + +impl InRegion { + /// Permite añadir un componente en la región de la variante seleccionada. + /// + /// # Ejemplo + /// + /// ```rust + /// use pagetop::prelude::*; + /// + /// // Banner global, en la región por defecto de cualquier página. + /// InRegion::Content.add(Child::with(Html::with( + /// html! { ("🎉 ¡Bienvenido!") } + /// ))); + /// + /// // Texto en la región "sidebar". + /// InRegion::Named("sidebar").add(Child::with(Html::with( + /// html! { ("Publicidad") } + /// ))); + /// ``` + pub fn add(&self, child: Child) -> &Self { + match self { + InRegion::Content => { + COMMON_REGIONS + .write() + .alter_in_region("region-content", ChildOp::Add(child)); + } + InRegion::Named(name) => { + COMMON_REGIONS + .write() + .alter_in_region(name, ChildOp::Add(child)); + } + InRegion::OfTheme(region, theme) => { + let mut regions = THEME_REGIONS.write(); + if let Some(r) = regions.get_mut(&theme.type_id()) { + r.alter_in_region(region, ChildOp::Add(child)); + } else { + regions.insert(theme.type_id(), ChildrenInRegions::with(region, child)); + } + } + } + self + } +} diff --git a/src/locale/en-US/theme.ftl b/src/locale/en-US/theme.ftl new file mode 100644 index 0000000..fd7f228 --- /dev/null +++ b/src/locale/en-US/theme.ftl @@ -0,0 +1 @@ +content = Content diff --git a/src/locale/es-ES/theme.ftl b/src/locale/es-ES/theme.ftl new file mode 100644 index 0000000..c2026c6 --- /dev/null +++ b/src/locale/es-ES/theme.ftl @@ -0,0 +1 @@ +content = Contenido