(pagetop): Mejora API y doc. de Children

- `From<T: Component> for ChildOp: with_child()` acepta componentes
  directamente sin envolverlos en `Child::with(...)`.
- `From<Child> for ChildOp` para completar las conversiones implícitas.
- Actualiza ejemplos y tests con la nueva API en bootsier y aliner.
This commit is contained in:
Manuel Cillero 2026-03-29 11:54:20 +02:00
parent cd9454a729
commit d10d546418
27 changed files with 346 additions and 313 deletions

View file

@ -73,17 +73,11 @@ impl Block {
self
}
/// Añade un nuevo componente hijo al bloque.
#[inline]
pub fn add_child(mut self, component: impl Component) -> Self {
self.children.add(Child::with(component));
self
}
/// Modifica la lista de componentes (`children`) aplicando una operación [`ChildOp`].
/// Añade un nuevo componente al bloque o modifica la lista de componentes (`children`) con una
/// operación [`ChildOp`].
#[builder_fn]
pub fn with_child(mut self, op: ChildOp) -> Self {
self.children.alter_child(op);
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into());
self
}
}

View file

@ -65,10 +65,10 @@ pub enum IntroOpening {
/// ```rust
/// # use pagetop::prelude::*;
/// let intro = Intro::default()
/// .add_child(
/// .with_child(
/// Block::new()
/// .with_title(L10n::l("intro_custom_block_title"))
/// .add_child(Html::with(move |cx| {
/// .with_child(Html::with(move |cx| {
/// html! {
/// p { (L10n::l("intro_custom_paragraph_1").using(cx)) }
/// p { (L10n::l("intro_custom_paragraph_2").using(cx)) }
@ -277,19 +277,13 @@ impl Intro {
self
}
/// Añade un nuevo componente hijo a la intro.
/// Añade un nuevo componente a la intro o modifica la lista de componentes (`children`) con una
/// operación [`ChildOp`].
///
/// Si es un bloque ([`Block`]) aplica estilos específicos para destacarlo.
#[inline]
pub fn add_child(mut self, component: impl Component) -> Self {
self.children.add(Child::with(component));
self
}
/// Modifica la lista de componentes (`children`) aplicando una operación [`ChildOp`].
/// Si se añade un bloque ([`Block`]) se aplicarán estilos específicos para destacarlo.
#[builder_fn]
pub fn with_child(mut self, op: ChildOp) -> Self {
self.children.alter_child(op);
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.children.alter_child(op.into());
self
}
}

View file

@ -30,22 +30,22 @@ async fn home(request: HttpRequest) -> ResultPage<Markup, ErrorPage> {
Page::new(request)
.with_title(L10n::l("welcome_title"))
.add_child(
.with_child(
Intro::new()
.add_child(
.with_child(
Block::new()
.with_title(L10n::l("welcome_status_title"))
.add_child(Html::with(move |cx| {
.with_child(Html::with(move |cx| {
html! {
p { (L10n::l("welcome_status_1").using(cx)) }
p { (L10n::l("welcome_status_2").using(cx)) }
}
})),
)
.add_child(
.with_child(
Block::new()
.with_title(L10n::l("welcome_support_title"))
.add_child(Html::with(move |cx| {
.with_child(Html::with(move |cx| {
html! {
p { (L10n::l("welcome_support_1").using(cx)) }
p { (L10n::l("welcome_support_2").with_arg("app", app).using(cx)) }

View file

@ -24,7 +24,7 @@ impl Theme for Basic {
))
.alter_child_in(
&DefaultRegion::Footer,
ChildOp::AddIfEmpty(Child::with(PoweredBy::new())),
ChildOp::AddIfEmpty(PoweredBy::new().into()),
);
}
}

View file

@ -9,10 +9,9 @@ mod definition;
pub use definition::{Component, ComponentClone, ComponentRender};
mod children;
pub use children::Slot;
pub use children::Children;
pub use children::ComponentGuard;
pub use children::{Child, ChildOp};
pub use children::{Child, ChildOp, Slot};
mod message;
pub use message::{MessageLevel, StatusMessage};

View file

@ -75,9 +75,9 @@ impl<C: Component + 'static> From<Slot<C>> for Child {
/// Útil cuando se tiene un [`Slot`] y se necesita añadirlo a una lista [`Children`]:
///
/// ```rust,ignore
/// children.add(Child::from(my_slot));
/// children.with_child(Child::from(my_slot));
/// // o equivalentemente:
/// children.add(my_slot.into());
/// children.with_child(my_slot.into());
/// ```
fn from(typed: Slot<C>) -> Self {
if let Some(m) = typed.0 {
@ -97,16 +97,33 @@ impl<T: Component + 'static> From<T> for Child {
}
}
impl<T: Component + 'static> From<T> for ChildOp {
/// Convierte un componente en [`ChildOp::Add`], permitiendo pasar componentes directamente a
/// métodos como [`Children::with_child`] sin envolverlos explícitamente.
#[inline]
fn from(component: T) -> Self {
ChildOp::Add(Child::with(component))
}
}
impl From<Child> for ChildOp {
/// Convierte un [`Child`] en [`ChildOp::Add`].
#[inline]
fn from(child: Child) -> Self {
ChildOp::Add(child)
}
}
// *************************************************************************************************
/// Variante tipada de [`Child`] para componentes con un tipo concreto conocido.
/// Contenedor tipado para un *único* componente de un tipo concreto conocido.
///
/// A diferencia de [`Child`], que encapsula cualquier componente como `dyn Component`, `Slot`
/// mantiene el tipo concreto `C` y permite acceder directamente a sus métodos específicos a través
/// de [`get()`](Slot::get).
///
/// Se utiliza habitualmente para incrustar un componente dentro de otro cuando no se necesita una
/// lista completa de hijos ([`Children`]), sino un único componente tipado en un campo concreto.
/// Se usa habitualmente para incluir un componente dentro de otro cuando no se necesita una lista
/// completa de hijos ([`Children`]), sino un único componente tipado en un campo concreto.
#[derive(AutoDefault)]
pub struct Slot<C: Component>(Option<Mutex<C>>);
@ -194,23 +211,59 @@ impl<C: Component> Slot<C> {
/// Operaciones para componentes hijo [`Child`] en una lista [`Children`].
pub enum ChildOp {
/// Añade un hijo al final de la lista.
Add(Child),
/// Añade un hijo solo si la lista está vacía.
AddIfEmpty(Child),
/// Añade varios hijos al final de la lista, en el orden recibido.
AddMany(Vec<Child>),
/// Inserta un hijo justo después del componente con el `id` dado, o al final si no existe.
InsertAfterId(&'static str, Child),
/// Inserta un hijo justo antes del componente con el `id` dado, o al principio si no existe.
InsertBeforeId(&'static str, Child),
/// Inserta un hijo al principio de la lista.
Prepend(Child),
/// Inserta varios hijos al principio de la lista, manteniendo el orden recibido.
PrependMany(Vec<Child>),
/// Elimina el primer hijo con el `id` dado.
RemoveById(&'static str),
/// Sustituye el primer hijo con el `id` dado por otro componente.
ReplaceById(&'static str, Child),
/// Vacía la lista eliminando todos los hijos.
Reset,
}
/// Lista ordenada de componentes hijo ([`Child`]) mantenida por un componente padre.
///
/// Esta lista permite añadir, modificar, renderizar y consultar componentes hijo en orden de
/// inserción, soportando operaciones avanzadas como inserción relativa o reemplazo por
/// identificador.
/// Permite añadir, modificar, renderizar y consultar componentes hijo en orden de inserción, con
/// soporte para operaciones avanzadas como inserción relativa o reemplazo por identificador a
/// través de [`ChildOp`].
///
/// Los tipos que completan este sistema son:
///
/// - [`Child`]: representa un componente hijo encapsulado dentro de la lista. Almacena cualquier
/// componente sin necesidad de conocer su tipo concreto.
/// - [`Slot<C>`]: contenedor tipado para un *único* componente de tipo `C`. Preferible a `Children`
/// cuando el padre solo necesita un componente y quiere acceso directo a los métodos de `C`.
/// - [`ChildOp`]: operaciones disponibles sobre la lista. Cuando se necesita algo más que añadir al
/// final, se construye la variante adecuada y se pasa a [`with_child`](Self::with_child).
/// - [`ComponentGuard`]: devuelto por [`Slot::get`] para garantizar acceso exclusivo al componente
/// tipado. Mientras está activo bloquea cualquier otro acceso por lo que conviene liberarlo
/// cuanto antes.
///
/// # Conversiones implícitas
///
/// Cualquier componente implementa `Into<ChildOp>` (equivalente a `ChildOp::Add`) e `Into<Child>`.
/// Gracias a esto, [`with_child`](Self::with_child) acepta un componente directamente o cualquier
/// variante de [`ChildOp`]:
///
/// ```rust,ignore
/// // Añadir al final de la lista (implícito):
/// children.with_child(MiComponente::new());
///
/// // Operación explícita:
/// children.with_child(ChildOp::Prepend(MiComponente::new().into()));
/// ```
#[derive(AutoDefault, Clone, Debug)]
pub struct Children(Vec<Child>);
@ -222,15 +275,15 @@ impl Children {
/// Crea una lista con un componente hijo inicial.
pub fn with(child: Child) -> Self {
Self::default().with_child(ChildOp::Add(child))
Self::default().with_child(child)
}
// **< Children BUILDER >***********************************************************************
/// Ejecuta una operación con [`ChildOp`] en la lista.
/// Añade un componente hijo o aplica una operación [`ChildOp`] sobre la lista.
#[builder_fn]
pub fn with_child(mut self, op: ChildOp) -> Self {
match op {
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
match op.into() {
ChildOp::Add(any) => self.add(any),
ChildOp::AddIfEmpty(any) => self.add_if_empty(any),
ChildOp::AddMany(many) => self.add_many(many),
@ -245,17 +298,15 @@ impl Children {
}
/// Añade un componente hijo al final de la lista.
///
/// Es un atajo para `children.alter_child(ChildOp::Add(child))`.
#[inline]
pub fn add(&mut self, child: Child) -> &mut Self {
pub(crate) fn add(&mut self, child: Child) -> &mut Self {
self.0.push(child);
self
}
/// Añade un componente hijo en la lista sólo si está vacía.
#[inline]
pub fn add_if_empty(&mut self, child: Child) -> &mut Self {
pub(crate) fn add_if_empty(&mut self, child: Child) -> &mut Self {
if self.0.is_empty() {
self.0.push(child);
}
@ -336,7 +387,7 @@ impl Children {
self
}
/// Inserta un hijo al principio de la colección.
/// Inserta un hijo al principio de la lista.
#[inline]
fn prepend(&mut self, child: Child) -> &mut Self {
self.0.insert(0, child);
@ -391,7 +442,7 @@ impl IntoIterator for Children {
/// Consume la estructura `Children`, devolviendo un iterador que consume los elementos.
///
/// # Ejemplo de uso:
/// # Ejemplo
///
/// ```rust,ignore
/// let children = Children::new().with(child1).with(child2);
@ -410,7 +461,7 @@ impl<'a> IntoIterator for &'a Children {
/// Itera sobre una referencia inmutable de `Children`, devolviendo un iterador de referencia.
///
/// # Ejemplo de uso:
/// # Ejemplo
///
/// ```rust,ignore
/// let children = Children::new().with(child1).with(child2);
@ -429,7 +480,7 @@ impl<'a> IntoIterator for &'a mut Children {
/// Itera sobre una referencia mutable de `Children`, devolviendo un iterador mutable.
///
/// # Ejemplo de uso:
/// # Ejemplo
///
/// ```rust,ignore
/// let mut children = Children::new().with(child1).with(child2);

View file

@ -1,6 +1,6 @@
use crate::core::component::{ChildOp, MessageLevel, StatusMessage};
use crate::core::theme::all::DEFAULT_THEME;
use crate::core::theme::{ChildrenInRegions, RegionRef, TemplateRef, ThemeRef};
use crate::core::theme::{ChildrenInRegions, DefaultRegion, RegionRef, TemplateRef, ThemeRef};
use crate::core::TypeInfo;
use crate::html::{html, Markup, RoutePath};
use crate::html::{Assets, Favicon, JavaScript, StyleSheet};
@ -137,9 +137,15 @@ pub trait Contextual: LangId {
#[builder_fn]
fn with_assets(self, op: AssetsOp) -> Self;
/// Opera con [`ChildOp`] en una región del documento.
/// Añade un componente o aplica una operación [`ChildOp`] en la región por defecto del
/// documento.
#[builder_fn]
fn with_child_in(self, region_ref: RegionRef, op: ChildOp) -> Self;
fn with_child(self, op: impl Into<ChildOp>) -> Self;
/// Añade un componente o aplica una operación [`ChildOp`] en una región específica del
/// documento.
#[builder_fn]
fn with_child_in(self, region_ref: RegionRef, op: impl Into<ChildOp>) -> Self;
// **< Contextual GETTERS >*********************************************************************
@ -557,8 +563,15 @@ impl Contextual for Context {
}
#[builder_fn]
fn with_child_in(mut self, region_ref: RegionRef, op: ChildOp) -> Self {
self.regions.alter_child_in(region_ref, op);
fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.regions
.alter_child_in(&DefaultRegion::Content, op.into());
self
}
#[builder_fn]
fn with_child_in(mut self, region_ref: RegionRef, op: impl Into<ChildOp>) -> Self {
self.regions.alter_child_in(region_ref, op.into());
self
}

View file

@ -1,5 +1,5 @@
use crate::base::component::{Html, Intro, IntroOpening};
use crate::core::component::{Child, ChildOp, Component, ComponentError, Context, Contextual};
use crate::core::component::{ChildOp, Component, ComponentError, Context, Contextual};
use crate::core::extension::Extension;
use crate::core::theme::{DefaultRegion, DefaultTemplate, TemplateRef};
use crate::global;
@ -247,14 +247,17 @@ pub trait Theme: Extension + Send + Sync {
.alter_template(&DefaultTemplate::Error)
.alter_child_in(
&DefaultRegion::Content,
ChildOp::Prepend(Child::with(Html::with(move |cx| {
html! {
div {
h1 { (L10n::l("error403_alert").using(cx)) }
p { (L10n::l("error403_help").using(cx)) }
ChildOp::Prepend(
Html::with(move |cx| {
html! {
div {
h1 { (L10n::l("error403_alert").using(cx)) }
p { (L10n::l("error403_help").using(cx)) }
}
}
}
}))),
})
.into(),
),
);
}
@ -270,14 +273,17 @@ pub trait Theme: Extension + Send + Sync {
.alter_template(&DefaultTemplate::Error)
.alter_child_in(
&DefaultRegion::Content,
ChildOp::Prepend(Child::with(Html::with(move |cx| {
html! {
div {
h1 { (L10n::l("error404_alert").using(cx)) }
p { (L10n::l("error404_help").using(cx)) }
ChildOp::Prepend(
Html::with(move |cx| {
html! {
div {
h1 { (L10n::l("error404_alert").using(cx)) }
p { (L10n::l("error404_help").using(cx)) }
}
}
}
}))),
})
.into(),
),
);
}
@ -300,19 +306,20 @@ pub trait Theme: Extension + Send + Sync {
.alter_template(&DefaultTemplate::Error)
.alter_child_in(
&DefaultRegion::Content,
ChildOp::Prepend(Child::with(
ChildOp::Prepend(
Intro::new()
.with_title(L10n::l("error_code").with_arg("code", code.to_string()))
.with_slogan(L10n::n(code.to_string()))
.with_button(None)
.with_opening(IntroOpening::Custom)
.add_child(Html::with(move |cx| {
.with_child(Html::with(move |cx| {
html! {
h1 { (alert.using(cx)) }
p { (help.using(cx)) }
}
})),
)),
}))
.into(),
),
);
}
}

View file

@ -44,16 +44,19 @@ pub(crate) struct ChildrenInRegions(HashMap<String, Children>);
impl ChildrenInRegions {
pub fn with(region_ref: RegionRef, child: Child) -> Self {
Self::default().with_child_in(region_ref, ChildOp::Add(child))
Self::default().with_child_in(region_ref, child)
}
#[builder_fn]
pub fn with_child_in(mut self, region_ref: RegionRef, op: ChildOp) -> Self {
pub fn with_child_in(mut self, region_ref: RegionRef, op: impl Into<ChildOp>) -> Self {
let child = op.into();
if let Some(region) = self.0.get_mut(region_ref.name()) {
region.alter_child(op);
region.alter_child(child);
} else {
self.0
.insert(region_ref.name().to_owned(), Children::new().with_child(op));
self.0.insert(
region_ref.name().to_owned(),
Children::new().with_child(child),
);
}
self
}

View file

@ -60,7 +60,7 @@ impl Extension for HelloWorld {
async fn hello_world(request: HttpRequest) -> ResultPage<Markup, ErrorPage> {
Page::new(request)
.add_child(Html::with(|_| html! { h1 { "Hello World!" } }))
.with_child(Html::with(|_| html! { h1 { "Hello World!" } }))
.render()
}

View file

@ -19,8 +19,7 @@ pub use error::ErrorPage;
pub use actix_web::Result as ResultPage;
use crate::base::action;
use crate::core::component::{AssetsOp, Context, Contextual};
use crate::core::component::{Child, ChildOp, Component};
use crate::core::component::{AssetsOp, ChildOp, Context, Contextual};
use crate::core::theme::{DefaultRegion, Region, RegionRef, TemplateRef, ThemeRef};
use crate::html::{html, Markup, DOCTYPE};
use crate::html::{Assets, Favicon, JavaScript, StyleSheet};
@ -160,22 +159,6 @@ impl Page {
self
}
/// Añade un componente hijo a la región de contenido por defecto.
pub fn add_child(mut self, component: impl Component) -> Self {
self.context.alter_child_in(
&DefaultRegion::Content,
ChildOp::Add(Child::with(component)),
);
self
}
/// Añade un componente hijo en la región `region_name` de la página.
pub fn add_child_in(mut self, region_ref: RegionRef, component: impl Component) -> Self {
self.context
.alter_child_in(region_ref, ChildOp::Add(Child::with(component)));
self
}
// **< Page GETTERS >***************************************************************************
/// Devuelve el título traducido para el idioma de la página, si existe.
@ -340,8 +323,15 @@ impl Contextual for Page {
}
#[builder_fn]
fn with_child_in(mut self, region_ref: RegionRef, op: ChildOp) -> Self {
self.context.alter_child_in(region_ref, op);
fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
self.context
.alter_child_in(&DefaultRegion::Content, op.into());
self
}
#[builder_fn]
fn with_child_in(mut self, region_ref: RegionRef, op: impl Into<ChildOp>) -> Self {
self.context.alter_child_in(region_ref, op.into());
self
}