Compare commits

...

2 commits

Author SHA1 Message Date
0748261692 Añade gestión de regiones en temas 2025-07-24 21:20:35 +02:00
126fe3a8ea 🧑‍💻 Mejora las operaciones de cambio en contexto 2025-07-24 13:16:39 +02:00
7 changed files with 235 additions and 70 deletions

View file

@ -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 (comoanimaciones,
//! *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;

View file

@ -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"))]
}
}

111
src/core/theme/regions.rs Normal file
View file

@ -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<RwLock<HashMap<UniqueId, ChildrenInRegions>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
static COMMON_REGIONS: LazyLock<RwLock<ChildrenInRegions>> =
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
}
}

View file

@ -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;

View file

@ -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<Favicon>),
/// 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::<Menu>(None);
/// let unique_id = cx.required_id::<Menu>(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>, // Favicon, si se ha definido.
stylesheets: Assets<StyleSheet>, // Hojas de estilo CSS.
javascripts: Assets<JavaScript>, // Scripts JavaScript.
@ -100,6 +136,7 @@ impl Context {
request,
langid : &DEFAULT_LANGID,
theme : *DEFAULT_THEME,
layout : "default",
favicon : None,
stylesheets: Assets::<StyleSheet>::new(),
javascripts: Assets::<JavaScript>::new(),
@ -108,56 +145,42 @@ impl Context {
}
}
/// Modifica el identificador de idioma del documento.
pub fn set_langid(&mut self, langid: &'static LanguageIdentifier) -> &mut Self {
/// 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;
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<str>) -> &mut Self {
self.theme = theme_by_short_name(short_name).unwrap_or(*DEFAULT_THEME);
self
ContextOp::Theme(theme_name) => {
self.theme = theme_by_short_name(theme_name).unwrap_or(*DEFAULT_THEME);
}
/// Define el *favicon* del documento. Sobrescribe cualquier valor anterior.
pub fn set_favicon(&mut self, favicon: Option<Favicon>) -> &mut Self {
ContextOp::Layout(layout) => {
self.layout = layout;
}
// Favicon.
ContextOp::SetFavicon(favicon) => {
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 {
ContextOp::SetFaviconIfNone(icon) => {
if self.favicon.is_none() {
self.favicon = Some(favicon);
self.favicon = Some(icon);
}
self
}
/// Añade una hoja de estilos CSS al documento.
pub fn add_stylesheet(&mut self, css: StyleSheet) -> &mut Self {
// Stylesheets.
ContextOp::AddStyleSheet(css) => {
self.stylesheets.add(css);
self
}
/// Elimina una hoja de estilos por su ruta o identificador.
pub fn remove_stylesheet(&mut self, name: impl AsRef<str>) -> &mut Self {
self.stylesheets.remove(name);
self
ContextOp::RemoveStyleSheet(path) => {
self.stylesheets.remove(path);
}
/// Añade un *script* JavaScript al documento.
pub fn add_javascript(&mut self, js: JavaScript) -> &mut Self {
// JavaScripts.
ContextOp::AddJavaScript(js) => {
self.javascripts.add(js);
self
}
/// Elimina un *script* por su ruta o identificador.
pub fn remove_javascript(&mut self, name: impl AsRef<str>) -> &mut Self {
self.javascripts.remove(name);
ContextOp::RemoveJavaScript(path) => {
self.javascripts.remove(path);
}
}
self
}
@ -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

View file

@ -0,0 +1 @@
content = Content

View file

@ -0,0 +1 @@
content = Contenido