✨ 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:
Manuel Cillero 2026-10-17 08:06:02 +02:00
parent e41e71cc78
commit 1a41a456d4
80 changed files with 14112 additions and 1218 deletions

View file

@ -0,0 +1,177 @@
# Actualizar periódicamente
**Objetivo:** que una parte de la página se refresque sola cada pocos segundos (el progreso de una
tarea larga, un contador, el estado de un servicio) y que deje de hacerlo cuando ya no haga falta.
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
## 1. Sondear cada pocos segundos
Con `hx-trigger="every 2s"`, el elemento repite su petición cada dos segundos mientras siga en la
página:
```rust,no_run
# use pagetop::prelude::*;
# fn f() -> Html {
Html::with(|_| html! {
div hx-get="/sensors" hx-trigger="every 2s" {
p { "Reading the sensors..." }
}
})
# }
```
La ruta devuelve el contenido actualizado y HTMX lo pone dentro del `div`. Es la forma más
sencilla de mantener un dato al día, sin conexiones permanentes ni JavaScript.
## 2. Parar cuando termina
Para el progreso de una tarea, el sondeo debe acabar cuando la tarea acaba. El truco es que **cada
respuesta decide si sigue el sondeo**: el fragmento sustituye al elemento entero (`outerHTML`) y
sólo lleva `hx-trigger` mientras la tarea no ha terminado.
```rust,no_run
# use pagetop::prelude::*;
fn progress(percent: u64) -> Markup {
if percent < 100 {
html! {
div id="watering" hx-get="/watering" hx-trigger="every 1s" hx-swap="outerHTML" {
progress value=(percent) max="100" {}
" " (percent) "%"
}
}
} else {
html! {
div id="watering" {
p { "Watering finished." }
button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
"Water again"
}
}
}
}
}
```
Cuando llega la versión final, sin `hx-trigger`, ya no queda nada que sondee.
Si prefieres no sustituir el elemento, hay otra forma de parar: responder con el código de estado
**286**. HTMX lo interpreta como «deja de sondear».
## 3. Arrancar la tarea
Un botón inicia la tarea con un `POST`; la respuesta es el primer fragmento de progreso, que ya
sondea por su cuenta:
```rust,no_run
# use pagetop::prelude::*;
# use std::sync::Mutex;
# use std::time::Instant;
# static STARTED: Mutex<Option<Instant>> = Mutex::new(None);
# fn progress(_: u64) -> Markup { html! {} }
# fn started() -> std::sync::MutexGuard<'static, Option<Instant>> { STARTED.lock().unwrap() }
async fn start() -> Markup {
*started() = Some(Instant::now());
progress(0)
}
```
En una aplicación real, `start` lanzaría el trabajo en segundo plano y guardaría su estado; la ruta
del sondeo sólo lo consulta. Aquí, para no depender de nada, el progreso se calcula a partir del
tiempo transcurrido.
## El ejemplo completo
```rust,no_run
use pagetop::prelude::*;
use std::sync::{Mutex, MutexGuard};
use std::time::Instant;
// Seconds that the simulated watering lasts.
const DURATION: u64 = 5;
static STARTED: Mutex<Option<Instant>> = Mutex::new(None);
fn started() -> MutexGuard<'static, Option<Instant>> {
STARTED.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
struct Watering;
#[async_trait]
impl Extension for Watering {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_htmx::Htmx]
}
fn configure_router(&self, router: Router) -> Router {
router
.route("/", web::get(home))
.route("/watering", web::get(status).post(start))
}
}
fn progress(percent: u64) -> Markup {
if percent < 100 {
html! {
div id="watering" hx-get="/watering" hx-trigger="every 1s" hx-swap="outerHTML" {
progress value=(percent) max="100" {}
" " (percent) "%"
}
}
} else {
html! {
div id="watering" {
p { "Watering finished." }
button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
"Water again"
}
}
}
}
}
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
Page::new(request)
.with_title(Lc::n("Watering"))
.with_child(Html::with(|_| html! {
h1 { "Watering" }
div id="watering" {
button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
"Start watering"
}
}
}))
.render()
.await
}
async fn start() -> Markup {
*started() = Some(Instant::now());
progress(0)
}
async fn status() -> Markup {
let elapsed = started().map_or(DURATION, |since| since.elapsed().as_secs());
progress((elapsed * 100 / DURATION).min(100))
}
#[pagetop::main]
async fn main() -> std::io::Result<()> {
Application::prepare(&Watering).await.run().await
}
```
## Comprueba
1. Pulsa *Start watering*: aparece una barra que avanza cada segundo.
2. A los cinco segundos, la barra da paso a «Watering finished.». En la pestaña *Red*, las
peticiones a `/watering` se detienen.
3. *Water again* vuelve a empezar.
## Siguiente
- [Dirigir al navegador desde el servidor](htmx-responses.md): avisar a otras partes de la página
cuando algo termina.
- [Cargar contenido bajo demanda](htmx-load.md).