✨ Serve the PageTop guides with pagetop-mdbook
Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.
Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.
Move the configuration to config/common.toml and translate the README
to English.
This commit is contained in:
parent
e41e71cc78
commit
1a41a456d4
80 changed files with 14112 additions and 1218 deletions
240
doc/v0.6/es/src/how-to/custom-components.md
Normal file
240
doc/v0.6/es/src/how-to/custom-components.md
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
# Crear un componente
|
||||
|
||||
**Objetivo:** convertir un fragmento de interfaz que se repite en un componente propio: con sus
|
||||
datos, sus métodos `with_*()`, su HTML, sus hijos y sus estilos.
|
||||
|
||||
Antes de crear uno, mira el [catálogo de componentes](../reference/components.md): quizá ya existe.
|
||||
|
||||
## 1. El mínimo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
pub struct Notice;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Notice {
|
||||
fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
async fn prepare(&self, _cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! { p class="notice" { "Scheduled maintenance on Sunday." } })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Tres requisitos:
|
||||
|
||||
- **`new()`** crea la instancia; lo habitual es devolver `Self::default()`.
|
||||
- **`prepare()`** devuelve el HTML. Es `async`, así que puede consultar una base de datos o un
|
||||
servicio externo.
|
||||
- **`Clone`** es obligatorio, aunque el compilador no lo exija directamente: sin él, el
|
||||
componente no podría clonarse para cada página.
|
||||
|
||||
Ya puedes usarlo como cualquier otro: `.with_child(Notice::new())`.
|
||||
|
||||
## 2. Datos y métodos `with_*()`
|
||||
|
||||
Lo normal es que un componente tenga datos. La receta de PageTop:
|
||||
|
||||
- Campos **privados**, con `Getters` para leerlos.
|
||||
- `AutoDefault` para los valores por defecto.
|
||||
- Métodos `with_*()` para configurarlo, en un bloque `impl` marcado con `#[builder_impl]`.
|
||||
- Los textos como `Lc`, para que se traduzcan al renderizar.
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Card {
|
||||
/// Returns the title of the card.
|
||||
title: Lc,
|
||||
/// Returns the text of the card.
|
||||
text: Lc,
|
||||
/// Returns the link target, if any.
|
||||
link: Option<Route>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Card {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! {
|
||||
div class="card" {
|
||||
h3 class="card-title" { (self.title().using(cx)) }
|
||||
p class="card-text" { (self.text().using(cx)) }
|
||||
@if let Some(link) = self.link() {
|
||||
a href=(link.resolve(cx)) { "Read more" }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Card {
|
||||
/// Sets the title.
|
||||
pub fn with_title(mut self, title: Lc) -> Self {
|
||||
self.title = title;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the text.
|
||||
pub fn with_text(mut self, text: Lc) -> Self {
|
||||
self.text = text;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the link target.
|
||||
pub fn with_link(mut self, link: impl Into<Option<Route>>) -> Self {
|
||||
self.link = link.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Y se usa así:
|
||||
|
||||
```rust,ignore
|
||||
Card::new()
|
||||
.with_title(Lc::n("Rust"))
|
||||
.with_text(Lc::n("Fast, reliable and productive."))
|
||||
.with_link(Route::from("/rust"))
|
||||
```
|
||||
|
||||
`#[builder_impl]` genera, junto a cada `with_*()`, un método `alter_*()` que modifica la instancia
|
||||
por referencia (`&mut self`). Lo agradecerás cuando un tema o una acción quieran cambiar el
|
||||
componente. Para un método suelto, fuera de un bloque así, existe `#[builder_fn]`.
|
||||
|
||||
## 3. Prepara y pinta
|
||||
|
||||
Cuando una página se renderiza, cada componente pasa por estos pasos, siempre en este orden:
|
||||
|
||||
1. **`is_renderable(cx)`**: ¿se pinta? Si devuelve `false`, el componente desaparece.
|
||||
2. **`setup(&mut self, cx)`**: ajusta su estado antes de pintarse. Es síncrono.
|
||||
3. Las extensiones pueden intervenir con la acción `BeforeRender`.
|
||||
4. El **tema** puede ajustarlo o pintarlo a su manera; si no lo hace, se llama a
|
||||
**`prepare(&self, cx)`**.
|
||||
5. Las extensiones pueden reaccionar (`AfterRender`) o retocar el HTML final
|
||||
(`TransformMarkup`).
|
||||
|
||||
Un ejemplo con los tres métodos propios:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Counter {
|
||||
/// Returns the number of notices.
|
||||
#[getters(copy)]
|
||||
notices: u32,
|
||||
/// Returns the computed CSS classes.
|
||||
classes: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Counter {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
// Nothing is rendered without notices.
|
||||
fn is_renderable(&self, _cx: &Context) -> bool {
|
||||
self.notices() > 0
|
||||
}
|
||||
|
||||
// Computes the classes from the state, before rendering.
|
||||
fn setup(&mut self, _cx: &mut Context) {
|
||||
self.classes = if self.notices > 9 { "counter counter-full" } else { "counter" }.into();
|
||||
}
|
||||
|
||||
async fn prepare(&self, _cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! { span class=(self.classes()) { (self.notices()) } })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
La regla de oro: **`setup()` prepara, `prepare()` pinta**. Las consultas a la base de datos y
|
||||
cualquier operación de entrada/salida van en `prepare()`, que es el único paso asíncrono.
|
||||
|
||||
## 4. Componentes que contienen componentes
|
||||
|
||||
Para aceptar hijos, guarda un `Children` y renderízalo dentro de `prepare()`:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Panel {
|
||||
/// Returns the child components.
|
||||
children: Children,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Panel {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! {
|
||||
div class="panel" { (self.children().render(cx).await) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Panel {
|
||||
/// Adds a child component.
|
||||
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
|
||||
self.children.alter_child(op.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Consejo:** nunca guardes `Markup` ya generado en un campo. Guarda el dato en bruto (`Lc`,
|
||||
> otro componente...) y conviértelo en HTML en `prepare()`. Así el componente se adapta al idioma
|
||||
> y al tema de cada petición.
|
||||
|
||||
## 5. Sus propios estilos
|
||||
|
||||
Un componente puede traer su hoja de estilos o su *script*. Los añade al contexto al renderizarse,
|
||||
así que sólo se cargan en las páginas que lo usan, y una sola vez aunque aparezca muchas veces:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(AutoDefault, Clone, Debug)]
|
||||
# pub struct Card;
|
||||
#[async_trait]
|
||||
impl Component for Card {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
cx.alter_assets(StyleSheet::from("/static/css/card.css").with_version("1.0"));
|
||||
Ok(html! { div class="card" { "..." } })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Cómo publicar ese archivo se explica en [Servir recursos estáticos](assets.md). Usa clases propias
|
||||
con el prefijo del componente (`card-title`, `card-text`...) para no chocar con las del tema.
|
||||
|
||||
## Comprueba
|
||||
|
||||
Usa el componente en una página y renderízala: si te falta `Clone` o un método obligatorio, no
|
||||
compila. Para comprobar su HTML sin servidor, mira [Probar rutas y
|
||||
componentes](testing.md#3-prueba-un-componente-suelto).
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Componentes, temas y renderizado](../explanation/rendering.md): el ciclo completo, con las
|
||||
acciones y el tema.
|
||||
- [Intervenir con acciones](actions.md): cómo otra extensión puede retocar tu componente.
|
||||
Loading…
Add table
Add a link
Reference in a new issue