♻️ Cambia en prepare_component() el tipo devuelto
Elimina `PrepareMarkup` como tipo de retorno de prepare_component() y de
`FnPrepareRender`, sustituyéndolo directamente por `Markup`. Se elimina
una capa innecesaria, ya que html! {} y html! { ... } cubren todos los
casos que ofrecía `PrepareMarkup`.
This commit is contained in:
parent
a5ee0fecb1
commit
3e1bc0fb0e
28 changed files with 241 additions and 335 deletions
|
|
@ -6,7 +6,7 @@ use crate::prelude::*;
|
|||
/// los componentes.
|
||||
///
|
||||
/// Recibe una referencia al componente `component` y una referencia mutable al contexto `cx`.
|
||||
pub type FnPrepareRender<C> = fn(component: &C, cx: &mut Context) -> PrepareMarkup;
|
||||
pub type FnPrepareRender<C> = fn(component: &C, cx: &mut Context) -> Markup;
|
||||
|
||||
/// Ejecuta [`FnPrepareRender`] para preparar el renderizado de un componente.
|
||||
///
|
||||
|
|
@ -43,8 +43,8 @@ impl<C: Component> PrepareRender<C> {
|
|||
|
||||
/// Despacha las acciones. Se detiene en cuanto una renderiza.
|
||||
#[inline]
|
||||
pub(crate) fn dispatch(component: &C, cx: &mut Context) -> PrepareMarkup {
|
||||
let mut render_component = PrepareMarkup::None;
|
||||
pub(crate) fn dispatch(component: &C, cx: &mut Context) -> Markup {
|
||||
let mut render_component = html! {};
|
||||
dispatch_actions(
|
||||
&ActionKey::new(
|
||||
UniqueId::of::<Self>(),
|
||||
|
|
|
|||
|
|
@ -29,23 +29,23 @@ impl Component for Block {
|
|||
self.alter_classes(ClassesOp::Prepend, "block");
|
||||
}
|
||||
|
||||
fn prepare_component(&self, cx: &mut Context) -> PrepareMarkup {
|
||||
fn prepare_component(&self, cx: &mut Context) -> Markup {
|
||||
let block_body = self.children().render(cx);
|
||||
|
||||
if block_body.is_empty() {
|
||||
return PrepareMarkup::None;
|
||||
return html! {};
|
||||
}
|
||||
|
||||
let id = cx.required_id::<Block>(self.id());
|
||||
|
||||
PrepareMarkup::With(html! {
|
||||
html! {
|
||||
div id=(id) class=[self.classes().get()] {
|
||||
@if let Some(title) = self.title().lookup(cx) {
|
||||
h2 class="block__title" { span { (title) } }
|
||||
}
|
||||
div class="block__body" { (block_body) }
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -42,8 +42,8 @@ impl Component for Html {
|
|||
Self::default()
|
||||
}
|
||||
|
||||
fn prepare_component(&self, cx: &mut Context) -> PrepareMarkup {
|
||||
PrepareMarkup::With(self.html(cx))
|
||||
fn prepare_component(&self, cx: &mut Context) -> Markup {
|
||||
self.html(cx)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -115,7 +115,7 @@ impl Component for Intro {
|
|||
));
|
||||
}
|
||||
|
||||
fn prepare_component(&self, cx: &mut Context) -> PrepareMarkup {
|
||||
fn prepare_component(&self, cx: &mut Context) -> Markup {
|
||||
if *self.opening() == IntroOpening::PageTop {
|
||||
cx.alter_assets(ContextOp::AddJavaScript(JavaScript::on_load_async("intro-js", |cx|
|
||||
util::indoc!(r#"
|
||||
|
|
@ -135,7 +135,7 @@ impl Component for Intro {
|
|||
)));
|
||||
}
|
||||
|
||||
PrepareMarkup::With(html! {
|
||||
html! {
|
||||
div class="intro" {
|
||||
div class="intro-header" {
|
||||
section class="intro-header__body" {
|
||||
|
|
@ -206,7 +206,7 @@ impl Component for Intro {
|
|||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ impl Component for PoweredBy {
|
|||
PoweredBy { copyright: Some(c) }
|
||||
}
|
||||
|
||||
fn prepare_component(&self, cx: &mut Context) -> PrepareMarkup {
|
||||
PrepareMarkup::With(html! {
|
||||
fn prepare_component(&self, cx: &mut Context) -> Markup {
|
||||
html! {
|
||||
div id=[self.id()] class="poweredby" {
|
||||
@if let Some(c) = self.copyright() {
|
||||
span class="poweredby__copyright" { (c) "." } " "
|
||||
|
|
@ -35,7 +35,7 @@ impl Component for PoweredBy {
|
|||
(L10n::l("poweredby_pagetop").with_arg("pagetop_link", LINK).using(cx))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ pub use all::dispatch_actions;
|
|||
/// impl Theme for MyTheme {}
|
||||
///
|
||||
/// fn before_render_button(c: &mut Button, cx: &mut Context) { todo!() }
|
||||
/// fn render_error404(c: &Error404, cx: &mut Context) -> PrepareMarkup { todo!() }
|
||||
/// fn render_error404(c: &Error404, cx: &mut Context) -> Markup { todo!() }
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! actions_boxed {
|
||||
|
|
|
|||
|
|
@ -38,8 +38,8 @@ pub use context::{Context, ContextError, ContextOp, Contextual};
|
|||
/// self.renderable.map_or(true, |f| f(cx))
|
||||
/// }
|
||||
///
|
||||
/// fn prepare_component(&self, _cx: &mut Context) -> PrepareMarkup {
|
||||
/// PrepareMarkup::Escaped("Visible component".into())
|
||||
/// fn prepare_component(&self, _cx: &mut Context) -> Markup {
|
||||
/// html! { "Visible component" }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ use crate::{builder_fn, util, CowStr};
|
|||
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Operaciones para modificar recursos asociados al [`Context`] de un documento.
|
||||
pub enum ContextOp {
|
||||
|
|
@ -45,6 +46,26 @@ pub enum ContextError {
|
|||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for ContextError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ContextError::ParamNotFound => {
|
||||
write!(f, "parameter not found")
|
||||
}
|
||||
ContextError::ParamTypeMismatch {
|
||||
key,
|
||||
expected,
|
||||
saved,
|
||||
} => write!(
|
||||
f,
|
||||
"type mismatch for parameter \"{key}\": expected \"{expected}\", found \"{saved}\""
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ContextError {}
|
||||
|
||||
/// Interfaz para gestionar el **contexto de renderizado** de un documento HTML.
|
||||
///
|
||||
/// `Contextual` extiende [`LangId`] para establecer el idioma del documento y añade métodos para:
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::base::action;
|
||||
use crate::core::component::Context;
|
||||
use crate::core::{AnyInfo, TypeInfo};
|
||||
use crate::html::{html, Markup, PrepareMarkup};
|
||||
use crate::html::{html, Markup};
|
||||
|
||||
/// Define la función de renderizado para todos los componentes.
|
||||
///
|
||||
|
|
@ -77,10 +77,10 @@ pub trait Component: AnyInfo + ComponentRender + Send + Sync {
|
|||
/// los campos de la estructura del componente. Es una forma de garantizar que los programadores
|
||||
/// podrán sobrescribir este método sin preocuparse por los detalles internos del componente.
|
||||
///
|
||||
/// Por defecto, devuelve [`PrepareMarkup::None`].
|
||||
/// Por defecto, devuelve un [`Markup`] vacío (`html! {}`).
|
||||
#[allow(unused_variables)]
|
||||
fn prepare_component(&self, cx: &mut Context) -> PrepareMarkup {
|
||||
PrepareMarkup::None
|
||||
fn prepare_component(&self, cx: &mut Context) -> Markup {
|
||||
html! {}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -137,6 +137,6 @@ impl<C: Component> ComponentRender for C {
|
|||
action::component::AfterRender::dispatch(self, cx);
|
||||
|
||||
// Devuelve el marcado final.
|
||||
prepare.render()
|
||||
prepare
|
||||
}
|
||||
}
|
||||
|
|
|
|||
80
src/html.rs
80
src/html.rs
|
|
@ -1,7 +1,5 @@
|
|||
//! HTML en código.
|
||||
|
||||
use crate::AutoDefault;
|
||||
|
||||
mod maud;
|
||||
pub use maud::{display, html, html_private, Escaper, Markup, PreEscaped, DOCTYPE};
|
||||
|
||||
|
|
@ -29,81 +27,3 @@ pub use classes::{Classes, ClassesOp};
|
|||
|
||||
mod unit;
|
||||
pub use unit::UnitValue;
|
||||
|
||||
// **< HTML PrepareMarkup >*************************************************************************
|
||||
|
||||
/// Prepara contenido HTML para su conversión a [`Markup`].
|
||||
///
|
||||
/// Este tipo encapsula distintos orígenes de contenido HTML (texto plano, HTML sin escapar o
|
||||
/// fragmentos ya procesados) para renderizarlos de forma homogénea en plantillas, sin interferir
|
||||
/// con el uso estándar de [`Markup`].
|
||||
///
|
||||
/// # Ejemplo
|
||||
///
|
||||
/// ```rust
|
||||
/// # use pagetop::prelude::*;
|
||||
/// // Texto normal, se escapa automáticamente para evitar inyección de HTML.
|
||||
/// let fragment = PrepareMarkup::Escaped("Hola <b>mundo</b>".to_string());
|
||||
/// assert_eq!(fragment.into_string(), "Hola <b>mundo</b>");
|
||||
///
|
||||
/// // HTML literal, se inserta directamente, sin escapado adicional.
|
||||
/// let raw_html = PrepareMarkup::Raw("<b>negrita</b>".to_string());
|
||||
/// assert_eq!(raw_html.into_string(), "<b>negrita</b>");
|
||||
///
|
||||
/// // Fragmento ya preparado con la macro `html!`.
|
||||
/// let prepared = PrepareMarkup::With(html! {
|
||||
/// h2 { "Título de ejemplo" }
|
||||
/// p { "Este es un párrafo con contenido dinámico." }
|
||||
/// });
|
||||
/// assert_eq!(
|
||||
/// prepared.into_string(),
|
||||
/// "<h2>Título de ejemplo</h2><p>Este es un párrafo con contenido dinámico.</p>"
|
||||
/// );
|
||||
/// ```
|
||||
#[derive(AutoDefault, Clone)]
|
||||
pub enum PrepareMarkup {
|
||||
/// No se genera contenido HTML (equivale a `html! {}`).
|
||||
#[default]
|
||||
None,
|
||||
/// Texto plano que se **escapará automáticamente** para que no sea interpretado como HTML.
|
||||
///
|
||||
/// Úsalo con textos que provengan de usuarios u otras fuentes externas para garantizar la
|
||||
/// seguridad contra inyección de código.
|
||||
Escaped(String),
|
||||
/// HTML literal que se inserta **sin escapado adicional**.
|
||||
///
|
||||
/// Úsalo únicamente para contenido generado de forma confiable o controlada, ya que cualquier
|
||||
/// etiqueta o script incluido será renderizado directamente en el documento.
|
||||
Raw(String),
|
||||
/// Fragmento HTML ya preparado como [`Markup`], listo para insertarse directamente.
|
||||
///
|
||||
/// Normalmente proviene de expresiones `html! { ... }`.
|
||||
With(Markup),
|
||||
}
|
||||
|
||||
impl PrepareMarkup {
|
||||
/// Devuelve `true` si el contenido está vacío y no generará HTML al renderizar.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
PrepareMarkup::None => true,
|
||||
PrepareMarkup::Escaped(text) => text.is_empty(),
|
||||
PrepareMarkup::Raw(string) => string.is_empty(),
|
||||
PrepareMarkup::With(markup) => markup.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convierte el contenido en una cadena HTML renderizada. Usar sólo para pruebas o depuración.
|
||||
pub fn into_string(&self) -> String {
|
||||
self.render().into_string()
|
||||
}
|
||||
|
||||
/// Integra el renderizado fácilmente en la macro [`html!`].
|
||||
pub(crate) fn render(&self) -> Markup {
|
||||
match self {
|
||||
PrepareMarkup::None => html! {},
|
||||
PrepareMarkup::Escaped(text) => html! { (text) },
|
||||
PrepareMarkup::Raw(string) => html! { (PreEscaped(string)) },
|
||||
PrepareMarkup::With(markup) => html! { (markup) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ use crate::AutoDefault;
|
|||
///
|
||||
/// ```rust
|
||||
/// # use pagetop::prelude::*;
|
||||
/// fn render_logo(cx: &mut Context) -> PrepareMarkup {
|
||||
/// PrepareMarkup::With(html! {
|
||||
/// fn render_logo(cx: &mut Context) -> Markup {
|
||||
/// html! {
|
||||
/// div class="logo_color" {
|
||||
/// (PageTopSvg::Color.render(cx))
|
||||
/// }
|
||||
|
|
@ -23,7 +23,7 @@ use crate::AutoDefault;
|
|||
/// div class="line_red" {
|
||||
/// (PageTopSvg::LineRGB(255, 0, 0).render(cx))
|
||||
/// }
|
||||
/// })
|
||||
/// }
|
||||
/// };
|
||||
/// ```
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue