diff --git a/src/core/theme.rs b/src/core/theme.rs index d67a445..d741cf8 100644 --- a/src/core/theme.rs +++ b/src/core/theme.rs @@ -1,24 +1,6 @@ //! 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 6f1e54a..e32ac48 100644 --- a/src/core/theme/definition.rs +++ b/src/core/theme/definition.rs @@ -1,5 +1,4 @@ use crate::core::extension::ExtensionTrait; -use crate::locale::L10n; /// Representa una referencia a un tema. /// @@ -28,8 +27,4 @@ pub type ThemeRef = &'static dyn ThemeTrait; /// /// impl ThemeTrait for MyTheme {} /// ``` -pub trait ThemeTrait: ExtensionTrait + Send + Sync { - fn regions(&self) -> Vec<(&'static str, L10n)> { - vec![("content", L10n::l("content"))] - } -} +pub trait ThemeTrait: ExtensionTrait + Send + Sync {} diff --git a/src/core/theme/regions.rs b/src/core/theme/regions.rs deleted file mode 100644 index 5beee25..0000000 --- a/src/core/theme/regions.rs +++ /dev/null @@ -1,111 +0,0 @@ -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/html.rs b/src/html.rs index 7f18ee8..3c9c796 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, ContextOp, ErrorParam}; +pub use context::{Context, ErrorParam}; mod opt_id; pub use opt_id::OptionId; diff --git a/src/html/context.rs b/src/html/context.rs index 4374b14..b362250 100644 --- a/src/html/context.rs +++ b/src/html/context.rs @@ -13,37 +13,6 @@ 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 { @@ -64,52 +33,48 @@ impl fmt::Display for ErrorParam { impl Error for ErrorParam {} -/// Representa el contexto de un documento HTML. +/// Representa el contexto asociado a un documento HTML. /// -/// 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. +/// 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. /// /// # Ejemplo /// /// ```rust /// use pagetop::prelude::*; /// -/// fn configure_context(mut cx: Context) { +/// fn configure_context(mut ctx: Context) { /// // Establece el idioma del documento a español. -/// cx.alter_assets(ContextOp::LangId( -/// LangMatch::langid_or_default("es-ES") -/// )) +/// ctx.set_langid(LangMatch::langid_or_default("es-ES")); +/// /// // Selecciona un tema (por su nombre corto). -/// .alter_assets(ContextOp::Theme("aliner")) +/// ctx.set_theme("aliner"); +/// /// // Asigna un favicon. -/// .alter_assets(ContextOp::SetFavicon(Some( -/// Favicon::new().with_icon("/icons/favicon.ico") -/// ))) +/// ctx.set_favicon(Some(Favicon::new().with_icon("/icons/favicon.ico"))); +/// /// // Añade una hoja de estilo externa. -/// .alter_assets(ContextOp::AddStyleSheet( -/// StyleSheet::from("/css/style.css") -/// )) +/// ctx.add_stylesheet(StyleSheet::from("/css/style.css")); +/// /// // Añade un script JavaScript. -/// .alter_assets(ContextOp::AddJavaScript( -/// JavaScript::defer("/js/main.js") -/// )); +/// ctx.add_javascript(JavaScript::defer("/js/main.js")); /// /// // Añade un parámetro dinámico al contexto. -/// cx.set_param("usuario_id", 42); +/// ctx.set_param("usuario_id", 42); /// /// // Recupera el parámetro y lo convierte a su tipo original. -/// let id: i32 = cx.get_param("usuario_id").unwrap(); +/// let id: i32 = ctx.get_param("usuario_id").unwrap(); /// assert_eq!(id, 42); /// /// // Recupera el tema seleccionado. -/// let active_theme = cx.theme(); +/// let active_theme = ctx.theme(); /// assert_eq!(active_theme.short_name(), "aliner"); /// /// // Genera un identificador único para un componente de tipo `Menu`. /// struct Menu; -/// let unique_id = cx.required_id::(None); +/// let unique_id = ctx.required_id::(None); /// assert_eq!(unique_id, "menu-1"); // Si es el primero generado. /// } /// ``` @@ -118,7 +83,6 @@ 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. @@ -136,7 +100,6 @@ impl Context { request, langid : &DEFAULT_LANGID, theme : *DEFAULT_THEME, - layout : "default", favicon : None, stylesheets: Assets::::new(), javascripts: Assets::::new(), @@ -145,45 +108,59 @@ impl Context { } } - /// 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); - } + /// 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); } 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 @@ -208,12 +185,6 @@ 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 diff --git a/src/locale/en-US/theme.ftl b/src/locale/en-US/theme.ftl deleted file mode 100644 index fd7f228..0000000 --- a/src/locale/en-US/theme.ftl +++ /dev/null @@ -1 +0,0 @@ -content = Content diff --git a/src/locale/es-ES/theme.ftl b/src/locale/es-ES/theme.ftl deleted file mode 100644 index c2026c6..0000000 --- a/src/locale/es-ES/theme.ftl +++ /dev/null @@ -1 +0,0 @@ -content = Contenido