Compare commits
No commits in common. "website-work-in-progress" and "main" have entirely different histories.
website-wo
...
main
85 changed files with 1208 additions and 16686 deletions
34
.gitignore
vendored
34
.gitignore
vendored
|
|
@ -1,28 +1,10 @@
|
||||||
# Build directories
|
# Ignora directorios de compilación
|
||||||
target/
|
**/target
|
||||||
|
|
||||||
# Log files
|
# Archivos de log
|
||||||
log/
|
**/log/*.log*
|
||||||
|
|
||||||
# Local configuration files
|
# Archivos de configuración locales
|
||||||
.cargo
|
**/local.*.toml
|
||||||
.claude
|
**/local.toml
|
||||||
.vscode
|
.env
|
||||||
config/local.*.toml
|
|
||||||
config/local.toml
|
|
||||||
|
|
||||||
# Books built by mdBook from doc/ (see build.rs)
|
|
||||||
static/
|
|
||||||
|
|
||||||
# System files and work directory
|
|
||||||
.DS_Store
|
|
||||||
Thumbs.db
|
|
||||||
workdir/
|
|
||||||
|
|
||||||
# Note: Cargo.lock is NOT ignored. This project contains binaries, so Cargo.lock
|
|
||||||
# must be versioned for reproducibility.
|
|
||||||
|
|
||||||
# Generated by tools/doccheck.sh
|
|
||||||
tools/doccheck/examples/
|
|
||||||
tools/doccheck/tests/generated_*.rs
|
|
||||||
tools/doccheck/Cargo.lock
|
|
||||||
|
|
|
||||||
1660
Cargo.lock
generated
1660
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
30
Cargo.toml
30
Cargo.toml
|
|
@ -1,33 +1,17 @@
|
||||||
[package]
|
[package]
|
||||||
name = "pagetop-website"
|
name = "pagetop-website"
|
||||||
version = "0.0.1"
|
version = "0.0.1"
|
||||||
edition = "2024"
|
edition = "2021"
|
||||||
description = "Official PageTop website, to introduce this development environment to the community."
|
|
||||||
|
description = """
|
||||||
|
Web oficial de PageTop para introducir este entorno de desarrollo a la comunidad.
|
||||||
|
"""
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
repository = "https://git.cillero.es/manuelcillero/pagetop-website"
|
repository = "https://git.cillero.es/manuelcillero/pagetop-website"
|
||||||
homepage = "https://pagetop.cillero.es"
|
homepage = "https://pagetop.cillero.es"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
authors = ["Manuel Cillero <manuel@cillero.es>"]
|
authors = ["Manuel Cillero <manuel@cillero.es>"]
|
||||||
|
|
||||||
[[bin]]
|
|
||||||
name = "pagetop-website"
|
|
||||||
path = "src/main.rs"
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
pagetop = { path = "../pagetop" }
|
pagetop = { version = "0.1", path = "../pagetop" }
|
||||||
pagetop-bootsier = { path = "../pagetop/extensions/pagetop-bootsier" }
|
|
||||||
pagetop-mdbook = { path = "../pagetop-mdbook" }
|
|
||||||
|
|
||||||
[build-dependencies]
|
|
||||||
pagetop-mdbook = { path = "../pagetop-mdbook" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
opt-level = 0
|
|
||||||
debug = true
|
|
||||||
split-debuginfo = "unpacked"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
opt-level = 3
|
|
||||||
lto = "fat"
|
|
||||||
codegen-units = 1
|
|
||||||
strip = true
|
|
||||||
|
|
|
||||||
137
README.md
137
README.md
|
|
@ -2,134 +2,41 @@
|
||||||
|
|
||||||
<h1>PageTop Website</h1>
|
<h1>PageTop Website</h1>
|
||||||
|
|
||||||
<p>Official website of <strong>PageTop</strong>, to introduce this development environment to the community.</p>
|
<p>Web oficial de <strong>PageTop</strong> para introducir este entorno de desarrollo a la comunidad.</p>
|
||||||
|
|
||||||
[](#license)
|
[](#-licencia)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
## Overview
|
## Descripción general
|
||||||
|
|
||||||
Web application built with [PageTop](https://docs.rs/pagetop) to present its own ecosystem to the
|
Aplicación web creada con `PageTop` para dar a conocer su propio ecosistema a la comunidad,
|
||||||
community, available at [pagetop.cillero.es](https://pagetop.cillero.es). It is the entry point to
|
disponible en [pagetop.cillero.es](https://pagetop.cillero.es). Funciona como portal de entrada con
|
||||||
the PageTop guides for developers and users.
|
documentación completa para desarrolladores y usuarios.
|
||||||
|
|
||||||
The guides are [mdBook](https://rust-lang.github.io/mdBook/) books under `doc/`, one per version and
|
## Sobre PageTop
|
||||||
language (`doc/<version>/<language>/`), all of them with the theme in `doc/theme/`. They are built
|
|
||||||
and embedded into the binary when the application is compiled, and served as PageTop pages with
|
|
||||||
[pagetop-mdbook](https://git.cillero.es/manuelcillero/pagetop-mdbook).
|
|
||||||
|
|
||||||
## Requirements
|
[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web
|
||||||
|
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
||||||
|
configurables, basadas en HTML, CSS y JavaScript.
|
||||||
|
|
||||||
- Rust (edition 2024).
|
|
||||||
- [mdBook](https://rust-lang.github.io/mdBook/) 0.4 on the `PATH`, to build the guides (`cargo
|
|
||||||
install mdbook --version "^0.4"`).
|
|
||||||
- The `pagetop` and `pagetop-mdbook` repositories next to this one, as in the `pagetop-projects`
|
|
||||||
workspace: the dependencies use relative paths.
|
|
||||||
|
|
||||||
## Running
|
# 🚧 Advertencia
|
||||||
|
|
||||||
```sh
|
`PageTop` es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su
|
||||||
cargo run
|
ecosistema. Su API está sujeta a cambios frecuentes. No se recomienda su uso en producción, al menos
|
||||||
```
|
hasta que se libere la versión **1.0.0**.
|
||||||
|
|
||||||
The server listens on `0.0.0.0:8080` by default. Routes:
|
|
||||||
|
|
||||||
| Route | Content |
|
# 📜 Licencia
|
||||||
|-----------------------------|------------------------------------------------------|
|
|
||||||
| `/` | PageTop welcome page |
|
|
||||||
| `/doc/latest/{lang}` | Redirects to the latest guides (Spanish only, by now)|
|
|
||||||
| `/doc/<version>/<lang>/...` | Chapters of the guides |
|
|
||||||
|
|
||||||
The books are built into `static/doc/` (not versioned) only when their sources change. The version
|
El código está disponible bajo una doble licencia:
|
||||||
that `/doc/latest/{lang}` points to, and the languages of the guides, are set in `src/lib.rs`
|
|
||||||
(`LATEST_DOC` and `DOC_LANGUAGES`).
|
|
||||||
|
|
||||||
## Checking the guides
|
* **Licencia MIT**
|
||||||
|
([LICENSE-MIT](LICENSE-MIT) o también https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
The guides document the current PageTop code, so they must be checked again whenever PageTop
|
* **Licencia Apache, Versión 2.0**
|
||||||
changes. `tools/doccheck.sh` does it in one step:
|
([LICENSE-APACHE](LICENSE-APACHE) o también https://www.apache.org/licenses/LICENSE-2.0)
|
||||||
|
|
||||||
```sh
|
Puedes elegir la licencia que prefieras. Este enfoque de doble licencia es el estándar de facto en
|
||||||
tools/doccheck.sh # the latest Spanish guide (doc/v0.6/es)
|
el ecosistema Rust.
|
||||||
tools/doccheck.sh doc/v0.7/es # any other book
|
|
||||||
```
|
|
||||||
|
|
||||||
It needs `mdbook` and `python3`, and the `pagetop` repository next to this one. It runs three
|
|
||||||
checks and ends with exit code 1 if any fails:
|
|
||||||
|
|
||||||
1. **Links.** Builds the book and checks that every internal link points to an existing page and
|
|
||||||
anchor.
|
|
||||||
2. **Examples.** Extracts every ```` ```rust ```` block into `tools/doccheck/examples/`, removing
|
|
||||||
the `# ` prefix of the lines that mdBook hides, and compiles them against PageTop. Blocks not
|
|
||||||
marked `no_run` are also executed, so their `assert!` are checked.
|
|
||||||
3. **Tests.** Blocks with `#[pagetop::test]` become tests, and run with `cargo test` together with
|
|
||||||
the fixed tests in `tools/doccheck/tests/` (for example, `localization.rs` checks the
|
|
||||||
translations of the localization chapter at run time).
|
|
||||||
|
|
||||||
### How the guides are organized
|
|
||||||
|
|
||||||
Each book follows the four kinds of documentation of [Diátaxis](https://diataxis.fr), one folder
|
|
||||||
each:
|
|
||||||
|
|
||||||
| Folder | Kind | Shape of a page |
|
|
||||||
|---|---|---|
|
|
||||||
| `tutorials/` | Learning by doing, in order | Time, prerequisites and result; numbered steps that run; "what you built"; next steps |
|
|
||||||
| `how-to/` | One task | A **goal** line; numbered steps; the complete example; how to check it; next steps |
|
|
||||||
| `reference/` | Looking things up | Tables: options, components, attributes |
|
|
||||||
| `explanation/` | The why | Prose and diagrams, few examples |
|
|
||||||
|
|
||||||
Every page ends linking the next ones to read. The interactive (HTMX) pages end with a complete,
|
|
||||||
runnable example. `doccheck.sh` compiles it, but what happens in the browser is only declared by its
|
|
||||||
`hx-*` attributes: after changing one of them, run it and try it in a browser.
|
|
||||||
|
|
||||||
When writing a chapter:
|
|
||||||
|
|
||||||
- Write the examples **in English**, whatever the language of the guide: identifiers, strings,
|
|
||||||
comments, paths and configuration values. Translating a guide is then only translating its
|
|
||||||
text. Use another language only where the example needs it (such as the Spanish values of an
|
|
||||||
`es-ES` translation file).
|
|
||||||
- Write every example as **complete, compilable code**. Hide the lines the reader does not need
|
|
||||||
(imports, a wrapping function, helper stubs) with a leading `# `; mdBook does not show them.
|
|
||||||
- Use ```` ```rust ```` only for examples that can run with no server (with `assert!`),
|
|
||||||
```` ```rust,no_run ```` for the rest, and ```` ```rust,ignore ```` only for loose fragments
|
|
||||||
that are not valid on their own.
|
|
||||||
- Examples can use `pagetop`, `pagetop-admin`, `pagetop-bootsier`, `pagetop-cron`,
|
|
||||||
`pagetop-htmx`, `pagetop-mail` (with its `queue` feature), `pagetop-seaorm` (with SQLite),
|
|
||||||
`pagetop-user`, `pagetop-build`, `serde`, `thiserror`, `tokio` and `tower-http` (with the
|
|
||||||
`compression-gzip`, `cors`, `limit` and `timeout` features); the translations in
|
|
||||||
`tools/doccheck/src/locale/` (`LOCALES_APP`), and a static files bundle named `app`. If a chapter needs anything else, add it to `tools/doccheck`.
|
|
||||||
- Examples and tests that start an application read `tools/doccheck/config/`: those with a database
|
|
||||||
get a new in-memory SQLite one on every run, mail is kept in memory (`pagetop_mail::outbox`) and
|
|
||||||
uploaded files go to `tools/doccheck/target/doccheck-uploads`.
|
|
||||||
- Tests that share state (a static store, a database) run in the same process: write one test per
|
|
||||||
flow, so that their results do not depend on the order they run in.
|
|
||||||
|
|
||||||
The first run compiles PageTop and takes a few minutes; the next ones only compile the examples.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Settings are loaded in cascade from the `config/` directory (or the one in the `CONFIG_DIR`
|
|
||||||
environment variable): `common.toml`, then `{run_mode}.toml` according to `PAGETOP_RUN_MODE`
|
|
||||||
(`default` by default), `local.{run_mode}.toml` and `local.toml`. The local files are not
|
|
||||||
versioned. Finally, environment variables named `PAGETOP_<SECTION>__<KEY>` override individual
|
|
||||||
keys (e.g. `PAGETOP_SERVER__BIND_PORT=80`).
|
|
||||||
|
|
||||||
## Warning
|
|
||||||
|
|
||||||
**PageTop** is a personal project to learn [Rust](https://www.rust-lang.org/) and its ecosystem. Its
|
|
||||||
API is subject to frequent changes. Production use is not recommended, at least until version
|
|
||||||
**1.0.0** is released.
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
The code is available under a dual license:
|
|
||||||
|
|
||||||
* **MIT License**
|
|
||||||
([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT)
|
|
||||||
|
|
||||||
* **Apache License, Version 2.0**
|
|
||||||
([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0)
|
|
||||||
|
|
||||||
You may choose either license. This dual-license approach is the de facto standard in the Rust
|
|
||||||
ecosystem.
|
|
||||||
|
|
|
||||||
5
build.rs
5
build.rs
|
|
@ -1,5 +0,0 @@
|
||||||
use pagetop_mdbook::build::{MdBookOptions, mdbooks_and_bundle};
|
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
|
||||||
mdbooks_and_bundle(MdBookOptions::new())
|
|
||||||
}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
# Settings common to all environments.
|
|
||||||
#
|
|
||||||
# Load order (all optional):
|
|
||||||
# 1. config/common.toml <- this file
|
|
||||||
# 2. config/{run_mode}.toml <- according to PAGETOP_RUN_MODE (default: "default")
|
|
||||||
# 3. config/local.{run_mode}.toml
|
|
||||||
# 4. config/local.toml <- local overrides, do not track in git
|
|
||||||
#
|
|
||||||
# Finally, environment variables named PAGETOP_<SECTION>__<KEY> override any key of these files,
|
|
||||||
# with each level separated by a double underscore (e.g. PAGETOP_SERVER__BIND_PORT=80). Besides,
|
|
||||||
# PAGETOP_RUN_MODE (see above) and CONFIG_DIR (an alternative to the "config" directory) choose
|
|
||||||
# which files are loaded.
|
|
||||||
|
|
||||||
# **< Application >*********************************************************************************
|
|
||||||
|
|
||||||
[app]
|
|
||||||
name = "PageTop"
|
|
||||||
theme = "Bootsier"
|
|
||||||
# Interface language: "es" (default) or "en".
|
|
||||||
language = "es"
|
|
||||||
|
|
||||||
# **< Theme >***************************************************************************************
|
|
||||||
|
|
||||||
[bootsier]
|
|
||||||
max_width = "1520px"
|
|
||||||
|
|
||||||
# **< Trace logging >*******************************************************************************
|
|
||||||
|
|
||||||
[log]
|
|
||||||
rolling = "Daily"
|
|
||||||
6
config/default.toml
Normal file
6
config/default.toml
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
[app]
|
||||||
|
name = "PageTop"
|
||||||
|
description = "An opinionated web framework to build modular Server-Side Rendering web solutions."
|
||||||
|
|
||||||
|
[log]
|
||||||
|
rolling = "Daily"
|
||||||
655
doc/theme/book.js
vendored
655
doc/theme/book.js
vendored
|
|
@ -1,655 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
// Fix back button cache problem
|
|
||||||
window.onunload = function () { };
|
|
||||||
|
|
||||||
// Global variable, shared between modules
|
|
||||||
function playground_text(playground, hidden = true) {
|
|
||||||
let code_block = playground.querySelector("code");
|
|
||||||
|
|
||||||
if (window.ace && code_block.classList.contains("editable")) {
|
|
||||||
let editor = window.ace.edit(code_block);
|
|
||||||
return editor.getValue();
|
|
||||||
} else if (hidden) {
|
|
||||||
return code_block.textContent;
|
|
||||||
} else {
|
|
||||||
return code_block.innerText;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(function codeSnippets() {
|
|
||||||
function fetch_with_timeout(url, options, timeout = 6000) {
|
|
||||||
return Promise.race([
|
|
||||||
fetch(url, options),
|
|
||||||
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
var playgrounds = Array.from(document.querySelectorAll(".playground"));
|
|
||||||
if (playgrounds.length > 0) {
|
|
||||||
fetch_with_timeout("https://play.rust-lang.org/meta/crates", {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': "application/json",
|
|
||||||
},
|
|
||||||
method: 'POST',
|
|
||||||
mode: 'cors',
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(response => {
|
|
||||||
// get list of crates available in the rust playground
|
|
||||||
let playground_crates = response.crates.map(item => item["id"]);
|
|
||||||
playgrounds.forEach(block => handle_crate_list_update(block, playground_crates));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function handle_crate_list_update(playground_block, playground_crates) {
|
|
||||||
// update the play buttons after receiving the response
|
|
||||||
update_play_button(playground_block, playground_crates);
|
|
||||||
|
|
||||||
// and install on change listener to dynamically update ACE editors
|
|
||||||
if (window.ace) {
|
|
||||||
let code_block = playground_block.querySelector("code");
|
|
||||||
if (code_block.classList.contains("editable")) {
|
|
||||||
let editor = window.ace.edit(code_block);
|
|
||||||
editor.addEventListener("change", function (e) {
|
|
||||||
update_play_button(playground_block, playground_crates);
|
|
||||||
});
|
|
||||||
// add Ctrl-Enter command to execute rust code
|
|
||||||
editor.commands.addCommand({
|
|
||||||
name: "run",
|
|
||||||
bindKey: {
|
|
||||||
win: "Ctrl-Enter",
|
|
||||||
mac: "Ctrl-Enter"
|
|
||||||
},
|
|
||||||
exec: _editor => run_rust_code(playground_block)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// updates the visibility of play button based on `no_run` class and
|
|
||||||
// used crates vs ones available on https://play.rust-lang.org
|
|
||||||
function update_play_button(pre_block, playground_crates) {
|
|
||||||
var play_button = pre_block.querySelector(".play-button");
|
|
||||||
|
|
||||||
// skip if code is `no_run`
|
|
||||||
if (pre_block.querySelector('code').classList.contains("no_run")) {
|
|
||||||
play_button.classList.add("hidden");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// get list of `extern crate`'s from snippet
|
|
||||||
var txt = playground_text(pre_block);
|
|
||||||
var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
|
|
||||||
var snippet_crates = [];
|
|
||||||
var item;
|
|
||||||
while (item = re.exec(txt)) {
|
|
||||||
snippet_crates.push(item[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if all used crates are available on play.rust-lang.org
|
|
||||||
var all_available = snippet_crates.every(function (elem) {
|
|
||||||
return playground_crates.indexOf(elem) > -1;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (all_available) {
|
|
||||||
play_button.classList.remove("hidden");
|
|
||||||
} else {
|
|
||||||
play_button.classList.add("hidden");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function run_rust_code(code_block) {
|
|
||||||
var result_block = code_block.querySelector(".result");
|
|
||||||
if (!result_block) {
|
|
||||||
result_block = document.createElement('code');
|
|
||||||
result_block.className = 'result hljs language-bash';
|
|
||||||
|
|
||||||
code_block.append(result_block);
|
|
||||||
}
|
|
||||||
|
|
||||||
let text = playground_text(code_block);
|
|
||||||
let classes = code_block.querySelector('code').classList;
|
|
||||||
let edition = "2015";
|
|
||||||
if(classes.contains("edition2018")) {
|
|
||||||
edition = "2018";
|
|
||||||
} else if(classes.contains("edition2021")) {
|
|
||||||
edition = "2021";
|
|
||||||
}
|
|
||||||
var params = {
|
|
||||||
version: "stable",
|
|
||||||
optimize: "0",
|
|
||||||
code: text,
|
|
||||||
edition: edition
|
|
||||||
};
|
|
||||||
|
|
||||||
if (text.indexOf("#![feature") !== -1) {
|
|
||||||
params.version = "nightly";
|
|
||||||
}
|
|
||||||
|
|
||||||
result_block.innerText = "Running...";
|
|
||||||
|
|
||||||
fetch_with_timeout("https://play.rust-lang.org/evaluate.json", {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': "application/json",
|
|
||||||
},
|
|
||||||
method: 'POST',
|
|
||||||
mode: 'cors',
|
|
||||||
body: JSON.stringify(params)
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(response => {
|
|
||||||
if (response.result.trim() === '') {
|
|
||||||
result_block.innerText = "No output";
|
|
||||||
result_block.classList.add("result-no-output");
|
|
||||||
} else {
|
|
||||||
result_block.innerText = response.result;
|
|
||||||
result_block.classList.remove("result-no-output");
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(error => result_block.innerText = "Playground Communication: " + error.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Syntax highlighting Configuration
|
|
||||||
hljs.configure({
|
|
||||||
tabReplace: ' ', // 4 spaces
|
|
||||||
languages: [], // Languages used for auto-detection
|
|
||||||
});
|
|
||||||
|
|
||||||
let code_nodes = Array
|
|
||||||
.from(document.querySelectorAll('code'))
|
|
||||||
// Don't highlight `inline code` blocks in headers.
|
|
||||||
.filter(function (node) {return !node.parentElement.classList.contains("header"); });
|
|
||||||
|
|
||||||
if (window.ace) {
|
|
||||||
// language-rust class needs to be removed for editable
|
|
||||||
// blocks or highlightjs will capture events
|
|
||||||
code_nodes
|
|
||||||
.filter(function (node) {return node.classList.contains("editable"); })
|
|
||||||
.forEach(function (block) { block.classList.remove('language-rust'); });
|
|
||||||
|
|
||||||
code_nodes
|
|
||||||
.filter(function (node) {return !node.classList.contains("editable"); })
|
|
||||||
.forEach(function (block) { hljs.highlightBlock(block); });
|
|
||||||
} else {
|
|
||||||
code_nodes.forEach(function (block) { hljs.highlightBlock(block); });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adding the hljs class gives code blocks the color css
|
|
||||||
// even if highlighting doesn't apply
|
|
||||||
code_nodes.forEach(function (block) { block.classList.add('hljs'); });
|
|
||||||
|
|
||||||
Array.from(document.querySelectorAll("code.hljs")).forEach(function (block) {
|
|
||||||
|
|
||||||
var lines = Array.from(block.querySelectorAll('.boring'));
|
|
||||||
// If no lines were hidden, return
|
|
||||||
if (!lines.length) { return; }
|
|
||||||
block.classList.add("hide-boring");
|
|
||||||
|
|
||||||
var buttons = document.createElement('div');
|
|
||||||
buttons.className = 'buttons';
|
|
||||||
buttons.innerHTML = "<button class=\"fa fa-eye\" title=\"Show hidden lines\" aria-label=\"Show hidden lines\"></button>";
|
|
||||||
|
|
||||||
// add expand button
|
|
||||||
var pre_block = block.parentNode;
|
|
||||||
pre_block.insertBefore(buttons, pre_block.firstChild);
|
|
||||||
|
|
||||||
pre_block.querySelector('.buttons').addEventListener('click', function (e) {
|
|
||||||
if (e.target.classList.contains('fa-eye')) {
|
|
||||||
e.target.classList.remove('fa-eye');
|
|
||||||
e.target.classList.add('fa-eye-slash');
|
|
||||||
e.target.title = 'Hide lines';
|
|
||||||
e.target.setAttribute('aria-label', e.target.title);
|
|
||||||
|
|
||||||
block.classList.remove('hide-boring');
|
|
||||||
} else if (e.target.classList.contains('fa-eye-slash')) {
|
|
||||||
e.target.classList.remove('fa-eye-slash');
|
|
||||||
e.target.classList.add('fa-eye');
|
|
||||||
e.target.title = 'Show hidden lines';
|
|
||||||
e.target.setAttribute('aria-label', e.target.title);
|
|
||||||
|
|
||||||
block.classList.add('hide-boring');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
if (window.playground_copyable) {
|
|
||||||
Array.from(document.querySelectorAll('pre code')).forEach(function (block) {
|
|
||||||
var pre_block = block.parentNode;
|
|
||||||
if (!pre_block.classList.contains('playground')) {
|
|
||||||
var buttons = pre_block.querySelector(".buttons");
|
|
||||||
if (!buttons) {
|
|
||||||
buttons = document.createElement('div');
|
|
||||||
buttons.className = 'buttons';
|
|
||||||
pre_block.insertBefore(buttons, pre_block.firstChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
var clipButton = document.createElement('button');
|
|
||||||
clipButton.className = 'fa fa-copy clip-button';
|
|
||||||
clipButton.title = 'Copy to clipboard';
|
|
||||||
clipButton.setAttribute('aria-label', clipButton.title);
|
|
||||||
clipButton.innerHTML = '<i class=\"tooltiptext\"></i>';
|
|
||||||
|
|
||||||
buttons.insertBefore(clipButton, buttons.firstChild);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process playground code blocks
|
|
||||||
Array.from(document.querySelectorAll(".playground")).forEach(function (pre_block) {
|
|
||||||
// Add play button
|
|
||||||
var buttons = pre_block.querySelector(".buttons");
|
|
||||||
if (!buttons) {
|
|
||||||
buttons = document.createElement('div');
|
|
||||||
buttons.className = 'buttons';
|
|
||||||
pre_block.insertBefore(buttons, pre_block.firstChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
var runCodeButton = document.createElement('button');
|
|
||||||
runCodeButton.className = 'fa fa-play play-button';
|
|
||||||
runCodeButton.hidden = true;
|
|
||||||
runCodeButton.title = 'Run this code';
|
|
||||||
runCodeButton.setAttribute('aria-label', runCodeButton.title);
|
|
||||||
|
|
||||||
buttons.insertBefore(runCodeButton, buttons.firstChild);
|
|
||||||
runCodeButton.addEventListener('click', function (e) {
|
|
||||||
run_rust_code(pre_block);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (window.playground_copyable) {
|
|
||||||
var copyCodeClipboardButton = document.createElement('button');
|
|
||||||
copyCodeClipboardButton.className = 'fa fa-copy clip-button';
|
|
||||||
copyCodeClipboardButton.innerHTML = '<i class="tooltiptext"></i>';
|
|
||||||
copyCodeClipboardButton.title = 'Copy to clipboard';
|
|
||||||
copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title);
|
|
||||||
|
|
||||||
buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
let code_block = pre_block.querySelector("code");
|
|
||||||
if (window.ace && code_block.classList.contains("editable")) {
|
|
||||||
var undoChangesButton = document.createElement('button');
|
|
||||||
undoChangesButton.className = 'fa fa-history reset-button';
|
|
||||||
undoChangesButton.title = 'Undo changes';
|
|
||||||
undoChangesButton.setAttribute('aria-label', undoChangesButton.title);
|
|
||||||
|
|
||||||
buttons.insertBefore(undoChangesButton, buttons.firstChild);
|
|
||||||
|
|
||||||
undoChangesButton.addEventListener('click', function () {
|
|
||||||
let editor = window.ace.edit(code_block);
|
|
||||||
editor.setValue(editor.originalCode);
|
|
||||||
editor.clearSelection();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
|
|
||||||
(function themes() {
|
|
||||||
var html = document.querySelector('html');
|
|
||||||
var themeToggleButton = document.getElementById('theme-toggle');
|
|
||||||
var themePopup = document.getElementById('theme-list');
|
|
||||||
var themeColorMetaTag = document.querySelector('meta[name="theme-color"]');
|
|
||||||
var stylesheets = {
|
|
||||||
ayuHighlight: document.querySelector("[href$='ayu-highlight.css']"),
|
|
||||||
tomorrowNight: document.querySelector("[href$='tomorrow-night.css']"),
|
|
||||||
highlight: document.querySelector("[href$='highlight.css']"),
|
|
||||||
};
|
|
||||||
|
|
||||||
function showThemes() {
|
|
||||||
themePopup.style.display = 'block';
|
|
||||||
themeToggleButton.setAttribute('aria-expanded', true);
|
|
||||||
themePopup.querySelector("button#" + get_theme()).focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateThemeSelected() {
|
|
||||||
themePopup.querySelectorAll('.theme-selected').forEach(function (el) {
|
|
||||||
el.classList.remove('theme-selected');
|
|
||||||
});
|
|
||||||
themePopup.querySelector("button#" + get_theme()).classList.add('theme-selected');
|
|
||||||
}
|
|
||||||
|
|
||||||
function hideThemes() {
|
|
||||||
themePopup.style.display = 'none';
|
|
||||||
themeToggleButton.setAttribute('aria-expanded', false);
|
|
||||||
themeToggleButton.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
function get_theme() {
|
|
||||||
var theme;
|
|
||||||
try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { }
|
|
||||||
if (theme === null || theme === undefined) {
|
|
||||||
return default_theme;
|
|
||||||
} else {
|
|
||||||
return theme;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function set_theme(theme, store = true) {
|
|
||||||
let ace_theme;
|
|
||||||
|
|
||||||
if (theme == 'coal' || theme == 'navy') {
|
|
||||||
stylesheets.ayuHighlight.disabled = true;
|
|
||||||
stylesheets.tomorrowNight.disabled = false;
|
|
||||||
stylesheets.highlight.disabled = true;
|
|
||||||
|
|
||||||
ace_theme = "ace/theme/tomorrow_night";
|
|
||||||
} else if (theme == 'ayu') {
|
|
||||||
stylesheets.ayuHighlight.disabled = false;
|
|
||||||
stylesheets.tomorrowNight.disabled = true;
|
|
||||||
stylesheets.highlight.disabled = true;
|
|
||||||
ace_theme = "ace/theme/tomorrow_night";
|
|
||||||
} else {
|
|
||||||
stylesheets.ayuHighlight.disabled = true;
|
|
||||||
stylesheets.tomorrowNight.disabled = true;
|
|
||||||
stylesheets.highlight.disabled = false;
|
|
||||||
ace_theme = "ace/theme/dawn";
|
|
||||||
}
|
|
||||||
|
|
||||||
setTimeout(function () {
|
|
||||||
themeColorMetaTag.content = getComputedStyle(document.documentElement).backgroundColor;
|
|
||||||
}, 1);
|
|
||||||
|
|
||||||
if (window.ace && window.editors) {
|
|
||||||
window.editors.forEach(function (editor) {
|
|
||||||
editor.setTheme(ace_theme);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
var previousTheme = get_theme();
|
|
||||||
|
|
||||||
if (store) {
|
|
||||||
try { localStorage.setItem('mdbook-theme', theme); } catch (e) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
html.classList.remove(previousTheme);
|
|
||||||
html.classList.add(theme);
|
|
||||||
updateThemeSelected();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set theme
|
|
||||||
var theme = get_theme();
|
|
||||||
|
|
||||||
set_theme(theme, false);
|
|
||||||
|
|
||||||
themeToggleButton.addEventListener('click', function () {
|
|
||||||
if (themePopup.style.display === 'block') {
|
|
||||||
hideThemes();
|
|
||||||
} else {
|
|
||||||
showThemes();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
themePopup.addEventListener('click', function (e) {
|
|
||||||
var theme;
|
|
||||||
if (e.target.className === "theme") {
|
|
||||||
theme = e.target.id;
|
|
||||||
} else if (e.target.parentElement.className === "theme") {
|
|
||||||
theme = e.target.parentElement.id;
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
set_theme(theme);
|
|
||||||
});
|
|
||||||
|
|
||||||
themePopup.addEventListener('focusout', function(e) {
|
|
||||||
// e.relatedTarget is null in Safari and Firefox on macOS (see workaround below)
|
|
||||||
if (!!e.relatedTarget && !themeToggleButton.contains(e.relatedTarget) && !themePopup.contains(e.relatedTarget)) {
|
|
||||||
hideThemes();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang/mdBook/issues/628
|
|
||||||
document.addEventListener('click', function(e) {
|
|
||||||
if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) {
|
|
||||||
hideThemes();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener('keydown', function (e) {
|
|
||||||
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
|
|
||||||
if (!themePopup.contains(e.target)) { return; }
|
|
||||||
|
|
||||||
switch (e.key) {
|
|
||||||
case 'Escape':
|
|
||||||
e.preventDefault();
|
|
||||||
hideThemes();
|
|
||||||
break;
|
|
||||||
case 'ArrowUp':
|
|
||||||
e.preventDefault();
|
|
||||||
var li = document.activeElement.parentElement;
|
|
||||||
if (li && li.previousElementSibling) {
|
|
||||||
li.previousElementSibling.querySelector('button').focus();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'ArrowDown':
|
|
||||||
e.preventDefault();
|
|
||||||
var li = document.activeElement.parentElement;
|
|
||||||
if (li && li.nextElementSibling) {
|
|
||||||
li.nextElementSibling.querySelector('button').focus();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'Home':
|
|
||||||
e.preventDefault();
|
|
||||||
themePopup.querySelector('li:first-child button').focus();
|
|
||||||
break;
|
|
||||||
case 'End':
|
|
||||||
e.preventDefault();
|
|
||||||
themePopup.querySelector('li:last-child button').focus();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
|
|
||||||
(function sidebar() {
|
|
||||||
var body = document.querySelector("body");
|
|
||||||
var sidebar = document.getElementById("sidebar");
|
|
||||||
var sidebarLinks = document.querySelectorAll('#sidebar a');
|
|
||||||
var sidebarToggleButton = document.getElementById("sidebar-toggle");
|
|
||||||
var sidebarResizeHandle = document.getElementById("sidebar-resize-handle");
|
|
||||||
var firstContact = null;
|
|
||||||
|
|
||||||
function showSidebar() {
|
|
||||||
body.classList.remove('sidebar-hidden')
|
|
||||||
body.classList.add('sidebar-visible');
|
|
||||||
Array.from(sidebarLinks).forEach(function (link) {
|
|
||||||
link.setAttribute('tabIndex', 0);
|
|
||||||
});
|
|
||||||
sidebarToggleButton.setAttribute('aria-expanded', true);
|
|
||||||
sidebar.setAttribute('aria-hidden', false);
|
|
||||||
try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
var sidebarAnchorToggles = document.querySelectorAll('#sidebar a.toggle');
|
|
||||||
|
|
||||||
function toggleSection(ev) {
|
|
||||||
ev.currentTarget.parentElement.classList.toggle('expanded');
|
|
||||||
}
|
|
||||||
|
|
||||||
Array.from(sidebarAnchorToggles).forEach(function (el) {
|
|
||||||
el.addEventListener('click', toggleSection);
|
|
||||||
});
|
|
||||||
|
|
||||||
function hideSidebar() {
|
|
||||||
body.classList.remove('sidebar-visible')
|
|
||||||
body.classList.add('sidebar-hidden');
|
|
||||||
Array.from(sidebarLinks).forEach(function (link) {
|
|
||||||
link.setAttribute('tabIndex', -1);
|
|
||||||
});
|
|
||||||
sidebarToggleButton.setAttribute('aria-expanded', false);
|
|
||||||
sidebar.setAttribute('aria-hidden', true);
|
|
||||||
try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle sidebar
|
|
||||||
sidebarToggleButton.addEventListener('click', function sidebarToggle() {
|
|
||||||
if (body.classList.contains("sidebar-hidden")) {
|
|
||||||
var current_width = parseInt(
|
|
||||||
document.documentElement.style.getPropertyValue('--sidebar-width'), 10);
|
|
||||||
if (current_width < 150) {
|
|
||||||
document.documentElement.style.setProperty('--sidebar-width', '150px');
|
|
||||||
}
|
|
||||||
showSidebar();
|
|
||||||
} else if (body.classList.contains("sidebar-visible")) {
|
|
||||||
hideSidebar();
|
|
||||||
} else {
|
|
||||||
if (getComputedStyle(sidebar)['transform'] === 'none') {
|
|
||||||
hideSidebar();
|
|
||||||
} else {
|
|
||||||
showSidebar();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
sidebarResizeHandle.addEventListener('mousedown', initResize, false);
|
|
||||||
|
|
||||||
function initResize(e) {
|
|
||||||
window.addEventListener('mousemove', resize, false);
|
|
||||||
window.addEventListener('mouseup', stopResize, false);
|
|
||||||
body.classList.add('sidebar-resizing');
|
|
||||||
}
|
|
||||||
function resize(e) {
|
|
||||||
var viewportOffset = sidebar.getBoundingClientRect();
|
|
||||||
var pos = (e.clientX - sidebar.offsetLeft - viewportOffset.left);
|
|
||||||
if (pos < 20) {
|
|
||||||
hideSidebar();
|
|
||||||
} else {
|
|
||||||
if (body.classList.contains("sidebar-hidden")) {
|
|
||||||
showSidebar();
|
|
||||||
}
|
|
||||||
pos = Math.min(pos, window.innerWidth - 100);
|
|
||||||
document.documentElement.style.setProperty('--sidebar-width', pos + 'px');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//on mouseup remove windows functions mousemove & mouseup
|
|
||||||
function stopResize(e) {
|
|
||||||
body.classList.remove('sidebar-resizing');
|
|
||||||
window.removeEventListener('mousemove', resize, false);
|
|
||||||
window.removeEventListener('mouseup', stopResize, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('touchstart', function (e) {
|
|
||||||
firstContact = {
|
|
||||||
x: e.touches[0].clientX,
|
|
||||||
time: Date.now()
|
|
||||||
};
|
|
||||||
}, { passive: true });
|
|
||||||
|
|
||||||
document.addEventListener('touchmove', function (e) {
|
|
||||||
if (!firstContact)
|
|
||||||
return;
|
|
||||||
|
|
||||||
var curX = e.touches[0].clientX;
|
|
||||||
var xDiff = curX - firstContact.x,
|
|
||||||
tDiff = Date.now() - firstContact.time;
|
|
||||||
|
|
||||||
if (tDiff < 250 && Math.abs(xDiff) >= 150) {
|
|
||||||
if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300))
|
|
||||||
showSidebar();
|
|
||||||
else if (xDiff < 0 && curX < 300)
|
|
||||||
hideSidebar();
|
|
||||||
|
|
||||||
firstContact = null;
|
|
||||||
}
|
|
||||||
}, { passive: true });
|
|
||||||
})();
|
|
||||||
|
|
||||||
(function chapterNavigation() {
|
|
||||||
document.addEventListener('keydown', function (e) {
|
|
||||||
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
|
|
||||||
if (window.search && window.search.hasFocus()) { return; }
|
|
||||||
var html = document.querySelector('html');
|
|
||||||
|
|
||||||
function next() {
|
|
||||||
var nextButton = document.querySelector('.nav-chapters.next');
|
|
||||||
if (nextButton) {
|
|
||||||
window.location.href = nextButton.href;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function prev() {
|
|
||||||
var previousButton = document.querySelector('.nav-chapters.previous');
|
|
||||||
if (previousButton) {
|
|
||||||
window.location.href = previousButton.href;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
switch (e.key) {
|
|
||||||
case 'ArrowRight':
|
|
||||||
e.preventDefault();
|
|
||||||
if (html.dir == 'rtl') {
|
|
||||||
prev();
|
|
||||||
} else {
|
|
||||||
next();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'ArrowLeft':
|
|
||||||
e.preventDefault();
|
|
||||||
if (html.dir == 'rtl') {
|
|
||||||
next();
|
|
||||||
} else {
|
|
||||||
prev();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
|
|
||||||
(function clipboard() {
|
|
||||||
var clipButtons = document.querySelectorAll('.clip-button');
|
|
||||||
|
|
||||||
function hideTooltip(elem) {
|
|
||||||
elem.firstChild.innerText = "";
|
|
||||||
elem.className = 'fa fa-copy clip-button';
|
|
||||||
}
|
|
||||||
|
|
||||||
function showTooltip(elem, msg) {
|
|
||||||
elem.firstChild.innerText = msg;
|
|
||||||
elem.className = 'fa fa-copy tooltipped';
|
|
||||||
}
|
|
||||||
|
|
||||||
var clipboardSnippets = new ClipboardJS('.clip-button', {
|
|
||||||
text: function (trigger) {
|
|
||||||
hideTooltip(trigger);
|
|
||||||
let playground = trigger.closest("pre");
|
|
||||||
return playground_text(playground, false);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Array.from(clipButtons).forEach(function (clipButton) {
|
|
||||||
clipButton.addEventListener('mouseout', function (e) {
|
|
||||||
hideTooltip(e.currentTarget);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
clipboardSnippets.on('success', function (e) {
|
|
||||||
e.clearSelection();
|
|
||||||
showTooltip(e.trigger, "Copied!");
|
|
||||||
});
|
|
||||||
|
|
||||||
clipboardSnippets.on('error', function (e) {
|
|
||||||
showTooltip(e.trigger, "Clipboard error!");
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
|
|
||||||
(function scrollToTop () {
|
|
||||||
var menuTitle = document.querySelector('.menu-title');
|
|
||||||
|
|
||||||
menuTitle.addEventListener('click', function () {
|
|
||||||
document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' });
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
|
|
||||||
(function controllMenu() {
|
|
||||||
var menu = document.getElementById('menu-bar');
|
|
||||||
|
|
||||||
(function controllBorder() {
|
|
||||||
function updateBorder() {
|
|
||||||
if (menu.offsetTop === 0) {
|
|
||||||
menu.classList.remove('bordered');
|
|
||||||
} else {
|
|
||||||
menu.classList.add('bordered');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
updateBorder();
|
|
||||||
document.addEventListener('scroll', updateBorder, { passive: true });
|
|
||||||
})();
|
|
||||||
})();
|
|
||||||
82
doc/theme/highlight.css
vendored
82
doc/theme/highlight.css
vendored
|
|
@ -1,82 +0,0 @@
|
||||||
/*
|
|
||||||
* An increased contrast highlighting scheme loosely based on the
|
|
||||||
* "Base16 Atelier Dune Light" theme by Bram de Haan
|
|
||||||
* (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)
|
|
||||||
* Original Base16 color scheme by Chris Kempson
|
|
||||||
* (https://github.com/chriskempson/base16)
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* Comment */
|
|
||||||
.hljs-comment,
|
|
||||||
.hljs-quote {
|
|
||||||
color: #575757;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Red */
|
|
||||||
.hljs-variable,
|
|
||||||
.hljs-template-variable,
|
|
||||||
.hljs-attribute,
|
|
||||||
.hljs-tag,
|
|
||||||
.hljs-name,
|
|
||||||
.hljs-regexp,
|
|
||||||
.hljs-link,
|
|
||||||
.hljs-name,
|
|
||||||
.hljs-selector-id,
|
|
||||||
.hljs-selector-class {
|
|
||||||
color: #d70025;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Orange */
|
|
||||||
.hljs-number,
|
|
||||||
.hljs-meta,
|
|
||||||
.hljs-built_in,
|
|
||||||
.hljs-builtin-name,
|
|
||||||
.hljs-literal,
|
|
||||||
.hljs-type,
|
|
||||||
.hljs-params {
|
|
||||||
color: #b21e00;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Green */
|
|
||||||
.hljs-string,
|
|
||||||
.hljs-symbol,
|
|
||||||
.hljs-bullet {
|
|
||||||
color: #008200;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Blue */
|
|
||||||
.hljs-title,
|
|
||||||
.hljs-section {
|
|
||||||
color: #0030f2;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Purple */
|
|
||||||
.hljs-keyword,
|
|
||||||
.hljs-selector-tag {
|
|
||||||
color: #9d00ec;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hljs {
|
|
||||||
display: block;
|
|
||||||
overflow-x: auto;
|
|
||||||
background: #f6f7f6;
|
|
||||||
color: #000;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hljs-emphasis {
|
|
||||||
font-style: italic;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hljs-strong {
|
|
||||||
font-weight: bold;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hljs-addition {
|
|
||||||
color: #22863a;
|
|
||||||
background-color: #f0fff4;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hljs-deletion {
|
|
||||||
color: #b31d28;
|
|
||||||
background-color: #ffeef0;
|
|
||||||
}
|
|
||||||
53
doc/theme/highlight.js
vendored
53
doc/theme/highlight.js
vendored
File diff suppressed because one or more lines are too long
292
doc/theme/index.hbs
vendored
292
doc/theme/index.hbs
vendored
|
|
@ -1,292 +0,0 @@
|
||||||
<!-- Lang: {{ language }} -->
|
|
||||||
<!-- Title: {{ title }} -->
|
|
||||||
<!-- Print: {{#if print_enable}}enabled{{else}}disabled{{/if}} -->
|
|
||||||
<!-- MathJax: {{#if mathjax_support}}supported{{else}}unsupported{{/if}} -->
|
|
||||||
|
|
||||||
<!-- mdBook -->
|
|
||||||
|
|
||||||
<!-- Provide site root to javascript -->
|
|
||||||
<script>
|
|
||||||
var path_to_root = "{{ path_to_root }}";
|
|
||||||
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "{{ preferred_dark_theme }}" : "{{ default_theme }}";
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
||||||
<script>
|
|
||||||
try {
|
|
||||||
var theme = localStorage.getItem('mdbook-theme');
|
|
||||||
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
||||||
|
|
||||||
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
||||||
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
||||||
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
||||||
}
|
|
||||||
} catch (e) { }
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
||||||
<script>
|
|
||||||
var theme;
|
|
||||||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
||||||
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
||||||
var html = document.querySelector('html');
|
|
||||||
html.classList.remove('{{ default_theme }}')
|
|
||||||
html.classList.add(theme);
|
|
||||||
var body = document.querySelector('body');
|
|
||||||
body.classList.remove('no-js')
|
|
||||||
body.classList.add('js');
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
||||||
|
|
||||||
<!-- Hide / unhide sidebar before it is displayed -->
|
|
||||||
<script>
|
|
||||||
var body = document.querySelector('body');
|
|
||||||
var sidebar = null;
|
|
||||||
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
||||||
if (document.body.clientWidth >= 1080) {
|
|
||||||
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
||||||
sidebar = sidebar || 'visible';
|
|
||||||
} else {
|
|
||||||
sidebar = 'hidden';
|
|
||||||
}
|
|
||||||
sidebar_toggle.checked = sidebar === 'visible';
|
|
||||||
body.classList.remove('sidebar-visible');
|
|
||||||
body.classList.add("sidebar-" + sidebar);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
||||||
<div class="sidebar-scrollbox">
|
|
||||||
{{#toc}}{{/toc}}
|
|
||||||
</div>
|
|
||||||
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
||||||
<div class="sidebar-resize-indicator"></div>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<!-- Track and set sidebar scroll position -->
|
|
||||||
<script>
|
|
||||||
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
||||||
sidebarScrollbox.addEventListener('click', function(e) {
|
|
||||||
if (e.target.tagName === 'A') {
|
|
||||||
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
||||||
}
|
|
||||||
}, { passive: true });
|
|
||||||
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
||||||
sessionStorage.removeItem('sidebar-scroll');
|
|
||||||
if (sidebarScrollTop) {
|
|
||||||
// preserve sidebar scroll position when navigating via links within sidebar
|
|
||||||
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
||||||
} else {
|
|
||||||
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
||||||
var activeSection = document.querySelector('#sidebar .active');
|
|
||||||
if (activeSection) {
|
|
||||||
activeSection.scrollIntoView({ block: 'center' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div id="page-wrapper" class="page-wrapper">
|
|
||||||
|
|
||||||
<div class="page">
|
|
||||||
{{> header}}
|
|
||||||
<div id="menu-bar-hover-placeholder"></div>
|
|
||||||
<div id="menu-bar" class="menu-bar sticky">
|
|
||||||
<div class="left-buttons">
|
|
||||||
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
||||||
<i class="fa fa-bars"></i>
|
|
||||||
</label>
|
|
||||||
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
||||||
<i class="fa fa-paint-brush"></i>
|
|
||||||
</button>
|
|
||||||
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
||||||
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
||||||
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
||||||
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
||||||
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
||||||
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
||||||
</ul>
|
|
||||||
{{#if search_enabled}}
|
|
||||||
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
||||||
<i class="fa fa-search"></i>
|
|
||||||
</button>
|
|
||||||
{{/if}}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h1 class="menu-title">{{ book_title }}</h1>
|
|
||||||
|
|
||||||
<div class="right-buttons">
|
|
||||||
{{#if print_enable}}
|
|
||||||
<a href="{{ path_to_root }}print.html" title="Print this book" aria-label="Print this book">
|
|
||||||
<i id="print-button" class="fa fa-print"></i>
|
|
||||||
</a>
|
|
||||||
{{/if}}
|
|
||||||
{{#if git_repository_url}}
|
|
||||||
<a href="{{git_repository_url}}" title="Git repository" aria-label="Git repository">
|
|
||||||
<i id="git-repository-button" class="fa {{git_repository_icon}}"></i>
|
|
||||||
</a>
|
|
||||||
{{/if}}
|
|
||||||
{{#if git_repository_edit_url}}
|
|
||||||
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit">
|
|
||||||
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
||||||
</a>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{{#if search_enabled}}
|
|
||||||
<div id="search-wrapper" class="hidden">
|
|
||||||
<form id="searchbar-outer" class="searchbar-outer">
|
|
||||||
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
||||||
</form>
|
|
||||||
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
||||||
<div id="searchresults-header" class="searchresults-header"></div>
|
|
||||||
<ul id="searchresults">
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
||||||
<script>
|
|
||||||
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
||||||
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
||||||
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
||||||
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div id="content" class="content">
|
|
||||||
<main>
|
|
||||||
{{{ content }}}
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
||||||
<!-- Mobile navigation buttons -->
|
|
||||||
{{#previous}}
|
|
||||||
<a rel="prev" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
||||||
<i class="fa fa-angle-left"></i>
|
|
||||||
</a>
|
|
||||||
{{/previous}}
|
|
||||||
|
|
||||||
{{#next}}
|
|
||||||
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
||||||
<i class="fa fa-angle-right"></i>
|
|
||||||
</a>
|
|
||||||
{{/next}}
|
|
||||||
|
|
||||||
<div style="clear: both"></div>
|
|
||||||
</nav>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
|
||||||
{{#previous}}
|
|
||||||
<a rel="prev" href="{{ path_to_root }}{{link}}" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
||||||
<i class="fa fa-angle-left"></i>
|
|
||||||
</a>
|
|
||||||
{{/previous}}
|
|
||||||
|
|
||||||
{{#next}}
|
|
||||||
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
||||||
<i class="fa fa-angle-right"></i>
|
|
||||||
</a>
|
|
||||||
{{/next}}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{{#if live_reload_endpoint}}
|
|
||||||
<!-- Livereload script (if served using the cli tool) -->
|
|
||||||
<script>
|
|
||||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
||||||
const wsAddress = wsProtocol + "//" + location.host + "/" + "{{{live_reload_endpoint}}}";
|
|
||||||
const socket = new WebSocket(wsAddress);
|
|
||||||
socket.onmessage = function (event) {
|
|
||||||
if (event.data === "reload") {
|
|
||||||
socket.close();
|
|
||||||
location.reload();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
window.onbeforeunload = function() {
|
|
||||||
socket.close();
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
{{#if google_analytics}}
|
|
||||||
<!-- Google Analytics Tag -->
|
|
||||||
<script>
|
|
||||||
var localAddrs = ["localhost", "127.0.0.1", ""];
|
|
||||||
|
|
||||||
// make sure we don't activate google analytics if the developer is
|
|
||||||
// inspecting the book locally...
|
|
||||||
if (localAddrs.indexOf(document.location.hostname) === -1) {
|
|
||||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
|
||||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
|
||||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
|
||||||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
|
||||||
|
|
||||||
ga('create', '{{google_analytics}}', 'auto');
|
|
||||||
ga('send', 'pageview');
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
{{#if playground_line_numbers}}
|
|
||||||
<script>
|
|
||||||
window.playground_line_numbers = true;
|
|
||||||
</script>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
{{#if playground_copyable}}
|
|
||||||
<script>
|
|
||||||
window.playground_copyable = true;
|
|
||||||
</script>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
{{#if playground_js}}
|
|
||||||
<script src="{{ path_to_root }}ace.js"></script>
|
|
||||||
<script src="{{ path_to_root }}editor.js"></script>
|
|
||||||
<script src="{{ path_to_root }}mode-rust.js"></script>
|
|
||||||
<script src="{{ path_to_root }}theme-dawn.js"></script>
|
|
||||||
<script src="{{ path_to_root }}theme-tomorrow_night.js"></script>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
{{#if search_js}}
|
|
||||||
<script src="{{ path_to_root }}elasticlunr.min.js"></script>
|
|
||||||
<script src="{{ path_to_root }}mark.min.js"></script>
|
|
||||||
<script src="{{ path_to_root }}searcher.js"></script>
|
|
||||||
{{/if}}
|
|
||||||
|
|
||||||
<script src="{{ path_to_root }}clipboard.min.js"></script>
|
|
||||||
<script src="{{ path_to_root }}highlight.js"></script>
|
|
||||||
<script src="{{ path_to_root }}book.js"></script>
|
|
||||||
|
|
||||||
<!-- Custom JS scripts -->
|
|
||||||
{{#each additional_js}}
|
|
||||||
<script src="{{ ../path_to_root }}{{this}}"></script>
|
|
||||||
{{/each}}
|
|
||||||
|
|
||||||
{{#if is_print}}
|
|
||||||
{{#if mathjax_support}}
|
|
||||||
<script>
|
|
||||||
window.addEventListener('load', function() {
|
|
||||||
MathJax.Hub.Register.StartupHook('End', function() {
|
|
||||||
window.setTimeout(window.print, 100);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
{{else}}
|
|
||||||
<script>
|
|
||||||
window.addEventListener('load', function() {
|
|
||||||
window.setTimeout(window.print, 100);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
{{/if}}
|
|
||||||
{{/if}}
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
[book]
|
|
||||||
authors = ["Manuel Cillero"]
|
|
||||||
language = "es"
|
|
||||||
src = "src"
|
|
||||||
title = "Guía de PageTop"
|
|
||||||
|
|
||||||
[output.html]
|
|
||||||
theme = "../../theme"
|
|
||||||
# The guides number the steps of each page themselves; the sidebar groups pages by kind.
|
|
||||||
no-section-label = true
|
|
||||||
|
|
||||||
# The examples need PageTop: they cannot run in the Rust playground.
|
|
||||||
[output.html.playground]
|
|
||||||
runnable = false
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
# Documento no encontrado (404)
|
|
||||||
|
|
||||||
Esta URL no es válida, lo sentimos. ¡Intenta buscar en su lugar!
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
# Summary
|
|
||||||
|
|
||||||
[PageTop](intro.md)
|
|
||||||
|
|
||||||
# Tutoriales
|
|
||||||
|
|
||||||
- [Tu primera aplicación](tutorials/first-app.md)
|
|
||||||
- [Recorrido por PageTop](tutorials/tour.md)
|
|
||||||
- [Tareas del huerto con HTMX](tutorials/htmx-tasks.md)
|
|
||||||
- [Guarda las tareas en una base de datos](tutorials/database.md)
|
|
||||||
|
|
||||||
# Guías prácticas
|
|
||||||
|
|
||||||
- [Páginas y componentes]()
|
|
||||||
- [Añadir rutas](how-to/routes.md)
|
|
||||||
- [Construir páginas](how-to/pages.md)
|
|
||||||
- [Mostrar páginas de error](how-to/error-pages.md)
|
|
||||||
- [Escribir HTML con `html!`](how-to/html.md)
|
|
||||||
- [Usar componentes](how-to/components.md)
|
|
||||||
- [Crear un componente](how-to/custom-components.md)
|
|
||||||
- [Maquetar con Flex y Grid](how-to/layout.md)
|
|
||||||
- [Añadir navegación](how-to/navigation.md)
|
|
||||||
- [Crear y procesar formularios](how-to/forms.md)
|
|
||||||
- [Subir y descargar archivos](how-to/uploads.md)
|
|
||||||
- [Mostrar tablas ordenables y paginadas](how-to/tables.md)
|
|
||||||
- [Interactividad con HTMX]()
|
|
||||||
- [Añadir HTMX a una aplicación](how-to/htmx-setup.md)
|
|
||||||
- [Cargar contenido bajo demanda](how-to/htmx-load.md)
|
|
||||||
- [Buscar mientras se escribe](how-to/htmx-search.md)
|
|
||||||
- [Validar un campo al vuelo](how-to/htmx-validation.md)
|
|
||||||
- [Editar en línea](how-to/htmx-edit.md)
|
|
||||||
- [Borrar con confirmación](how-to/htmx-delete.md)
|
|
||||||
- [Ordenar y paginar sin recargar](how-to/htmx-tables.md)
|
|
||||||
- [Cargar más al hacer *scroll*](how-to/htmx-infinite.md)
|
|
||||||
- [Actualizar periódicamente](how-to/htmx-polling.md)
|
|
||||||
- [Dirigir al navegador desde el servidor](how-to/htmx-responses.md)
|
|
||||||
- [Datos y usuarios]()
|
|
||||||
- [Conectar una base de datos](how-to/database.md)
|
|
||||||
- [Añadir usuarios y permisos](how-to/users.md)
|
|
||||||
- [Conectar tu propia autenticación](how-to/auth.md)
|
|
||||||
- [Añadir páginas al panel de administración](how-to/admin.md)
|
|
||||||
- [La aplicación]()
|
|
||||||
- [Configurar la aplicación](how-to/configuration.md)
|
|
||||||
- [Compartir un servicio entre rutas](how-to/services.md)
|
|
||||||
- [Programar tareas periódicas](how-to/cron.md)
|
|
||||||
- [Enviar correo electrónico](how-to/mail.md)
|
|
||||||
- [Añadir *middleware*](how-to/middleware.md)
|
|
||||||
- [Traducir la aplicación](how-to/localization.md)
|
|
||||||
- [Servir recursos estáticos](how-to/assets.md)
|
|
||||||
- [Probar rutas y componentes](how-to/testing.md)
|
|
||||||
- [Registrar trazas](how-to/logging.md)
|
|
||||||
- [Desplegar en producción](how-to/deployment.md)
|
|
||||||
- [Extender PageTop]()
|
|
||||||
- [Crear una extensión](how-to/extensions.md)
|
|
||||||
- [Intervenir con acciones](how-to/actions.md)
|
|
||||||
- [Crear un tema](how-to/themes.md)
|
|
||||||
|
|
||||||
# Referencia
|
|
||||||
|
|
||||||
- [Opciones de configuración](reference/configuration.md)
|
|
||||||
- [Catálogo de componentes](reference/components.md)
|
|
||||||
- [HTMX: atributos, cabeceras y respuestas](reference/htmx.md)
|
|
||||||
- [Extensiones oficiales](reference/extensions.md)
|
|
||||||
- [Referencia rápida](reference/cheatsheet.md)
|
|
||||||
|
|
||||||
# Explicación
|
|
||||||
|
|
||||||
- [Por qué PageTop](explanation/why.md)
|
|
||||||
- [PageTop frente a otros *frameworks*](explanation/comparison.md)
|
|
||||||
- [Arquitectura: del arranque a la respuesta](explanation/architecture.md)
|
|
||||||
- [Componentes, temas y renderizado](explanation/rendering.md)
|
|
||||||
- [HTML por la red: por qué HTMX](explanation/htmx.md)
|
|
||||||
- [Si vienes de Axum](explanation/coming-from-axum.md)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
[Preguntas frecuentes](faq.md)
|
|
||||||
|
|
@ -1,188 +0,0 @@
|
||||||
# Arquitectura: del arranque a la respuesta
|
|
||||||
|
|
||||||
Una aplicación PageTop vive dos momentos distintos: el **arranque**, que ocurre una vez y prepara
|
|
||||||
todo, y la **petición**, que ocurre miles de veces y debe ser rápida. Entender qué pasa en cada uno
|
|
||||||
explica casi todas las decisiones de diseño de PageTop.
|
|
||||||
|
|
||||||
## Un árbol de extensiones
|
|
||||||
|
|
||||||
Una aplicación es un **árbol de extensiones**. En la raíz está la tuya; de ella cuelgan las que
|
|
||||||
declara como dependencias, y de esas, las suyas:
|
|
||||||
|
|
||||||
```text
|
|
||||||
MyApp <- root extension
|
|
||||||
├── Bootsier <- theme
|
|
||||||
├── User <- accounts and permissions
|
|
||||||
│ ├── Admin
|
|
||||||
│ ├── SeaORM <- database
|
|
||||||
│ └── Htmx
|
|
||||||
└── Blog <- your feature
|
|
||||||
└── SeaORM <- the same one: each extension is registered once
|
|
||||||
```
|
|
||||||
|
|
||||||
Este árbol es independiente de las dependencias de `Cargo.toml`: Cargo decide qué se **compila**;
|
|
||||||
`dependencies()` decide qué se **activa** y en qué orden. Una extensión compilada pero que nadie
|
|
||||||
declara no registra rutas ni ajustes.
|
|
||||||
|
|
||||||
Separar la extensión raíz en `src/lib.rs` y dejar `src/main.rs` con lo mínimo permite usar la
|
|
||||||
aplicación como biblioteca, por ejemplo desde las pruebas:
|
|
||||||
|
|
||||||
```text
|
|
||||||
my-app/
|
|
||||||
├── Cargo.toml
|
|
||||||
├── config/
|
|
||||||
│ ├── common.toml <- common settings
|
|
||||||
│ └── local.toml <- local settings (not versioned)
|
|
||||||
└── src/
|
|
||||||
├── lib.rs <- root extension
|
|
||||||
├── main.rs <- startup
|
|
||||||
└── locale/ <- translations
|
|
||||||
├── en-US/
|
|
||||||
└── es-ES/
|
|
||||||
```
|
|
||||||
|
|
||||||
## El arranque
|
|
||||||
|
|
||||||
`Application::prepare()` sigue siempre los mismos pasos:
|
|
||||||
|
|
||||||
```text
|
|
||||||
Application::prepare(&MyApp)
|
|
||||||
1. banner and traces [log] settles how much is traced and where
|
|
||||||
2. language and time zone the defaults of [app]
|
|
||||||
3. register extensions walks the tree: dependencies first, each one once
|
|
||||||
4. load settings every settings() section, validated
|
|
||||||
5. default theme the one in [app] theme, or Basic with a warning
|
|
||||||
6. register actions every actions(), sorted by weight
|
|
||||||
7. initialize extensions every initialize(), dependencies first
|
|
||||||
|
|
|
||||||
v
|
|
||||||
.run()
|
|
||||||
8. build the server routes + middleware + static files
|
|
||||||
9. start extensions every start(): background services, such as pagetop-cron
|
|
||||||
10. serve requests until Ctrl+C or SIGTERM
|
|
||||||
11. shut down extensions every shutdown(), in reverse order
|
|
||||||
```
|
|
||||||
|
|
||||||
Tres consecuencias importantes:
|
|
||||||
|
|
||||||
- **Lo que falla, falla al arrancar.** Una clave mal escrita, un valor no válido, una base de datos
|
|
||||||
que no responde o una migración rota detienen la aplicación antes de servir una sola petición,
|
|
||||||
con un mensaje que explica la causa. Nunca hay una aplicación a medias en producción.
|
|
||||||
- **Lo costoso se hace una vez.** Las traducciones, los ajustes, las acciones y los recursos
|
|
||||||
estáticos se cargan o se registran al arrancar; en cada petición sólo se consultan.
|
|
||||||
- **Las pruebas no lanzan nada en segundo plano.** Una prueba prepara la aplicación con
|
|
||||||
`prepare()` y obtiene su servidor con `test()`, sin llamar a `run()`: hace los pasos 1 a 8, pero
|
|
||||||
ni arranca los servicios de las extensiones ni ejecuta tareas programadas por su cuenta.
|
|
||||||
|
|
||||||
## La petición
|
|
||||||
|
|
||||||
Cuando llega una petición, recorre las capas que construyó `run()`:
|
|
||||||
|
|
||||||
```text
|
|
||||||
request
|
|
||||||
|
|
|
||||||
v
|
|
||||||
+------------------------------------------------------------+
|
|
||||||
| cross-origin check (CSRF) -> 403 for a POST, PUT... |
|
|
||||||
| from another origin |
|
|
||||||
+------------------------------------------------------------+
|
|
||||||
| static files (/static, /htmx...) -> served directly, |
|
|
||||||
| without middleware |
|
|
||||||
+------------------------------------------------------------+
|
|
||||||
| middleware of the extensions (session, current user...) |
|
|
||||||
| +------------------------------------------------------+ |
|
|
||||||
| | router -> access of the route -> 403, or sign in | |
|
|
||||||
| | -> your handler | |
|
|
||||||
| | Page::new(request) builds the Context: | |
|
|
||||||
| | language, theme, user, zone | |
|
|
||||||
| | .with_child(...) adds components, not HTML | |
|
|
||||||
| | .render() the theme lays out the page | |
|
|
||||||
| +------------------------------------------------------+ |
|
|
||||||
+------------------------------------------------------------+
|
|
||||||
|
|
|
||||||
v
|
|
||||||
response (complete HTML, or a fragment for HTMX)
|
|
||||||
```
|
|
||||||
|
|
||||||
- La **comprobación de origen** rechaza con `403`, antes de llegar al *middleware* de las
|
|
||||||
extensiones, las peticiones que pueden cambiar algo (`POST`, `PUT`...) y que el navegador indica
|
|
||||||
que vienen de otro origen: es la protección contra CSRF, sin *tokens* en los formularios. Ver
|
|
||||||
[Sin *tokens* contra CSRF](../how-to/forms.md#6-sin-tokens-contra-csrf).
|
|
||||||
- Los **archivos estáticos** se registran después del *middleware*, así que no pasan por él:
|
|
||||||
servir una hoja de estilos no resuelve sesiones ni consulta la base de datos.
|
|
||||||
- El **middleware** de cada extensión (`configure_middleware()`) envuelve las rutas de **todas**
|
|
||||||
las extensiones. Así, `pagetop-user` resuelve la sesión una vez y cualquier ruta sabe quién pide.
|
|
||||||
- El **acceso de la ruta** se comprueba antes de llegar al *handler*: quien no lo cumple no
|
|
||||||
ejecuta nada de él (ver abajo).
|
|
||||||
- El ***handler*** es un *handler* de Axum normal. `Page::new(request)` crea el **contexto** de la
|
|
||||||
petición, que viajará por todos los componentes: el idioma negociado, el tema, el usuario, la
|
|
||||||
zona horaria, los recursos y los mensajes.
|
|
||||||
|
|
||||||
Qué pasa dentro de `render()` se explica en [Componentes, temas y renderizado](rendering.md).
|
|
||||||
|
|
||||||
## El acceso a cada ruta
|
|
||||||
|
|
||||||
En PageTop no se puede registrar una ruta sin decir quién puede llegar a ella. `configure_router()`
|
|
||||||
no recibe el `Router` de Axum, sino `Routes`, cuyo `route()` exige un acceso:
|
|
||||||
|
|
||||||
| Acceso | Quién llega al *handler* |
|
|
||||||
|---|---|
|
|
||||||
| `Access::Public` | Cualquiera, también un anónimo |
|
|
||||||
| `Access::Authenticated` | Quien haya iniciado sesión |
|
|
||||||
| `Access::Permission(&P)` | Quien tenga el permiso `P` |
|
|
||||||
|
|
||||||
Lo público hay que escribirlo (con `Access::Public` o con `routes.public_route()`, que equivale),
|
|
||||||
así que una página no queda abierta porque alguien olvidara protegerla: sin indicar el acceso, no
|
|
||||||
compila. El acceso se fija al montar la ruta; en cada petición sólo se comprueba, y una ruta pública
|
|
||||||
no añade nada.
|
|
||||||
|
|
||||||
Las rutas del **panel de administración** son un caso más estricto. El permiso se declara una sola
|
|
||||||
vez, en la página del panel (`AdminPage`), y sus rutas se montan con `routes.admin_route()`, que lo
|
|
||||||
toma de la página de la que cuelgan: `user/users/{id}/edit` exige el de `user/users`. Una ruta del
|
|
||||||
panel montada de otra forma, o que no cuelgue de ninguna página, impide arrancar la aplicación. El
|
|
||||||
menú del panel y la ruta no pueden quedar desalineados.
|
|
||||||
|
|
||||||
El resto de rutas consiguen lo mismo con `Endpoint`: un `enum` por extensión cuyas variantes
|
|
||||||
declaran su ruta y su acceso, que se montan con `routes.endpoint()` y se usan como destino de los
|
|
||||||
enlaces. El acceso con el que se monta una ruta queda dentro de su capa y no se puede consultar
|
|
||||||
después, así que es el enlace el que lleva consigo el acceso, sin guardarlo en ningún registro: el
|
|
||||||
mismo valor protege la ruta y decide si el enlace se muestra
|
|
||||||
([Enlaces según el acceso](../how-to/navigation.md#enlaces-según-el-acceso)). Es una ayuda para la
|
|
||||||
interfaz, no para la seguridad: quien escriba la URL recibe la respuesta del acceso de la ruta.
|
|
||||||
|
|
||||||
Quién tiene cada permiso no lo sabe PageTop: lo decide una **extensión de autenticación**, como
|
|
||||||
`pagetop-user`. Deja el usuario actual (`CurrentUser`) en la petición desde su *middleware*, concede
|
|
||||||
permisos con la acción `CheckPermission` y, si quiere, decide qué responder a un anónimo sin acceso
|
|
||||||
con `AnonymousDenied` (`pagetop-user` le lleva al inicio de sesión y le devuelve después a donde
|
|
||||||
iba). Sin ella, nadie tiene ningún permiso y quien no cumple un acceso recibe un 403. Cómo escribir
|
|
||||||
una, en [Conectar tu propia autenticación](../how-to/auth.md).
|
|
||||||
|
|
||||||
Lo que el acceso de la ruta no puede expresar, como «sólo el autor edita su aviso», lo comprueba el
|
|
||||||
propio *handler* con `require_permission()` o con su lógica. Los archivos estáticos son siempre
|
|
||||||
públicos; una descarga que deba protegerse se sirve desde una ruta con su acceso
|
|
||||||
(`web::Download`).
|
|
||||||
|
|
||||||
## Sin estado mutable compartido
|
|
||||||
|
|
||||||
Los ajustes son de sólo lectura, las acciones se registran una vez y los componentes globales
|
|
||||||
(`InRegion`) se **clonan** para cada página. Cada petición trabaja con su propio contexto y sus
|
|
||||||
propias copias: lo que un componente cambia al renderizarse no afecta a otras peticiones. El estado
|
|
||||||
que debe compartirse entre peticiones (datos, sesiones) vive en la base de datos o, si es tuyo, en
|
|
||||||
tus propias estructuras.
|
|
||||||
|
|
||||||
## El preludio
|
|
||||||
|
|
||||||
Casi todo lo que necesitas está en un solo `use`:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
```
|
|
||||||
|
|
||||||
Trae los tipos principales (`Extension`, `Page`, `Component`, `Lc`...), los componentes base, las
|
|
||||||
macros (`html!`, `include_locales!`...) y accesos directos a módulos como `web`, `trace`, `util` o
|
|
||||||
`global`. Las extensiones tienen el suyo: `pagetop_htmx::prelude::*`, `pagetop_user::prelude::*`...
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Componentes, temas y renderizado](rendering.md).
|
|
||||||
- [Si vienes de Axum](coming-from-axum.md): qué es igual y qué cambia.
|
|
||||||
|
|
@ -1,59 +0,0 @@
|
||||||
# Si vienes de Axum
|
|
||||||
|
|
||||||
PageTop está construido **sobre** [Axum](https://docs.rs/axum) y [Tokio](https://tokio.rs), no al
|
|
||||||
lado. Lo que sabes de Axum sigue valiendo: las rutas, los extractores, las respuestas y el
|
|
||||||
*middleware* son los suyos, reexportados en `web`. PageTop añade lo que una aplicación web completa
|
|
||||||
necesita encima, y una forma de organizarlo.
|
|
||||||
|
|
||||||
## Lo que se traduce directamente
|
|
||||||
|
|
||||||
| En Axum | En PageTop | Qué cambia |
|
|
||||||
|---|---|---|
|
|
||||||
| `Router::new().route(...)` | `routes.route(ruta, acceso, ...)` en `configure_router()` | Cada ruta declara quién puede llegar a su *handler* (`Access`); un `Router` propio se añade con `routes.nest()` |
|
|
||||||
| `axum::routing::get`, `post`... | `web::get`, `web::post`... | Nada: son los mismos |
|
|
||||||
| `Path`, `Query`, `Form`, `Json` | `web::Path`, `web::Query`, `web::Form`, `Json` | Nada |
|
|
||||||
| `Request` | `HttpRequest` | Una vista clonable de la petición, que no consume el cuerpo y se puede pedir junto a cualquier extractor |
|
|
||||||
| `impl IntoResponse` | `IntoResponse`, `Response` | Nada; `Markup` y `ErrorPage` también la implementan |
|
|
||||||
| `Redirect::to(...)` | `Redirect::see_other(...)`, `found()`, `temporary()`... | Un constructor por código de estado |
|
|
||||||
| `middleware::from_fn` | `web::middleware::from_fn` en `configure_middleware()` | Se aplica a las rutas de todas las extensiones |
|
|
||||||
| `ServeDir` | `serve_static_files!` en `configure_static_files()` | Los archivos pueden ir dentro del binario |
|
|
||||||
| `#[tokio::main]` | `#[pagetop::main]` | Prepara el *runtime* que usa PageTop |
|
|
||||||
| `#[tokio::test]` | `#[pagetop::test]` | Igual, para las pruebas |
|
|
||||||
| `State<T>` | Ajustes con `#[settings]`, estáticos propios | Ver abajo |
|
|
||||||
|
|
||||||
## Lo que PageTop añade
|
|
||||||
|
|
||||||
- **Páginas completas** con `Page`: el `<head>`, los recursos sin duplicados, el idioma, la
|
|
||||||
dirección del texto y la estructura del tema.
|
|
||||||
- **Componentes** con su HTML, sus estilos y su comportamiento, que se adaptan al tema activo.
|
|
||||||
- **Temas intercambiables** desde la configuración.
|
|
||||||
- **Configuración en cascada** con validación al arrancar.
|
|
||||||
- **Traducciones** con Fluent, integradas en el binario.
|
|
||||||
- **Extensiones** con dependencias y un orden de arranque garantizado, que se suman con una línea.
|
|
||||||
- **Páginas de error** (403, 404, 500...) con el aspecto del sitio.
|
|
||||||
|
|
||||||
## El estado de la aplicación
|
|
||||||
|
|
||||||
En Axum, el estado compartido suele viajar con `State<T>`. En PageTop, cada extensión gestiona el
|
|
||||||
suyo:
|
|
||||||
|
|
||||||
- La **configuración** se declara con `#[settings]` y se lee desde cualquier sitio con su estático
|
|
||||||
(`SETTINGS.page_size`), sin pasarla de *handler* en *handler*.
|
|
||||||
- Los **recursos** que se crean al arrancar (una conexión, un cliente HTTP, una caché) se
|
|
||||||
inicializan en `initialize()` y se guardan en un estático (`OnceLock`, `LazyLock`). Así lo hace
|
|
||||||
`pagetop-seaorm` con su `dbconn()`. Paso a paso en [Compartir un servicio entre
|
|
||||||
rutas](../how-to/services.md).
|
|
||||||
- Lo que depende de **cada petición** (el idioma, el usuario, el tema) está en el `Context` que crea
|
|
||||||
`Page::new(request)` y que reciben todos los componentes.
|
|
||||||
|
|
||||||
## Mezclar código de Axum
|
|
||||||
|
|
||||||
`configure_router()` recibe y devuelve un `Router` de Axum, así que puedes añadirle cualquier cosa
|
|
||||||
que Axum admita: rutas con capas propias, servicios de Tower, rutas anidadas o un `Router`
|
|
||||||
existente con `merge()`. Una ruta que devuelve JSON convive sin problemas con las que devuelven
|
|
||||||
páginas.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Arquitectura: del arranque a la respuesta](architecture.md).
|
|
||||||
- [Tu primera aplicación](../tutorials/first-app.md).
|
|
||||||
|
|
@ -1,137 +0,0 @@
|
||||||
# PageTop frente a otros *frameworks*
|
|
||||||
|
|
||||||
Rust tiene muy buenos *frameworks* web, y es justo preguntarse por qué elegir uno u otro. Esta
|
|
||||||
página compara PageTop con los más conocidos, con sus puntos fuertes y también con lo que a PageTop
|
|
||||||
todavía le falta.
|
|
||||||
|
|
||||||
A grandes rasgos hay dos familias. Los **modulares** (Actix Web, Axum, Poem) te dan las piezas
|
|
||||||
básicas para atender peticiones y te dejan elegir el resto: base de datos, plantillas, usuarios. Los
|
|
||||||
**completos** (Rocket en parte, Loco, Cot, Topcoat) traen de serie muchas de esas piezas y unas
|
|
||||||
convenciones para encajarlas. PageTop está en la segunda familia, con un matiz: lo que trae lo
|
|
||||||
organiza en **extensiones**, **componentes** y **temas**, y casi todo es opcional.
|
|
||||||
|
|
||||||
Ten en cuenta también la madurez: PageTop sigue en versiones 0.x, su API todavía cambia entre
|
|
||||||
versiones y su comunidad es más pequeña que la de la mayoría de los *frameworks* de esta página.
|
|
||||||
|
|
||||||
## Tabla comparativa
|
|
||||||
|
|
||||||
| | PageTop | Rocket | Poem | Loco | Cot | Topcoat |
|
|
||||||
|:--|:--|:--|:--|:--|:--|:--|
|
|
||||||
| **Enfoque** | Completo, por extensiones | Completo en parte | Modular, con OpenAPI | Completo (como Rails) | Completo (como Django) | Completo, interfaz reactiva |
|
|
||||||
| **Base** | Axum | Hyper y Tokio | Hyper y Tokio | Axum | Axum | Hyper y Tokio |
|
|
||||||
| **HTML** | `html!` con componentes y temas | Tera, Handlebars o MiniJinja | A tu elección | Tera (u otro motor) | Askama (u otro motor) | `view!` con componentes |
|
|
||||||
| **Interactividad** | HTMX (extensión) | A tu elección | A tu elección | HTMX en sus generadores | A tu elección | Reactividad propia; también HTMX, Alpine AJAX o Datastar |
|
|
||||||
| **Base de datos** | SeaORM (extensión) | Varias, con su integración | A tu elección | SeaORM | ORM propio | Toasty, recomendado |
|
|
||||||
| **Migraciones** | Escritas en Rust, aplicadas al arrancar | Herramientas externas | Herramientas externas | Generadas con su CLI | Generadas a partir de los modelos | Generadas a partir de los modelos (Toasty) |
|
|
||||||
| **Usuarios y permisos** | Extensión (roles y permisos); CSRF en el núcleo | No | No (sesiones y CSRF) | Autenticación (JWT y claves de API) | Autenticación | Sesiones; autenticación prevista |
|
|
||||||
| **Panel de administración** | Extensible, con formularios de ajustes | No | No | No | Generado a partir de los modelos | No |
|
|
||||||
| **Traducciones** | Fluent, de serie | No | Fluent, opcional | Fluent, en su plantilla de proyecto | No | Fluent |
|
|
||||||
| **Tareas en segundo plano y correo** | Tareas programadas y correo con cola persistente (extensiones); sin cola de trabajos genérica | No | No | Colas, tareas programadas y correo | Correo y caché | Correo; tareas en segundo plano previstas |
|
|
||||||
|
|
||||||
## PageTop frente a Rocket
|
|
||||||
|
|
||||||
Rocket es conocido por lo agradable que resulta escribir rutas con sus macros, por sus guardas de
|
|
||||||
petición y por llevar la seguridad de tipos muy lejos. Trae de serie plantillas, *cookies* privadas,
|
|
||||||
WebSocket, perfiles de configuración, pruebas e integración con varias bases de datos.
|
|
||||||
|
|
||||||
- **Elige Rocket si** te gusta su estilo de API y prefieres montar tú los usuarios, los permisos y
|
|
||||||
la interfaz sobre esas piezas.
|
|
||||||
- **Elige PageTop si** quieres que esas piezas vengan resueltas: usuarios y permisos, panel de
|
|
||||||
administración, temas y traducciones.
|
|
||||||
|
|
||||||
## PageTop frente a Poem
|
|
||||||
|
|
||||||
[Poem](https://github.com/poem-web/poem) es un *framework* modular, como Axum o Actix Web, pero con
|
|
||||||
muchas piezas opcionales que se activan por *features* (sesiones, CSRF, WebSocket, traducciones con
|
|
||||||
Fluent...). Destaca por `poem-openapi`, que genera la especificación OpenAPI a partir de los tipos
|
|
||||||
de la API, y por su soporte para gRPC.
|
|
||||||
|
|
||||||
- **Elige Poem si** construyes una API y quieres la documentación OpenAPI generada de serie, con
|
|
||||||
Swagger UI u otros visores, o quieres servir también gRPC con el mismo *framework*.
|
|
||||||
- **Elige PageTop si** vas a generar páginas: Poem no trae componentes, temas, usuarios ni panel de
|
|
||||||
administración, y la interfaz queda en tus manos.
|
|
||||||
|
|
||||||
## PageTop frente a Loco
|
|
||||||
|
|
||||||
Loco se presenta como «Rust on Rails» y como el *framework* para quien trabaja en solitario:
|
|
||||||
convenciones fuertes, una CLI que genera código y muchas piezas incluidas, también sobre Axum y
|
|
||||||
SeaORM.
|
|
||||||
|
|
||||||
- **Elige Loco si** te gusta la filosofía de Rails, quieres generadores de código, o necesitas ya
|
|
||||||
**colas de trabajos** genéricas que sobrevivan a un reinicio (en la base de datos o en Redis), que
|
|
||||||
PageTop todavía no tiene. Las tareas programadas y el correo sí los tiene PageTop, con sus
|
|
||||||
extensiones, y el correo puede guardarse en una cola persistente.
|
|
||||||
- **Elige PageTop si** tu aplicación es sobre todo interfaz: los componentes tipados y los temas
|
|
||||||
que pueden cambiar cualquier componente no tienen equivalente en Loco, que construye la interfaz
|
|
||||||
con plantillas (sus generadores sí pueden crear vistas con HTMX).
|
|
||||||
|
|
||||||
## PageTop frente a summer-rs
|
|
||||||
|
|
||||||
[summer-rs](https://summer-rs.github.io) (antes spring-rs) se inspira en Spring Boot: un núcleo
|
|
||||||
pequeño de *plugins* que integran piezas del ecosistema (Axum, SQLx, SeaORM, Redis, correo con
|
|
||||||
lettre, tareas programadas, autenticación con Sa-Token, OpenTelemetry, gRPC...), configurados en
|
|
||||||
TOML y con inyección de dependencias en tiempo de compilación.
|
|
||||||
|
|
||||||
- **Elige summer-rs si** construyes servicios o APIs y quieres tener ya integrados la caché, las
|
|
||||||
colas o la observabilidad.
|
|
||||||
- **Elige PageTop si** lo que construyes son páginas: summer-rs no trae plantillas, componentes,
|
|
||||||
temas ni traducciones. La idea de los *plugins* es muy parecida a la de las extensiones; donde
|
|
||||||
summer-rs inyecta componentes, PageTop guarda los servicios en estáticos (ve [Compartir un
|
|
||||||
servicio entre rutas](../how-to/services.md)).
|
|
||||||
|
|
||||||
## PageTop frente a Cot
|
|
||||||
|
|
||||||
Cot toma la filosofía de Django: un ORM propio que genera las migraciones a partir de los modelos y
|
|
||||||
un panel de administración que se construye solo.
|
|
||||||
|
|
||||||
- **Elige Cot si** te gusta Django y quieres un panel de administración con altas, bajas y
|
|
||||||
modificaciones de tus modelos sin escribir nada, o una API JSON con su documentación OpenAPI y
|
|
||||||
Swagger UI generadas.
|
|
||||||
- **Elige PageTop si** prefieres SeaORM, quieres construir la interfaz con componentes y temas en
|
|
||||||
lugar de plantillas, o necesitas traducciones. El panel de PageTop no genera páginas a partir de
|
|
||||||
los modelos, pero cada extensión le añade las suyas, con sus permisos (ve [Añadir páginas al panel
|
|
||||||
de administración](../how-to/admin.md)).
|
|
||||||
|
|
||||||
## PageTop frente a Topcoat
|
|
||||||
|
|
||||||
[Topcoat](https://tokio.rs/blog/2026-07-22-announcing-topcoat), del proyecto Tokio (lo firman Carl
|
|
||||||
Lerche, creador de Tokio, y Julien Scholz), es el más parecido a PageTop en la forma de construir la
|
|
||||||
interfaz: todo se renderiza en el servidor, con páginas y componentes escritos en Rust (`#[page]`,
|
|
||||||
`#[component]` y la macro `view!`). Añade su propio sistema de reactividad, con señales cuyo código
|
|
||||||
se compila a JavaScript y fragmentos de la página que se vuelven a renderizar en el servidor, y
|
|
||||||
también se integra con HTMX, Alpine AJAX o Datastar. Es muy reciente: se presentó en julio de 2026
|
|
||||||
y, como PageTop, avisa de que su API cambiará.
|
|
||||||
|
|
||||||
- **Elige Topcoat si** quieres reactividad en el navegador sin escribir JavaScript ni compilar a
|
|
||||||
WebAssembly, o su biblioteca de componentes con Tailwind.
|
|
||||||
- **Elige PageTop si** necesitas ya usuarios y permisos, panel de administración o tareas
|
|
||||||
programadas, que en Topcoat todavía no existen o están en su hoja de ruta, o temas capaces de
|
|
||||||
cambiar el aspecto de cualquier componente sin tocar la aplicación.
|
|
||||||
|
|
||||||
## ¿Y Axum o Actix Web?
|
|
||||||
|
|
||||||
No están en la tabla porque casi todas sus filas dirían «A tu elección» o «No»: son la base sobre
|
|
||||||
la que se construye una aplicación, no la aplicación hecha. PageTop **está construido sobre Axum**,
|
|
||||||
así que comparten rutas, extractores y respuestas, y lo que sabes de Axum lo puedes usar en PageTop
|
|
||||||
(lo cuenta [Si vienes de Axum](coming-from-axum.md)). Actix Web es maduro y uno de los más rápidos
|
|
||||||
que existen, aunque Rust y Axum ya dan un rendimiento de sobra para la inmensa mayoría de
|
|
||||||
aplicaciones de gestión. Son buena elección si quieres controlar cada pieza, construyes una API o un
|
|
||||||
microservicio sin interfaz, o ya tienes código sobre alguno de ellos. Si vas a generar páginas,
|
|
||||||
PageTop te ahorra juntar plantillas, traducciones, recursos estáticos, configuración y extensiones,
|
|
||||||
y sigues teniendo Axum debajo cuando lo necesites.
|
|
||||||
|
|
||||||
## ¿Y Leptos o Dioxus?
|
|
||||||
|
|
||||||
Leptos y Dioxus son *frameworks* **de pila completa** con reactividad fina: la interfaz se compila a
|
|
||||||
WebAssembly y se ejecuta en el navegador, y puede renderizarse antes en el servidor e hidratarse
|
|
||||||
después. Dioxus, además, lleva la misma aplicación al escritorio y al móvil. Es el modelo contrario
|
|
||||||
al de PageTop: aquí la interfaz vive en el servidor y HTMX sólo intercambia fragmentos de HTML. Si
|
|
||||||
tu aplicación necesita mucha lógica en el navegador, funcionar sin conexión o ejecutarse también
|
|
||||||
fuera de él, mira hacia ellos (lo explica también
|
|
||||||
[Por qué PageTop](why.md#cuándo-no-es-la-mejor-opción)).
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Por qué PageTop](why.md): las ideas detrás del diseño.
|
|
||||||
- [Si vienes de Axum](coming-from-axum.md): lo que ya sabes y lo que cambia.
|
|
||||||
- [HTML por la red: por qué HTMX](htmx.md).
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
# HTML por la red: por qué HTMX
|
|
||||||
|
|
||||||
PageTop genera HTML en el servidor. Para la interactividad podría haber elegido un *framework* de
|
|
||||||
JavaScript que pidiera JSON y pintara la interfaz en el navegador. Elige [HTMX](https://htmx.org)
|
|
||||||
porque encaja con todo lo demás: el servidor sigue generando el HTML, y el navegador sólo decide
|
|
||||||
cuándo pedirlo y dónde ponerlo.
|
|
||||||
|
|
||||||
## Dos formas de hacer una interfaz interactiva
|
|
||||||
|
|
||||||
| | Aplicación de una sola página (SPA) | HTMX |
|
|
||||||
|---|---|---|
|
|
||||||
| El servidor envía | JSON | HTML |
|
|
||||||
| La interfaz se genera en | El navegador, con JavaScript | El servidor, con los mismos componentes que la página |
|
|
||||||
| Estado de la interfaz | Duplicado: en el servidor y en el cliente | En el servidor |
|
|
||||||
| Lo que hay que mantener | Dos aplicaciones y la API que las une | Una aplicación |
|
|
||||||
| Validación | En los dos lados | En el servidor |
|
|
||||||
| Sin JavaScript | No funciona | Funciona, con recargas completas, si se diseña así |
|
|
||||||
|
|
||||||
Con HTMX, una ruta que responde a una interacción es una ruta como las demás: recibe la petición,
|
|
||||||
consulta lo que haga falta y devuelve HTML. No hay que diseñar una API, ni serializar, ni mantener
|
|
||||||
en sincronía dos modelos de datos.
|
|
||||||
|
|
||||||
## Por qué encaja con PageTop
|
|
||||||
|
|
||||||
- **Los mismos componentes.** El fragmento que devuelve una ruta para HTMX se genera con los mismos
|
|
||||||
componentes, el mismo tema y las mismas traducciones que la página entera. No hay una segunda
|
|
||||||
versión de la interfaz en JavaScript.
|
|
||||||
- **Los atributos son sólo atributos.** Los componentes de PageTop no conocen HTMX. Aceptan
|
|
||||||
atributos con `with_prop()`, y `hx-get` es uno más. Por eso HTMX es una extensión opcional, y
|
|
||||||
un componente sirve igual con HTMX o sin él.
|
|
||||||
- **Lo que se prueba es HTML.** Una ruta para HTMX se prueba como cualquier otra: se envía la
|
|
||||||
petición y se comprueba el HTML y las cabeceras de la respuesta. El comportamiento en el navegador
|
|
||||||
lo declaran los atributos, sin lógica propia que probar.
|
|
||||||
- **Un solo lenguaje.** La lógica de la interfaz está en Rust, comprobada por el compilador.
|
|
||||||
|
|
||||||
## Mejora progresiva
|
|
||||||
|
|
||||||
Una página bien hecha con HTMX funciona **antes** de que HTMX llegue: los enlaces llevan su `href` y
|
|
||||||
los formularios su `action`. HTMX intercepta esa navegación y la convierte en una petición parcial,
|
|
||||||
y la ruta responde según quién llame:
|
|
||||||
|
|
||||||
```text
|
|
||||||
+--> HX-Request: true --> only the fragment
|
|
||||||
GET /plants?q=to ------+
|
|
||||||
+--> (no header) --> the whole page
|
|
||||||
```
|
|
||||||
|
|
||||||
Así, la misma URL sirve para buscar sin recargar, para compartir el resultado y para recargar la
|
|
||||||
página. Las guías de [búsqueda](../how-to/htmx-search.md) y de [tablas](../how-to/htmx-tables.md) lo
|
|
||||||
aplican.
|
|
||||||
|
|
||||||
## Cuándo no es la herramienta adecuada
|
|
||||||
|
|
||||||
HTMX resuelve muy bien las interfaces de gestión, los formularios, los listados, los paneles y la
|
|
||||||
mayoría de webs con contenido. No es la mejor opción para:
|
|
||||||
|
|
||||||
- interfaces que deben funcionar **sin conexión**;
|
|
||||||
- interacciones de **alta frecuencia** en el propio navegador, como un editor gráfico, un juego o
|
|
||||||
arrastrar elementos con respuesta inmediata a cada píxel;
|
|
||||||
- aplicaciones donde casi todo ocurre en el cliente y el servidor apenas interviene.
|
|
||||||
|
|
||||||
Para esos casos puntuales, nada impide añadir JavaScript propio a una página o a un componente:
|
|
||||||
PageTop lo gestiona como cualquier otro recurso.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Tareas del huerto con HTMX](../tutorials/htmx-tasks.md): el enfoque en la práctica.
|
|
||||||
- [HTMX: atributos, cabeceras y respuestas](../reference/htmx.md).
|
|
||||||
|
|
@ -1,109 +0,0 @@
|
||||||
# Componentes, temas y renderizado
|
|
||||||
|
|
||||||
En PageTop, una página no se escribe: se **compone**. El *handler* añade componentes; el tema decide
|
|
||||||
dónde va cada uno y cómo se ve; las extensiones pueden intervenir en el camino. Esta página explica
|
|
||||||
quién decide qué, y en qué orden.
|
|
||||||
|
|
||||||
## Componentes, no HTML
|
|
||||||
|
|
||||||
`with_child()` no añade HTML a la página, sino **un componente**: un valor Rust con sus datos.
|
|
||||||
El HTML se genera más tarde, al llamar a `render()`, cuando ya se sabe:
|
|
||||||
|
|
||||||
- el **idioma** de quien visita, para resolver cada `Lc`;
|
|
||||||
- el **tema** activo, que puede ajustar o reescribir el componente;
|
|
||||||
- el **usuario**, para mostrar u ocultar lo que corresponda;
|
|
||||||
- los **recursos** que necesita cada componente, para ponerlos en el `<head>`.
|
|
||||||
|
|
||||||
Por eso un componente no debe guardar HTML ya generado: guarda los datos (un `Lc`, una ruta, otros
|
|
||||||
componentes) y los convierte en HTML al renderizarse.
|
|
||||||
|
|
||||||
## Regiones y plantillas
|
|
||||||
|
|
||||||
Un tema reparte la página en **regiones** (cabecera, contenido, barra lateral, pie...) según una
|
|
||||||
**plantilla**. Los componentes llegan a una región por tres caminos:
|
|
||||||
|
|
||||||
| Camino | Alcance |
|
|
||||||
|---|---|
|
|
||||||
| `page.with_child(c)` / `with_child_in(®ion, c)` | Sólo esta página |
|
|
||||||
| `InRegion::Global(®ion).add(c)` | Todas las páginas, con cualquier tema |
|
|
||||||
| `InRegion::ForTheme(&theme, ®ion).add(c)` | Todas las páginas, sólo con ese tema |
|
|
||||||
|
|
||||||
Las regiones de `CoreRegions` (`Header`, `Content`, `Aside`, `Footer`) existen en cualquier tema,
|
|
||||||
así que una extensión que las use funciona con todos. Un tema puede definir más.
|
|
||||||
|
|
||||||
## El renderizado de una página
|
|
||||||
|
|
||||||
`Page::render()` sigue este orden:
|
|
||||||
|
|
||||||
```text
|
|
||||||
Page::render()
|
|
||||||
1. theme: before_render_page_body(page) the theme adds its own assets
|
|
||||||
2. extensions: BeforeRenderBody e.g. HTMX adds its script
|
|
||||||
3. <body>: the theme renders the regions every component, see below
|
|
||||||
4. theme: after_render_page_body(page)
|
|
||||||
5. extensions: AfterRenderBody
|
|
||||||
6. deferred: postponed components, in place e.g. the messages of Content
|
|
||||||
7. <head>: title, metadata and every asset collected so far
|
|
||||||
```
|
|
||||||
|
|
||||||
El `<head>` se genera **al final**: así recoge los estilos y *scripts* que los componentes
|
|
||||||
añadieron al contexto mientras se renderizaban. Un componente que sólo aparece en algunas páginas
|
|
||||||
sólo carga sus recursos en esas páginas, y una vez aunque aparezca muchas veces.
|
|
||||||
|
|
||||||
Un componente puede pedir que se le **aplace** (`is_deferred()` devuelve `true`): en el paso 3 deja
|
|
||||||
una marca en su sitio y se renderiza en el 6, cuando ya está hecho el resto. Se aplaza el momento,
|
|
||||||
no la posición: se muestra donde estaba. Así funciona el `Messages` con el que empieza la región
|
|
||||||
`Content`: aunque aparece al principio, recoge los avisos que añadan los componentes de toda la
|
|
||||||
página. Si un componente aplazado no genera nada, la marca, un comentario HTML, se queda en su
|
|
||||||
sitio; por eso los temas ocultan las regiones vacías con el selector `.region:empty`.
|
|
||||||
|
|
||||||
## El renderizado de un componente
|
|
||||||
|
|
||||||
Cada componente, en cada región, pasa por estos pasos:
|
|
||||||
|
|
||||||
```text
|
|
||||||
component.render(cx)
|
|
||||||
1. is_renderable(cx)? no -> nothing is rendered
|
|
||||||
2. setup(cx) the component adjusts its own state
|
|
||||||
3. BeforeRender<C> extensions adjust it (add classes, change texts...)
|
|
||||||
4. for the active theme, then its parent, and so on:
|
|
||||||
setup_component() the theme adjusts it
|
|
||||||
render_component() the theme may render it its own way -> done
|
|
||||||
5. prepare(cx) if no theme rendered it, the component does
|
|
||||||
6. AfterRender<C> extensions react
|
|
||||||
7. TransformMarkup<C> extensions retouch the final HTML
|
|
||||||
```
|
|
||||||
|
|
||||||
Tres ideas salen de aquí:
|
|
||||||
|
|
||||||
- **El componente propone, el tema dispone.** El componente define sus datos y un HTML por defecto;
|
|
||||||
el tema puede retocar los datos (`setup_component()`) o reemplazar el HTML entero
|
|
||||||
(`render_component()`). Por eso los componentes exponen sus datos con *getters*: el tema los lee
|
|
||||||
sin depender de sus detalles internos.
|
|
||||||
- **Los temas se heredan.** Si el tema activo no reescribe un componente, se pregunta a su padre, y
|
|
||||||
así hasta llegar al HTML del propio componente. Un tema hijo sólo cambia lo que necesita.
|
|
||||||
- **Las extensiones no se pisan.** Varias acciones del mismo tipo se ejecutan en orden de peso, y
|
|
||||||
cada `TransformMarkup` recibe el HTML que dejó la anterior.
|
|
||||||
|
|
||||||
Si `prepare()` devuelve un error, la página no se cae: se registra una traza con el componente y la
|
|
||||||
ruta, y se pinta un contenido de reserva en su lugar.
|
|
||||||
|
|
||||||
## `setup()` prepara, `prepare()` pinta
|
|
||||||
|
|
||||||
`setup()` es síncrono y recibe el componente mutable: es el sitio para calcular clases o ajustar
|
|
||||||
datos. `prepare()` es asíncrono y recibe el componente sin poder modificarlo: es el sitio para
|
|
||||||
consultar una base de datos o un servicio y generar el HTML. Separarlos permite que las acciones y
|
|
||||||
el tema actúen **entre** los dos, sobre un componente ya ajustado.
|
|
||||||
|
|
||||||
## Fragmentos para HTMX
|
|
||||||
|
|
||||||
Un componente también se renderiza fuera de una página, con `component.render(&mut cx)`, para
|
|
||||||
devolverlo como fragmento a [HTMX](htmx.md). Pasa por los mismos pasos, con el mismo tema y las
|
|
||||||
mismas acciones, así que el fragmento es idéntico a como se vería dentro de la página. Lo único que
|
|
||||||
no tiene es `<head>`: los recursos que el componente añada al contexto no llegan al navegador, y la
|
|
||||||
página que recibe el fragmento debe cargarlos ya.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear un componente](../how-to/custom-components.md).
|
|
||||||
- [Crear un tema](../how-to/themes.md) e [Intervenir con acciones](../how-to/actions.md).
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
# Por qué PageTop
|
|
||||||
|
|
||||||
Durante años, la web se construyó así: el servidor genera HTML, el navegador lo muestra y un poco
|
|
||||||
de JavaScript lo hace más ágil. Funcionaba, se entendía y cualquiera podía inspeccionarlo. Luego
|
|
||||||
llegaron las aplicaciones de una sola página, los *frameworks* isomórficos y los *builds* de
|
|
||||||
*frontend* con cientos de dependencias.
|
|
||||||
|
|
||||||
PageTop apuesta por volver a lo esencial, pero con herramientas de hoy:
|
|
||||||
|
|
||||||
| La web clásica | Lo que añade PageTop |
|
|
||||||
|---|---|
|
|
||||||
| HTML generado en el servidor | Generado con código Rust comprobado por el compilador |
|
|
||||||
| Plantillas sueltas | Componentes tipados, configurables y reutilizables |
|
|
||||||
| *Plugins* con efectos inesperados | Extensiones con dependencias declaradas y orden de arranque garantizado |
|
|
||||||
| Temas que se pelean con el contenido | Temas que deciden cómo se pinta cada componente |
|
|
||||||
| Despliegue de muchos archivos | Un binario con los recursos dentro |
|
|
||||||
|
|
||||||
## Cuatro ideas, nada más
|
|
||||||
|
|
||||||
Todo PageTop gira alrededor de cuatro conceptos. Los verás una y otra vez en esta guía:
|
|
||||||
|
|
||||||
- **Extensiones.** Unidades de funcionalidad. Tu aplicación es una extensión, y las que añadas
|
|
||||||
(base de datos, usuarios, un tema...) también lo son.
|
|
||||||
- **Componentes.** Piezas de interfaz que encapsulan HTML, CSS y JavaScript. Se combinan como
|
|
||||||
bloques para formar páginas.
|
|
||||||
- **Temas.** Extensiones especiales que dan el aspecto: maquetan la página por regiones y pueden
|
|
||||||
ajustar o reescribir cualquier componente.
|
|
||||||
- **Acciones.** Puntos de enganche: permiten que una extensión modifique lo que hace otra sin
|
|
||||||
tocar su código.
|
|
||||||
|
|
||||||
## Lo que hay debajo
|
|
||||||
|
|
||||||
PageTop no reinventa la rueda; reúne piezas consolidadas del ecosistema Rust:
|
|
||||||
|
|
||||||
- [Axum](https://docs.rs/axum) y [Tokio](https://tokio.rs) para el servidor web asíncrono.
|
|
||||||
- [Maud](https://maud.lambda.xyz) para escribir HTML dentro de Rust.
|
|
||||||
- [Fluent](https://projectfluent.org) para las traducciones.
|
|
||||||
- [config-rs](https://docs.rs/config) para la configuración en archivos TOML.
|
|
||||||
- [tracing](https://docs.rs/tracing) para las trazas.
|
|
||||||
|
|
||||||
Y se apoya en extensiones opcionales para todo lo demás: [Bootstrap](https://getbootstrap.com) como
|
|
||||||
tema, [HTMX](https://htmx.org) para la interactividad o [SeaORM](https://www.sea-ql.org/SeaORM)
|
|
||||||
para las bases de datos.
|
|
||||||
|
|
||||||
## Cuándo no es la mejor opción
|
|
||||||
|
|
||||||
PageTop está pensado para aplicaciones web generadas en el servidor: gestión, portales, intranets,
|
|
||||||
sitios con contenido. Probablemente **no** sea lo que buscas si:
|
|
||||||
|
|
||||||
- necesitas una aplicación que funcione **sin conexión**, o casi toda su lógica vive en el
|
|
||||||
navegador;
|
|
||||||
- sólo quieres una **API** JSON, sin páginas: Axum a secas es más directo;
|
|
||||||
- necesitas **estabilidad** de API a largo plazo hoy mismo: PageTop todavía cambia entre versiones
|
|
||||||
hasta la 1.0.
|
|
||||||
|
|
||||||
Para todo lo demás, sigue leyendo: [HTML por la red: por qué HTMX](htmx.md) explica cómo cubre
|
|
||||||
PageTop la interactividad sin un *frontend* aparte.
|
|
||||||
|
|
||||||
## Licencia
|
|
||||||
|
|
||||||
PageTop es software libre con doble licencia **MIT o Apache 2.0**, a tu elección. Puedes usarlo en
|
|
||||||
proyectos abiertos o cerrados.
|
|
||||||
|
|
@ -1,157 +0,0 @@
|
||||||
# Preguntas frecuentes
|
|
||||||
|
|
||||||
## Desarrollo
|
|
||||||
|
|
||||||
**¿En qué se diferencia PageTop de Loco, Cot o Axum?**
|
|
||||||
|
|
||||||
En que organiza la aplicación en extensiones, componentes y temas, y genera la interfaz en el
|
|
||||||
servidor con HTMX para la interactividad. La comparación completa, con lo que a PageTop todavía le
|
|
||||||
falta, está en [PageTop frente a otros *frameworks*](explanation/comparison.md).
|
|
||||||
|
|
||||||
**¿Cómo reinicio la aplicación sola cada vez que cambio el código?**
|
|
||||||
|
|
||||||
Con una herramienta que vigile los archivos, como [watchexec](https://github.com/watchexec/watchexec):
|
|
||||||
|
|
||||||
```sh
|
|
||||||
watchexec -r -e rs,toml,ftl -- cargo run
|
|
||||||
```
|
|
||||||
|
|
||||||
Reinicia el servidor al cambiar el código, la configuración o las traducciones.
|
|
||||||
[bacon](https://dystroy.org/bacon/) es otra buena opción.
|
|
||||||
|
|
||||||
**¿Puedo cambiar el CSS sin recompilar?**
|
|
||||||
|
|
||||||
Sí. Si publicas tus archivos con `serve_static_files!(files, ["./static", app] => "/static")`,
|
|
||||||
mientras el directorio `static/` exista se sirven desde el disco: editas, recargas el navegador y
|
|
||||||
ves el cambio. En producción, sin ese directorio, se sirven desde el binario. Ver [Servir recursos
|
|
||||||
estáticos](how-to/assets.md).
|
|
||||||
|
|
||||||
**¿Cómo cambio el puerto?**
|
|
||||||
|
|
||||||
En `config/local.toml`, sin recompilar:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[server]
|
|
||||||
bind_port = 3000
|
|
||||||
```
|
|
||||||
|
|
||||||
**Mi aplicación no arranca después de tocar la configuración.**
|
|
||||||
|
|
||||||
Es a propósito: una clave desconocida o un valor no válido detienen el arranque. El mensaje dice la
|
|
||||||
sección y la clave. Compara con las [opciones de configuración](reference/configuration.md).
|
|
||||||
|
|
||||||
**¿Por qué los enlaces de mi página añaden `?lang=es`?**
|
|
||||||
|
|
||||||
Porque el visitante eligió idioma con `?lang=es` y ése no es el idioma por defecto. Los enlaces
|
|
||||||
internos lo conservan para que no lo pierda al navegar. Si construyes las URL con `cx.route()` o
|
|
||||||
pasas rutas a los componentes, PageTop se encarga solo. Ver [Añadir
|
|
||||||
navegación](how-to/navigation.md#enlaces-que-conservan-el-idioma).
|
|
||||||
|
|
||||||
## Interfaz
|
|
||||||
|
|
||||||
**¿Puedo usar mi propio CSS, o Tailwind?**
|
|
||||||
|
|
||||||
Sí. Puedes añadir hojas de estilo a cualquier página o componente, o crear un tema que las cargue
|
|
||||||
en todas. Los componentes usan clases propias y el tema decide cómo se ven; un tema hijo puede
|
|
||||||
traducir esas clases a las de tu *framework* CSS. Ver [Crear un tema](how-to/themes.md).
|
|
||||||
|
|
||||||
**¿Cómo añado JavaScript propio?**
|
|
||||||
|
|
||||||
Como un recurso más: `JavaScript::defer("/static/js/app.js")` en una página o un componente, o
|
|
||||||
`JavaScript::on_load()` para código que se ejecuta cuando el DOM está listo. Ver [Construir
|
|
||||||
páginas](how-to/pages.md#4-añade-estilos-y-scripts).
|
|
||||||
|
|
||||||
**Mi fragmento de HTMX no aparece en la página.**
|
|
||||||
|
|
||||||
Las causas habituales, en este orden:
|
|
||||||
|
|
||||||
1. La ruta responde con un código **4xx o 5xx**: HTMX no coloca esas respuestas. Usa 200 para los
|
|
||||||
errores que el usuario deba ver.
|
|
||||||
2. El **destino** no existe: revisa el selector de `hx-target`. Si el fragmento sustituyó al propio
|
|
||||||
destino (`outerHTML`) sin incluir su `id`, la siguiente petición ya no lo encuentra.
|
|
||||||
3. Un atributo **heredado** de un elemento padre (`hx-swap`, `hx-target`) cambia el comportamiento.
|
|
||||||
|
|
||||||
En la pestaña *Red* de las herramientas del navegador ves la petición, su código y el HTML
|
|
||||||
recibido.
|
|
||||||
|
|
||||||
**¿Puedo tener una API JSON en la misma aplicación?**
|
|
||||||
|
|
||||||
Sí. Una ruta puede devolver `Json<T>` con cualquier tipo serializable, junto a las que devuelven
|
|
||||||
páginas. Ver [Añadir rutas](how-to/routes.md#4-elige-la-respuesta).
|
|
||||||
|
|
||||||
## Datos
|
|
||||||
|
|
||||||
**¿Qué bases de datos admite?**
|
|
||||||
|
|
||||||
PostgreSQL, MySQL (y MariaDB) y SQLite, a través de `pagetop-seaorm`. El código es el mismo para
|
|
||||||
las tres; cambian la *feature* y la configuración. Ver [Conectar una base de
|
|
||||||
datos](how-to/database.md).
|
|
||||||
|
|
||||||
**¿Puedo escribir SQL a mano?**
|
|
||||||
|
|
||||||
Sí. `fetch_all()` y `fetch_one()` ejecutan consultas construidas con `db::query`, y `execute()`
|
|
||||||
sentencias que modifican datos. Ver [Escribe SQL a mano](how-to/database.md#8-escribe-sql-a-mano).
|
|
||||||
|
|
||||||
**¿Cómo muestro una página 404 o 500 con el aspecto del sitio?**
|
|
||||||
|
|
||||||
Devuelve `Err(ErrorPage::NotFound(Some(request)))` (o la variante que toque) desde el *handler*. Ver
|
|
||||||
[Mostrar páginas de error](how-to/error-pages.md).
|
|
||||||
|
|
||||||
**¿Cómo comprimo las respuestas o limito el tamaño de lo que se envía?**
|
|
||||||
|
|
||||||
Con las capas de `tower-http` en `configure_middleware()`. Ver [Añadir
|
|
||||||
*middleware*](how-to/middleware.md).
|
|
||||||
|
|
||||||
**¿Puedo programar tareas periódicas o enviar correos?**
|
|
||||||
|
|
||||||
Sí, con dos extensiones oficiales: `pagetop-cron` ejecuta trabajos en segundo plano según una
|
|
||||||
expresión cron o a intervalos (ve [Programar tareas periódicas](how-to/cron.md)), y `pagetop-mail`
|
|
||||||
envía correo (ve [Enviar correo electrónico](how-to/mail.md)), con una cola opcional
|
|
||||||
que guarda los correos en la base de datos y reintenta los que fallan. Lo que todavía no tiene
|
|
||||||
PageTop es una cola de trabajos genérica que sobreviva a un reinicio, como las de Loco (ve la
|
|
||||||
[comparación con otros *frameworks*](explanation/comparison.md)).
|
|
||||||
|
|
||||||
**¿Tengo que usar una base de datos?**
|
|
||||||
|
|
||||||
No. Sólo la necesitan las extensiones que la usan, como `pagetop-user`. Una aplicación sin datos
|
|
||||||
persistentes, o que los guarda en otro sitio, funciona igual.
|
|
||||||
|
|
||||||
## Producción
|
|
||||||
|
|
||||||
**¿Necesito Cargo o Rust en el servidor?**
|
|
||||||
|
|
||||||
No. El binario de `cargo build --release` lleva dentro los estilos, los *scripts*, las imágenes y
|
|
||||||
las traducciones. En el servidor sólo necesita, a su lado, el directorio `config/`. Ver [Desplegar
|
|
||||||
en producción](how-to/deployment.md).
|
|
||||||
|
|
||||||
**¿Está listo para producción?**
|
|
||||||
|
|
||||||
PageTop está en desarrollo activo y su API puede cambiar entre versiones hasta la 1.0. Se apoya en
|
|
||||||
piezas maduras del ecosistema (Axum, Tokio, SeaORM, Fluent), pero conviene evaluarlo con tus
|
|
||||||
propios requisitos antes de llevarlo a un sistema crítico.
|
|
||||||
|
|
||||||
**¿Necesito *tokens* CSRF en los formularios?**
|
|
||||||
|
|
||||||
No. PageTop rechaza con `403` las peticiones que pueden cambiar algo (`POST`, `PUT`...) cuando el
|
|
||||||
navegador indica que vienen de otro origen, sin campos ocultos ni *cookies* adicionales. Sólo debes
|
|
||||||
cuidar que ningún `GET` cambie nada. Ver [Sin *tokens* contra
|
|
||||||
CSRF](how-to/forms.md#6-sin-tokens-contra-csrf).
|
|
||||||
|
|
||||||
**Un formulario responde con 403 en producción.**
|
|
||||||
|
|
||||||
Las causas habituales, en este orden:
|
|
||||||
|
|
||||||
1. El formulario está en **otro origen** (otro dominio, subdominio o puerto). Si es una aplicación
|
|
||||||
tuya, añade su origen a `trusted_origins` de `[server]`.
|
|
||||||
2. El **proxy inverso** cambia la cabecera `Host`. Conserva la original (`proxy_set_header Host
|
|
||||||
$host;` en nginx). Ver [Detrás de un proxy
|
|
||||||
inverso](how-to/deployment.md#5-detrás-de-un-proxy-inverso).
|
|
||||||
3. Falta un **permiso**: el 403 es de la aplicación, no de la protección contra CSRF.
|
|
||||||
|
|
||||||
Las trazas lo distinguen: cada petición rechazada por venir de otro origen deja un aviso con la
|
|
||||||
ruta y las cabeceras `Sec-Fetch-Site` y `Origin` recibidas.
|
|
||||||
|
|
||||||
**¿Cómo se detiene sin perder peticiones?**
|
|
||||||
|
|
||||||
Con `Ctrl+C` o con `SIGTERM` (lo que envían `systemd` y Docker), PageTop deja de aceptar
|
|
||||||
conexiones, termina las peticiones en curso y vuelca las trazas pendientes.
|
|
||||||
|
|
@ -1,118 +0,0 @@
|
||||||
# Intervenir con acciones
|
|
||||||
|
|
||||||
**Objetivo:** cambiar lo que hace otra extensión (cómo se ve un componente, qué HTML genera, qué
|
|
||||||
lleva cada página) sin tocar su código.
|
|
||||||
|
|
||||||
Una **acción** permite a una extensión intervenir en lo que hace otra sin tocar su código: ajustar
|
|
||||||
un componente antes de pintarlo, retocar su HTML o añadir algo a todas las páginas.
|
|
||||||
|
|
||||||
Se declaran en `actions()` con la macro `actions!`. PageTop las registra una sola vez al arrancar.
|
|
||||||
|
|
||||||
## 1. Ajusta un componente antes de renderizarlo
|
|
||||||
|
|
||||||
`BeforeRender<C>` recibe el componente (mutable) y el contexto, justo antes de que se pinte. Por
|
|
||||||
ejemplo, añadir una clase a **todos** los botones de la aplicación:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct RoundButtons;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for RoundButtons {
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![action::component::BeforeRender::<Button>::new(round)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn round(button: &mut Button, _cx: &mut Context) {
|
|
||||||
button.alter_prop(PropsOp::add_classes("rounded-pill"));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para actuar sólo sobre un componente concreto, fíltralo por su identificador:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn highlight(button: &mut Button, _cx: &mut Context) {}
|
|
||||||
# fn f() -> Vec<ActionBox> {
|
|
||||||
actions![
|
|
||||||
action::component::BeforeRender::<Button>::new(highlight).filter_by_referer_id("buy"),
|
|
||||||
]
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Retoca el HTML final
|
|
||||||
|
|
||||||
`TransformMarkup<C>` recibe el HTML ya generado y devuelve el nuevo. Si hay varias, se encadenan:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Marker;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Marker {
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![action::component::TransformMarkup::<Block>::new(mark_block)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mark_block(_block: &Block, _cx: &Context, markup: Markup) -> Markup {
|
|
||||||
html! {
|
|
||||||
div class="marked-block" { (markup) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`AfterRender<C>` se ejecuta tras renderizar, por si sólo necesitas reaccionar (registrar algo,
|
|
||||||
por ejemplo).
|
|
||||||
|
|
||||||
## 3. Interviene en todas las páginas
|
|
||||||
|
|
||||||
`BeforeRenderBody` y `AfterRenderBody` reciben la página entera. Así añade la extensión HTMX su
|
|
||||||
*script* a todas las páginas:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Analytics;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Analytics {
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![action::page::BeforeRenderBody::new(add_script)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_script(page: &mut Page) {
|
|
||||||
page.alter_assets(JavaScript::defer("/static/js/analytics.js"));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Decide el orden
|
|
||||||
|
|
||||||
Las acciones de un mismo tipo se ejecutan por **peso** (de menor a mayor; admite negativos) y,
|
|
||||||
a igualdad de peso, por orden de registro:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn first(b: &mut Button, cx: &mut Context) {}
|
|
||||||
# fn f() -> Vec<ActionBox> {
|
|
||||||
actions![action::component::BeforeRender::<Button>::new(first).with_weight(-10)]
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Resumen
|
|
||||||
|
|
||||||
| Acción | Recibe | Momento |
|
|
||||||
|---|---|---|
|
|
||||||
| `component::BeforeRender<C>` | `&mut C`, `&mut Context` | Antes de renderizar `C` |
|
|
||||||
| `component::AfterRender<C>` | `&mut C`, `&mut Context` | Después de renderizar `C` |
|
|
||||||
| `component::TransformMarkup<C>` | `&C`, `&Context`, `Markup` | Para sustituir el HTML de `C` |
|
|
||||||
| `page::BeforeRenderBody` | `&mut Page` | Antes de renderizar el `<body>` |
|
|
||||||
| `page::AfterRenderBody` | `&mut Page` | Después de renderizar el `<body>` |
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear un tema](themes.md): un tema puede hacer lo mismo para todos los componentes.
|
|
||||||
- [Componentes, temas y renderizado](../explanation/rendering.md): en qué momento exacto actúa cada
|
|
||||||
acción.
|
|
||||||
|
|
@ -1,408 +0,0 @@
|
||||||
# Añadir páginas al panel de administración
|
|
||||||
|
|
||||||
**Objetivo:** dar a tu extensión su sitio en el panel `/admin`: una página de ajustes que el panel
|
|
||||||
construye y guarda por ti, y una página propia con tu contenido, cada una protegida por su permiso.
|
|
||||||
|
|
||||||
El panel es de PageTop: las páginas se **declaran** con acciones, y el panel las coloca en su
|
|
||||||
sección, las enlaza desde su página de inicio (*dashboard*) y las muestra sólo a quien tenga
|
|
||||||
permiso. Los permisos los concede [`pagetop-user`](users.md), que además declara en el panel la
|
|
||||||
gestión de usuarios y roles. Los formularios de ajustes que se guardan en la base de datos los
|
|
||||||
aporta `pagetop-admin`.
|
|
||||||
|
|
||||||
## 1. Añade la dependencia
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop-admin = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
pagetop-user = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
Tu extensión depende de `pagetop_user::User`, como en [Añadir usuarios y permisos](users.md), y de
|
|
||||||
`pagetop_admin::Admin`, que monta las páginas de ajustes. Una extensión que sólo aporte páginas
|
|
||||||
propias, sin ajustes, no necesita `pagetop-admin`.
|
|
||||||
|
|
||||||
Ese es el `Cargo.toml` de la **aplicación**, la única que elige el motor de base de datos (aquí
|
|
||||||
SQLite) para todas sus extensiones. Si escribes una extensión aparte, declara `pagetop-admin` y
|
|
||||||
`pagetop-user` igual, pero sin `pagetop-seaorm` (ve [Elige el motor](database.md#1-elige-el-motor)).
|
|
||||||
|
|
||||||
## 2. Define el permiso de cada página
|
|
||||||
|
|
||||||
Cada página del panel exige un permiso. Decláralo como cualquier otro:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum GardenPermission {
|
|
||||||
Configure,
|
|
||||||
SeeHarvest,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permission for GardenPermission {
|
|
||||||
fn key(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::Configure => "garden.configure".into(),
|
|
||||||
Self::SeeHarvest => "garden.see_harvest".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn label(&self) -> Lc {
|
|
||||||
match self {
|
|
||||||
Self::Configure => Lc::n("Configure the garden"),
|
|
||||||
Self::SeeHarvest => Lc::n("See the harvest report"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group(&self) -> &'static str {
|
|
||||||
"garden"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group_label(&self) -> Lc {
|
|
||||||
Lc::n("Community garden")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Decláralo con `DeclarePermissions` para que aparezca en la pantalla de roles (lo verás en el
|
|
||||||
ejemplo completo).
|
|
||||||
|
|
||||||
## 3. Deja que el panel construya tus ajustes
|
|
||||||
|
|
||||||
Para una página de ajustes no necesitas ni *handler* ni ruta. Describe los campos con un
|
|
||||||
`SettingsSchema` y declara la página junto a su esquema con la acción `DeclareConfigForms` de
|
|
||||||
`pagetop-admin`. El panel registra la ruta, pinta el formulario con los valores actuales y guarda
|
|
||||||
lo que se envía, salvo que falte algún campo obligatorio o llegue vacío:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_admin::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum GardenPermission { Configure }
|
|
||||||
# impl Permission for GardenPermission {
|
|
||||||
# fn key(&self) -> CowStr { "garden.configure".into() }
|
|
||||||
# }
|
|
||||||
fn garden_settings() -> SettingsSchema {
|
|
||||||
SettingsSchema::new("garden")
|
|
||||||
.with_field(
|
|
||||||
SettingField::text("notice", Lc::n("Notice for the gardeners"))
|
|
||||||
.with_help(Lc::n("Shown on the home page. Leave it empty to hide it.")),
|
|
||||||
)
|
|
||||||
.with_field(SettingField::number("plots", Lc::n("Number of plots")).with_required(true))
|
|
||||||
.with_field(SettingField::boolean("open", Lc::n("Open to new gardeners")))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
|
||||||
bag.add(ConfigFormPage {
|
|
||||||
page: AdminPage::new(
|
|
||||||
"config/garden",
|
|
||||||
"config",
|
|
||||||
Lc::n("Garden"),
|
|
||||||
&GardenPermission::Configure,
|
|
||||||
)
|
|
||||||
.with_description(Lc::n("Notice, plots and new gardeners.")),
|
|
||||||
schema: garden_settings(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Regístrala en tu extensión con `actions![DeclareConfigForms::new(declare_forms)]`.
|
|
||||||
|
|
||||||
Los campos pueden ser `text`, `number`, `boolean` o `select` (con sus opciones), y admiten
|
|
||||||
`with_required()`, `with_help()` y `with_default()`. Las etiquetas, la ayuda y las opciones son
|
|
||||||
`Lc`, como cualquier texto visible: con `Lc::t()` salen traducidas al idioma de quien administra.
|
|
||||||
|
|
||||||
Las páginas se agrupan en las secciones del panel: `people` (personas), `structure` (estructura),
|
|
||||||
`config` (configuración), `reports` (informes) y `help` (ayuda). El primer argumento de
|
|
||||||
`AdminPage::new()` es la ruta de la página **relativa a la raíz del panel**, que suele colgar de la
|
|
||||||
de su sección: `"config/garden"` es `/admin/config/garden` con la raíz por defecto (el ajuste
|
|
||||||
[`admin_path`](../reference/configuration.md) de `[app]`).
|
|
||||||
|
|
||||||
## 4. Lee los ajustes guardados
|
|
||||||
|
|
||||||
Cada campo se guarda con la clave `<ámbito>.<campo>`: aquí, `garden.notice`, `garden.plots` y
|
|
||||||
`garden.open`. Léelos con `pagetop_admin::settings::get_or()`, con el valor que quieras mientras
|
|
||||||
nadie los haya guardado:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let notice: String = pagetop_admin::settings::get_or("garden.notice", String::new()).await;
|
|
||||||
let open = pagetop_admin::settings::get_or("garden.open", String::new()).await == "true";
|
|
||||||
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Community garden"))
|
|
||||||
.with_child(Html::with(move |_| {
|
|
||||||
html! {
|
|
||||||
@if !notice.is_empty() {
|
|
||||||
p class="garden-notice" { (notice) }
|
|
||||||
}
|
|
||||||
p { @if open { "We are open to new gardeners." } @else { "No free plots now." } }
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El formulario guarda todos los valores **como texto**, también los números y las casillas
|
|
||||||
(`"true"` o `"false"`): conviértelos al leerlos.
|
|
||||||
|
|
||||||
## 5. Añade una página con tu propio contenido
|
|
||||||
|
|
||||||
Cuando la página no es un formulario de ajustes, declárala con la acción `DeclareAdminPages` y
|
|
||||||
registra tú su ruta con `routes.admin_route()`. El *handler* crea la página con
|
|
||||||
`Page::admin()`, le da título y añade su contenido. La plantilla de administración añade el resto:
|
|
||||||
la navegación del panel, la ruta de migas, el título y las pestañas y botones de la página:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum GardenPermission { SeeHarvest }
|
|
||||||
# impl Permission for GardenPermission {
|
|
||||||
# fn key(&self) -> CowStr { "garden.see_harvest".into() }
|
|
||||||
# }
|
|
||||||
fn declare_report(bag: &mut AdminPageBag) {
|
|
||||||
bag.add(
|
|
||||||
AdminPage::new(
|
|
||||||
"reports/harvest",
|
|
||||||
"reports",
|
|
||||||
Lc::n("Harvest"),
|
|
||||||
&GardenPermission::SeeHarvest,
|
|
||||||
)
|
|
||||||
.with_description(Lc::n("Kilos harvested by crop.")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let rows = [("Tomatoes", 42), ("Lettuces", 18), ("Courgettes", 27)];
|
|
||||||
Page::admin(request)
|
|
||||||
.with_title(Lc::n("Harvest"))
|
|
||||||
.with_child(Html::with(move |_| {
|
|
||||||
html! {
|
|
||||||
ul {
|
|
||||||
@for (crop, kilos) in rows {
|
|
||||||
li { (crop) ": " (kilos) " kg" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
La ruta se monta en `configure_router()` con `routes.admin_route("reports/harvest",
|
|
||||||
web::get(harvest))`, relativa a la raíz del panel como la página. No lleva permiso: exige el de la
|
|
||||||
página de la que cuelga, que se declara sólo una vez, en la página. PageTop lo comprueba antes de
|
|
||||||
llegar a `harvest()`, así que el *handler* no tiene que hacerlo.
|
|
||||||
|
|
||||||
Una ruta cuelga de la página más cercana que se encuentra quitándole tramos por el final:
|
|
||||||
`reports/harvest/{year}` cuelga de `reports/harvest` y exige su mismo permiso. Una ruta del panel
|
|
||||||
que no cuelgue de ninguna página, o que se monte con `routes.route()` en vez de con
|
|
||||||
`admin_route()`, impide arrancar la aplicación. Sólo hace falta `require_permission()` para un
|
|
||||||
permiso más concreto que el de la página, como el de una acción que no todos pueden hacer.
|
|
||||||
|
|
||||||
## 6. Crea una sección propia (opcional)
|
|
||||||
|
|
||||||
Si ninguna sección encaja, declara la tuya con `DeclareAdminSections`. Aparece en el panel en
|
|
||||||
cuanto tenga alguna página que el usuario pueda abrir:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
fn declare_sections(bag: &mut AdminSectionBag) {
|
|
||||||
bag.add(AdminSection::new("garden", Lc::n("Garden")).with_weight(25));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Regístrala junto a las páginas:
|
|
||||||
`actions![action::admin::DeclareAdminSections::new(declare_sections), ...]`. El peso decide su
|
|
||||||
posición entre las demás (las de serie usan 10, 20, 30...). Con `DeclareAdminTasks` y
|
|
||||||
`DeclareAdminActions` puedes añadir también pestañas y botones a una página.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_admin::prelude::*;
|
|
||||||
use pagetop_user::prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum GardenPermission {
|
|
||||||
Configure,
|
|
||||||
SeeHarvest,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permission for GardenPermission {
|
|
||||||
fn key(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::Configure => "garden.configure".into(),
|
|
||||||
Self::SeeHarvest => "garden.see_harvest".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn label(&self) -> Lc {
|
|
||||||
match self {
|
|
||||||
Self::Configure => Lc::n("Configure the garden"),
|
|
||||||
Self::SeeHarvest => Lc::n("See the harvest report"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group(&self) -> &'static str {
|
|
||||||
"garden"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group_label(&self) -> Lc {
|
|
||||||
Lc::n("Community garden")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
|
||||||
registry.register(&GardenPermission::Configure);
|
|
||||||
registry.register(&GardenPermission::SeeHarvest);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn garden_settings() -> SettingsSchema {
|
|
||||||
SettingsSchema::new("garden")
|
|
||||||
.with_field(
|
|
||||||
SettingField::text("notice", Lc::n("Notice for the gardeners"))
|
|
||||||
.with_help(Lc::n("Shown on the home page. Leave it empty to hide it.")),
|
|
||||||
)
|
|
||||||
.with_field(SettingField::number("plots", Lc::n("Number of plots")).with_required(true))
|
|
||||||
.with_field(SettingField::boolean("open", Lc::n("Open to new gardeners")))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
|
||||||
bag.add(ConfigFormPage {
|
|
||||||
page: AdminPage::new(
|
|
||||||
"config/garden",
|
|
||||||
"config",
|
|
||||||
Lc::n("Garden"),
|
|
||||||
&GardenPermission::Configure,
|
|
||||||
)
|
|
||||||
.with_description(Lc::n("Notice, plots and new gardeners.")),
|
|
||||||
schema: garden_settings(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_pages(bag: &mut AdminPageBag) {
|
|
||||||
bag.add(
|
|
||||||
AdminPage::new(
|
|
||||||
"reports/harvest",
|
|
||||||
"reports",
|
|
||||||
Lc::n("Harvest"),
|
|
||||||
&GardenPermission::SeeHarvest,
|
|
||||||
)
|
|
||||||
.with_description(Lc::n("Kilos harvested by crop.")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_user::User, &pagetop_admin::Admin]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![
|
|
||||||
action::auth::DeclarePermissions::new(declare_permissions),
|
|
||||||
DeclareConfigForms::new(declare_forms),
|
|
||||||
action::admin::DeclareAdminPages::new(declare_pages),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.admin_route("reports/harvest", web::get(harvest))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(AutoDefault, Clone, Debug)]
|
|
||||||
struct TopBar;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Component for TopBar {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
let brand = Brand::new()
|
|
||||||
.with_title(Lc::n("Community garden"))
|
|
||||||
.with_route(Route::from("/"));
|
|
||||||
Ok(Navbar::brand_left(brand)
|
|
||||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
|
||||||
.render(cx)
|
|
||||||
.await)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let notice: String = pagetop_admin::settings::get_or("garden.notice", String::new()).await;
|
|
||||||
let open = pagetop_admin::settings::get_or("garden.open", String::new()).await == "true";
|
|
||||||
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Community garden"))
|
|
||||||
.with_child(Html::with(move |_| {
|
|
||||||
html! {
|
|
||||||
@if !notice.is_empty() {
|
|
||||||
p class="garden-notice" { (notice) }
|
|
||||||
}
|
|
||||||
p { @if open { "We are open to new gardeners." } @else { "No free plots now." } }
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let rows = [("Tomatoes", 42), ("Lettuces", 18), ("Courgettes", 27)];
|
|
||||||
Page::admin(request)
|
|
||||||
.with_title(Lc::n("Harvest"))
|
|
||||||
.with_child(Html::with(move |_| {
|
|
||||||
html! {
|
|
||||||
ul {
|
|
||||||
@for (crop, kilos) in rows {
|
|
||||||
li { (crop) ": " (kilos) " kg" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Usa la misma configuración de base de datos y del administrador que en [Añadir usuarios y
|
|
||||||
permisos](users.md#2-configura-la-base-de-datos-y-el-primer-administrador).
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Sin iniciar sesión, <http://localhost:8080/admin/reports/harvest> te lleva al formulario de
|
|
||||||
inicio de sesión.
|
|
||||||
2. Inicia sesión como `admin` y entra en **Administración** desde el menú de cuenta. El inicio del
|
|
||||||
panel muestra «Garden» en Configuración y «Harvest» en Informes.
|
|
||||||
3. Abre «Garden», escribe un aviso, marca «Open to new gardeners» y guarda. La portada muestra el
|
|
||||||
aviso y «We are open to new gardeners.».
|
|
||||||
4. En la pantalla de roles aparece el grupo «Community garden» con sus dos permisos. Concede «See
|
|
||||||
the harvest report» a otro rol: sus usuarios verán el informe, pero no los ajustes.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Añadir usuarios y permisos](users.md): roles, permisos y el menú de cuenta.
|
|
||||||
- [Extensiones oficiales](../reference/extensions.md#administración): lo que aporta
|
|
||||||
`pagetop-admin`.
|
|
||||||
- [Intervenir con acciones](actions.md): `DeclareAdminPages`, `DeclareConfigForms` y compañía son
|
|
||||||
acciones.
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
# Servir recursos estáticos
|
|
||||||
|
|
||||||
**Objetivo:** incluir en el binario las hojas de estilo, *scripts*, fuentes e imágenes de tu
|
|
||||||
aplicación, publicarlos en una ruta y usarlos en las páginas.
|
|
||||||
|
|
||||||
Hojas de estilo, *scripts*, fuentes e imágenes se **incluyen en el binario** al compilar. En
|
|
||||||
producción no hay que copiar ningún directorio: el ejecutable lo lleva todo.
|
|
||||||
|
|
||||||
## 1. Sigue la convención `assets/` -> `static/`
|
|
||||||
|
|
||||||
```text
|
|
||||||
my-app/
|
|
||||||
├── assets/ <- versioned sources (SCSS, JS, images...)
|
|
||||||
├── static/ <- generated when compiling; add it to .gitignore
|
|
||||||
└── build.rs <- turns assets/ into static/ and prepares the bundles
|
|
||||||
```
|
|
||||||
|
|
||||||
Añade `pagetop-build` como dependencia de compilación:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[build-dependencies]
|
|
||||||
pagetop-build = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Prepara el `build.rs`
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop_build::*;
|
|
||||||
|
|
||||||
fn main() -> std::io::Result<()> {
|
|
||||||
// Regenerates static/ only if something changes in assets/.
|
|
||||||
println!("cargo:rerun-if-changed=assets");
|
|
||||||
let _ = std::fs::remove_dir_all("static");
|
|
||||||
|
|
||||||
// Transforms the sources.
|
|
||||||
compile_scss("assets/scss/app.scss", "static/css/app.min.css")?;
|
|
||||||
minify_js("assets/js/app.js", "static/js/app.min.js")?;
|
|
||||||
copy_dir("assets/img", "static/img")?;
|
|
||||||
|
|
||||||
// Bundles static/ to include it in the binary with the name "app".
|
|
||||||
StaticFilesBundle::from_dir("./static", None)
|
|
||||||
.with_name("app")
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Funciones disponibles: `compile_scss()`, `minify_js()`, `copy_dir()`, `copy_file()` y
|
|
||||||
`copy_file_replacing()`, que copia sustituyendo textos (útil para corregir referencias al renombrar
|
|
||||||
archivos). Puedes crear varios paquetes, cada uno con su nombre.
|
|
||||||
|
|
||||||
## 3. Sirve los archivos
|
|
||||||
|
|
||||||
En la extensión, publica el paquete con `serve_static_files!` dentro de
|
|
||||||
`configure_static_files()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct MyApp;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for MyApp {
|
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
|
||||||
serve_static_files!(files, ["./static", app] => "/static");
|
|
||||||
files
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Con la forma `["./static", app]`, si el directorio existe en disco (durante el desarrollo) los
|
|
||||||
archivos se sirven desde ahí y puedes editarlos sin recompilar; si no existe (en producción), se
|
|
||||||
sirven desde el binario. Con `[app]` se sirven siempre desde el binario.
|
|
||||||
|
|
||||||
Las rutas de `configure_static_files()` no pasan por el *middleware* de las extensiones: servir un
|
|
||||||
archivo no resuelve sesiones ni hace trabajo innecesario. Los archivos se sirven con `ETag`, así
|
|
||||||
que el navegador sólo los descarga de nuevo si cambian.
|
|
||||||
|
|
||||||
## 4. Úsalos en las páginas
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_assets(StyleSheet::from("/static/css/app.min.css").with_version("1.0"))
|
|
||||||
.with_assets(JavaScript::defer("/static/js/app.min.js").with_version("1.0"))
|
|
||||||
.with_child(Html::with(|_| html! { img src="/static/img/logo.svg" alt="Logo"; }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si tu extensión es un componente o un tema, añade sus recursos en el `setup()` del componente o
|
|
||||||
en el tema: así se cargan sólo cuando hacen falta.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Pide uno de los archivos directamente (`curl -I http://localhost:8080/static/css/app.min.css`):
|
|
||||||
responde `200` con su `ETag`. Compila en modo *release*, borra `static/` y arranca el binario:
|
|
||||||
sigue sirviéndolo, desde dentro del ejecutable.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear un componente](custom-components.md#5-sus-propios-estilos): componentes que traen sus
|
|
||||||
propios estilos.
|
|
||||||
- [Desplegar en producción](deployment.md).
|
|
||||||
|
|
@ -1,301 +0,0 @@
|
||||||
# Conectar tu propia autenticación
|
|
||||||
|
|
||||||
**Objetivo:** que PageTop sepa quién hace cada petición y qué permisos tiene cuando los usuarios no
|
|
||||||
vienen de `pagetop-user`, sino de otro sistema: un *proxy* que autentica, un directorio LDAP, un
|
|
||||||
proveedor OAuth o tu propia base de datos.
|
|
||||||
|
|
||||||
PageTop no guarda usuarios ni decide quién tiene cada permiso. Sólo define cómo se **expresa** un
|
|
||||||
permiso y comprueba el acceso de cada ruta antes de llegar a su *handler*. Una extensión de
|
|
||||||
autenticación aporta tres piezas, cada una en su sitio:
|
|
||||||
|
|
||||||
| Pieza | Dónde | Qué responde |
|
|
||||||
|---|---|---|
|
|
||||||
| `CurrentUser` | Un *middleware* en `configure_middleware()` | ¿Quién hace la petición? |
|
|
||||||
| `CheckPermission` | Una acción | ¿Tiene este permiso? |
|
|
||||||
| `AnonymousDenied` | Una acción (opcional) | ¿Qué se responde a un anónimo sin acceso? |
|
|
||||||
|
|
||||||
`pagetop-user` es una extensión así. En esta guía escribes una más sencilla para el caso habitual
|
|
||||||
de un *proxy* inverso que ya ha autenticado al usuario y lo pasa en la cabecera `Remote-User`.
|
|
||||||
|
|
||||||
> **Aviso:** fíate de `Remote-User` sólo si la aplicación únicamente es accesible a través del
|
|
||||||
> *proxy* y éste elimina la cabecera de las peticiones que recibe. Si un cliente puede llegar
|
|
||||||
> directamente a la aplicación, podría enviarla él mismo y hacerse pasar por cualquier usuario.
|
|
||||||
|
|
||||||
## 1. Di quién hace la petición
|
|
||||||
|
|
||||||
Un *middleware* lee la cabecera y deja un `CurrentUser` en la petición. PageTop lo recoge al crear
|
|
||||||
la página (`cx.current_user()`) y lo ven las acciones de permisos. Sin `CurrentUser`, el usuario es
|
|
||||||
anónimo.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
// Users the proxy can send: name, id and granted permissions.
|
|
||||||
const USERS: &[(&str, i32, &[&str])] = &[
|
|
||||||
("ana", 1, &["garden:see_harvest"]),
|
|
||||||
("luis", 2, &[]),
|
|
||||||
];
|
|
||||||
|
|
||||||
async fn resolve_user(mut request: web::Request, next: web::middleware::Next) -> Response {
|
|
||||||
let user = request
|
|
||||||
.headers()
|
|
||||||
.get("remote-user")
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.and_then(|name| USERS.iter().find(|(user, ..)| *user == name));
|
|
||||||
if let Some((name, id, _)) = user {
|
|
||||||
request
|
|
||||||
.extensions_mut()
|
|
||||||
.insert(CurrentUser::authenticated(*id, *name));
|
|
||||||
}
|
|
||||||
next.run(request).await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Regístralo en `configure_middleware()`, que envuelve las rutas de todas las extensiones:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# async fn resolve_user(request: web::Request, next: web::middleware::Next) -> Response {
|
|
||||||
# next.run(request).await
|
|
||||||
# }
|
|
||||||
# pub struct ProxyAuth;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for ProxyAuth {
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
|
||||||
layers.layer(web::middleware::from_fn(resolve_user))
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Concede los permisos
|
|
||||||
|
|
||||||
La acción `CheckPermission` recibe la petición y un permiso, y pone `granted` a `true` si lo
|
|
||||||
concede. La consultan el acceso de cada ruta (`Access::Permission`), las rutas del panel de
|
|
||||||
administración y `has_permission()`. Si ninguna extensión concede un permiso, nadie lo tiene.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# const USERS: &[(&str, i32, &[&str])] = &[("ana", 1, &["garden:see_harvest"])];
|
|
||||||
fn grant(request: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
|
|
||||||
let Some(id) = request.extension::<CurrentUser>().and_then(CurrentUser::id) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let key = perm.key();
|
|
||||||
*granted = USERS
|
|
||||||
.iter()
|
|
||||||
.any(|(_, user, keys)| *user == id && keys.contains(&key.as_ref()));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Se registra en `actions()`. Si hay varias extensiones de autenticación, basta con que una lo
|
|
||||||
conceda.
|
|
||||||
|
|
||||||
## 3. Ofrece el inicio de sesión al anónimo
|
|
||||||
|
|
||||||
A quien no cumple el acceso de una ruta, PageTop le responde con la página de acceso denegado
|
|
||||||
(403). A un anónimo es mejor llevarle a identificarse: la acción `AnonymousDenied` devuelve esa
|
|
||||||
respuesta, aquí una redirección al inicio de sesión del *proxy* con la ruta a la que volver.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
fn offer_login(request: &HttpRequest) -> Option<Response> {
|
|
||||||
let login = RoutePath::new("/auth/login").with_param("rd", request.uri());
|
|
||||||
// HTMX would follow the redirect and paint the login form inside the fragment it expected:
|
|
||||||
// ask it to load the whole page instead.
|
|
||||||
if request.headers().contains_key("hx-request") {
|
|
||||||
return Some([("hx-redirect", login.to_string())].into_response());
|
|
||||||
}
|
|
||||||
Some(Redirect::see_other(login))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si devuelve `None`, responde la siguiente acción o, si no hay más, la página 403. Un usuario
|
|
||||||
autenticado sin el permiso recibe siempre el 403.
|
|
||||||
|
|
||||||
## 4. Protege las rutas
|
|
||||||
|
|
||||||
Las rutas no cambian: cada una declara su acceso, con independencia de qué extensión autentique
|
|
||||||
(ver [Añadir rutas](routes.md)).
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum GardenPermission { SeeHarvest }
|
|
||||||
# impl Permission for GardenPermission {
|
|
||||||
# fn key(&self) -> CowStr { "garden:see_harvest".into() }
|
|
||||||
# }
|
|
||||||
# async fn home() -> &'static str { "" }
|
|
||||||
# async fn harvest() -> &'static str { "" }
|
|
||||||
# pub struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.route(
|
|
||||||
"/harvest",
|
|
||||||
Access::Permission(&GardenPermission::SeeHarvest),
|
|
||||||
web::get(harvest),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`Access::Authenticated` sirve para lo que sólo pide haber iniciado sesión: lo cumple cualquier
|
|
||||||
petición con un `CurrentUser` autenticado.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
// Users the proxy can send: name, id and granted permissions.
|
|
||||||
const USERS: &[(&str, i32, &[&str])] = &[
|
|
||||||
("ana", 1, &["garden:see_harvest"]),
|
|
||||||
("luis", 2, &[]),
|
|
||||||
];
|
|
||||||
|
|
||||||
// **< Authentication >*****************************************************************************
|
|
||||||
|
|
||||||
pub struct ProxyAuth;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for ProxyAuth {
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![
|
|
||||||
action::auth::CheckPermission::new(grant),
|
|
||||||
action::auth::AnonymousDenied::new(offer_login),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
|
||||||
layers.layer(web::middleware::from_fn(resolve_user))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn resolve_user(mut request: web::Request, next: web::middleware::Next) -> Response {
|
|
||||||
let user = request
|
|
||||||
.headers()
|
|
||||||
.get("remote-user")
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.and_then(|name| USERS.iter().find(|(user, ..)| *user == name));
|
|
||||||
if let Some((name, id, _)) = user {
|
|
||||||
request
|
|
||||||
.extensions_mut()
|
|
||||||
.insert(CurrentUser::authenticated(*id, *name));
|
|
||||||
}
|
|
||||||
next.run(request).await
|
|
||||||
}
|
|
||||||
|
|
||||||
fn grant(request: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
|
|
||||||
let Some(id) = request.extension::<CurrentUser>().and_then(CurrentUser::id) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let key = perm.key();
|
|
||||||
*granted = USERS
|
|
||||||
.iter()
|
|
||||||
.any(|(_, user, keys)| *user == id && keys.contains(&key.as_ref()));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn offer_login(request: &HttpRequest) -> Option<Response> {
|
|
||||||
let login = RoutePath::new("/auth/login").with_param("rd", request.uri());
|
|
||||||
if request.headers().contains_key("hx-request") {
|
|
||||||
return Some([("hx-redirect", login.to_string())].into_response());
|
|
||||||
}
|
|
||||||
Some(Redirect::see_other(login))
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< Application >********************************************************************************
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum GardenPermission {
|
|
||||||
SeeHarvest,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permission for GardenPermission {
|
|
||||||
fn key(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::SeeHarvest => "garden:see_harvest".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn label(&self) -> Lc {
|
|
||||||
Lc::n("See the harvest")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
|
||||||
registry.register(&GardenPermission::SeeHarvest);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&ProxyAuth]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![action::auth::DeclarePermissions::new(declare_permissions)]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.route(
|
|
||||||
"/harvest",
|
|
||||||
Access::Permission(&GardenPermission::SeeHarvest),
|
|
||||||
web::get(harvest),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Urban garden"))
|
|
||||||
.with_child(Html::with(|cx| {
|
|
||||||
let user = cx.current_user();
|
|
||||||
html! {
|
|
||||||
@if let Some(name) = user.display_name() {
|
|
||||||
p { "Hello, " (name) "." }
|
|
||||||
} @else {
|
|
||||||
p { "Hello, visitor." }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Harvest"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "Tomatoes: 42 kg." } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Sin el *proxy* delante, puedes simular sus cabeceras con `curl`:
|
|
||||||
|
|
||||||
1. `curl -i -H "Remote-User: ana" http://localhost:8080/harvest` responde 200 con la cosecha.
|
|
||||||
2. `curl -i -H "Remote-User: luis" http://localhost:8080/harvest` responde 403: ha iniciado sesión,
|
|
||||||
pero no tiene el permiso.
|
|
||||||
3. `curl -i http://localhost:8080/harvest` responde 303 hacia `/auth/login?rd=%2Fharvest`.
|
|
||||||
4. `curl -i -H "HX-Request: true" http://localhost:8080/harvest` responde 200 sin cuerpo y con la
|
|
||||||
cabecera `HX-Redirect`.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Añadir usuarios y permisos](users.md): la extensión `pagetop-user`, con cuentas, sesiones y
|
|
||||||
roles.
|
|
||||||
- [Añadir rutas](routes.md): los tres accesos de una ruta.
|
|
||||||
- [Arquitectura](../explanation/architecture.md#el-acceso-a-cada-ruta): cómo encaja el acceso en el
|
|
||||||
recorrido de una petición.
|
|
||||||
|
|
@ -1,201 +0,0 @@
|
||||||
# Usar componentes
|
|
||||||
|
|
||||||
**Objetivo:** construir la interfaz con los componentes que trae PageTop: crearlos, configurarlos,
|
|
||||||
anidarlos y ajustar sus clases y atributos sin tocar su código.
|
|
||||||
|
|
||||||
Un **componente** es una pieza de interfaz con su propio HTML (y, si los necesita, sus estilos y
|
|
||||||
*scripts*). Se crea con un constructor, se configura con métodos `with_*()` encadenados y se añade
|
|
||||||
a una página o a otro componente.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(
|
|
||||||
Block::new()
|
|
||||||
.with_title(Lc::n("What's new"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "Version 2 is here." } }))
|
|
||||||
.with_child(Button::anchor(Lc::n("Download"), "/downloads")),
|
|
||||||
)
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Los componentes **no se pintan al crearlos**, sino al renderizar la página. Por eso pueden
|
|
||||||
adaptarse al idioma de cada visitante, al tema activo o al usuario conectado.
|
|
||||||
|
|
||||||
## El catálogo básico
|
|
||||||
|
|
||||||
PageTop trae un conjunto de componentes que funcionan con cualquier tema. La lista completa, con
|
|
||||||
sus constructores, está en el [catálogo de componentes](../reference/components.md).
|
|
||||||
|
|
||||||
| Componente | Para qué sirve |
|
|
||||||
|---|---|
|
|
||||||
| `Html` | Marcado puntual con `html!` |
|
|
||||||
| `Container` | Agrupa componentes en un `<div>`, `<section>`, `<header>`... |
|
|
||||||
| `Block` | Bloque con título y contenido |
|
|
||||||
| `Intro` | Portada de bienvenida con título, eslogan y botón |
|
|
||||||
| `Button` | Botones y enlaces con aspecto de botón |
|
|
||||||
| `Badge` | Etiquetas pequeñas de estado |
|
|
||||||
| `Image` | Imágenes, también *responsive* |
|
|
||||||
| `Brand` | Logotipo y nombre del sitio |
|
|
||||||
| `Breadcrumb` | Migas de pan |
|
|
||||||
| `Messages` | Avisos al usuario |
|
|
||||||
| `Dialog` | Ventanas de diálogo |
|
|
||||||
| `Flex`, `Grid` | [Maquetación](layout.md) |
|
|
||||||
| `Nav`, `Navbar`, `Dropdown` | [Navegación](navigation.md) |
|
|
||||||
| `Form` y sus campos | [Formularios](forms.md) |
|
|
||||||
| `Table`, `Pager` | [Tablas y paginación](tables.md) |
|
|
||||||
| `PoweredBy` | Pie con el crédito «Funciona con PageTop» |
|
|
||||||
|
|
||||||
## Contenedores
|
|
||||||
|
|
||||||
`Container` agrupa varios componentes. Elige la etiqueta con el constructor:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Container {
|
|
||||||
Container::section()
|
|
||||||
.with_id("team")
|
|
||||||
.with_child(Html::with(|_| html! { h2 { "The team" } }))
|
|
||||||
.with_child(Block::new().with_title(Lc::n("Ana")))
|
|
||||||
.with_child(Block::new().with_title(Lc::n("Luke")))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`Container::new()` genera un `<div>`; también están `header()`, `main()`, `section()`,
|
|
||||||
`article()` y `footer()`.
|
|
||||||
|
|
||||||
## Botones
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Vec<Button> { vec![
|
|
||||||
// A link that looks like a button.
|
|
||||||
Button::anchor(Lc::n("See the catalog"), "/catalog"),
|
|
||||||
// A form submit button, with style and intent.
|
|
||||||
Button::submit(Lc::n("Save"))
|
|
||||||
.with_style(button::Style::Solid(Intent::Success))
|
|
||||||
.with_size(button::Size::Large),
|
|
||||||
// An outline button, disabled.
|
|
||||||
Button::plain(Lc::n("Delete"))
|
|
||||||
.with_style(button::Style::Outline(Intent::Severe))
|
|
||||||
.with_disabled(true),
|
|
||||||
# ] }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Intenciones
|
|
||||||
|
|
||||||
Muchos componentes reciben una `Intent`: el **significado** del color, no el color. El tema decide
|
|
||||||
cómo se ve cada una.
|
|
||||||
|
|
||||||
| `Intent` | Significado |
|
|
||||||
|---|---|
|
|
||||||
| `Primary` | Acción principal |
|
|
||||||
| `Neutral` | Sin énfasis |
|
|
||||||
| `Info` | Información |
|
|
||||||
| `Success` | Éxito o confirmación |
|
|
||||||
| `Warning` | Advertencia |
|
|
||||||
| `Severe` | Error o acción peligrosa |
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Vec<Badge> { vec![
|
|
||||||
Badge::success(Lc::n("Active")),
|
|
||||||
Badge::warning(Lc::n("Pending")),
|
|
||||||
Badge::neutral(Lc::n("Archived")),
|
|
||||||
# ] }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Imágenes
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Image {
|
|
||||||
Image::with(image::Source::responsive("/static/img/cover.jpg"))
|
|
||||||
.with_alternative(Lc::n("View of the harbour at dawn"))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
El origen (`image::Source`) decide cómo se muestra: `plain()` a su tamaño, `responsive()` ajustada
|
|
||||||
al ancho disponible y `thumbnail()` como miniatura.
|
|
||||||
|
|
||||||
## Identificadores, clases y estilos
|
|
||||||
|
|
||||||
Todos los componentes aceptan `with_id()` y `with_prop()`. Con `PropsOp` añades clases, atributos
|
|
||||||
o estilos sin tocar el componente:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Block {
|
|
||||||
Block::new()
|
|
||||||
.with_id("featured")
|
|
||||||
.with_prop(PropsOp::add_classes("block-highlight shadow"))
|
|
||||||
.with_prop(PropsOp::set("data-section", "home"))
|
|
||||||
.with_prop(PropsOp::add_style("border-radius", "8px"))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Para márgenes y rellenos hay tipos propios, `Margin` y `Padding`, con unidades tipadas:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Block {
|
|
||||||
Block::new()
|
|
||||||
.with_prop(Margin::new().with_bottom(UnitValue::RelRem(2.0)))
|
|
||||||
.with_prop(Padding::new().with_all(UnitValue::Px(16)))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Mensajes al usuario
|
|
||||||
|
|
||||||
`Page` acumula avisos en su contexto, y la región de contenido empieza siempre por un componente
|
|
||||||
`Messages` que los muestra. Basta con añadirlos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn saved(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let mut page = Page::new(request);
|
|
||||||
page.push_message(MessageLevel::Info, Lc::n("Your changes have been saved."));
|
|
||||||
page.render().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Ese `Messages` se renderiza el último, cuando ya está hecho el resto de la página, así que recoge
|
|
||||||
también los avisos que añadan los componentes al renderizarse, aunque se muestre al principio. Cada
|
|
||||||
aviso aparece una sola vez: añade tu propio `Messages::new()` sólo para mostrarlos en otro lugar,
|
|
||||||
por ejemplo justo antes de un formulario, o en un fragmento de HTMX, que no tiene página.
|
|
||||||
|
|
||||||
Para avisar en la página a la que rediriges, añade el mensaje a la respuesta con `with_message()`
|
|
||||||
(ver [Crear y procesar formularios](forms.md#3-recibe-y-valida-los-datos)).
|
|
||||||
|
|
||||||
## Una portada en un minuto
|
|
||||||
|
|
||||||
`Intro` monta una página de presentación con un solo componente:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn landing(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(
|
|
||||||
Intro::custom()
|
|
||||||
.with_title(Lc::n("Urban Garden"))
|
|
||||||
.with_slogan(Lc::n("Grow your city"))
|
|
||||||
.with_button(Some((Lc::n("Start here"), Route::from("/guide"))))
|
|
||||||
.with_child(
|
|
||||||
Block::new()
|
|
||||||
.with_title(Lc::n("What is it?"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "A network of community gardens." } })),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear un componente](custom-components.md), cuando ninguno encaja.
|
|
||||||
- [Maquetar con Flex y Grid](layout.md).
|
|
||||||
- [Catálogo de componentes](../reference/components.md).
|
|
||||||
|
|
@ -1,164 +0,0 @@
|
||||||
# Configurar la aplicación
|
|
||||||
|
|
||||||
**Objetivo:** ajustar la aplicación con archivos TOML, distintos por entorno y sin recompilar, y
|
|
||||||
dar a tu extensión sus propios ajustes, validados al arrancar.
|
|
||||||
|
|
||||||
La configuración vive en archivos [TOML](https://toml.io) dentro del directorio `config/`, junto
|
|
||||||
al `Cargo.toml`. Cambiar un puerto o un idioma no requiere recompilar.
|
|
||||||
|
|
||||||
## 1. Entiende la cascada de archivos
|
|
||||||
|
|
||||||
PageTop lee estos archivos, todos opcionales, en este orden. Cada uno sobrescribe a los anteriores
|
|
||||||
**sólo** en las claves que define:
|
|
||||||
|
|
||||||
| Archivo | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `config/common.toml` | Ajustes comunes a todos los entornos |
|
|
||||||
| `config/{mode}.toml` | Ajustes del modo de ejecución |
|
|
||||||
| `config/local.{mode}.toml` | Ajustes locales de ese modo (no se versiona) |
|
|
||||||
| `config/local.toml` | Ajustes locales para cualquier modo (no se versiona) |
|
|
||||||
|
|
||||||
El modo lo da la variable de entorno `PAGETOP_RUN_MODE` (`default` si no se define):
|
|
||||||
|
|
||||||
```sh
|
|
||||||
PAGETOP_RUN_MODE=production ./my-app # reads common.toml, production.toml, ...
|
|
||||||
```
|
|
||||||
|
|
||||||
`CONFIG_DIR` cambia el directorio `config/`. Las contraseñas y demás secretos van en un
|
|
||||||
`local.toml` que no se sube al repositorio, o en variables de entorno: cualquier clave se
|
|
||||||
sobrescribe con `PAGETOP_<SECCIÓN>__<CLAVE>`, con cada nivel separado por dos guiones bajos.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
PAGETOP_DATABASE__DB_PASS=secret ./my-app # db_pass of [database]
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Ajusta PageTop
|
|
||||||
|
|
||||||
Un `config/common.toml` típico:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[app]
|
|
||||||
name = "Urban Garden"
|
|
||||||
theme = "Bootsier"
|
|
||||||
language = "es-ES"
|
|
||||||
timezone = "Europe/Madrid"
|
|
||||||
|
|
||||||
[server]
|
|
||||||
bind_address = "0.0.0.0"
|
|
||||||
bind_port = 8080
|
|
||||||
|
|
||||||
[log]
|
|
||||||
tracing = "Info"
|
|
||||||
rolling = "Daily"
|
|
||||||
```
|
|
||||||
|
|
||||||
| Sección | Claves principales |
|
|
||||||
|---|---|
|
|
||||||
| `[app]` | `name`, `theme` (por defecto `"Basic"`), `language`, `lang_negotiation`, `timezone`, `startup_banner` |
|
|
||||||
| `[server]` | `bind_address` (por defecto `"localhost"`), `bind_port` (por defecto `8080`) |
|
|
||||||
| `[log]` | `enabled`, `tracing`, `rolling`, `path`, `prefix`, `format` |
|
|
||||||
| `[dev]` | `pagetop_static_dir`, para servir los recursos de PageTop desde disco |
|
|
||||||
|
|
||||||
Todas las opciones, con su tipo y su valor por defecto, están en [Opciones de
|
|
||||||
configuración](../reference/configuration.md).
|
|
||||||
|
|
||||||
## 3. Léelos desde el código
|
|
||||||
|
|
||||||
Los ajustes de PageTop se leen en `global::SETTINGS`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() {
|
|
||||||
let name = &global::SETTINGS.app.name;
|
|
||||||
let port = global::SETTINGS.server.bind_port;
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Errores que no pasan desapercibidos
|
|
||||||
|
|
||||||
Una **clave desconocida** (típicamente, una errata) o un **valor no válido** impiden arrancar la
|
|
||||||
aplicación, con un mensaje que lo localiza: el archivo y la línea si el TOML está mal escrito, o la
|
|
||||||
sección y la clave si el valor no es válido. Una sección que no corresponde a
|
|
||||||
ninguna extensión se ignora, con un aviso al arrancar.
|
|
||||||
|
|
||||||
## 5. Ajustes de tu extensión
|
|
||||||
|
|
||||||
Cada extensión declara sus ajustes en una estructura con `#[settings]`, ligada a una **sección
|
|
||||||
propia** del archivo. Los valores por defecto van en los campos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
/// Settings of the `[blog]` section.
|
|
||||||
pub static SETTINGS: LazySettings<BlogSettings> = LazySettings::new();
|
|
||||||
|
|
||||||
/// The **`[blog]`** section of the configuration.
|
|
||||||
#[settings(section = "blog")]
|
|
||||||
pub struct BlogSettings {
|
|
||||||
/// Title of the blog.
|
|
||||||
#[default = "My blog"]
|
|
||||||
pub title: String,
|
|
||||||
/// Posts per page.
|
|
||||||
#[default = 10]
|
|
||||||
pub page_size: u32,
|
|
||||||
/// Optional footer text (no default value: `None`).
|
|
||||||
pub footer: Option<String>,
|
|
||||||
/// Comments, in the `[blog.comments]` subsection.
|
|
||||||
pub comments: CommentsSettings,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The **`[blog.comments]`** subsection.
|
|
||||||
#[settings]
|
|
||||||
pub struct CommentsSettings {
|
|
||||||
/// Whether comments are allowed.
|
|
||||||
#[default = true]
|
|
||||||
pub enabled: bool,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
La extensión los devuelve en `settings()` para que se carguen (y se validen) al arrancar:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# pub static SETTINGS: LazySettings<BlogSettings> = LazySettings::new();
|
|
||||||
# #[settings(section = "blog")]
|
|
||||||
# pub struct BlogSettings {
|
|
||||||
# #[default = 10]
|
|
||||||
# pub page_size: u32,
|
|
||||||
# }
|
|
||||||
pub struct Blog;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Blog {
|
|
||||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
|
||||||
Some(&SETTINGS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn posts_per_page() -> u32 {
|
|
||||||
SETTINGS.page_size
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Y en `config/common.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[blog]
|
|
||||||
title = "Garden diary"
|
|
||||||
|
|
||||||
[blog.comments]
|
|
||||||
enabled = false
|
|
||||||
```
|
|
||||||
|
|
||||||
Los ajustes son de **sólo lectura** mientras la aplicación está en marcha.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Escribe mal una clave en `config/common.toml` (`bind_prot = 9000`) y arranca: la aplicación se
|
|
||||||
detiene y señala la clave. Corrígela y arranca con `PAGETOP_RUN_MODE=production`: se leen además
|
|
||||||
`production.toml` y `local.production.toml`, si existen.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Opciones de configuración](../reference/configuration.md): la referencia completa.
|
|
||||||
- [Desplegar en producción](deployment.md): la configuración en el servidor.
|
|
||||||
|
|
@ -1,339 +0,0 @@
|
||||||
# Programar tareas periódicas
|
|
||||||
|
|
||||||
**Objetivo:** ejecutar código en segundo plano mientras la aplicación está en marcha, según un
|
|
||||||
calendario (cada noche a las 4:30, cada lunes) o a intervalos (cada diez minutos), y dejar que
|
|
||||||
quien administra la aplicación lo cambie o lo desactive sin recompilar.
|
|
||||||
|
|
||||||
Lo aporta la extensión `pagetop-cron`. Cada extensión **declara** sus trabajos con una acción, y el
|
|
||||||
planificador los ejecuta cuando toca. El planificador sólo se pone en marcha con
|
|
||||||
`Application::run()`: en las pruebas no se ejecuta nada por sí solo, y cada prueba ejecuta el
|
|
||||||
trabajo que quiere cuando quiere.
|
|
||||||
|
|
||||||
## 1. Añade la dependencia
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop-cron = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y declara `pagetop_cron::Cron` en `dependencies()` de la extensión que aporta los trabajos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_cron::Cron]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Escribe el trabajo
|
|
||||||
|
|
||||||
Un trabajo es una función asíncrona que recibe un `JobContext` y devuelve un `JobResult`. Lee los
|
|
||||||
ajustes y los servicios de la aplicación igual que un *handler* (ve [Compartir un servicio entre
|
|
||||||
rutas](services.md)), y con `?` propaga cualquier error, que queda registrado en las trazas:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_cron::prelude::*;
|
|
||||||
async fn water_plots(cx: JobContext) -> JobResult {
|
|
||||||
let plan = std::fs::read_to_string("watering-plan.txt")?;
|
|
||||||
trace::info!("Watering {} plots ({:?})", plan.lines().count(), cx.trigger());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si el trabajo devuelve un error o provoca un `panic!`, la aplicación sigue en marcha y el trabajo
|
|
||||||
vuelve a ejecutarse cuando le toque.
|
|
||||||
|
|
||||||
## 3. Declara cuándo se ejecuta
|
|
||||||
|
|
||||||
Los trabajos se declaran con la acción `DeclareCronJobs`. Cada uno tiene una **clave** única, que
|
|
||||||
conviene empezar por el nombre de la extensión, y una programación (`Schedule`):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_cron::prelude::*;
|
|
||||||
# async fn water_plots(_cx: JobContext) -> JobResult { Ok(()) }
|
|
||||||
fn declare_jobs(jobs: &mut CronJobs) {
|
|
||||||
jobs.add(
|
|
||||||
Job::new("garden.water", Schedule::cron("30 6 * * *"), water_plots)
|
|
||||||
.with_title(Lc::n("Water the plots")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_cron::Cron]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![DeclareCronJobs::new(declare_jobs)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Hay tres formas de programarlo:
|
|
||||||
|
|
||||||
| Programación | Se ejecuta... |
|
|
||||||
|---|---|
|
|
||||||
| `Schedule::cron("30 6 * * *")` | Según una expresión cron: cada día a las 6:30 |
|
|
||||||
| `Schedule::fixed_rate(Duration::minutes(10))` | Cada 10 minutos desde que **empieza** la ejecución anterior |
|
|
||||||
| `Schedule::fixed_delay(Duration::seconds(30))` | 30 segundos después de que **termina** la ejecución anterior |
|
|
||||||
|
|
||||||
Las expresiones cron tienen los cinco campos clásicos (minuto, hora, día del mes, mes y día de la
|
|
||||||
semana), con un sexto campo opcional al principio para los segundos. Algunos ejemplos:
|
|
||||||
|
|
||||||
| Expresión | Se ejecuta... |
|
|
||||||
|---|---|
|
|
||||||
| `*/10 * * * *` | Cada diez minutos |
|
|
||||||
| `0 8-18 * * MON-FRI` | A cada hora en punto, de 8 a 18, de lunes a viernes |
|
|
||||||
| `0 0 L * *` | A medianoche del último día de cada mes |
|
|
||||||
| `0 9 * * MON#1` | A las 9:00 del primer lunes de cada mes |
|
|
||||||
| `*/30 * * * * *` | Cada treinta segundos |
|
|
||||||
| `@daily`, `@hourly`... | Al principio de cada día, de cada hora... |
|
|
||||||
|
|
||||||
Se interpretan en la zona horaria de la aplicación (`[app] timezone`) y respetan los cambios de
|
|
||||||
hora: una ejecución en una hora que no existe se hace al empezar la siguiente, y una en una hora
|
|
||||||
que se repite, una sola vez. La sintaxis completa está en la documentación de `Schedule`.
|
|
||||||
|
|
||||||
Para procesar algo pendiente (una cola, una lista de avisos), `fixed_delay()` suele ser la mejor
|
|
||||||
opción: dos ejecuciones nunca coinciden, y cada una empieza con lo que dejó la anterior.
|
|
||||||
|
|
||||||
## 4. Ajusta cómo se ejecuta
|
|
||||||
|
|
||||||
`Job` admite además:
|
|
||||||
|
|
||||||
| Método | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `with_timeout(Duration::minutes(5))` | Cancela la ejecución si dura más |
|
|
||||||
| `with_overlap(Overlap::Allow)` | Ejecuta aunque siga en curso la anterior; por defecto se omite (`Overlap::Skip`) |
|
|
||||||
| `with_run_on_start()` | Ejecuta también al arrancar, sin esperar a la primera hora programada |
|
|
||||||
| `with_timezone(Tz::Europe__Madrid)` | Interpreta su expresión cron en otra zona horaria |
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_cron::prelude::*;
|
|
||||||
# async fn check_sensors(_cx: JobContext) -> JobResult { Ok(()) }
|
|
||||||
# fn f() -> Job {
|
|
||||||
Job::new("garden.sensors", Schedule::fixed_delay(Duration::seconds(30)), check_sensors)
|
|
||||||
.with_timeout(Duration::seconds(20))
|
|
||||||
.with_run_on_start()
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
La función también puede ser un cierre, útil para trabajos cortos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_cron::prelude::*;
|
|
||||||
# fn f() -> Job {
|
|
||||||
Job::new("garden.heartbeat", Schedule::fixed_rate(Duration::minutes(1)), |cx| async move {
|
|
||||||
trace::debug!("Still alive ({})", cx.key());
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Cámbialo desde la configuración
|
|
||||||
|
|
||||||
Quien administra la aplicación puede cambiar cada trabajo por su clave, sin tocar el código, en la
|
|
||||||
subsección `[cron.jobs."clave"]`. La clave va entre comillas porque lleva un punto:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[cron.jobs."garden.water"]
|
|
||||||
schedule = "0 7 * * *" # Water at 7:00 instead.
|
|
||||||
timeout_secs = 600 # At most 10 minutes (0 = no limit).
|
|
||||||
|
|
||||||
[cron.jobs."garden.heartbeat"]
|
|
||||||
enabled = false # Never runs on its own.
|
|
||||||
```
|
|
||||||
|
|
||||||
`schedule` admite una expresión cron y también `"@every 10m"` (como `fixed_rate()`) y
|
|
||||||
`"@delay 30s"` (como `fixed_delay()`). Si una programación no es válida, la aplicación no arranca e
|
|
||||||
indica el trabajo; una clave que no corresponde a ningún trabajo sólo produce un aviso en las
|
|
||||||
trazas.
|
|
||||||
|
|
||||||
## 6. Con varias instancias, elige el modo
|
|
||||||
|
|
||||||
Por defecto (`mode = "internal"`) cada instancia de la aplicación ejecuta todos los trabajos. Si
|
|
||||||
despliegas varias (por ejemplo, detrás de un balanceador), cada trabajo se ejecutaría una vez por
|
|
||||||
instancia. Tienes dos opciones:
|
|
||||||
|
|
||||||
- **Uno solo ejecuta los trabajos:** deja `"internal"` en una instancia y pon `"off"` en las demás.
|
|
||||||
- **Un programa externo marca el ritmo:** pon `"external"` en todas y programa una sola llamada
|
|
||||||
cada minuto. Cada llamada llega a una instancia, que ejecuta lo programado en el último minuto:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[cron]
|
|
||||||
mode = "external"
|
|
||||||
trigger_token = "a-long-and-secret-token" # Better in config/local.toml.
|
|
||||||
```
|
|
||||||
|
|
||||||
```text
|
|
||||||
# System crontab: checks the jobs every minute. The file holds the line
|
|
||||||
# "Authorization: Bearer a-long-and-secret-token".
|
|
||||||
* * * * * curl -fsS -X POST -H @/etc/garden/cron-header https://garden.example.com/cron > /dev/null
|
|
||||||
```
|
|
||||||
|
|
||||||
La clave viaja en la cabecera `Authorization` y no en la ruta, que suelen registrar los *proxies*;
|
|
||||||
necesita al menos 16 letras, dígitos, `-` o `_`. Sin la clave correcta, la ruta responde `404`. La
|
|
||||||
llamada responde `200 OK` cuando terminan los trabajos, con una línea por trabajo y su resultado,
|
|
||||||
así que el programa externo debe esperar más de lo que tarde el más largo.
|
|
||||||
|
|
||||||
Como ninguna instancia recuerda lo que hicieron las demás, el programa externo debe llamar una vez,
|
|
||||||
y sólo una, cada minuto: si falta una llamada se pierden sus ejecuciones, y si sobra, pueden
|
|
||||||
repetirse. Para llamar con otra frecuencia, indícala en `trigger_interval_secs`. En este modo, un
|
|
||||||
trabajo no se ejecuta más a menudo que las llamadas.
|
|
||||||
|
|
||||||
Una llamada de más suele ser un reintento tras un error de red, que puede llegar a otra instancia.
|
|
||||||
Desactiva los reintentos del programa externo (p. ej. `backoffLimit: 0` en un *CronJob* de
|
|
||||||
Kubernetes) y, si un trabajo no debe repetirse nunca, haz que lo compruebe él mismo en la base de
|
|
||||||
datos antes de hacer nada.
|
|
||||||
|
|
||||||
Con `"off"`, los trabajos sólo se ejecutan si alguien lo pide con `pagetop_cron::run_now()`.
|
|
||||||
|
|
||||||
## 7. Termina a tiempo al detener la aplicación
|
|
||||||
|
|
||||||
Al detener la aplicación (Ctrl+C o `SIGTERM`), el planificador deja de lanzar ejecuciones y espera
|
|
||||||
hasta `shutdown_timeout_secs` (30 segundos por defecto) a que terminen las que están en curso. Un
|
|
||||||
trabajo largo puede preguntar por `is_stopping()` y dejar su trabajo en un punto seguro:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_cron::prelude::*;
|
|
||||||
# async fn send_reminder(_n: usize) {}
|
|
||||||
async fn send_reminders(cx: JobContext) -> JobResult {
|
|
||||||
for n in 0..500 {
|
|
||||||
if cx.is_stopping() {
|
|
||||||
trace::info!("Stopping at reminder {n}; the rest go in the next run");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
send_reminder(n).await;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
Riega el huerto según su programación y muestra en la portada cuántas veces se ha regado y cuándo
|
|
||||||
fue la última, a partir del estado del trabajo (`pagetop_cron::job()`):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_cron::prelude::*;
|
|
||||||
|
|
||||||
async fn water_plots(cx: JobContext) -> JobResult {
|
|
||||||
trace::info!("Watering the plots ({:?})", cx.trigger());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_jobs(jobs: &mut CronJobs) {
|
|
||||||
jobs.add(
|
|
||||||
Job::new("garden.water", Schedule::cron("30 6 * * *"), water_plots)
|
|
||||||
.with_title(Lc::n("Water the plots"))
|
|
||||||
.with_timeout(Duration::minutes(5)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_cron::Cron]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![DeclareCronJobs::new(declare_jobs)]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/", web::get(home))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let status = pagetop_cron::job("garden.water");
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden"))
|
|
||||||
.with_child(Html::with(move |_| match &status {
|
|
||||||
Some(status) => html! {
|
|
||||||
p { "Watered " (status.runs()) " times." }
|
|
||||||
@if let Some(last) = status.last_run() {
|
|
||||||
p { "Last time: " (last.started_at().format("%H:%M:%S UTC")) "." }
|
|
||||||
}
|
|
||||||
@if let Some(next) = status.next_run() {
|
|
||||||
p { "Next time: " (next.format("%Y-%m-%d %H:%M UTC")) "." }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
None => html! { p { "No watering job." } },
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Para no esperar a las 6:30, programa el riego cada diez segundos en `config/local.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[cron.jobs."garden.water"]
|
|
||||||
schedule = "@every 10s"
|
|
||||||
```
|
|
||||||
|
|
||||||
Arranca con `cargo run`: el terminal anuncia `Cron scheduler started with 1 of 1 jobs` y, cada diez
|
|
||||||
segundos, `Watering the plots (Schedule)`. Recarga `/` y verás crecer el número de riegos.
|
|
||||||
|
|
||||||
En las pruebas el planificador no arranca: ejecuta el trabajo con `run_now()`, que espera a que
|
|
||||||
termine y devuelve cómo fue:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_cron::prelude::*;
|
|
||||||
# async fn water_plots(_cx: JobContext) -> JobResult { Ok(()) }
|
|
||||||
# fn declare_jobs(jobs: &mut CronJobs) {
|
|
||||||
# jobs.add(Job::new("garden.water", Schedule::cron("30 6 * * *"), water_plots));
|
|
||||||
# }
|
|
||||||
# struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
# vec![&pagetop_cron::Cron]
|
|
||||||
# }
|
|
||||||
# fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
# actions![DeclareCronJobs::new(declare_jobs)]
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn watering_succeeds() {
|
|
||||||
Application::prepare(&Garden).await;
|
|
||||||
|
|
||||||
let run = pagetop_cron::run_now("garden.water").await.unwrap();
|
|
||||||
assert!(run.outcome().is_success(), "{}", run.outcome());
|
|
||||||
assert_eq!(pagetop_cron::job("garden.water").unwrap().runs(), 1);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para vigilar todos los trabajos (registrar sus ejecuciones, avisar cuando uno falla), registra la
|
|
||||||
acción `AfterJobRun`, que recibe el informe de cada ejecución terminada.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Opciones de configuración](../reference/configuration.md#cron): todas las claves de `[cron]`.
|
|
||||||
- [Compartir un servicio entre rutas](services.md): los servicios que usan los trabajos.
|
|
||||||
- [Desplegar en producción](deployment.md): la aplicación como servicio, que se detiene de forma
|
|
||||||
ordenada.
|
|
||||||
|
|
@ -1,240 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,813 +0,0 @@
|
||||||
# Conectar una base de datos
|
|
||||||
|
|
||||||
**Objetivo:** conectar la aplicación a PostgreSQL, MySQL o SQLite con `pagetop-seaorm`, mantener el
|
|
||||||
esquema con migraciones, consultar los datos con entidades tipadas, relacionar tablas y escribir
|
|
||||||
SQL cuando haga falta.
|
|
||||||
|
|
||||||
El tutorial [Guarda las tareas en una base de datos](../tutorials/database.md) recorre un caso
|
|
||||||
completo paso a paso. Esta guía reúne lo que necesitarás después.
|
|
||||||
|
|
||||||
## 1. Elige el motor
|
|
||||||
|
|
||||||
En una **aplicación**, activa el motor con una *feature* de `pagetop-seaorm`. Declararlas como
|
|
||||||
*features* propias te permite cambiar de motor al compilar:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[features]
|
|
||||||
default = ["postgres"]
|
|
||||||
postgres = ["pagetop-seaorm/postgres"]
|
|
||||||
mysql = ["pagetop-seaorm/mysql"]
|
|
||||||
sqlite = ["pagetop-seaorm/sqlite"]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
```
|
|
||||||
|
|
||||||
En una **extensión**, declara la dependencia sin *features*: el motor lo elige la aplicación que la
|
|
||||||
use, y Cargo lo activa para todo el árbol de dependencias.
|
|
||||||
|
|
||||||
## 2. Configura la conexión
|
|
||||||
|
|
||||||
La sección `[database]` describe la conexión. Lo que cambia entre motores:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# PostgreSQL (port 5432 by default)
|
|
||||||
[database]
|
|
||||||
db_type = "postgres"
|
|
||||||
db_name = "garden"
|
|
||||||
db_user = "garden"
|
|
||||||
db_host = "localhost"
|
|
||||||
```
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# MySQL or MariaDB (port 3306 by default)
|
|
||||||
[database]
|
|
||||||
db_type = "mysql"
|
|
||||||
db_name = "garden"
|
|
||||||
db_user = "garden"
|
|
||||||
db_host = "localhost"
|
|
||||||
```
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# SQLite: db_name is the file; mode=rwc creates it if it does not exist
|
|
||||||
[database]
|
|
||||||
db_type = "sqlite"
|
|
||||||
db_name = "garden.db?mode=rwc"
|
|
||||||
```
|
|
||||||
|
|
||||||
La contraseña, `db_pass`, va en `config/local.toml`, que no se sube al repositorio. `db_port` fija
|
|
||||||
otro puerto y `max_pool_size` el número máximo de conexiones simultáneas (5 por defecto).
|
|
||||||
|
|
||||||
Declara la extensión como dependencia de la tuya. Al arrancar, abre el *pool* de conexiones antes
|
|
||||||
de inicializar tu extensión; si no puede conectar, la aplicación no arranca y explica por qué.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_seaorm::SeaORM]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. Escribe las migraciones
|
|
||||||
|
|
||||||
Cada migración es un módulo dentro de `migration/`, con un nombre que empieza por la fecha para que
|
|
||||||
el orden sea el cronológico:
|
|
||||||
|
|
||||||
```text
|
|
||||||
src/
|
|
||||||
├── lib.rs
|
|
||||||
└── migration/
|
|
||||||
├── m20261015_000001_create_plots.rs
|
|
||||||
└── m20261101_000002_add_plot_notes.rs
|
|
||||||
```
|
|
||||||
|
|
||||||
Una crea la tabla y un índice:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
// src/migration/m20261015_000001_create_plots.rs
|
|
||||||
use pagetop_seaorm::migration::*;
|
|
||||||
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[pagetop::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
table_auto(Plots::Table)
|
|
||||||
.col(pk_auto(Plots::Id))
|
|
||||||
.col(string_uniq(Plots::Name))
|
|
||||||
.col(string(Plots::Holder))
|
|
||||||
.col(integer(Plots::Area))
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
manager
|
|
||||||
.create_index(
|
|
||||||
Index::create()
|
|
||||||
.name("idx_plots_holder")
|
|
||||||
.table(Plots::Table)
|
|
||||||
.col(Plots::Holder)
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.drop_table(Table::drop().table(Plots::Table).to_owned())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Plots {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
Name,
|
|
||||||
Holder,
|
|
||||||
Area,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Y otra, más adelante, añade una columna opcional:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
// src/migration/m20261101_000002_add_plot_notes.rs
|
|
||||||
use pagetop_seaorm::migration::*;
|
|
||||||
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[pagetop::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.alter_table(
|
|
||||||
Table::alter()
|
|
||||||
.table(Plots::Table)
|
|
||||||
.add_column(text_null(Plots::Notes))
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Plots {
|
|
||||||
Table,
|
|
||||||
Notes,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Las funciones de columna siguen un patrón: `string()`, `integer()`, `boolean()`, `date()`... son
|
|
||||||
obligatorias; con `_null` admiten nulos y con `_uniq` son únicas. `table_auto()` añade las columnas
|
|
||||||
`created_at` y `updated_at`.
|
|
||||||
|
|
||||||
## 4. Aplícalas al arrancar
|
|
||||||
|
|
||||||
En `src/lib.rs`, declara el módulo y aplica las migraciones en `initialize()`, en orden:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_seaorm::install_migrations;
|
|
||||||
|
|
||||||
mod migration {
|
|
||||||
pub mod m20261015_000001_create_plots;
|
|
||||||
pub mod m20261101_000002_add_plot_notes;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
// ...
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
install_migrations!(
|
|
||||||
m20261015_000001_create_plots,
|
|
||||||
m20261101_000002_add_plot_notes,
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Cada migración aplicada queda anotada en la tabla `seaql_migrations`, así que en los arranques
|
|
||||||
siguientes sólo se aplican las nuevas. Si una falla, la aplicación no arranca.
|
|
||||||
|
|
||||||
## 5. Define las entidades
|
|
||||||
|
|
||||||
Una entidad describe una fila. El *struct* se llama `Model` y sus campos son públicos; a partir de
|
|
||||||
él, `DeriveEntityModel` genera `Entity`, `Column` y `ActiveModel`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
// src/entity/plot.rs
|
|
||||||
use pagetop_seaorm::db::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
#[sea_orm(table_name = "plots")]
|
|
||||||
pub struct Model {
|
|
||||||
#[sea_orm(primary_key)]
|
|
||||||
pub id: i32,
|
|
||||||
pub name: String,
|
|
||||||
pub holder: String,
|
|
||||||
pub area: i32,
|
|
||||||
pub notes: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
pub enum Relation {}
|
|
||||||
|
|
||||||
impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
```
|
|
||||||
|
|
||||||
Una columna que admite nulos es un `Option` en la entidad.
|
|
||||||
|
|
||||||
## 6. Consulta los datos
|
|
||||||
|
|
||||||
Todas las consultas reciben el *pool* con `dbconn()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod plot {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "plots")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub name: String,
|
|
||||||
# pub holder: String,
|
|
||||||
# pub area: i32,
|
|
||||||
# pub notes: Option<String>,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
async fn examples() -> Result<(), DbErr> {
|
|
||||||
// All of them, ordered.
|
|
||||||
let plots = plot::Entity::find()
|
|
||||||
.order_by_asc(plot::Column::Name)
|
|
||||||
.all(dbconn())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Filtered, and by primary key.
|
|
||||||
let large = plot::Entity::find()
|
|
||||||
.filter(plot::Column::Area.gte(20))
|
|
||||||
.all(dbconn())
|
|
||||||
.await?;
|
|
||||||
let first = plot::Entity::find_by_id(1).one(dbconn()).await?;
|
|
||||||
|
|
||||||
// Insert.
|
|
||||||
let added = plot::ActiveModel {
|
|
||||||
name: Set("C3".into()),
|
|
||||||
holder: Set("Marta".into()),
|
|
||||||
area: Set(15),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
.insert(dbconn())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Update only some columns.
|
|
||||||
let mut changed = added.into_active_model();
|
|
||||||
changed.holder = Set("Luke".into());
|
|
||||||
changed.update(dbconn()).await?;
|
|
||||||
|
|
||||||
// Delete.
|
|
||||||
plot::Entity::delete_by_id(3).exec(dbconn()).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para un listado paginado, `paginate()` devuelve la página pedida con el total de elementos y de
|
|
||||||
páginas, justo lo que necesita un [`Pager`](tables.md#3-pagina-el-listado):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod plot {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "plots")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub name: String,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# async fn f(page_number: u64) -> Result<(), DbErr> {
|
|
||||||
let page = paginate(plot::Entity::find().order_by_asc(plot::Column::Name), page_number, 20).await?;
|
|
||||||
// page.items, page.total, page.page, page.per_page, page.total_pages
|
|
||||||
# Ok(())
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y para varias operaciones que deben aplicarse todas o ninguna, una transacción. Si cualquiera de
|
|
||||||
ellas falla, se deshacen todas: el intercambio de titulares nunca se queda a medias:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod plot {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "plots")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub holder: String,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# async fn f() -> Result<(), DbErr> {
|
|
||||||
// Swaps the holders of two plots.
|
|
||||||
dbconn()
|
|
||||||
.transaction::<_, (), DbErr>(|txn| {
|
|
||||||
Box::pin(async move {
|
|
||||||
plot::ActiveModel {
|
|
||||||
id: Unchanged(1),
|
|
||||||
holder: Set("Luke".into()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
.update(txn)
|
|
||||||
.await?;
|
|
||||||
plot::ActiveModel {
|
|
||||||
id: Unchanged(2),
|
|
||||||
holder: Set("Ana".into()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
.update(txn)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(flatten_txn_err)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`flatten_txn_err` convierte el error de la transacción en un `DbErr` normal, para seguir usando
|
|
||||||
`?`.
|
|
||||||
|
|
||||||
## 7. Relaciona tablas
|
|
||||||
|
|
||||||
Cada parcela da varias cosechas. La tabla `harvests` guarda el `id` de su parcela en `plot_id`, con
|
|
||||||
una clave ajena que impide apuntar a una parcela que no existe y borra sus cosechas si se borra la
|
|
||||||
parcela:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
// src/migration/m20261120_000003_create_harvests.rs
|
|
||||||
use pagetop_seaorm::migration::*;
|
|
||||||
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[pagetop::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
table_auto(Harvests::Table)
|
|
||||||
.col(pk_auto(Harvests::Id))
|
|
||||||
.col(integer(Harvests::PlotId))
|
|
||||||
.col(string(Harvests::Crop))
|
|
||||||
.col(integer(Harvests::Kilos))
|
|
||||||
.foreign_key(
|
|
||||||
ForeignKey::create()
|
|
||||||
.name("fk_harvests_plot")
|
|
||||||
.from(Harvests::Table, Harvests::PlotId)
|
|
||||||
.to(Plots::Table, Plots::Id)
|
|
||||||
.on_delete(ForeignKeyAction::Cascade),
|
|
||||||
)
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Harvests {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
PlotId,
|
|
||||||
Crop,
|
|
||||||
Kilos,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Plots {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
La relación se declara en las dos entidades. La cosecha **pertenece a** una parcela (`belongs_to`),
|
|
||||||
indicando qué columna apunta a cuál:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# mod harvest {
|
|
||||||
// src/entity/harvest.rs
|
|
||||||
use pagetop_seaorm::db::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
#[sea_orm(table_name = "harvests")]
|
|
||||||
pub struct Model {
|
|
||||||
#[sea_orm(primary_key)]
|
|
||||||
pub id: i32,
|
|
||||||
pub plot_id: i32,
|
|
||||||
pub crop: String,
|
|
||||||
pub kilos: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
pub enum Relation {
|
|
||||||
#[sea_orm(
|
|
||||||
belongs_to = "super::plot::Entity",
|
|
||||||
from = "Column::PlotId",
|
|
||||||
to = "super::plot::Column::Id"
|
|
||||||
)]
|
|
||||||
Plot,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Related<super::plot::Entity> for Entity {
|
|
||||||
fn to() -> RelationDef {
|
|
||||||
Relation::Plot.def()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# mod plot {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "plots")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y la parcela **tiene muchas** cosechas (`has_many`). Su `Relation`, vacía hasta ahora, queda así:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
// src/entity/plot.rs
|
|
||||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
pub enum Relation {
|
|
||||||
#[sea_orm(has_many = "super::harvest::Entity")]
|
|
||||||
Harvests,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Related<super::harvest::Entity> for Entity {
|
|
||||||
fn to() -> RelationDef {
|
|
||||||
Relation::Harvests.def()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Con las dos declaradas, puedes ir de una a otra sin escribir el `JOIN`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod plot {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "plots")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub name: String,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {
|
|
||||||
# #[sea_orm(has_many = "super::harvest::Entity")]
|
|
||||||
# Harvests,
|
|
||||||
# }
|
|
||||||
# impl Related<super::harvest::Entity> for Entity {
|
|
||||||
# fn to() -> RelationDef {
|
|
||||||
# Relation::Harvests.def()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# mod harvest {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "harvests")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub plot_id: i32,
|
|
||||||
# pub crop: String,
|
|
||||||
# pub kilos: i32,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {
|
|
||||||
# #[sea_orm(
|
|
||||||
# belongs_to = "super::plot::Entity",
|
|
||||||
# from = "Column::PlotId",
|
|
||||||
# to = "super::plot::Column::Id"
|
|
||||||
# )]
|
|
||||||
# Plot,
|
|
||||||
# }
|
|
||||||
# impl Related<super::plot::Entity> for Entity {
|
|
||||||
# fn to() -> RelationDef {
|
|
||||||
# Relation::Plot.def()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# async fn f() -> Result<(), DbErr> {
|
|
||||||
// Each harvest together with its plot, in a single query.
|
|
||||||
let rows: Vec<(harvest::Model, Option<plot::Model>)> = harvest::Entity::find()
|
|
||||||
.find_also_related(plot::Entity)
|
|
||||||
.all(dbconn())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// The harvests of one plot.
|
|
||||||
if let Some(plot) = plot::Entity::find_by_id(1).one(dbconn()).await? {
|
|
||||||
let harvests = plot.find_related(harvest::Entity).all(dbconn()).await?;
|
|
||||||
}
|
|
||||||
# Ok(())
|
|
||||||
# }
|
|
||||||
# fn main() {}
|
|
||||||
```
|
|
||||||
|
|
||||||
La parcela de `find_also_related()` es un `Option` porque, en general, la columna podría estar
|
|
||||||
vacía; con una clave ajena obligatoria como esta, siempre llega.
|
|
||||||
|
|
||||||
## 8. Escribe SQL a mano
|
|
||||||
|
|
||||||
Para lo que no encaja en una entidad, como un total por grupos, construye la consulta con
|
|
||||||
`db::query` y léela con `fetch_all()`. Cada fila llega sin tipo, y cada columna se extrae con
|
|
||||||
`try_get()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
use pagetop_seaorm::db::query::*;
|
|
||||||
|
|
||||||
# async fn f() -> Result<(), DbErr> {
|
|
||||||
// Kilos by crop, the largest first.
|
|
||||||
let stmt = Query::select()
|
|
||||||
.column(Alias::new("crop"))
|
|
||||||
.expr_as(Expr::col(Alias::new("kilos")).sum(), Alias::new("total"))
|
|
||||||
.from(Alias::new("harvests"))
|
|
||||||
.group_by_col(Alias::new("crop"))
|
|
||||||
.order_by(Alias::new("total"), Order::Desc)
|
|
||||||
.to_owned();
|
|
||||||
|
|
||||||
for row in fetch_all(&stmt).await? {
|
|
||||||
let crop: String = row.try_get("", "crop")?;
|
|
||||||
let total: i64 = row.try_get("", "total")?;
|
|
||||||
println!("{crop}: {total} kg");
|
|
||||||
}
|
|
||||||
# Ok(())
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`fetch_one()` devuelve sólo la primera fila. Para modificar datos sin entidad, `execute()` recibe
|
|
||||||
la sentencia como texto y devuelve cuántas filas ha cambiado:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# async fn f() -> Result<(), DbErr> {
|
|
||||||
let result = execute("DELETE FROM harvests WHERE kilos = 0").await?;
|
|
||||||
println!("{} empty harvests removed", result.rows_affected());
|
|
||||||
# Ok(())
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`execute()` envía el texto tal cual: **nunca** pegues en él datos que vengan del usuario, porque
|
|
||||||
abrirías la puerta a la inyección de SQL. Con esos datos, usa las entidades o el constructor de
|
|
||||||
consultas, que los escapan por ti.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Una prueba con SQLite en memoria aplica las migraciones y verifica las consultas, sin tocar tu base
|
|
||||||
de datos (ve [Usa otra configuración para las pruebas](testing.md#5-usa-otra-configuración-para-las-pruebas)):
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# use pagetop_seaorm::install_migrations;
|
|
||||||
# mod migration {
|
|
||||||
# pub mod m20261015_000001_create_plots {
|
|
||||||
# use pagetop_seaorm::migration::*;
|
|
||||||
# pub struct Migration;
|
|
||||||
# #[pagetop::async_trait]
|
|
||||||
# impl MigrationTrait for Migration {
|
|
||||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
# manager
|
|
||||||
# .create_table(
|
|
||||||
# table_auto(Plots::Table)
|
|
||||||
# .col(pk_auto(Plots::Id))
|
|
||||||
# .col(string_uniq(Plots::Name))
|
|
||||||
# .col(string(Plots::Holder))
|
|
||||||
# .col(integer(Plots::Area))
|
|
||||||
# .to_owned(),
|
|
||||||
# )
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[derive(DeriveIden)]
|
|
||||||
# enum Plots { Table, Id, Name, Holder, Area }
|
|
||||||
# }
|
|
||||||
# pub mod m20261101_000002_add_plot_notes {
|
|
||||||
# use pagetop_seaorm::migration::*;
|
|
||||||
# pub struct Migration;
|
|
||||||
# #[pagetop::async_trait]
|
|
||||||
# impl MigrationTrait for Migration {
|
|
||||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
# manager
|
|
||||||
# .alter_table(
|
|
||||||
# Table::alter()
|
|
||||||
# .table(Plots::Table)
|
|
||||||
# .add_column(text_null(Plots::Notes))
|
|
||||||
# .to_owned(),
|
|
||||||
# )
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[derive(DeriveIden)]
|
|
||||||
# enum Plots { Table, Notes }
|
|
||||||
# }
|
|
||||||
# pub mod m20261120_000003_create_harvests {
|
|
||||||
# use pagetop_seaorm::migration::*;
|
|
||||||
# pub struct Migration;
|
|
||||||
# #[pagetop::async_trait]
|
|
||||||
# impl MigrationTrait for Migration {
|
|
||||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
# manager
|
|
||||||
# .create_table(
|
|
||||||
# table_auto(Harvests::Table)
|
|
||||||
# .col(pk_auto(Harvests::Id))
|
|
||||||
# .col(integer(Harvests::PlotId))
|
|
||||||
# .col(string(Harvests::Crop))
|
|
||||||
# .col(integer(Harvests::Kilos))
|
|
||||||
# .foreign_key(
|
|
||||||
# ForeignKey::create()
|
|
||||||
# .name("fk_harvests_plot")
|
|
||||||
# .from(Harvests::Table, Harvests::PlotId)
|
|
||||||
# .to(Plots::Table, Plots::Id)
|
|
||||||
# .on_delete(ForeignKeyAction::Cascade),
|
|
||||||
# )
|
|
||||||
# .to_owned(),
|
|
||||||
# )
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[derive(DeriveIden)]
|
|
||||||
# enum Harvests { Table, Id, PlotId, Crop, Kilos }
|
|
||||||
# #[derive(DeriveIden)]
|
|
||||||
# enum Plots { Table, Id }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# mod plot {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "plots")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub name: String,
|
|
||||||
# pub holder: String,
|
|
||||||
# pub area: i32,
|
|
||||||
# pub notes: Option<String>,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {
|
|
||||||
# #[sea_orm(has_many = "super::harvest::Entity")]
|
|
||||||
# Harvests,
|
|
||||||
# }
|
|
||||||
# impl Related<super::harvest::Entity> for Entity {
|
|
||||||
# fn to() -> RelationDef {
|
|
||||||
# Relation::Harvests.def()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# mod harvest {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "harvests")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub plot_id: i32,
|
|
||||||
# pub crop: String,
|
|
||||||
# pub kilos: i32,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {
|
|
||||||
# #[sea_orm(
|
|
||||||
# belongs_to = "super::plot::Entity",
|
|
||||||
# from = "Column::PlotId",
|
|
||||||
# to = "super::plot::Column::Id"
|
|
||||||
# )]
|
|
||||||
# Plot,
|
|
||||||
# }
|
|
||||||
# impl Related<super::plot::Entity> for Entity {
|
|
||||||
# fn to() -> RelationDef {
|
|
||||||
# Relation::Plot.def()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# pub struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
# vec![&pagetop_seaorm::SeaORM]
|
|
||||||
# }
|
|
||||||
# async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
# install_migrations!(
|
|
||||||
# m20261015_000001_create_plots,
|
|
||||||
# m20261101_000002_add_plot_notes,
|
|
||||||
# m20261120_000003_create_harvests,
|
|
||||||
# )?;
|
|
||||||
# Ok(())
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# fn new_plot(name: &str, holder: &str, area: i32) -> plot::ActiveModel {
|
|
||||||
# plot::ActiveModel {
|
|
||||||
# name: Set(name.into()),
|
|
||||||
# holder: Set(holder.into()),
|
|
||||||
# area: Set(area),
|
|
||||||
# ..Default::default()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# fn new_harvest(plot_id: i32, crop: &str, kilos: i32) -> harvest::ActiveModel {
|
|
||||||
# harvest::ActiveModel {
|
|
||||||
# plot_id: Set(plot_id),
|
|
||||||
# crop: Set(crop.into()),
|
|
||||||
# kilos: Set(kilos),
|
|
||||||
# ..Default::default()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn plots_and_harvests_are_stored_and_queried() {
|
|
||||||
Application::prepare(&Garden).await;
|
|
||||||
|
|
||||||
for (name, holder, area) in [("A1", "Ana", 25), ("A2", "Luke", 12), ("B1", "Marta", 30)] {
|
|
||||||
new_plot(name, holder, area).insert(dbconn()).await.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
let large = plot::Entity::find()
|
|
||||||
.filter(plot::Column::Area.gte(20))
|
|
||||||
.count(dbconn())
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(large, 2);
|
|
||||||
|
|
||||||
let page = paginate(plot::Entity::find().order_by_asc(plot::Column::Name), 2, 2)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!((page.total, page.total_pages), (3, 2));
|
|
||||||
assert_eq!(page.items[0].name, "B1");
|
|
||||||
assert_eq!(page.items[0].notes, None);
|
|
||||||
|
|
||||||
// Plot 1 (A1) gives two harvests and plot 3 (B1) one.
|
|
||||||
for (plot_id, crop, kilos) in [(1, "Tomatoes", 12), (1, "Lettuces", 5), (3, "Tomatoes", 9)] {
|
|
||||||
new_harvest(plot_id, crop, kilos).insert(dbconn()).await.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
let a1 = plot::Entity::find_by_id(1).one(dbconn()).await.unwrap().unwrap();
|
|
||||||
let harvests = a1.find_related(harvest::Entity).all(dbconn()).await.unwrap();
|
|
||||||
assert_eq!(harvests.len(), 2);
|
|
||||||
|
|
||||||
let rows = harvest::Entity::find()
|
|
||||||
.find_also_related(plot::Entity)
|
|
||||||
.all(dbconn())
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(rows.iter().all(|(_, plot)| plot.is_some()));
|
|
||||||
|
|
||||||
use pagetop_seaorm::db::query::*;
|
|
||||||
let stmt = Query::select()
|
|
||||||
.column(Alias::new("crop"))
|
|
||||||
.expr_as(Expr::col(Alias::new("kilos")).sum(), Alias::new("total"))
|
|
||||||
.from(Alias::new("harvests"))
|
|
||||||
.group_by_col(Alias::new("crop"))
|
|
||||||
.order_by(Alias::new("total"), Order::Desc)
|
|
||||||
.to_owned();
|
|
||||||
let first = &fetch_all(&stmt).await.unwrap()[0];
|
|
||||||
let crop: String = first.try_get("", "crop").unwrap();
|
|
||||||
let total: i64 = first.try_get("", "total").unwrap();
|
|
||||||
assert_eq!((crop.as_str(), total), ("Tomatoes", 21));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Añadir usuarios y permisos](users.md): `pagetop-user` guarda usuarios y sesiones en esta misma
|
|
||||||
base de datos.
|
|
||||||
- [Ordenar y paginar sin recargar](htmx-tables.md): un listado paginado con HTMX.
|
|
||||||
|
|
@ -1,166 +0,0 @@
|
||||||
# Desplegar en producción
|
|
||||||
|
|
||||||
**Objetivo:** compilar la aplicación en modo optimizado y ponerla en marcha en un servidor, como
|
|
||||||
servicio del sistema o en un contenedor, detrás de un proxy inverso con HTTPS.
|
|
||||||
|
|
||||||
## 1. Compila para producción
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo build --release
|
|
||||||
```
|
|
||||||
|
|
||||||
Para un binario más pequeño y rápido, añade a tu `Cargo.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[profile.release]
|
|
||||||
opt-level = 3
|
|
||||||
lto = "fat"
|
|
||||||
codegen-units = 1
|
|
||||||
strip = true
|
|
||||||
```
|
|
||||||
|
|
||||||
El ejecutable de `target/release/` incluye estilos, *scripts*, imágenes y traducciones. Sólo
|
|
||||||
necesita, a su lado, el directorio `config/`.
|
|
||||||
|
|
||||||
## 2. Ponla en marcha
|
|
||||||
|
|
||||||
```text
|
|
||||||
/opt/my-app/
|
|
||||||
├── my-app <- the binary
|
|
||||||
└── config/
|
|
||||||
├── common.toml
|
|
||||||
├── production.toml
|
|
||||||
└── local.production.toml <- secrets of this server
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cd /opt/my-app
|
|
||||||
PAGETOP_RUN_MODE=production ./my-app
|
|
||||||
```
|
|
||||||
|
|
||||||
O, desde cualquier directorio, indicando dónde está la configuración:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
CONFIG_DIR=/opt/my-app/config PAGETOP_RUN_MODE=production /opt/my-app/my-app
|
|
||||||
```
|
|
||||||
|
|
||||||
Los secretos pueden ir también en variables de entorno en lugar de `local.production.toml`:
|
|
||||||
cualquier clave se sobrescribe con `PAGETOP_<SECCIÓN>__<CLAVE>` (p. ej.
|
|
||||||
`PAGETOP_DATABASE__DB_PASS`), como explica la
|
|
||||||
[referencia de la configuración](../reference/configuration.md).
|
|
||||||
|
|
||||||
Recuerda que, por defecto, el servidor sólo escucha en `localhost`. Para aceptar conexiones de
|
|
||||||
fuera, o de un proxy en otro equipo, fija `bind_address = "0.0.0.0"` en `[server]`.
|
|
||||||
|
|
||||||
## 3. Como servicio del sistema
|
|
||||||
|
|
||||||
PageTop se detiene de forma ordenada con `SIGTERM`, la señal que envían `systemd` o Docker: deja de
|
|
||||||
aceptar conexiones, termina las peticiones en curso, espera a las tareas de `pagetop-cron` que estén
|
|
||||||
en marcha y vuelca las trazas pendientes. Una unidad de `systemd` sencilla:
|
|
||||||
|
|
||||||
```ini
|
|
||||||
[Unit]
|
|
||||||
Description=My PageTop application
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
WorkingDirectory=/opt/my-app
|
|
||||||
Environment=PAGETOP_RUN_MODE=production
|
|
||||||
EnvironmentFile=-/etc/my-app/secrets.env
|
|
||||||
ExecStart=/opt/my-app/my-app
|
|
||||||
Restart=on-failure
|
|
||||||
User=my-app
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
```
|
|
||||||
|
|
||||||
`EnvironmentFile` es opcional (el `-` lo admite ausente): un archivo legible sólo por `root`, con
|
|
||||||
una variable por línea, como `PAGETOP_DATABASE__DB_PASS=secret`.
|
|
||||||
|
|
||||||
## 4. En un contenedor
|
|
||||||
|
|
||||||
El binario no necesita nada a su lado salvo `config/`, así que la imagen final puede ser mínima. Un
|
|
||||||
`Dockerfile` en dos fases, que compila en una imagen de Rust y copia sólo el resultado:
|
|
||||||
|
|
||||||
```dockerfile
|
|
||||||
FROM rust:1.88 AS build
|
|
||||||
WORKDIR /src
|
|
||||||
COPY . .
|
|
||||||
RUN cargo build --release
|
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
|
||||||
WORKDIR /app
|
|
||||||
COPY --from=build /src/target/release/my-app /app/my-app
|
|
||||||
COPY config /app/config
|
|
||||||
ENV PAGETOP_RUN_MODE=production
|
|
||||||
EXPOSE 8080
|
|
||||||
CMD ["/app/my-app"]
|
|
||||||
```
|
|
||||||
|
|
||||||
Dentro del contenedor, el servidor debe escuchar en todas las interfaces: pon
|
|
||||||
`bind_address = "0.0.0.0"` en `config/production.toml`. Docker detiene los contenedores con
|
|
||||||
`SIGTERM`, que PageTop atiende cerrando de forma ordenada. Los secretos no van en la imagen: se
|
|
||||||
pasan al arrancar el contenedor, por ejemplo con `docker run --env-file secrets.env`.
|
|
||||||
|
|
||||||
## 5. Detrás de un proxy inverso
|
|
||||||
|
|
||||||
Para HTTPS, certificados y compresión, pon delante un proxy inverso como nginx o Caddy. Un ejemplo
|
|
||||||
con nginx:
|
|
||||||
|
|
||||||
```nginx
|
|
||||||
server {
|
|
||||||
listen 443 ssl;
|
|
||||||
server_name my-app.example.com;
|
|
||||||
|
|
||||||
# ssl_certificate ... ssl_certificate_key ...
|
|
||||||
|
|
||||||
# Allows uploads up to upload.max_request_size (nginx accepts 1 MiB by default).
|
|
||||||
client_max_body_size 32m;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_pass http://127.0.0.1:8080;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Con el proxy delante, deja `bind_address = "localhost"` (el valor por defecto): así sólo el proxy
|
|
||||||
llega a la aplicación.
|
|
||||||
|
|
||||||
Todas las conexiones llegan entonces desde el proxy. Para que la aplicación conozca la dirección de
|
|
||||||
cada visitante, que usan por ejemplo los límites por IP de `pagetop-user`, indica la cabecera en
|
|
||||||
la que el proxy la escribe:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[server]
|
|
||||||
client_ip_header = "X-Forwarded-For"
|
|
||||||
```
|
|
||||||
|
|
||||||
Si la cabecera trae varias direcciones, vale la última, la que añade el proxy: las anteriores las
|
|
||||||
envía el navegador y podrían ser falsas. Configúrala sólo si todas las peticiones pasan por el
|
|
||||||
proxy y éste escribe siempre la cabecera, como hace `$proxy_add_x_forwarded_for` en el ejemplo.
|
|
||||||
|
|
||||||
Conserva la línea `proxy_set_header Host $host;`. La protección contra CSRF compara la cabecera
|
|
||||||
`Origin` del navegador con `Host` cuando el navegador no envía `Sec-Fetch-Site` (los antiguos, o
|
|
||||||
cualquiera en una conexión HTTP sin cifrar fuera de `localhost`). Si el proxy cambia `Host` por
|
|
||||||
`127.0.0.1:8080`, esos navegadores reciben un `403` al enviar cualquier formulario.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
```sh
|
|
||||||
curl -I https://my-app.example.com/
|
|
||||||
```
|
|
||||||
|
|
||||||
Responde `200` a través del proxy. En el servidor, `systemctl status my-app` (o `docker logs`)
|
|
||||||
muestra las trazas de arranque, y `systemctl stop my-app` detiene la aplicación sin cortar las
|
|
||||||
peticiones en curso.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Registrar trazas](logging.md): trazas en archivos con rotación.
|
|
||||||
- [Programar tareas periódicas](cron.md#6-con-varias-instancias-elige-el-modo): con varias
|
|
||||||
instancias, quién ejecuta las tareas.
|
|
||||||
- [Opciones de configuración](../reference/configuration.md).
|
|
||||||
|
|
@ -1,286 +0,0 @@
|
||||||
# Mostrar páginas de error
|
|
||||||
|
|
||||||
**Objetivo:** responder con una página de error cuando algo no sale bien (un recurso que no existe,
|
|
||||||
un acceso no permitido, un fallo al leer los datos) sin que el visitante pierda la navegación del
|
|
||||||
sitio, responder con JSON cuando quien llama es una API, y saber qué ocurre cuando el fallo es
|
|
||||||
grave.
|
|
||||||
|
|
||||||
Las cosas fallan: alguien escribe mal una dirección, un archivo desaparece o la base de datos no
|
|
||||||
responde. PageTop distingue dos niveles. Los **errores controlados** los decide tu código y se
|
|
||||||
muestran como una página más del sitio, con su cabecera, su menú y su pie. Los **fallos graves**
|
|
||||||
(un `panic!`) los atrapa PageTop y responde con una página mínima. Esta guía recorre los dos.
|
|
||||||
|
|
||||||
## 1. Devuelve el error desde el *handler*
|
|
||||||
|
|
||||||
Un *handler* que construye una página devuelve `Result<Markup, ErrorPage>`. Para responder con un
|
|
||||||
error, devuelve la variante que corresponda:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
const PLOTS: [(&str, &str); 2] = [("a1", "Ana"), ("b2", "Luke")];
|
|
||||||
|
|
||||||
async fn plot(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(code): web::Path<String>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
let Some((_, holder)) = PLOTS.iter().find(|(c, _)| *c == code) else {
|
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
};
|
|
||||||
let holder = holder.to_string();
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n(code))
|
|
||||||
.with_child(Html::with(move |_| html! { p { "Holder: " (holder) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`/plots/a1` muestra la parcela y `/plots/z9` responde con un 404 que conserva el aspecto del sitio.
|
|
||||||
Elige la variante por lo que ha pasado:
|
|
||||||
|
|
||||||
| Variante | Código | Cuándo |
|
|
||||||
|---|---|---|
|
|
||||||
| `ErrorPage::BadRequest` | 400 | Los datos de la petición no tienen sentido |
|
|
||||||
| `ErrorPage::AccessDenied` | 403 | El usuario no tiene permiso para verlo |
|
|
||||||
| `ErrorPage::NotFound` | 404 | Lo que se pide no existe |
|
|
||||||
| `ErrorPage::InternalError` | 500 | Algo ha fallado en el servidor |
|
|
||||||
| `ErrorPage::ServiceUnavailable` | 503 | El servicio no puede atender ahora (mantenimiento, carga) |
|
|
||||||
| `ErrorPage::GatewayTimeout` | 504 | Un servicio externo no ha respondido a tiempo |
|
|
||||||
|
|
||||||
Pásale siempre la petición (`Some(request)`): con ella la página de error sale en el idioma del
|
|
||||||
visitante y sabe quién es, por ejemplo para mostrar su menú de cuenta. Con `None` también se
|
|
||||||
muestra, pero sin esos datos.
|
|
||||||
|
|
||||||
Las rutas que no existen no necesitan nada: PageTop responde por sí solo con la misma página 404.
|
|
||||||
|
|
||||||
## 2. Convierte tus errores en un `ErrorPage`
|
|
||||||
|
|
||||||
Lo normal es que el error venga de otra parte: un archivo que no se puede leer, una consulta que
|
|
||||||
falla. Conviértelo con `map_err()` y sigue usando `?`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn report(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let text = std::fs::read_to_string("data/report.txt").map_err(|err| {
|
|
||||||
trace::error!(%err, "Cannot read the report");
|
|
||||||
ErrorPage::InternalError(Some(request.clone()))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| html! { pre { (text) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Clonar la petición es barato, así que no te preocupes por el `request.clone()`.
|
|
||||||
|
|
||||||
## 3. Guarda los detalles en el registro, no en la página
|
|
||||||
|
|
||||||
La página de error **nunca** muestra el motivo del fallo: dice qué ha pasado en términos que
|
|
||||||
entiende el visitante («se ha producido un error interno») y nada más. Es deliberado: un mensaje
|
|
||||||
de la base de datos o una ruta de un archivo darían pistas a quien no debe tenerlas.
|
|
||||||
|
|
||||||
Los detalles van al registro, como en el ejemplo anterior con `trace::error!`. Allí los encontrarás
|
|
||||||
cuando tengas que averiguar qué ocurrió (ve [Registrar trazas](logging.md)).
|
|
||||||
|
|
||||||
## 4. Cambia su contenido desde el tema
|
|
||||||
|
|
||||||
Los textos de las páginas de error vienen traducidos de serie. Si quieres otro contenido, por
|
|
||||||
ejemplo una página 404 con un enlace a la portada, el tema activo puede sustituirlo con
|
|
||||||
`error_403()`, `error_404()` y `error_fatal()` (este último para 400, 500, 503 y 504). Lo explica
|
|
||||||
[Crear un tema](themes.md#6-cambia-las-páginas-de-error).
|
|
||||||
|
|
||||||
## 5. Ten en cuenta HTMX
|
|
||||||
|
|
||||||
Si la petición la hace HTMX, recuerda que HTMX **no sustituye** el contenido cuando la respuesta es
|
|
||||||
un 4xx o un 5xx: el usuario no vería nada. Para avisar de un error en un fragmento, responde con un
|
|
||||||
200 y el mensaje, o cambia el destino con `HtmxResponse` (ve [Dirigir al navegador desde el
|
|
||||||
servidor](htmx-responses.md)).
|
|
||||||
|
|
||||||
## 6. Los fallos graves
|
|
||||||
|
|
||||||
Un `panic!` en un *handler*, un componente o el tema no tumba el servidor. PageTop lo atrapa,
|
|
||||||
anota el motivo en el registro y responde con un 500 y una página mínima, sin tema ni componentes:
|
|
||||||
después de un fallo así no es seguro volver a usar el mismo ciclo de renderizado que acaba de
|
|
||||||
fallar.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
async fn boom() -> &'static str {
|
|
||||||
panic!("This should never happen");
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Es la red de seguridad, no una forma de gestionar errores: reserva `panic!` para lo que de verdad
|
|
||||||
no puede ocurrir y devuelve un `ErrorPage` en todo lo demás.
|
|
||||||
|
|
||||||
## 7. Errores de una API JSON
|
|
||||||
|
|
||||||
Una ruta que devuelve JSON no debe responder a un error con una página HTML: quien la llama es un
|
|
||||||
programa, y espera JSON. Define un tipo de error con [`thiserror`](https://docs.rs/thiserror),
|
|
||||||
decide en `IntoResponse` el código de cada variante y devuelve el mensaje en un cuerpo JSON:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
enum ApiError {
|
|
||||||
#[error("Plot {0} not found")]
|
|
||||||
PlotNotFound(String),
|
|
||||||
#[error("The harvest must weigh more than zero kilos")]
|
|
||||||
InvalidKilos,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
struct ErrorBody {
|
|
||||||
status: u16,
|
|
||||||
error: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl web::IntoResponse for ApiError {
|
|
||||||
fn into_response(self) -> Response {
|
|
||||||
let status = match self {
|
|
||||||
Self::PlotNotFound(_) => web::http::StatusCode::NOT_FOUND,
|
|
||||||
Self::InvalidKilos => web::http::StatusCode::UNPROCESSABLE_ENTITY,
|
|
||||||
};
|
|
||||||
let body = ErrorBody { status: status.as_u16(), error: self.to_string() };
|
|
||||||
(status, Json(body)).into_response()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
struct Plot {
|
|
||||||
code: String,
|
|
||||||
holder: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn api_plot(web::Path(code): web::Path<String>) -> Result<Json<Plot>, ApiError> {
|
|
||||||
match code.as_str() {
|
|
||||||
"a1" => Ok(Json(Plot { code, holder: "Ana" })),
|
|
||||||
_ => Err(ApiError::PlotNotFound(code)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`/api/plots/z9` responde con un 404 y `{"status":404,"error":"Plot z9 not found"}`. Como el tipo
|
|
||||||
implementa `IntoResponse`, el *handler* sigue usando `?` con normalidad.
|
|
||||||
|
|
||||||
Aquí los mensajes son para quien usa la API, así que se envían tal cual. Un error interno (una
|
|
||||||
consulta que falla) es otra cosa: regístralo con `trace::error!` y responde con un 500 y un mensaje
|
|
||||||
genérico, igual que haría una página de error.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
const PLOTS: [(&str, &str); 2] = [("a1", "Ana"), ("b2", "Luke")];
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/plots/{code}", web::get(plot))
|
|
||||||
.public_route("/report", web::get(report))
|
|
||||||
.public_route("/boom", web::get(boom))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn plot(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(code): web::Path<String>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
let Some((_, holder)) = PLOTS.iter().find(|(c, _)| *c == code) else {
|
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
};
|
|
||||||
let holder = holder.to_string();
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n(code))
|
|
||||||
.with_child(Html::with(move |_| html! { p { "Holder: " (holder) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn report(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let text = std::fs::read_to_string("data/report.txt").map_err(|err| {
|
|
||||||
trace::error!(%err, "Cannot read the report");
|
|
||||||
ErrorPage::InternalError(Some(request.clone()))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| html! { pre { (text) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn boom() -> &'static str {
|
|
||||||
panic!("This should never happen");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Arranca la aplicación con `cargo run` y prueba cada caso:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
curl -i http://localhost:8080/plots/a1 # 200 OK, the plot page
|
|
||||||
curl -i http://localhost:8080/plots/z9 # 404 Not Found, with the site's error page
|
|
||||||
curl -i http://localhost:8080/report # 500 until data/report.txt exists (reason in the log)
|
|
||||||
curl -i http://localhost:8080/boom # 500 with the minimal page; the panic is in the log
|
|
||||||
```
|
|
||||||
|
|
||||||
En el navegador, la 404 y la 500 tienen la cabecera y el pie del sitio; la de `/boom`, no.
|
|
||||||
|
|
||||||
También puedes comprobarlo en una prueba (ve [Probar rutas y componentes](testing.md)):
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# const PLOTS: [(&str, &str); 2] = [("a1", "Ana"), ("b2", "Luke")];
|
|
||||||
# struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
# fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
# routes.public_route("/plots/{code}", web::get(plot))
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# async fn plot(
|
|
||||||
# request: HttpRequest,
|
|
||||||
# web::Path(code): web::Path<String>,
|
|
||||||
# ) -> Result<Markup, ErrorPage> {
|
|
||||||
# let Some((_, holder)) = PLOTS.iter().find(|(c, _)| *c == code) else {
|
|
||||||
# return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
# };
|
|
||||||
# let holder = holder.to_string();
|
|
||||||
# Page::new(request)
|
|
||||||
# .with_title(Lc::n(code))
|
|
||||||
# .with_child(Html::with(move |_| html! { p { "Holder: " (holder) } }))
|
|
||||||
# .render()
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn an_unknown_plot_shows_the_not_found_page() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get().uri("/plots/z9").to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::NOT_FOUND);
|
|
||||||
let body = web::test::read_body_text(response).await;
|
|
||||||
assert!(body.contains("The requested page could not be found."));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear un tema](themes.md#6-cambia-las-páginas-de-error): otro contenido para las páginas de
|
|
||||||
error.
|
|
||||||
- [Registrar trazas](logging.md): dónde acaban los detalles de cada fallo.
|
|
||||||
- [Añadir usuarios y permisos](users.md): `AccessDenied` en acción.
|
|
||||||
|
|
@ -1,190 +0,0 @@
|
||||||
# Crear una extensión
|
|
||||||
|
|
||||||
**Objetivo:** empaquetar una funcionalidad (rutas, componentes, ajustes, traducciones) en una
|
|
||||||
extensión que cualquier aplicación pueda añadir con una línea.
|
|
||||||
|
|
||||||
Una extensión es una estructura que implementa `Extension`. Todos sus métodos son opcionales:
|
|
||||||
sobrescribe sólo los que necesites.
|
|
||||||
|
|
||||||
| Método | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `name()`, `description()` | Nombre y descripción legibles (con `Lc`, traducibles) |
|
|
||||||
| `dependencies()` | Extensiones que deben arrancar antes |
|
|
||||||
| `settings()` | [Ajustes](configuration.md#5-ajustes-de-tu-extensión) que se cargan al arrancar |
|
|
||||||
| `actions()` | [Acciones](actions.md) que registra |
|
|
||||||
| `initialize()` | Código que se ejecuta al arrancar |
|
|
||||||
| `configure_router()` | [Rutas](routes.md) |
|
|
||||||
| `configure_middleware()` | Capas que envuelven las rutas de **todas** las extensiones |
|
|
||||||
| `configure_static_files()` | [Recursos estáticos](assets.md) |
|
|
||||||
| `theme()` | Si la extensión es un [tema](themes.md) |
|
|
||||||
|
|
||||||
## 1. Una extensión completa
|
|
||||||
|
|
||||||
Un pequeño blog: declara sus dependencias, añade un enlace al pie de todas las páginas y registra
|
|
||||||
sus rutas.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct Blog;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Blog {
|
|
||||||
fn name(&self) -> Lc {
|
|
||||||
Lc::n("Blog")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn description(&self) -> Lc {
|
|
||||||
Lc::n("Posts and news")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
InRegion::Global(&CoreRegions::Footer)
|
|
||||||
.add(Html::with(|cx| html! { a href=(cx.route("/blog")) { "Blog" } }));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/blog", web::get(index))
|
|
||||||
.public_route("/blog/{slug}", web::get(post))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn index(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request).with_title(Lc::n("Blog")).render().await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn post(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(slug): web::Path<String>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| html! { h1 { (slug) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para usarla, la aplicación sólo tiene que declararla como dependencia:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&blog::Blog]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Declara sus dependencias
|
|
||||||
|
|
||||||
`dependencies()` construye el árbol de la aplicación. PageTop garantiza que cada dependencia está
|
|
||||||
registrada e inicializada **antes** que la extensión que la declara. Es independiente de las
|
|
||||||
dependencias de `Cargo.toml`, que sólo resuelven la compilación.
|
|
||||||
|
|
||||||
## 3. Inicialízala al arrancar
|
|
||||||
|
|
||||||
`initialize()` es `async`: puede conectar con una base de datos, aplicar migraciones o cargar
|
|
||||||
datos. Si devuelve un error, la aplicación **no arranca**: PageTop muestra el error con sus
|
|
||||||
causas y termina. Gracias a `BoxError`, puedes propagar cualquier error con `?`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Catalog;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Catalog {
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
let data = std::fs::read_to_string("catalog.json")?;
|
|
||||||
trace::info!("Catalog loaded: {} bytes", data.len());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`initialize()` se ejecuta cada vez que se prepara la aplicación, también en las pruebas. Lo que
|
|
||||||
debe funcionar sólo mientras la aplicación está **en marcha**, como una tarea en segundo plano que
|
|
||||||
vacía una cola, se lanza en `start()`: sólo lo llama `run()`, una vez enlazado el puerto y antes
|
|
||||||
de la primera petición, y nunca las pruebas. Su pareja, `shutdown()`, se llama al detener la
|
|
||||||
aplicación, cuando ya han terminado las peticiones en curso. El ejemplo lanza la tarea con
|
|
||||||
[Tokio](https://tokio.rs), que debes añadir a tu `Cargo.toml`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Outbox;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Outbox {
|
|
||||||
async fn start(&self) -> Result<(), BoxError> {
|
|
||||||
tokio::spawn(async {
|
|
||||||
loop {
|
|
||||||
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
|
|
||||||
trace::info!("Flushing the outbox");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn shutdown(&self) {
|
|
||||||
trace::info!("Outbox stopped");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para tareas periódicas no hace falta escribir el bucle: [Programar tareas periódicas](cron.md)
|
|
||||||
lo resuelve con una extensión.
|
|
||||||
|
|
||||||
## 4. Pon componentes en todas las páginas
|
|
||||||
|
|
||||||
`InRegion` registra un componente una sola vez para que aparezca en todas las páginas:
|
|
||||||
|
|
||||||
| Variante | Dónde aparece |
|
|
||||||
|---|---|
|
|
||||||
| `InRegion::Content` | Región de contenido, en todas las páginas |
|
|
||||||
| `InRegion::Global(®ion)` | La región indicada, con cualquier tema |
|
|
||||||
| `InRegion::ForTheme(&theme, ®ion)` | La región indicada, sólo con ese tema |
|
|
||||||
|
|
||||||
Cada página recibe una **copia nueva** del componente. Si debe mostrarse sólo a veces (por
|
|
||||||
ejemplo, a usuarios autenticados), haz que lo decida su `is_renderable()`.
|
|
||||||
|
|
||||||
## 5. Añade *middleware*
|
|
||||||
|
|
||||||
Las capas añadidas en `configure_middleware()` se aplican a las rutas de todas las extensiones,
|
|
||||||
sin importar el orden. Así funciona, por ejemplo, la resolución de la sesión de usuario:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn custom_header(request: web::Request, next: web::middleware::Next) -> Response {
|
|
||||||
let mut response = next.run(request).await;
|
|
||||||
response.headers_mut().insert("x-powered-by", web::http::HeaderValue::from_static("PageTop"));
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Headers;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Headers {
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
|
||||||
layers.layer(web::middleware::from_fn(custom_header))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`configure_middleware()` sólo admite capas: las rutas se registran en `configure_router()`, cada
|
|
||||||
una con su acceso. Para una capa que sólo afecte a tus rutas, crea un `Router` propio, aplica la
|
|
||||||
capa sobre él y anídalo con `routes.nest(prefijo, acceso, router)`. Compresión, límites, tiempo
|
|
||||||
máximo, CORS y el orden de las capas, en [Añadir *middleware*](middleware.md).
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Declara la extensión en `dependencies()` de tu aplicación y arranca: sus rutas responden y, si su
|
|
||||||
`initialize()` falla, la aplicación no arranca y lo explica en el terminal.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Intervenir con acciones](actions.md): cómo una extensión modifica lo que hace otra.
|
|
||||||
- [Configurar la aplicación](configuration.md#5-ajustes-de-tu-extensión): ajustes propios de la
|
|
||||||
extensión.
|
|
||||||
- [Arquitectura: del arranque a la respuesta](../explanation/architecture.md).
|
|
||||||
|
|
@ -1,219 +0,0 @@
|
||||||
# Crear y procesar formularios
|
|
||||||
|
|
||||||
**Objetivo:** construir un formulario accesible, recibir sus datos en el servidor, validarlos y
|
|
||||||
responder sin que una recarga lo reenvíe.
|
|
||||||
|
|
||||||
## 1. Construye el formulario
|
|
||||||
|
|
||||||
Un formulario se construye con `Form` y sus campos, que generan el HTML accesible (etiquetas,
|
|
||||||
textos de ayuda, atributos ARIA) por ti.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
fn contact_form() -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_id("contact")
|
|
||||||
.with_action("/contact")
|
|
||||||
.with_method(form::Method::Post)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("name")
|
|
||||||
.with_label(Lc::n("Name"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::email()
|
|
||||||
.with_name("email")
|
|
||||||
.with_label(Lc::n("Email"))
|
|
||||||
.with_help_text(Lc::n("We will only use it to reply to you.")),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::Textarea::new()
|
|
||||||
.with_name("message")
|
|
||||||
.with_label(Lc::n("Message"))
|
|
||||||
.with_rows(5),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Send")))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Elige los campos
|
|
||||||
|
|
||||||
| Campo | Constructor |
|
|
||||||
|---|---|
|
|
||||||
| Texto, correo, URL, teléfono, búsqueda | `form::input::Field::text()`, `email()`, `url()`, `telephone()`, `search()` |
|
|
||||||
| Contraseña | `form::input::Field::password()` |
|
|
||||||
| Número | `form::Number::new()` con `with_min()`, `with_max()`, `with_step()` |
|
|
||||||
| Rango | `form::Range::new()` |
|
|
||||||
| Área de texto | `form::Textarea::new()` |
|
|
||||||
| Casilla o interruptor | `form::Checkbox::check()`, `form::Checkbox::switch()` |
|
|
||||||
| Grupo de casillas | `form::check::Field` con `form::check::Item` |
|
|
||||||
| Opciones excluyentes | `form::radio::Field` con `form::radio::Item` |
|
|
||||||
| Lista desplegable | `form::select::Field` con `form::select::Item` |
|
|
||||||
| Fecha, hora, fecha y hora | `form::date::Field::date()`, `time()`, `datetime()` |
|
|
||||||
| Campo oculto | `form::Hidden::field(name, value)` |
|
|
||||||
| Idioma, tema, zona horaria | `form::SelectLanguage`, `form::SelectTheme`, `form::SelectTimezone` |
|
|
||||||
|
|
||||||
Agrupa campos relacionados con `form::Fieldset`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> form::Fieldset {
|
|
||||||
form::Fieldset::new()
|
|
||||||
.with_legend(Lc::n("Preferences"))
|
|
||||||
.with_child(
|
|
||||||
form::radio::Field::new()
|
|
||||||
.with_name("frequency")
|
|
||||||
.with_label(Lc::n("How often do you want news?"))
|
|
||||||
.with_item(form::radio::Item::new("weekly", Lc::n("Every week")).with_checked(true))
|
|
||||||
.with_item(form::radio::Item::new("monthly", Lc::n("Every month"))),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::select::Field::new()
|
|
||||||
.with_name("country")
|
|
||||||
.with_label(Lc::n("Country"))
|
|
||||||
.with_item(form::select::Item::new("es", Lc::n("Spain")))
|
|
||||||
.with_item(form::select::Item::new("mx", Lc::n("Mexico")))
|
|
||||||
.with_item(form::select::Item::new("ar", Lc::n("Argentina"))),
|
|
||||||
)
|
|
||||||
.with_child(form::Checkbox::switch().with_name("alerts").with_label(Lc::n("Alert me")))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. Recibe y valida los datos
|
|
||||||
|
|
||||||
Atiende `GET` y `POST` en la misma ruta. El *handler* del envío recibe los campos con
|
|
||||||
`web::Form`, siempre como **último** parámetro (consume el cuerpo de la petición):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
# fn contact_form() -> Form { Form::new() }
|
|
||||||
pub struct Contact;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Contact {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/contact", web::get(show).post(send))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ContactData {
|
|
||||||
name: String,
|
|
||||||
email: String,
|
|
||||||
message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn show(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Contact"))
|
|
||||||
.with_child(contact_form())
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Form(data): web::Form<ContactData>,
|
|
||||||
) -> Result<Response, ErrorPage> {
|
|
||||||
if data.message.trim().is_empty() {
|
|
||||||
// Shows the form again with a message.
|
|
||||||
let mut page = Page::new(request).with_child(contact_form());
|
|
||||||
page.push_message(MessageLevel::Error, Lc::n("Please write a message."));
|
|
||||||
return page.render().await.map(IntoResponse::into_response);
|
|
||||||
}
|
|
||||||
// ... save or send `data` ...
|
|
||||||
let cx = Context::new(request);
|
|
||||||
Ok(Redirect::see_other(cx.route("/contact")).with_message(
|
|
||||||
&cx,
|
|
||||||
MessageLevel::Info,
|
|
||||||
Lc::n("Thank you, we will reply soon."),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si el mensaje está en blanco, la página se repite con un aviso. No hace falta añadir el componente
|
|
||||||
`Messages`: la región de contenido ya empieza por uno que muestra los avisos acumulados con
|
|
||||||
`push_message()`.
|
|
||||||
|
|
||||||
Tras guardar, redirige con `see_other()` (patrón *Post/Redirect/Get*): así, si el usuario recarga
|
|
||||||
la página, no reenvía el formulario. Para avisar del resultado en la página a la que rediriges,
|
|
||||||
añade el mensaje a la respuesta con `with_message()`: viaja en una *cookie* de vida corta, ya
|
|
||||||
traducido, y la página siguiente lo muestra como si se hubiera añadido con `push_message()`. Si esa
|
|
||||||
página vuelve a redirigir, el mensaje espera a la siguiente.
|
|
||||||
|
|
||||||
## 4. Campos con varios valores
|
|
||||||
|
|
||||||
`web::Form` no admite claves repetidas (`interest=rust&interest=web`), que es lo que envían un grupo
|
|
||||||
de casillas o una lista de selección múltiple. Para ellas, lee el cuerpo en bruto con
|
|
||||||
`web::RawForm` y deserialízalo con [`serde_qs`](https://docs.rs/serde_qs):
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Interests {
|
|
||||||
#[serde(default)]
|
|
||||||
interest: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn save(request: HttpRequest, web::RawForm(body): web::RawForm) -> Response {
|
|
||||||
let data: Interests = serde_qs::from_bytes(&body).unwrap_or(Interests { interest: vec![] });
|
|
||||||
// ...
|
|
||||||
# todo!()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Fechas en el idioma del usuario
|
|
||||||
|
|
||||||
`form::date::Field` muestra y lee las fechas con el formato del idioma activo (`dd/mm/aaaa` en
|
|
||||||
español). Para interpretar el texto recibido, usa los métodos del contexto:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
fn read_date(cx: &Context, text: &str) {
|
|
||||||
match cx.parse_date(text) {
|
|
||||||
Ok(Some(date)) => { /* a valid date: a `NaiveDate` */ }
|
|
||||||
Ok(None) => { /* empty field */ }
|
|
||||||
Err(_) => { /* invalid format */ }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 6. Sin *tokens* contra CSRF
|
|
||||||
|
|
||||||
Los formularios no necesitan ningún campo oculto contra CSRF (*Cross-Site Request Forgery*), el
|
|
||||||
ataque en el que otra web hace que el navegador de tus usuarios envíe peticiones a tu aplicación
|
|
||||||
con su sesión abierta. PageTop rechaza con `403` cualquier petición que pueda cambiar algo (todos
|
|
||||||
los métodos salvo `GET`, `HEAD` y `OPTIONS`) si el navegador indica, con las cabeceras
|
|
||||||
`Sec-Fetch-Site` y `Origin`, que llega desde otro origen, también desde otro subdominio del mismo
|
|
||||||
sitio. Vale igual para formularios, HTMX y `fetch`, y no afecta a `curl`, a otros servidores ni a
|
|
||||||
las pruebas, que no envían esas cabeceras.
|
|
||||||
|
|
||||||
A cambio, dos reglas:
|
|
||||||
|
|
||||||
- **Un `GET` nunca cambia nada.** Borrar, cerrar sesión o confirmar van siempre con `POST` (o
|
|
||||||
`PUT`, `PATCH`, `DELETE`), aunque el formulario sea sólo un botón.
|
|
||||||
- **Otra aplicación tuya, servida desde otro origen,** que envíe formularios o peticiones a ésta
|
|
||||||
debe figurar en `trusted_origins`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[server]
|
|
||||||
trusted_origins = ["https://shop.example.com"]
|
|
||||||
```
|
|
||||||
|
|
||||||
Ninguna protección contra CSRF resiste un fallo de XSS en la propia aplicación: por eso `html!`
|
|
||||||
escapa siempre el texto que insertas.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Envía el formulario vacío: el navegador lo impide, porque `name` es obligatorio.
|
|
||||||
2. Envía un mensaje en blanco (sólo espacios): el servidor lo rechaza y el formulario vuelve con el
|
|
||||||
aviso.
|
|
||||||
3. Envía uno correcto: vuelves al formulario con el aviso de agradecimiento. Recarga la página: el
|
|
||||||
aviso ya no aparece y el navegador no ofrece reenviar el formulario.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Validar un campo al vuelo](htmx-validation.md): los mismos errores, sin recargar la página.
|
|
||||||
- [Añadir usuarios y permisos](users.md): formularios que sólo ven algunos usuarios.
|
|
||||||
|
|
@ -1,233 +0,0 @@
|
||||||
# Escribir HTML con `html!`
|
|
||||||
|
|
||||||
**Objetivo:** escribir marcado con la macro `html!`: elementos, valores de Rust, atributos
|
|
||||||
condicionales, bucles y fragmentos reutilizables, todo comprobado al compilar.
|
|
||||||
|
|
||||||
PageTop escribe HTML con la macro `html!`, basada en [Maud](https://maud.lambda.xyz). Es Rust: si
|
|
||||||
cierras mal una etiqueta o te equivocas con una variable, **no compila**.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
let markup = html! {
|
|
||||||
article class="post" {
|
|
||||||
h2 { "Title" }
|
|
||||||
p { "A paragraph with " strong { "bold" } " text." }
|
|
||||||
img src="/photo.jpg" alt="A photo";
|
|
||||||
}
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
markup.into_string(),
|
|
||||||
r#"<article class="post"><h2>Title</h2><p>A paragraph with <strong>bold</strong> text.</p><img src="/photo.jpg" alt="A photo"></article>"#
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
Las reglas básicas:
|
|
||||||
|
|
||||||
- Un elemento con contenido lleva llaves: `p { ... }`.
|
|
||||||
- Un elemento vacío termina en punto y coma: `br;`, `img src="...";`.
|
|
||||||
- El texto va entre comillas y los atributos se escriben como en HTML.
|
|
||||||
- Los comentarios son los de Rust (`// ...`) y no llegan al HTML.
|
|
||||||
|
|
||||||
No hace falta escribir el `<!DOCTYPE>`, el `<head>` ni el `<body>`: los pone `Page` (ve
|
|
||||||
[Construir páginas](pages.md)). Con `html!` escribes sólo el contenido.
|
|
||||||
|
|
||||||
## Insertar valores de Rust
|
|
||||||
|
|
||||||
Cualquier expresión entre paréntesis se inserta en el HTML, **escapada**:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
let name = "<Ana>";
|
|
||||||
let total = 3;
|
|
||||||
let markup = html! { p { "Hello, " (name) ". You have " (total) " notices." } };
|
|
||||||
assert_eq!(markup.into_string(), "<p>Hello, <Ana>. You have 3 notices.</p>");
|
|
||||||
```
|
|
||||||
|
|
||||||
El escape es lo que te protege de la inyección de código (XSS): si un usuario escribe
|
|
||||||
`<script>` en un formulario, la página muestra el texto, no lo ejecuta.
|
|
||||||
|
|
||||||
Si necesitas insertar HTML que ya es seguro, envuélvelo en `PreEscaped`:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
let fragment = "<em>already escaped</em>";
|
|
||||||
let markup = html! { p { (PreEscaped(fragment)) } };
|
|
||||||
assert_eq!(markup.into_string(), "<p><em>already escaped</em></p>");
|
|
||||||
```
|
|
||||||
|
|
||||||
Lo que pongas en `PreEscaped` llega al navegador tal cual. Úsalo sólo con contenido de confianza,
|
|
||||||
nunca con texto que venga de un usuario.
|
|
||||||
|
|
||||||
## Atributos dinámicos
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
let url = "/profile";
|
|
||||||
let title: Option<&str> = None;
|
|
||||||
let active = true;
|
|
||||||
let markup = html! {
|
|
||||||
a href=(url) title=[title] { "Profile" }
|
|
||||||
input type="checkbox" checked[active];
|
|
||||||
li class="item" .active[active] { "Home" }
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
markup.into_string(),
|
|
||||||
r#"<a href="/profile">Profile</a><input type="checkbox" checked><li class="item active">Home</li>"#
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
- `attr=(expr)` fija el valor.
|
|
||||||
- `attr=[option]` sólo escribe el atributo si la opción es `Some`.
|
|
||||||
- `attr[condition]` escribe un atributo booleano si la condición es cierta.
|
|
||||||
- `.class[condition]` añade una clase si la condición es cierta. Se combina con `class="..."`:
|
|
||||||
`html!` junta las fijas y las condicionadas en un único atributo `class`.
|
|
||||||
- Los atributos con guiones se escriben tal cual: `hx-get="/time"`, `aria-label="Close"`,
|
|
||||||
`data-id=(id)`.
|
|
||||||
|
|
||||||
## Control de flujo
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
let tasks = ["Read", "Code", "Rest"];
|
|
||||||
let user: Option<&str> = Some("Ana");
|
|
||||||
let markup = html! {
|
|
||||||
@if let Some(name) = user {
|
|
||||||
p { "Signed in as " (name) }
|
|
||||||
} @else {
|
|
||||||
p { "Not signed in" }
|
|
||||||
}
|
|
||||||
ul {
|
|
||||||
@for (i, task) in tasks.iter().enumerate() {
|
|
||||||
@let number = i + 1;
|
|
||||||
li { (number) ". " (task) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
assert!(markup.into_string().starts_with("<p>Signed in as Ana</p><ul><li>1. Read</li>"));
|
|
||||||
```
|
|
||||||
|
|
||||||
`@match` elige el marcado según un valor, con los mismos patrones que un `match` de Rust:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
enum Plot {
|
|
||||||
Free,
|
|
||||||
Taken(&'static str),
|
|
||||||
}
|
|
||||||
|
|
||||||
let plots = [Plot::Taken("Ana"), Plot::Free];
|
|
||||||
let markup = html! {
|
|
||||||
@for plot in &plots {
|
|
||||||
@match plot {
|
|
||||||
Plot::Free => span class="free" { "Free" },
|
|
||||||
Plot::Taken(holder) => span { "Taken by " (holder) },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
assert_eq!(markup.into_string(), r#"<span>Taken by Ana</span><span class="free">Free</span>"#);
|
|
||||||
```
|
|
||||||
|
|
||||||
También existe `@while`.
|
|
||||||
|
|
||||||
## Reutilizar fragmentos
|
|
||||||
|
|
||||||
Un fragmento que se repite se convierte en una función que devuelve `Markup`, y se inserta como
|
|
||||||
cualquier otro valor:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
fn plot_card(name: &str, holder: &str) -> Markup {
|
|
||||||
html! {
|
|
||||||
article class="plot-card" {
|
|
||||||
h3 { (name) }
|
|
||||||
p { "Holder: " (holder) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let markup = html! {
|
|
||||||
(plot_card("A1", "Ana"))
|
|
||||||
(plot_card("B2", "Luke"))
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
markup.into_string(),
|
|
||||||
concat!(
|
|
||||||
r#"<article class="plot-card"><h3>A1</h3><p>Holder: Ana</p></article>"#,
|
|
||||||
r#"<article class="plot-card"><h3>B2</h3><p>Holder: Luke</p></article>"#,
|
|
||||||
)
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
Es lo que en un motor de plantillas haría un *include*, pero con parámetros tipados: si te olvidas
|
|
||||||
de uno, no compila. Y no necesitas una plantilla base de la que heredar: la estructura común de
|
|
||||||
todas las páginas (cabecera, menú, pie) la ponen el tema y sus regiones.
|
|
||||||
|
|
||||||
## Insertar tus propios tipos
|
|
||||||
|
|
||||||
Cualquier tipo que implemente `Display` se inserta directamente, escapado:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
struct Holder {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for Holder {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(f, "{} (gardener)", self.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let holder = Holder { name: "Ana".to_string() };
|
|
||||||
let markup = html! { p { (holder) } };
|
|
||||||
assert_eq!(markup.into_string(), "<p>Ana (gardener)</p>");
|
|
||||||
```
|
|
||||||
|
|
||||||
Para que un tipo genere su propio marcado, implementa `Render`:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
struct Area(u32);
|
|
||||||
|
|
||||||
impl Render for Area {
|
|
||||||
fn render(&self) -> Markup {
|
|
||||||
html! { span class="area" { (self.0) " m²" } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let markup = html! { p { "Size: " (Area(25)) } };
|
|
||||||
assert_eq!(markup.into_string(), r#"<p>Size: <span class="area">25 m²</span></p>"#);
|
|
||||||
```
|
|
||||||
|
|
||||||
Una función o un tipo con `Render` bastan para piezas pequeñas sin estado. Cuando la pieza necesita
|
|
||||||
el idioma, la petición o que un tema pueda cambiarla, conviértela en un
|
|
||||||
[componente](custom-components.md).
|
|
||||||
|
|
||||||
## `Html`: el componente comodín
|
|
||||||
|
|
||||||
En una página no se inserta `Markup` directamente, sino **componentes**. El más sencillo es
|
|
||||||
`Html`, que envuelve un cierre con `html!`. El cierre recibe el contexto de renderizado (`cx`), con
|
|
||||||
el idioma, el tema o la petición actuales:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(|cx| {
|
|
||||||
let greeting = Lc::n("Welcome");
|
|
||||||
html! { h1 { (greeting.using(cx)) } }
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Úsalo para marcado puntual. Cuando un fragmento se repite o tiene entidad propia, conviértelo en
|
|
||||||
un [componente](custom-components.md).
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Usar componentes](components.md): antes de escribir HTML, mira si ya existe un componente.
|
|
||||||
- [Crear un componente](custom-components.md).
|
|
||||||
|
|
@ -1,235 +0,0 @@
|
||||||
# Borrar con confirmación
|
|
||||||
|
|
||||||
**Objetivo:** un botón en cada fila de una tabla que pide confirmación, borra en el servidor y
|
|
||||||
retira la fila con un fundido, actualizando a la vez un contador que está fuera de la tabla.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md) y de una tabla como las de [Mostrar
|
|
||||||
tablas ordenables y paginadas](tables.md).
|
|
||||||
|
|
||||||
## 1. Un botón de borrar en cada fila
|
|
||||||
|
|
||||||
Las piezas de `Table` (filas, celdas, cabeceras) aceptan atributos con `with_prop()`, igual que los
|
|
||||||
componentes. El botón de cada fila lleva cuatro:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
struct Plot {
|
|
||||||
id: u32,
|
|
||||||
name: &'static str,
|
|
||||||
holder: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plot_row(plot: &Plot) -> table::Row {
|
|
||||||
let delete = Button::plain(Lc::n("Delete"))
|
|
||||||
.with_style(button::Style::Outline(Intent::Severe))
|
|
||||||
.with_prop(PropsOp::set(hx::DELETE, util::join!("/plots/", plot.id.to_string())))
|
|
||||||
.with_prop(PropsOp::set(hx::CONFIRM, "Delete this plot?"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "closest tr"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, "outerHTML swap:300ms"));
|
|
||||||
table::Row::new()
|
|
||||||
.with_cell(plot.name)
|
|
||||||
.with_cell(plot.holder)
|
|
||||||
.with_cell(delete)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `hx-confirm` muestra el diálogo de confirmación del navegador. Si el usuario cancela, no se envía
|
|
||||||
nada.
|
|
||||||
- `hx-target="closest tr"` apunta a la fila que contiene el botón, sin necesidad de darle un `id`.
|
|
||||||
- `swap:300ms` espera 300 ms antes de sustituir la fila. Es el tiempo del fundido del paso 3.
|
|
||||||
|
|
||||||
## 2. La ruta devuelve un fragmento vacío
|
|
||||||
|
|
||||||
Al sustituir la fila (`outerHTML`) por una respuesta vacía, la fila desaparece. Y el contador de
|
|
||||||
parcelas, que está fuera de la tabla, viaja en la misma respuesta **fuera de banda**:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
# struct Plot { id: u32 }
|
|
||||||
# fn plots() -> std::sync::MutexGuard<'static, Vec<Plot>> { todo!() }
|
|
||||||
|
|
||||||
fn count_update(count: usize) -> Markup {
|
|
||||||
html! { span id="plot-count" hx-swap-oob="true" { (count) } }
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete(web::Path(id): web::Path<u32>) -> HtmxResponse {
|
|
||||||
let mut plots = plots();
|
|
||||||
plots.retain(|plot| plot.id != id);
|
|
||||||
HtmxResponse::empty().oob(count_update(plots.len()))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. El fundido
|
|
||||||
|
|
||||||
Durante esos 300 ms, HTMX pone la clase `htmx-swapping` en la fila. Con una regla CSS en la hoja de
|
|
||||||
estilos de tu aplicación, la fila se desvanece antes de irse:
|
|
||||||
|
|
||||||
```css
|
|
||||||
tr.htmx-swapping {
|
|
||||||
opacity: 0;
|
|
||||||
transition: opacity 300ms ease-out;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Cuando no queda nada
|
|
||||||
|
|
||||||
Al borrar la última fila, lo correcto es mostrar la tabla vacía con su mensaje («No plots left»),
|
|
||||||
no una tabla sin filas. La ruta puede **cambiar el destino** de su respuesta: en lugar de la fila,
|
|
||||||
sustituye el contenedor de la tabla entera.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# struct Plot { id: u32 }
|
|
||||||
# fn plots() -> std::sync::MutexGuard<'static, Vec<Plot>> { todo!() }
|
|
||||||
# fn count_update(_: usize) -> Markup { html! {} }
|
|
||||||
# fn plots_table(_: &[Plot]) -> Container { Container::new() }
|
|
||||||
async fn delete(request: HttpRequest, web::Path(id): web::Path<u32>) -> HtmxResponse {
|
|
||||||
let (empty_table, count) = {
|
|
||||||
let mut plots = plots();
|
|
||||||
plots.retain(|plot| plot.id != id);
|
|
||||||
(plots.is_empty().then(|| plots_table(&plots)), count_update(plots.len()))
|
|
||||||
};
|
|
||||||
if let Some(mut table) = empty_table {
|
|
||||||
let table = table.render(&mut Context::new(request)).await;
|
|
||||||
return HtmxResponse::new(table)
|
|
||||||
.retarget("#plots")
|
|
||||||
.reswap(hx::swap::OUTER_HTML)
|
|
||||||
.oob(count);
|
|
||||||
}
|
|
||||||
HtmxResponse::empty().oob(count)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`plots_table()` construye la tabla dentro de un `Container` con `id="plots"`, que es el nuevo
|
|
||||||
destino (lo tienes en el ejemplo completo). El bloque `{ ... }` suelta el `Mutex` **antes** del
|
|
||||||
`.await`: un candado de la biblioteca estándar no puede quedar abierto mientras la tarea espera.
|
|
||||||
|
|
||||||
`retarget()` y `reswap()` envían las cabeceras `HX-Retarget` y `HX-Reswap`, que mandan sobre lo que
|
|
||||||
dijeran los atributos del botón.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
use std::sync::{LazyLock, Mutex, MutexGuard};
|
|
||||||
|
|
||||||
struct Plot {
|
|
||||||
id: u32,
|
|
||||||
name: &'static str,
|
|
||||||
holder: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
static PLOTS: LazyLock<Mutex<Vec<Plot>>> = LazyLock::new(|| {
|
|
||||||
Mutex::new(vec![
|
|
||||||
Plot { id: 1, name: "A1", holder: "Ana" },
|
|
||||||
Plot { id: 2, name: "A2", holder: "Luke" },
|
|
||||||
Plot { id: 3, name: "B1", holder: "Marta" },
|
|
||||||
])
|
|
||||||
});
|
|
||||||
|
|
||||||
fn plots() -> MutexGuard<'static, Vec<Plot>> {
|
|
||||||
PLOTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Allotments;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Allotments {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/plots/{id}", web::delete(delete))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plot_row(plot: &Plot) -> table::Row {
|
|
||||||
let delete = Button::plain(Lc::n("Delete"))
|
|
||||||
.with_style(button::Style::Outline(Intent::Severe))
|
|
||||||
.with_prop(PropsOp::set(hx::DELETE, util::join!("/plots/", plot.id.to_string())))
|
|
||||||
.with_prop(PropsOp::set(hx::CONFIRM, "Delete this plot?"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "closest tr"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, "outerHTML swap:300ms"));
|
|
||||||
table::Row::new()
|
|
||||||
.with_cell(plot.name)
|
|
||||||
.with_cell(plot.holder)
|
|
||||||
.with_cell(delete)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plots_table(plots: &[Plot]) -> Container {
|
|
||||||
let mut table = Table::new()
|
|
||||||
.with_column(table::Column::new(Lc::n("Plot")))
|
|
||||||
.with_column(table::Column::new(Lc::n("Holder")))
|
|
||||||
.with_column(table::Column::new(Lc::none()))
|
|
||||||
.with_empty(Lc::n("No plots left."));
|
|
||||||
for plot in plots {
|
|
||||||
table = table.with_row(plot_row(plot));
|
|
||||||
}
|
|
||||||
Container::new().with_id("plots").with_child(table)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn count_update(count: usize) -> Markup {
|
|
||||||
html! { span id="plot-count" hx-swap-oob="true" { (count) } }
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let (table, count) = {
|
|
||||||
let plots = plots();
|
|
||||||
(plots_table(&plots), plots.len())
|
|
||||||
};
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Allotments"))
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
style { "tr.htmx-swapping { opacity: 0; transition: opacity 300ms ease-out; }" }
|
|
||||||
h1 { "Allotments (" span id="plot-count" { (count) } ")" }
|
|
||||||
}))
|
|
||||||
.with_child(table)
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete(request: HttpRequest, web::Path(id): web::Path<u32>) -> HtmxResponse {
|
|
||||||
let (empty_table, count) = {
|
|
||||||
let mut plots = plots();
|
|
||||||
plots.retain(|plot| plot.id != id);
|
|
||||||
(plots.is_empty().then(|| plots_table(&plots)), count_update(plots.len()))
|
|
||||||
};
|
|
||||||
if let Some(mut table) = empty_table {
|
|
||||||
let table = table.render(&mut Context::new(request)).await;
|
|
||||||
return HtmxResponse::new(table)
|
|
||||||
.retarget("#plots")
|
|
||||||
.reswap(hx::swap::OUTER_HTML)
|
|
||||||
.oob(count);
|
|
||||||
}
|
|
||||||
HtmxResponse::empty().oob(count)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Allotments).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El ejemplo pone la regla CSS en un `<style>` para que quepa en un archivo; en una aplicación, va en
|
|
||||||
su [hoja de estilos](assets.md).
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Pulsa *Delete* en una fila y acepta: la fila se desvanece y el contador del título baja.
|
|
||||||
2. Pulsa *Delete* y cancela: no pasa nada, y en la pestaña *Red* no hay petición.
|
|
||||||
3. Borra todas: al irse la última, aparece «No plots left.» y el contador marca 0.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Ordenar y paginar sin recargar](htmx-tables.md).
|
|
||||||
- [Dirigir al navegador desde el servidor](htmx-responses.md): todas las cabeceras que puede enviar
|
|
||||||
una respuesta.
|
|
||||||
|
|
@ -1,273 +0,0 @@
|
||||||
# Editar en línea
|
|
||||||
|
|
||||||
**Objetivo:** que un bloque de datos se convierta en un formulario al pulsar *Edit*, y vuelva a ser
|
|
||||||
un bloque al guardar o cancelar, sin salir de la página.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md). El tutorial [Tareas del huerto con
|
|
||||||
HTMX](../tutorials/htmx-tasks.md) hace lo mismo con elementos de una lista; aquí se hace con
|
|
||||||
componentes: un `Block` con un `Form` dentro.
|
|
||||||
|
|
||||||
## 1. Dos versiones del mismo bloque
|
|
||||||
|
|
||||||
La idea es tener dos funciones que construyen **el mismo bloque** (mismo `id`) en sus dos estados.
|
|
||||||
Los dos llevan `hx-target="this"` y `hx-swap="outerHTML"`, que heredan sus botones: cualquier
|
|
||||||
petición que salga de dentro sustituye el bloque entero.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct Contact {
|
|
||||||
name: String,
|
|
||||||
phone: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn contact_block() -> Block {
|
|
||||||
Block::new()
|
|
||||||
.with_id("contact")
|
|
||||||
.with_title(Lc::n("Garden coordinator"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "this"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn view_block(contact: &Contact) -> Block {
|
|
||||||
let contact = contact.clone();
|
|
||||||
contact_block()
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
p { (contact.name) }
|
|
||||||
p { (contact.phone) }
|
|
||||||
}))
|
|
||||||
.with_child(Button::plain(Lc::n("Edit")).with_prop(PropsOp::set(hx::GET, "/contact/edit")))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edit_block(contact: &Contact) -> Block {
|
|
||||||
contact_block().with_child(Messages::new()).with_child(
|
|
||||||
Form::new()
|
|
||||||
.with_prop(PropsOp::set(hx::PUT, "/contact"))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("name")
|
|
||||||
.with_value(&contact.name)
|
|
||||||
.with_label(Lc::n("Name"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::telephone()
|
|
||||||
.with_name("phone")
|
|
||||||
.with_value(&contact.phone)
|
|
||||||
.with_label(Lc::n("Phone")),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Save")))
|
|
||||||
.with_child(Button::plain(Lc::n("Cancel")).with_prop(PropsOp::set(hx::GET, "/contact"))),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El formulario no necesita `hx-target` propio: lo hereda del bloque. *Cancel* es un botón normal
|
|
||||||
(`type="button"`), así que no envía el formulario; sólo pide la vista.
|
|
||||||
|
|
||||||
## 2. Tres rutas pequeñas
|
|
||||||
|
|
||||||
| Ruta | Devuelve |
|
|
||||||
|---|---|
|
|
||||||
| `GET /contact/edit` | El bloque con el formulario |
|
|
||||||
| `GET /contact` | El bloque en modo vista (para *Cancel*) |
|
|
||||||
| `PUT /contact` | El bloque en modo vista con los datos nuevos, o el formulario con un error |
|
|
||||||
|
|
||||||
Las tres renderizan un `Block` fuera de una página, con un `Context` creado a partir de la
|
|
||||||
petición. Una función común lo hace, y de paso añade el error si lo hay:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
async fn fragment(request: HttpRequest, mut block: Block, error: Option<Lc>) -> HtmxResponse {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
if let Some(error) = error {
|
|
||||||
cx.push_message(MessageLevel::Error, error);
|
|
||||||
}
|
|
||||||
HtmxResponse::new(block.render(&mut cx).await)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Guardar valida antes de cambiar nada. Si algo falla, el usuario recibe su formulario **con lo que
|
|
||||||
escribió** y el motivo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# use serde::Deserialize;
|
|
||||||
# use std::sync::Mutex;
|
|
||||||
# #[derive(Clone)]
|
|
||||||
# struct Contact { name: String, phone: String }
|
|
||||||
# static CONTACT: Mutex<Option<Contact>> = Mutex::new(None);
|
|
||||||
# fn stored() -> std::sync::MutexGuard<'static, Option<Contact>> { CONTACT.lock().unwrap() }
|
|
||||||
# fn view_block(_: &Contact) -> Block { Block::new() }
|
|
||||||
# fn edit_block(_: &Contact) -> Block { Block::new() }
|
|
||||||
# async fn fragment(_: HttpRequest, _: Block, _: Option<Lc>) -> HtmxResponse { todo!() }
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ContactForm {
|
|
||||||
name: String,
|
|
||||||
phone: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn save(request: HttpRequest, web::Form(form): web::Form<ContactForm>) -> HtmxResponse {
|
|
||||||
let contact = Contact {
|
|
||||||
name: form.name.trim().to_string(),
|
|
||||||
phone: form.phone.trim().to_string(),
|
|
||||||
};
|
|
||||||
if contact.name.is_empty() {
|
|
||||||
let error = Lc::n("The coordinator needs a name.");
|
|
||||||
return fragment(request, edit_block(&contact), Some(error)).await;
|
|
||||||
}
|
|
||||||
*stored() = Some(contact.clone());
|
|
||||||
fragment(request, view_block(&contact), None).await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
use std::sync::{Mutex, MutexGuard};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct Contact {
|
|
||||||
name: String,
|
|
||||||
phone: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
static CONTACT: Mutex<Option<Contact>> = Mutex::new(None);
|
|
||||||
|
|
||||||
fn stored() -> MutexGuard<'static, Option<Contact>> {
|
|
||||||
CONTACT.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn current_contact() -> Contact {
|
|
||||||
stored().clone().unwrap_or_else(|| Contact {
|
|
||||||
name: "Ana Pérez".into(),
|
|
||||||
phone: "+34 600 000 000".into(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Coordinator;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Coordinator {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/contact", web::get(show).put(save))
|
|
||||||
.public_route("/contact/edit", web::get(edit))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn contact_block() -> Block {
|
|
||||||
Block::new()
|
|
||||||
.with_id("contact")
|
|
||||||
.with_title(Lc::n("Garden coordinator"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "this"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn view_block(contact: &Contact) -> Block {
|
|
||||||
let contact = contact.clone();
|
|
||||||
contact_block()
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
p { (contact.name) }
|
|
||||||
p { (contact.phone) }
|
|
||||||
}))
|
|
||||||
.with_child(Button::plain(Lc::n("Edit")).with_prop(PropsOp::set(hx::GET, "/contact/edit")))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edit_block(contact: &Contact) -> Block {
|
|
||||||
contact_block().with_child(Messages::new()).with_child(
|
|
||||||
Form::new()
|
|
||||||
.with_prop(PropsOp::set(hx::PUT, "/contact"))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("name")
|
|
||||||
.with_value(&contact.name)
|
|
||||||
.with_label(Lc::n("Name"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::telephone()
|
|
||||||
.with_name("phone")
|
|
||||||
.with_value(&contact.phone)
|
|
||||||
.with_label(Lc::n("Phone")),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Save")))
|
|
||||||
.with_child(Button::plain(Lc::n("Cancel")).with_prop(PropsOp::set(hx::GET, "/contact"))),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn fragment(request: HttpRequest, mut block: Block, error: Option<Lc>) -> HtmxResponse {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
if let Some(error) = error {
|
|
||||||
cx.push_message(MessageLevel::Error, error);
|
|
||||||
}
|
|
||||||
HtmxResponse::new(block.render(&mut cx).await)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Our garden"))
|
|
||||||
.with_child(view_block(¤t_contact()))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn show(request: HttpRequest) -> HtmxResponse {
|
|
||||||
fragment(request, view_block(¤t_contact()), None).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn edit(request: HttpRequest) -> HtmxResponse {
|
|
||||||
fragment(request, edit_block(¤t_contact()), None).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ContactForm {
|
|
||||||
name: String,
|
|
||||||
phone: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn save(request: HttpRequest, web::Form(form): web::Form<ContactForm>) -> HtmxResponse {
|
|
||||||
let contact = Contact {
|
|
||||||
name: form.name.trim().to_string(),
|
|
||||||
phone: form.phone.trim().to_string(),
|
|
||||||
};
|
|
||||||
if contact.name.is_empty() {
|
|
||||||
let error = Lc::n("The coordinator needs a name.");
|
|
||||||
return fragment(request, edit_block(&contact), Some(error)).await;
|
|
||||||
}
|
|
||||||
*stored() = Some(contact.clone());
|
|
||||||
fragment(request, view_block(&contact), None).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Coordinator).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Pulsa *Edit*: el bloque se convierte en un formulario con los datos actuales.
|
|
||||||
2. Pulsa *Cancel*: vuelve la vista, sin cambios.
|
|
||||||
3. Borra el nombre (con espacios, para que el navegador no lo impida) y guarda: el formulario
|
|
||||||
vuelve con el aviso y con el teléfono que habías escrito.
|
|
||||||
4. Escribe otro nombre y guarda: la vista muestra el nuevo. Recarga la página: el cambio se
|
|
||||||
mantiene.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Borrar con confirmación](htmx-delete.md).
|
|
||||||
- [Validar un campo al vuelo](htmx-validation.md), para avisar antes de guardar.
|
|
||||||
|
|
@ -1,157 +0,0 @@
|
||||||
# Cargar más al hacer *scroll*
|
|
||||||
|
|
||||||
**Objetivo:** una lista larga que carga los siguientes elementos al pulsar «Load more» o, mejor
|
|
||||||
aún, sola, cuando el usuario llega al final.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
|
||||||
|
|
||||||
## 1. Un lote de elementos y un testigo
|
|
||||||
|
|
||||||
La ruta devuelve un **lote** de elementos y, si quedan más, un último elemento especial: el
|
|
||||||
**testigo**, que sabe pedir el lote siguiente y ocupa su lugar.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
const PER_PAGE: usize = 10;
|
|
||||||
const TOTAL: usize = 35;
|
|
||||||
|
|
||||||
fn entries(page: usize) -> Markup {
|
|
||||||
let start = (page - 1) * PER_PAGE;
|
|
||||||
let end = (start + PER_PAGE).min(TOTAL);
|
|
||||||
let next = util::join!("/diary/entries?page=", (page + 1).to_string());
|
|
||||||
html! {
|
|
||||||
@for day in start + 1..=end {
|
|
||||||
li { "Day " (day) ": the garden is growing." }
|
|
||||||
}
|
|
||||||
@if end < TOTAL {
|
|
||||||
li {
|
|
||||||
button hx-get=(next) hx-target="closest li" hx-swap="outerHTML" { "Load more" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Al pulsar el botón, la respuesta (diez elementos y un testigo nuevo) **sustituye al testigo**: la
|
|
||||||
lista crece por abajo y el botón baja con ella. Cuando no quedan elementos, el último lote no trae
|
|
||||||
testigo y la carga termina sola.
|
|
||||||
|
|
||||||
## 2. Sin botón: al llegar al final
|
|
||||||
|
|
||||||
Para cargar sin que el usuario pulse nada, el testigo se dispara con `revealed`, que ocurre cuando
|
|
||||||
el elemento entra en la pantalla:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f(next: String) -> Markup {
|
|
||||||
html! {
|
|
||||||
li hx-get=(next) hx-trigger="revealed" hx-swap="outerHTML" { "Loading more..." }
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Es el mismo patrón con otro disparador. Si la lista está dentro de un contenedor con su propio
|
|
||||||
*scroll* (`overflow: auto`), usa `hx-trigger="intersect once"`, que funciona con cualquier
|
|
||||||
contenedor.
|
|
||||||
|
|
||||||
## 3. La página y la ruta del lote
|
|
||||||
|
|
||||||
La página pinta el primer lote dentro de la lista; la ruta del lote devuelve sólo los `<li>`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn entries(_: usize) -> Markup { html! {} }
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
async fn diary(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden diary"))
|
|
||||||
.with_child(Html::with(|_| html! { ul id="diary" { (entries(1)) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Batch {
|
|
||||||
page: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn more_entries(web::Query(batch): web::Query<Batch>) -> Markup {
|
|
||||||
entries(batch.page.max(1))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
const PER_PAGE: usize = 10;
|
|
||||||
const TOTAL: usize = 35;
|
|
||||||
|
|
||||||
struct Diary;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Diary {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(diary))
|
|
||||||
.public_route("/diary/entries", web::get(more_entries))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn entries(page: usize) -> Markup {
|
|
||||||
let start = (page - 1) * PER_PAGE;
|
|
||||||
let end = (start + PER_PAGE).min(TOTAL);
|
|
||||||
let next = util::join!("/diary/entries?page=", (page + 1).to_string());
|
|
||||||
html! {
|
|
||||||
@for day in start + 1..=end {
|
|
||||||
li { "Day " (day) ": the garden is growing." }
|
|
||||||
}
|
|
||||||
@if end < TOTAL {
|
|
||||||
li hx-get=(next) hx-trigger="revealed" hx-swap="outerHTML" { "Loading more..." }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn diary(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden diary"))
|
|
||||||
.with_child(Html::with(|_| html! { ul id="diary" { (entries(1)) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Batch {
|
|
||||||
page: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn more_entries(web::Query(batch): web::Query<Batch>) -> Markup {
|
|
||||||
entries(batch.page.max(1))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Diary).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Abre la página y baja: cada vez que el testigo «Loading more...» asoma por abajo, llegan diez
|
|
||||||
días más. Si la ventana es alta y el testigo ya se ve al cargar, el segundo lote llega sin
|
|
||||||
esperar: está a la vista.
|
|
||||||
2. Sigue bajando hasta el día 35: el testigo ya no aparece.
|
|
||||||
3. En la pestaña *Red* hay tres peticiones a `/diary/entries`, una por lote.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Ordenar y paginar sin recargar](htmx-tables.md): cuando el usuario necesita saltar a una página
|
|
||||||
concreta, un paginador es mejor opción.
|
|
||||||
- [Actualizar periódicamente](htmx-polling.md).
|
|
||||||
|
|
@ -1,168 +0,0 @@
|
||||||
# Cargar contenido bajo demanda
|
|
||||||
|
|
||||||
**Objetivo:** que una parte de la página se cargue después que el resto: cuando el usuario la pida,
|
|
||||||
en cuanto la página esté lista o cuando se haga visible. La página aparece antes, y lo costoso
|
|
||||||
llega por su cuenta.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
|
||||||
|
|
||||||
## 1. Al pulsar
|
|
||||||
|
|
||||||
El caso básico: un botón trae el contenido y lo pone en su sitio.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
button hx-get="/forecast" hx-target="#forecast" { "Show the forecast" }
|
|
||||||
div id="forecast" {}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Para que el botón desaparezca y su lugar lo ocupe el contenido, apunta al propio botón y sustitúyelo
|
|
||||||
entero:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
button hx-get="/forecast" hx-swap="outerHTML" { "Show the forecast" }
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. En cuanto se carga la página
|
|
||||||
|
|
||||||
Con `hx-trigger="load"`, el elemento pide su contenido nada más aparecer. Mientras llega, muestra
|
|
||||||
lo que tenga dentro:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
div hx-get="/forecast" hx-trigger="load" hx-swap="outerHTML" {
|
|
||||||
p { "Loading the forecast..." }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Úsalo para lo que tarda (un servicio externo, una consulta pesada): la página se sirve al momento y
|
|
||||||
ese bloque se completa después.
|
|
||||||
|
|
||||||
## 3. Cuando se hace visible
|
|
||||||
|
|
||||||
Con `hx-trigger="revealed"`, la petición espera a que el elemento entre en la pantalla. Ideal para
|
|
||||||
lo que queda al final de una página larga, como los comentarios:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
section hx-get="/comments" hx-trigger="revealed" hx-swap="outerHTML" {
|
|
||||||
p { "Comments will load when you get here." }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Si el usuario nunca baja hasta ahí, la petición no se hace.
|
|
||||||
|
|
||||||
## 4. Muestra que está cargando
|
|
||||||
|
|
||||||
Mientras dura una petición, HTMX añade la clase `htmx-request` al elemento que la hizo. Los
|
|
||||||
elementos con la clase `htmx-indicator` están ocultos y se muestran sólo durante la petición del
|
|
||||||
elemento que los contiene, o de quien los señale con `hx-indicator`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
button hx-get="/forecast" hx-target="#forecast" hx-indicator="#spinner" {
|
|
||||||
"Show the forecast"
|
|
||||||
}
|
|
||||||
span id="spinner" class="htmx-indicator" { " Loading..." }
|
|
||||||
div id="forecast" {}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
HTMX trae los estilos de `htmx-indicator`, así que funciona sin escribir CSS.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
Una página con las tres formas, sobre las mismas dos rutas:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/forecast", web::get(forecast))
|
|
||||||
.public_route("/comments", web::get(comments))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("The garden today"))
|
|
||||||
.with_child(Html::with(|_| html! {
|
|
||||||
h1 { "The garden today" }
|
|
||||||
|
|
||||||
h2 { "Forecast" }
|
|
||||||
button hx-get="/forecast" hx-swap="outerHTML" { "Show the forecast" }
|
|
||||||
|
|
||||||
h2 { "Forecast, on load" }
|
|
||||||
div hx-get="/forecast" hx-trigger="load" hx-swap="outerHTML" {
|
|
||||||
p { "Loading the forecast..." }
|
|
||||||
}
|
|
||||||
|
|
||||||
h2 { "Comments" }
|
|
||||||
div style="height: 150vh" { p { "Scroll down..." } }
|
|
||||||
section hx-get="/comments" hx-trigger="revealed" hx-swap="outerHTML" {
|
|
||||||
p { "Comments will load when you get here." }
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn forecast() -> Markup {
|
|
||||||
html! { p class="forecast" { "Sunny, 24 °C. Water in the evening." } }
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn comments() -> Markup {
|
|
||||||
html! {
|
|
||||||
ul class="comments" {
|
|
||||||
li { "Ana: the lettuces are ready." }
|
|
||||||
li { "Luke: who has the hose key?" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Al abrir la página, el segundo bloque ya muestra la previsión: se pidió nada más cargarse.
|
|
||||||
2. El botón del primero se sustituye por la previsión al pulsarlo.
|
|
||||||
3. En la pestaña *Red*, `/comments` no aparece hasta que bajas al final de la página.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Cargar más al hacer *scroll*](htmx-infinite.md): `revealed` aplicado a listas largas.
|
|
||||||
- [Actualizar periódicamente](htmx-polling.md): pedir el mismo fragmento cada pocos segundos.
|
|
||||||
|
|
@ -1,177 +0,0 @@
|
||||||
# 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, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_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).
|
|
||||||
|
|
@ -1,224 +0,0 @@
|
||||||
# Dirigir al navegador desde el servidor
|
|
||||||
|
|
||||||
**Objetivo:** que sea el servidor, y no los atributos de la página, quien decida qué pasa tras una
|
|
||||||
petición: poner la respuesta en otro sitio, avisar a otras partes de la página, cambiar la URL o
|
|
||||||
redirigir.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md). Todo se hace con `HtmxResponse`, que
|
|
||||||
añade a la respuesta las cabeceras `HX-*` que HTMX entiende.
|
|
||||||
|
|
||||||
## 1. Cambiar el destino según el resultado
|
|
||||||
|
|
||||||
Un formulario de suscripción coloca su respuesta en `#signup`. Si el correo no es válido, el error
|
|
||||||
debe ir a otro sitio, junto al campo. La ruta lo decide:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Signup {
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn looks_like_an_email(email: &str) -> bool {
|
|
||||||
email
|
|
||||||
.split_once('@')
|
|
||||||
.is_some_and(|(name, domain)| !name.is_empty() && domain.contains('.'))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn subscribe(web::Form(signup): web::Form<Signup>) -> HtmxResponse {
|
|
||||||
if !looks_like_an_email(&signup.email) {
|
|
||||||
return HtmxResponse::new(html! { "That does not look like an email." })
|
|
||||||
.retarget("#signup-error")
|
|
||||||
.reswap(hx::swap::INNER_HTML);
|
|
||||||
}
|
|
||||||
// ... store the subscription ...
|
|
||||||
HtmxResponse::new(html! { p { "Subscribed! See you at the next harvest." } })
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`retarget()` y `reswap()` mandan sobre `hx-target` y `hx-swap`. El formulario sigue en su sitio y
|
|
||||||
el usuario puede corregir el correo.
|
|
||||||
|
|
||||||
## 2. Avisar a otras partes de la página
|
|
||||||
|
|
||||||
Tras una suscripción, el contador de suscriptores de la cabecera debería actualizarse. En lugar de
|
|
||||||
que la ruta sepa qué hay en la cabecera, **dispara un evento**:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# fn f() -> HtmxResponse {
|
|
||||||
HtmxResponse::new(html! { p { "Subscribed! See you at the next harvest." } })
|
|
||||||
.trigger("subscribed")
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y quien quiera enterarse, lo escucha. El evento sube hasta `body`, así que basta con
|
|
||||||
`from:body`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
span hx-get="/subscribers" hx-trigger="subscribed from:body" { "0" }
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Las dos partes no se conocen: el formulario anuncia y el contador escucha. Puedes añadir más
|
|
||||||
oyentes sin tocar la ruta. Para enviar varios eventos o datos con ellos, `trigger()` admite una
|
|
||||||
lista separada por comas o un objeto JSON.
|
|
||||||
|
|
||||||
## 3. Redirigir
|
|
||||||
|
|
||||||
Tras una acción con HTMX, una redirección normal (`303`) la seguiría HTMX por su cuenta y pondría
|
|
||||||
la página nueva **dentro** del destino. Para cambiar de página de verdad, usa `redirect()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
async fn close_season() -> HtmxResponse {
|
|
||||||
// ... close the season ...
|
|
||||||
HtmxResponse::empty().redirect("/season/closed")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`location()` es la alternativa suave: navega con HTMX, sin recargar los estilos y *scripts* de la
|
|
||||||
página.
|
|
||||||
|
|
||||||
Con las dos, los avisos que añadas con `with_message()` esperan a la página de destino, como tras
|
|
||||||
una redirección normal: convierte antes la respuesta con `.into_response()`.
|
|
||||||
|
|
||||||
## Las cabeceras disponibles
|
|
||||||
|
|
||||||
| Método | Cabecera | Efecto |
|
|
||||||
|---|---|---|
|
|
||||||
| `retarget(selector)` | `HX-Retarget` | Pone la respuesta en otro elemento |
|
|
||||||
| `reswap(estrategia)` | `HX-Reswap` | Cambia cómo se coloca (`innerHTML`, `outerHTML`...) |
|
|
||||||
| `reselect(selector)` | `HX-Reselect` | Usa sólo una parte de la respuesta |
|
|
||||||
| `trigger(eventos)` | `HX-Trigger` | Dispara eventos al recibir la respuesta |
|
|
||||||
| `trigger_after_swap(eventos)` | `HX-Trigger-After-Swap` | ...después de colocarla |
|
|
||||||
| `trigger_after_settle(eventos)` | `HX-Trigger-After-Settle` | ...cuando se ha asentado |
|
|
||||||
| `push_url(url)` | `HX-Push-Url` | Añade una entrada al historial |
|
|
||||||
| `replace_url(url)` | `HX-Replace-Url` | Cambia la URL sin añadir entrada |
|
|
||||||
| `redirect(url)` | `HX-Redirect` | Navegación completa a otra página |
|
|
||||||
| `location(url)` | `HX-Location` | Navegación con HTMX, sin recargar la página |
|
|
||||||
| `refresh()` | `HX-Refresh` | Recarga la página entera |
|
|
||||||
| `oob(markup)` | - | Añade un fragmento [fuera de banda](htmx-delete.md#2-la-ruta-devuelve-un-fragmento-vacío) |
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
||||||
|
|
||||||
static SUBSCRIBERS: AtomicUsize = AtomicUsize::new(0);
|
|
||||||
|
|
||||||
struct Newsletter;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Newsletter {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/subscribe", web::post(subscribe))
|
|
||||||
.public_route("/subscribers", web::get(subscribers))
|
|
||||||
.public_route("/season/close", web::post(close_season))
|
|
||||||
.public_route("/season/closed", web::get(season_closed))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Newsletter"))
|
|
||||||
.with_child(Html::with(|_| html! {
|
|
||||||
p {
|
|
||||||
"Subscribers: "
|
|
||||||
span hx-get="/subscribers" hx-trigger="subscribed from:body" {
|
|
||||||
(SUBSCRIBERS.load(Ordering::Relaxed))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
div id="signup" {
|
|
||||||
form hx-post="/subscribe" hx-target="#signup" {
|
|
||||||
input type="email" name="email" placeholder="you@example.com";
|
|
||||||
button type="submit" { "Subscribe" }
|
|
||||||
p id="signup-error" {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
button hx-post="/season/close" hx-confirm="Close the season?" { "Close the season" }
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Signup {
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn looks_like_an_email(email: &str) -> bool {
|
|
||||||
email
|
|
||||||
.split_once('@')
|
|
||||||
.is_some_and(|(name, domain)| !name.is_empty() && domain.contains('.'))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn subscribe(web::Form(signup): web::Form<Signup>) -> HtmxResponse {
|
|
||||||
if !looks_like_an_email(&signup.email) {
|
|
||||||
return HtmxResponse::new(html! { "That does not look like an email." })
|
|
||||||
.retarget("#signup-error")
|
|
||||||
.reswap(hx::swap::INNER_HTML);
|
|
||||||
}
|
|
||||||
SUBSCRIBERS.fetch_add(1, Ordering::Relaxed);
|
|
||||||
HtmxResponse::new(html! { p { "Subscribed! See you at the next harvest." } })
|
|
||||||
.trigger("subscribed")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn subscribers() -> Markup {
|
|
||||||
html! { (SUBSCRIBERS.load(Ordering::Relaxed)) }
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn close_season() -> HtmxResponse {
|
|
||||||
HtmxResponse::empty().redirect("/season/closed")
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn season_closed(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Season closed"))
|
|
||||||
.with_child(Html::with(|_| html! { h1 { "The season is closed. See you in spring!" } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Newsletter).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El formulario de este ejemplo está escrito en `html!` para que se vea entero; con `Form` y sus
|
|
||||||
campos, los atributos se ponen igual, con `with_prop()`.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Escribe `ana@garden` y suscríbete: el navegador lo da por bueno, pero el servidor exige un
|
|
||||||
dominio con punto. El aviso aparece bajo el campo y el formulario sigue ahí.
|
|
||||||
2. Escribe un correo válido: el formulario se sustituye por la confirmación y el contador de
|
|
||||||
suscriptores sube, sin que la ruta lo haya tocado.
|
|
||||||
3. Pulsa *Close the season* y acepta: el navegador cambia de página.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [HTMX: atributos, cabeceras y respuestas](../reference/htmx.md), la referencia completa.
|
|
||||||
- [Probar rutas y componentes](testing.md): las cabeceras `HX-*` también se pueden comprobar en
|
|
||||||
las pruebas.
|
|
||||||
|
|
@ -1,219 +0,0 @@
|
||||||
# Buscar mientras se escribe
|
|
||||||
|
|
||||||
**Objetivo:** un buscador que filtra los resultados a medida que el usuario escribe, que deja en la
|
|
||||||
barra de direcciones una URL que se puede compartir y que funciona también sin JavaScript.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
|
||||||
|
|
||||||
## 1. Un buscador de toda la vida
|
|
||||||
|
|
||||||
Empieza por lo que funcionaría sin HTMX: un formulario `GET` que envía `q` a `/plants`, y una ruta
|
|
||||||
que muestra los resultados.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
const PLANTS: &[&str] = &[
|
|
||||||
"Basil", "Bean", "Beetroot", "Cabbage", "Carrot", "Chard", "Courgette", "Cucumber", "Garlic",
|
|
||||||
"Leek", "Lettuce", "Onion", "Parsley", "Pepper", "Potato", "Pumpkin", "Radish", "Spinach",
|
|
||||||
"Strawberry", "Tomato",
|
|
||||||
];
|
|
||||||
|
|
||||||
fn results(q: &str) -> Markup {
|
|
||||||
let q = q.trim().to_lowercase();
|
|
||||||
let found: Vec<&str> = PLANTS
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.filter(|plant| plant.to_lowercase().contains(&q))
|
|
||||||
.collect();
|
|
||||||
html! {
|
|
||||||
div id="results" {
|
|
||||||
@if found.is_empty() {
|
|
||||||
p { "No plants found." }
|
|
||||||
} @else {
|
|
||||||
ul {
|
|
||||||
@for plant in &found {
|
|
||||||
li { (plant) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El contenedor `#results` forma parte del fragmento. Así, al sustituirlo entero (`outerHTML`), el
|
|
||||||
destino sigue existiendo para la búsqueda siguiente.
|
|
||||||
|
|
||||||
## 2. Que busque al escribir
|
|
||||||
|
|
||||||
Al formulario se le añaden cinco atributos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
fn search_form(q: &str) -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/plants")
|
|
||||||
.with_method(form::Method::Get)
|
|
||||||
.with_prop(PropsOp::set(hx::GET, "/plants"))
|
|
||||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:300ms, submit"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#results"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
|
||||||
.with_prop(PropsOp::set(hx::REPLACE_URL, "true"))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::search()
|
|
||||||
.with_name("q")
|
|
||||||
.with_value(q)
|
|
||||||
.with_label(Lc::n("Search plants")),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `hx-trigger="input delay:300ms, submit"`: busca cuando cambia el texto, pero espera a que el
|
|
||||||
usuario lleve 300 ms sin teclear. Así, escribir «tomato» hace una petición, no seis. `submit`
|
|
||||||
mantiene la tecla Intro.
|
|
||||||
- El evento `input` sube desde el campo hasta el formulario, y una petición `GET` de un formulario
|
|
||||||
incluye todos sus campos: no hay que decir qué enviar.
|
|
||||||
- `hx-replace-url="true"`: la barra de direcciones pasa a `/plants?q=tom`, sin llenar el historial
|
|
||||||
con una entrada por búsqueda.
|
|
||||||
|
|
||||||
## 3. Una ruta, dos respuestas
|
|
||||||
|
|
||||||
La URL que queda en la barra se puede recargar o compartir. Esa petición llega **sin** HTMX y
|
|
||||||
espera una página entera; las de HTMX, sólo los resultados:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# fn results(_: &str) -> Markup { html! {} }
|
|
||||||
# fn search_form(_: &str) -> Form { Form::new() }
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Search {
|
|
||||||
#[serde(default)]
|
|
||||||
q: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn plants(request: HttpRequest, web::Query(search): web::Query<Search>) -> Response {
|
|
||||||
if request.is_htmx() {
|
|
||||||
return HtmxResponse::new(results(&search.q)).into_response();
|
|
||||||
}
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Plants"))
|
|
||||||
.with_child(search_form(&search.q))
|
|
||||||
.with_child(Html::with(move |_| results(&search.q)))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
.into_response()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Sin JavaScript, el formulario se envía como siempre y la misma ruta devuelve la página completa: el
|
|
||||||
buscador funciona igual, sólo que pulsando Intro.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
const PLANTS: &[&str] = &[
|
|
||||||
"Basil", "Bean", "Beetroot", "Cabbage", "Carrot", "Chard", "Courgette", "Cucumber", "Garlic",
|
|
||||||
"Leek", "Lettuce", "Onion", "Parsley", "Pepper", "Potato", "Pumpkin", "Radish", "Spinach",
|
|
||||||
"Strawberry", "Tomato",
|
|
||||||
];
|
|
||||||
|
|
||||||
struct PlantFinder;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for PlantFinder {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(|| async { Redirect::see_other("/plants") }))
|
|
||||||
.public_route("/plants", web::get(plants))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Search {
|
|
||||||
#[serde(default)]
|
|
||||||
q: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn plants(request: HttpRequest, web::Query(search): web::Query<Search>) -> Response {
|
|
||||||
if request.is_htmx() {
|
|
||||||
return HtmxResponse::new(results(&search.q)).into_response();
|
|
||||||
}
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Plants"))
|
|
||||||
.with_child(search_form(&search.q))
|
|
||||||
.with_child(Html::with(move |_| results(&search.q)))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn search_form(q: &str) -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/plants")
|
|
||||||
.with_method(form::Method::Get)
|
|
||||||
.with_prop(PropsOp::set(hx::GET, "/plants"))
|
|
||||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:300ms, submit"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#results"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
|
||||||
.with_prop(PropsOp::set(hx::REPLACE_URL, "true"))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::search()
|
|
||||||
.with_name("q")
|
|
||||||
.with_value(q)
|
|
||||||
.with_label(Lc::n("Search plants")),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn results(q: &str) -> Markup {
|
|
||||||
let q = q.trim().to_lowercase();
|
|
||||||
let found: Vec<&str> = PLANTS
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.filter(|plant| plant.to_lowercase().contains(&q))
|
|
||||||
.collect();
|
|
||||||
html! {
|
|
||||||
div id="results" {
|
|
||||||
@if found.is_empty() {
|
|
||||||
p { "No plants found." }
|
|
||||||
} @else {
|
|
||||||
ul {
|
|
||||||
@for plant in &found {
|
|
||||||
li { (plant) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&PlantFinder).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Abre <http://localhost:8080/plants> y escribe `to`: la lista se reduce a *Potato* y *Tomato*
|
|
||||||
sin pulsar nada, y la barra de direcciones muestra `/plants?q=to`.
|
|
||||||
2. Recarga la página: sale la misma búsqueda, ya resuelta por el servidor.
|
|
||||||
3. En la pestaña *Red*, escribir una palabra seguida produce una sola petición.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Ordenar y paginar sin recargar](htmx-tables.md): el mismo patrón sobre una tabla con su
|
|
||||||
paginador.
|
|
||||||
- [Validar un campo al vuelo](htmx-validation.md).
|
|
||||||
|
|
@ -1,216 +0,0 @@
|
||||||
# Añadir HTMX a una aplicación
|
|
||||||
|
|
||||||
**Objetivo:** que tus páginas carguen [HTMX](https://htmx.org), que sus elementos pidan fragmentos
|
|
||||||
de HTML al servidor y que tus rutas sepan responderlos.
|
|
||||||
|
|
||||||
Si es tu primer contacto con HTMX, el tutorial [Tareas del huerto con
|
|
||||||
HTMX](../tutorials/htmx-tasks.md) lo presenta paso a paso. Esta guía reúne lo esencial para
|
|
||||||
cualquier aplicación.
|
|
||||||
|
|
||||||
## 1. Declara la extensión
|
|
||||||
|
|
||||||
Añade `pagetop-htmx` a `Cargo.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop-htmx = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y declárala como dependencia de tu extensión:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct MyApp;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for MyApp {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
No hace falta nada más: la extensión añade el *script* de HTMX 2 a **todas** las páginas, con
|
|
||||||
`defer`, y lo sirve desde el propio binario. No hay que descargar nada ni configurar una CDN.
|
|
||||||
|
|
||||||
## 2. Escribe atributos `hx-*` en `html!`
|
|
||||||
|
|
||||||
Los atributos de HTMX se escriben en `html!` como cualquier otro:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|_| html! {
|
|
||||||
button hx-get="/time" hx-target="#time" { "What time is it?" }
|
|
||||||
span id="time" {}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Al pulsar el botón, HTMX hace `GET /time` y pone la respuesta dentro de `#time`. Los atributos
|
|
||||||
principales:
|
|
||||||
|
|
||||||
| Atributo | Qué indica | Por defecto |
|
|
||||||
|---|---|---|
|
|
||||||
| `hx-get`, `hx-post`, `hx-put`, `hx-patch`, `hx-delete` | Método y URL de la petición | - |
|
|
||||||
| `hx-trigger` | Qué evento la lanza | `click`; `change` en campos; `submit` en formularios |
|
|
||||||
| `hx-target` | Dónde va la respuesta (selector CSS, `this`, `closest tr`...) | El propio elemento |
|
|
||||||
| `hx-swap` | Cómo se coloca | `innerHTML`: sustituye el contenido |
|
|
||||||
|
|
||||||
La lista completa está en la [referencia de HTMX](../reference/htmx.md).
|
|
||||||
|
|
||||||
## 3. Ponlos en componentes con `with_prop()`
|
|
||||||
|
|
||||||
Los componentes no conocen HTMX, pero todos aceptan atributos con `with_prop()`. El módulo `hx` de
|
|
||||||
`pagetop-htmx` tiene una constante para cada atributo y para sus valores habituales:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
# fn f() -> Button {
|
|
||||||
Button::plain(Lc::n("What time is it?"))
|
|
||||||
.with_prop(PropsOp::set(hx::GET, "/time"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#time"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Con las constantes, una errata como `hx::GTE` no compila; escrita como texto, `"hx-gte"` fallaría
|
|
||||||
en silencio en el navegador.
|
|
||||||
|
|
||||||
## 4. Responde con un fragmento
|
|
||||||
|
|
||||||
Una ruta para HTMX devuelve **sólo el trozo de HTML** que va en el destino, no una página. Lo más
|
|
||||||
sencillo es devolver `Markup`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn time() -> Markup {
|
|
||||||
html! { (Utc::now().format("%H:%M:%S")) " UTC" }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si además necesitas cabeceras de HTMX (cambiar el destino, disparar eventos, redirigir...),
|
|
||||||
devuelve un `HtmxResponse`. Lo verás en [Dirigir al navegador desde el
|
|
||||||
servidor](htmx-responses.md):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
async fn time() -> HtmxResponse {
|
|
||||||
HtmxResponse::new(html! { (Utc::now().format("%H:%M:%S")) " UTC" })
|
|
||||||
.trigger("timeShown")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Renderiza componentes en un fragmento
|
|
||||||
|
|
||||||
Fuera de una `Page`, un componente se renderiza con un `Context` creado a partir de la petición. El
|
|
||||||
contexto aporta el idioma, el tema y las rutas, así que el fragmento sale igual que dentro de la
|
|
||||||
página:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
async fn notice(request: HttpRequest) -> HtmxResponse {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
let mut badge = Badge::success(Lc::n("Saved"));
|
|
||||||
HtmxResponse::new(badge.render(&mut cx).await)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **Los recursos de un componente no viajan en un fragmento.** Si un componente añade su hoja de
|
|
||||||
> estilos o su *script* al contexto, en una página acaban en el `<head>`; en un fragmento suelto no
|
|
||||||
> hay `<head>` donde ponerlos. Asegúrate de que la página que recibe el fragmento ya los carga, por
|
|
||||||
> ejemplo usando ese mismo componente en ella o añadiéndolos con `with_assets()`.
|
|
||||||
|
|
||||||
## 6. Una ruta, dos respuestas
|
|
||||||
|
|
||||||
Cuando la misma URL puede pedirse con HTMX (para un fragmento) o directamente (al recargar, desde
|
|
||||||
un enlace compartido o sin JavaScript), comprueba quién llama con `is_htmx()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
async fn plants(request: HttpRequest) -> Response {
|
|
||||||
let list = html! { ul { li { "Tomato" } li { "Pepper" } } };
|
|
||||||
if request.is_htmx() {
|
|
||||||
HtmxResponse::new(list).into_response()
|
|
||||||
} else {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Plants"))
|
|
||||||
.with_child(Html::with(move |_| list.clone()))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
.into_response()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`is_htmx()` lee la cabecera `HX-Request` que HTMX añade a sus peticiones. El trait
|
|
||||||
`HtmxRequestExt` también ofrece `hx_target()`, `hx_trigger_id()`, `is_boosted()`... para leer las
|
|
||||||
demás.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
struct Clock;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Clock {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/time", web::get(time))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Clock"))
|
|
||||||
.with_child(
|
|
||||||
Button::plain(Lc::n("What time is it?"))
|
|
||||||
.with_prop(PropsOp::set(hx::GET, "/time"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#time")),
|
|
||||||
)
|
|
||||||
.with_child(Html::with(|_| html! { p id="time" { "Not asked yet." } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn time(request: HttpRequest) -> HtmxResponse {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
let mut badge = Badge::info(Lc::n(Utc::now().format("%H:%M:%S UTC").to_string()));
|
|
||||||
HtmxResponse::new(badge.render(&mut cx).await)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Clock).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Arranca la aplicación y abre <http://localhost:8080>.
|
|
||||||
2. Pulsa el botón: la hora aparece en una etiqueta, sin recargar.
|
|
||||||
3. En las herramientas de desarrollo del navegador (pestaña *Red*), la petición a `/time` lleva la
|
|
||||||
cabecera `HX-Request: true` y la respuesta es una sola etiqueta `<span>`.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Cargar contenido bajo demanda](htmx-load.md): al pulsar, al cargar la página o al hacerse
|
|
||||||
visible.
|
|
||||||
- [Probar rutas y componentes](testing.md): cómo probar una ruta de HTMX sin navegador.
|
|
||||||
- [HTML por la red: por qué HTMX](../explanation/htmx.md).
|
|
||||||
|
|
@ -1,252 +0,0 @@
|
||||||
# Ordenar y paginar sin recargar
|
|
||||||
|
|
||||||
**Objetivo:** una tabla que se ordena al pulsar sus cabeceras y se pagina con su `Pager`, sustituyendo
|
|
||||||
sólo la tabla, con URLs reales en la barra de direcciones y sin perder nada si JavaScript no está
|
|
||||||
disponible.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md) y de lo visto en [Mostrar tablas
|
|
||||||
ordenables y paginadas](tables.md): `Table`, `SortLink` y `Pager` ya generan enlaces normales que
|
|
||||||
funcionan sin HTMX. Aquí sólo se les añade el comportamiento.
|
|
||||||
|
|
||||||
## 1. Un contenedor como destino
|
|
||||||
|
|
||||||
La tabla y su paginador van juntos en un `Container` con `id`. Ése es el destino de todas las
|
|
||||||
peticiones: al ordenar o cambiar de página, se sustituyen los dos.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn table() -> Table { Table::new() }
|
|
||||||
# fn pager() -> Pager { Pager::new() }
|
|
||||||
# fn f() -> Container {
|
|
||||||
Container::new()
|
|
||||||
.with_id("harvests")
|
|
||||||
.with_child(table())
|
|
||||||
.with_child(pager())
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Cabeceras que ordenan con HTMX
|
|
||||||
|
|
||||||
`hx_table::sort_link()` crea el enlace de una cabecera con los atributos de HTMX ya puestos: hace
|
|
||||||
`GET` a la misma URL del enlace, sustituye el destino, vuelve arriba y actualiza la barra de
|
|
||||||
direcciones. Sólo hay que darle la URL, el destino y la dirección actual de esa columna:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
fn sortable(cx: &Context, field: &str, label: Lc, sort: &str, dir: SortDir) -> table::Column {
|
|
||||||
// `Some` only if the table is sorted by this column right now.
|
|
||||||
let active = (field == sort).then_some(dir);
|
|
||||||
let href = cx
|
|
||||||
.route("/harvests")
|
|
||||||
.with_param("sort", field)
|
|
||||||
.with_param("dir", SortDir::next_for(active));
|
|
||||||
table::Column::new(label).with_sort(hx_table::sort_link(href, "#harvests", active))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`SortDir::next_for()` calcula la dirección del siguiente clic: ascendente si la columna no ordena
|
|
||||||
ahora, la contraria si ya lo hace. `cx.route()` conserva el parámetro `?lang=` cuando lo hay.
|
|
||||||
|
|
||||||
## 3. Un paginador que navega con HTMX
|
|
||||||
|
|
||||||
`Pager` no necesita atributos en cada enlace: con `hx-boost` en su `<nav>`, HTMX convierte en
|
|
||||||
peticiones AJAX todos los enlaces que contiene, reutilizando su `href`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
# fn f(sort: &str, dir: SortDir, page: u64, total: u64) -> Pager {
|
|
||||||
Pager::new()
|
|
||||||
.with_base_path("/harvests")
|
|
||||||
.with_extra_query("sort", sort)
|
|
||||||
.with_extra_query("dir", dir.as_str())
|
|
||||||
.with_current_page(page)
|
|
||||||
.with_items_per_page(5)
|
|
||||||
.with_total_items(total)
|
|
||||||
.with_prop(PropsOp::set(hx::BOOST, "true"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#harvests"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
|
|
||||||
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`with_extra_query()` mantiene el orden al cambiar de página.
|
|
||||||
|
|
||||||
## 4. La ruta: página entera o sólo la tabla
|
|
||||||
|
|
||||||
Una sola ruta atiende todo. Lee el estado de la URL, construye el contenedor y lo devuelve solo (con
|
|
||||||
HTMX) o dentro de una página (sin HTMX, al recargar o desde un enlace compartido). En los dos casos
|
|
||||||
usa un `Context`: el de la página, o uno creado a partir de la petición.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# fn harvests(_: &Context, _: &str, _: SortDir, _: u64) -> Container { Container::new() }
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ListQuery {
|
|
||||||
sort: Option<String>,
|
|
||||||
dir: Option<String>,
|
|
||||||
page: Option<u64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list(request: HttpRequest, web::Query(query): web::Query<ListQuery>) -> Response {
|
|
||||||
let sort = query.sort.as_deref().unwrap_or("crop");
|
|
||||||
let dir = SortDir::from_query(query.dir.as_deref());
|
|
||||||
let page = query.page.unwrap_or(1).max(1);
|
|
||||||
|
|
||||||
if request.is_htmx() {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
let mut table = harvests(&cx, sort, dir, page);
|
|
||||||
return HtmxResponse::new(table.render(&mut cx).await).into_response();
|
|
||||||
}
|
|
||||||
let full = Page::new(request).with_title(Lc::n("Harvests"));
|
|
||||||
let table = harvests(full.context(), sort, dir, page);
|
|
||||||
full.with_child(table).render().await.into_response()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
const PER_PAGE: u64 = 5;
|
|
||||||
|
|
||||||
struct Harvest {
|
|
||||||
crop: &'static str,
|
|
||||||
plot: &'static str,
|
|
||||||
kilos: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
const HARVESTS: &[Harvest] = &[
|
|
||||||
Harvest { crop: "Tomato", plot: "A1", kilos: 42 },
|
|
||||||
Harvest { crop: "Lettuce", plot: "A2", kilos: 12 },
|
|
||||||
Harvest { crop: "Pepper", plot: "B1", kilos: 18 },
|
|
||||||
Harvest { crop: "Courgette", plot: "B2", kilos: 35 },
|
|
||||||
Harvest { crop: "Onion", plot: "A1", kilos: 20 },
|
|
||||||
Harvest { crop: "Potato", plot: "C1", kilos: 60 },
|
|
||||||
Harvest { crop: "Bean", plot: "C2", kilos: 9 },
|
|
||||||
Harvest { crop: "Pumpkin", plot: "B1", kilos: 51 },
|
|
||||||
Harvest { crop: "Chard", plot: "A2", kilos: 14 },
|
|
||||||
Harvest { crop: "Carrot", plot: "C1", kilos: 16 },
|
|
||||||
Harvest { crop: "Garlic", plot: "C2", kilos: 7 },
|
|
||||||
Harvest { crop: "Strawberry", plot: "B2", kilos: 11 },
|
|
||||||
];
|
|
||||||
|
|
||||||
struct HarvestLog;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for HarvestLog {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(|| async { Redirect::see_other("/harvests") }))
|
|
||||||
.public_route("/harvests", web::get(list))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct ListQuery {
|
|
||||||
sort: Option<String>,
|
|
||||||
dir: Option<String>,
|
|
||||||
page: Option<u64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list(request: HttpRequest, web::Query(query): web::Query<ListQuery>) -> Response {
|
|
||||||
let sort = query.sort.as_deref().unwrap_or("crop");
|
|
||||||
let dir = SortDir::from_query(query.dir.as_deref());
|
|
||||||
let page = query.page.unwrap_or(1).max(1);
|
|
||||||
|
|
||||||
if request.is_htmx() {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
let mut table = harvests(&cx, sort, dir, page);
|
|
||||||
return HtmxResponse::new(table.render(&mut cx).await).into_response();
|
|
||||||
}
|
|
||||||
let full = Page::new(request).with_title(Lc::n("Harvests"));
|
|
||||||
let table = harvests(full.context(), sort, dir, page);
|
|
||||||
full.with_child(table).render().await.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn harvests(cx: &Context, sort: &str, dir: SortDir, page: u64) -> Container {
|
|
||||||
let mut rows: Vec<&Harvest> = HARVESTS.iter().collect();
|
|
||||||
match sort {
|
|
||||||
"kilos" => rows.sort_by_key(|harvest| harvest.kilos),
|
|
||||||
_ => rows.sort_by_key(|harvest| harvest.crop),
|
|
||||||
}
|
|
||||||
if dir == SortDir::Desc {
|
|
||||||
rows.reverse();
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut table = Table::new()
|
|
||||||
.with_column(sortable(cx, "crop", Lc::n("Crop"), sort, dir))
|
|
||||||
.with_column(table::Column::new(Lc::n("Plot")))
|
|
||||||
.with_column(sortable(cx, "kilos", Lc::n("Kilos"), sort, dir));
|
|
||||||
let skip = ((page - 1) * PER_PAGE) as usize;
|
|
||||||
for harvest in rows.iter().skip(skip).take(PER_PAGE as usize) {
|
|
||||||
table = table.with_row(
|
|
||||||
table::Row::new()
|
|
||||||
.with_cell(harvest.crop)
|
|
||||||
.with_cell(harvest.plot)
|
|
||||||
.with_cell(harvest.kilos.to_string()),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let pager = Pager::new()
|
|
||||||
.with_base_path("/harvests")
|
|
||||||
.with_extra_query("sort", sort)
|
|
||||||
.with_extra_query("dir", dir.as_str())
|
|
||||||
.with_current_page(page)
|
|
||||||
.with_items_per_page(PER_PAGE)
|
|
||||||
.with_total_items(rows.len() as u64)
|
|
||||||
.with_prop(PropsOp::set(hx::BOOST, "true"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#harvests"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
|
|
||||||
.with_prop(PropsOp::set(hx::PUSH_URL, "true"));
|
|
||||||
|
|
||||||
Container::new()
|
|
||||||
.with_id("harvests")
|
|
||||||
.with_child(table)
|
|
||||||
.with_child(pager)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sortable(cx: &Context, field: &str, label: Lc, sort: &str, dir: SortDir) -> table::Column {
|
|
||||||
// `Some` only if the table is sorted by this column right now.
|
|
||||||
let active = (field == sort).then_some(dir);
|
|
||||||
let href = cx
|
|
||||||
.route("/harvests")
|
|
||||||
.with_param("sort", field)
|
|
||||||
.with_param("dir", SortDir::next_for(active));
|
|
||||||
table::Column::new(label).with_sort(hx_table::sort_link(href, "#harvests", active))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&HarvestLog).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Abre <http://localhost:8080/harvests>: cinco cosechas ordenadas por cultivo y un paginador de
|
|
||||||
tres páginas.
|
|
||||||
2. Pulsa la cabecera *Kilos*: la tabla se ordena de menos a más; púlsala otra vez, de más a menos.
|
|
||||||
La barra de direcciones refleja cada estado (`?sort=kilos&dir=desc`).
|
|
||||||
3. Ve a la página 2: se conserva el orden. Usa el botón *Atrás* del navegador y recarga: la URL
|
|
||||||
muestra exactamente lo que había.
|
|
||||||
4. Desactiva JavaScript y repite: todo funciona igual, con recargas de página completas.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Buscar mientras se escribe](htmx-search.md): añade un buscador que filtre la misma tabla.
|
|
||||||
- [Cargar más al hacer *scroll*](htmx-infinite.md): la alternativa al paginador para listas que se
|
|
||||||
leen de arriba abajo.
|
|
||||||
|
|
@ -1,315 +0,0 @@
|
||||||
# Validar un campo al vuelo
|
|
||||||
|
|
||||||
**Objetivo:** avisar de un error mientras el usuario rellena el formulario (un nombre de usuario ya
|
|
||||||
ocupado, por ejemplo) y, al enviarlo, mostrar los errores **dentro** del formulario sin recargar la
|
|
||||||
página ni perder lo escrito.
|
|
||||||
|
|
||||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md) y de lo visto en [Crear y procesar
|
|
||||||
formularios](forms.md).
|
|
||||||
|
|
||||||
## 1. El formulario y su validación
|
|
||||||
|
|
||||||
Un formulario para unirse al huerto, con su validación en el servidor. Una función construye el
|
|
||||||
formulario con los valores recibidos, para poder repetirlo sin perder lo escrito:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
const TAKEN: &[&str] = &["admin", "ana", "luke"];
|
|
||||||
|
|
||||||
#[derive(Default, Deserialize)]
|
|
||||||
#[serde(default)]
|
|
||||||
struct JoinData {
|
|
||||||
username: String,
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate(data: &JoinData) -> Option<Lc> {
|
|
||||||
let username = data.username.trim();
|
|
||||||
if username.chars().count() < 3 {
|
|
||||||
Some(Lc::n("The username needs at least 3 characters."))
|
|
||||||
} else if TAKEN.contains(&username) {
|
|
||||||
Some(Lc::n("That username is already taken."))
|
|
||||||
} else if !data.email.contains('@') {
|
|
||||||
Some(Lc::n("Write a valid email."))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`#[serde(default)]` permite deserializar el formulario aunque falte algún campo, lo que vendrá bien
|
|
||||||
en el paso 2.
|
|
||||||
|
|
||||||
## 2. Comprobar un campo mientras se escribe
|
|
||||||
|
|
||||||
Los atributos `hx-*` de un campo se ponen con su `with_prop()`. El campo hace un `POST` a
|
|
||||||
`/join/check` cuando el usuario deja de escribir medio segundo, y la respuesta va a `#username-check`,
|
|
||||||
justo debajo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
# #[derive(Default)]
|
|
||||||
# struct JoinData { username: String, email: String }
|
|
||||||
|
|
||||||
fn username_field(data: &JoinData) -> form::input::Field {
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("username")
|
|
||||||
.with_value(&data.username)
|
|
||||||
.with_label(Lc::n("Username"))
|
|
||||||
.with_required(true)
|
|
||||||
.with_prop(PropsOp::set(hx::POST, "/join/check"))
|
|
||||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:500ms"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#username-check"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`hx-swap` parece innecesario, porque `innerHTML` es el valor por defecto. Pero los atributos de
|
|
||||||
HTMX **se heredan**: en el paso 3 el formulario tendrá `hx-swap="outerHTML"`, y el campo lo
|
|
||||||
heredaría, así que la etiqueta sustituiría al propio `#username-check` y la siguiente comprobación
|
|
||||||
ya no tendría dónde ir.
|
|
||||||
|
|
||||||
Una petición que no es `GET` incluye **todos** los campos del formulario que la contiene, así que la
|
|
||||||
ruta recibe el mismo `JoinData`. Sólo mira el nombre:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# const TAKEN: &[&str] = &[];
|
|
||||||
# #[derive(Default, serde::Deserialize)]
|
|
||||||
# #[serde(default)]
|
|
||||||
# struct JoinData { username: String }
|
|
||||||
async fn check_username(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> HtmxResponse {
|
|
||||||
let username = data.username.trim();
|
|
||||||
if username.is_empty() {
|
|
||||||
return HtmxResponse::empty();
|
|
||||||
}
|
|
||||||
let mut badge = if TAKEN.contains(&username) {
|
|
||||||
Badge::severe(Lc::n("Already taken"))
|
|
||||||
} else {
|
|
||||||
Badge::success(Lc::n("Available"))
|
|
||||||
};
|
|
||||||
HtmxResponse::new(badge.render(&mut Context::new(request)).await)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **Responde con 200, también a los errores.** Por defecto, HTMX **no coloca** las respuestas con
|
|
||||||
> código 4xx o 5xx. Un error de validación es una respuesta normal que el usuario debe ver.
|
|
||||||
|
|
||||||
## 3. Errores dentro del formulario al enviarlo
|
|
||||||
|
|
||||||
Para que el formulario completo se envíe con HTMX y se sustituya por la respuesta, el formulario y
|
|
||||||
sus mensajes van en un contenedor con `id`, y ése es el destino:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# #[derive(Default)]
|
|
||||||
# struct JoinData { username: String, email: String }
|
|
||||||
# fn username_field(_: &JoinData) -> form::input::Field { form::input::Field::text() }
|
|
||||||
fn join_box(data: &JoinData) -> Container {
|
|
||||||
Container::new().with_id("join").with_child(Messages::new()).with_child(
|
|
||||||
Form::new()
|
|
||||||
.with_action("/join")
|
|
||||||
.with_prop(PropsOp::set(hx::POST, "/join"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#join"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
|
||||||
.with_child(username_field(data))
|
|
||||||
.with_child(Html::with(|_| html! { div id="username-check" {} }))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::email()
|
|
||||||
.with_name("email")
|
|
||||||
.with_value(&data.email)
|
|
||||||
.with_label(Lc::n("Email")),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Join"))),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn welcome_box(username: &str) -> Container {
|
|
||||||
let username = username.trim().to_string();
|
|
||||||
Container::new()
|
|
||||||
.with_id("join")
|
|
||||||
.with_child(Html::with(move |_| html! { p { "Welcome to the garden, " (username) "!" } }))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
La ruta del envío valida y responde con uno u otro contenedor. Con HTMX, sólo el contenedor; sin
|
|
||||||
JavaScript, una página entera con él. El error viaja como un mensaje del contexto, que muestra
|
|
||||||
`Messages`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# #[derive(Default, serde::Deserialize)]
|
|
||||||
# struct JoinData { username: String }
|
|
||||||
# fn validate(_: &JoinData) -> Option<Lc> { None }
|
|
||||||
# fn join_box(_: &JoinData) -> Container { Container::new() }
|
|
||||||
# fn welcome_box(_: &str) -> Container { Container::new() }
|
|
||||||
async fn join(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> Response {
|
|
||||||
let error = validate(&data);
|
|
||||||
let mut content = match error {
|
|
||||||
Some(_) => join_box(&data),
|
|
||||||
None => welcome_box(&data.username),
|
|
||||||
};
|
|
||||||
if request.is_htmx() {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
if let Some(error) = error {
|
|
||||||
cx.push_message(MessageLevel::Error, error);
|
|
||||||
}
|
|
||||||
return HtmxResponse::new(content.render(&mut cx).await).into_response();
|
|
||||||
}
|
|
||||||
let mut page = Page::new(request).with_child(content);
|
|
||||||
if let Some(error) = error {
|
|
||||||
page.push_message(MessageLevel::Error, error);
|
|
||||||
}
|
|
||||||
page.render().await.into_response()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
const TAKEN: &[&str] = &["admin", "ana", "luke"];
|
|
||||||
|
|
||||||
struct JoinTheGarden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for JoinTheGarden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/join", web::post(join))
|
|
||||||
.public_route("/join/check", web::post(check_username))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Deserialize)]
|
|
||||||
#[serde(default)]
|
|
||||||
struct JoinData {
|
|
||||||
username: String,
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate(data: &JoinData) -> Option<Lc> {
|
|
||||||
let username = data.username.trim();
|
|
||||||
if username.chars().count() < 3 {
|
|
||||||
Some(Lc::n("The username needs at least 3 characters."))
|
|
||||||
} else if TAKEN.contains(&username) {
|
|
||||||
Some(Lc::n("That username is already taken."))
|
|
||||||
} else if !data.email.contains('@') {
|
|
||||||
Some(Lc::n("Write a valid email."))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn username_field(data: &JoinData) -> form::input::Field {
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("username")
|
|
||||||
.with_value(&data.username)
|
|
||||||
.with_label(Lc::n("Username"))
|
|
||||||
.with_required(true)
|
|
||||||
.with_prop(PropsOp::set(hx::POST, "/join/check"))
|
|
||||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:500ms"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#username-check"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn join_box(data: &JoinData) -> Container {
|
|
||||||
Container::new().with_id("join").with_child(Messages::new()).with_child(
|
|
||||||
Form::new()
|
|
||||||
.with_action("/join")
|
|
||||||
.with_prop(PropsOp::set(hx::POST, "/join"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#join"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
|
||||||
.with_child(username_field(data))
|
|
||||||
.with_child(Html::with(|_| html! { div id="username-check" {} }))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::email()
|
|
||||||
.with_name("email")
|
|
||||||
.with_value(&data.email)
|
|
||||||
.with_label(Lc::n("Email")),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Join"))),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn welcome_box(username: &str) -> Container {
|
|
||||||
let username = username.trim().to_string();
|
|
||||||
Container::new()
|
|
||||||
.with_id("join")
|
|
||||||
.with_child(Html::with(move |_| html! { p { "Welcome to the garden, " (username) "!" } }))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Join the garden"))
|
|
||||||
.with_child(join_box(&JoinData::default()))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn check_username(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> HtmxResponse {
|
|
||||||
let username = data.username.trim();
|
|
||||||
if username.is_empty() {
|
|
||||||
return HtmxResponse::empty();
|
|
||||||
}
|
|
||||||
let mut badge = if TAKEN.contains(&username) {
|
|
||||||
Badge::severe(Lc::n("Already taken"))
|
|
||||||
} else {
|
|
||||||
Badge::success(Lc::n("Available"))
|
|
||||||
};
|
|
||||||
HtmxResponse::new(badge.render(&mut Context::new(request)).await)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn join(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> Response {
|
|
||||||
let error = validate(&data);
|
|
||||||
let mut content = match error {
|
|
||||||
Some(_) => join_box(&data),
|
|
||||||
None => welcome_box(&data.username),
|
|
||||||
};
|
|
||||||
if request.is_htmx() {
|
|
||||||
let mut cx = Context::new(request);
|
|
||||||
if let Some(error) = error {
|
|
||||||
cx.push_message(MessageLevel::Error, error);
|
|
||||||
}
|
|
||||||
return HtmxResponse::new(content.render(&mut cx).await).into_response();
|
|
||||||
}
|
|
||||||
let mut page = Page::new(request).with_child(content);
|
|
||||||
if let Some(error) = error {
|
|
||||||
page.push_message(MessageLevel::Error, error);
|
|
||||||
}
|
|
||||||
page.render().await.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&JoinTheGarden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Escribe `ana` en el nombre de usuario y espera: aparece «Already taken». Cambia a `marta`:
|
|
||||||
«Available».
|
|
||||||
2. Envía el formulario con `ana`: el error aparece encima del formulario y lo escrito sigue ahí.
|
|
||||||
3. Corrige el nombre, escribe un correo y envía: el formulario se sustituye por la bienvenida.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Editar en línea](htmx-edit.md): el mismo intercambio de formulario y vista, sobre un dato
|
|
||||||
existente.
|
|
||||||
- [Dirigir al navegador desde el servidor](htmx-responses.md): cambiar el destino de la respuesta
|
|
||||||
según el resultado.
|
|
||||||
|
|
@ -1,136 +0,0 @@
|
||||||
# Maquetar con Flex y Grid
|
|
||||||
|
|
||||||
**Objetivo:** colocar componentes en filas, columnas o rejillas, y adaptarlos al tamaño de la
|
|
||||||
pantalla, sin escribir CSS.
|
|
||||||
|
|
||||||
Para colocar componentes en filas, columnas o rejillas no hace falta escribir CSS: `Flex` y `Grid`
|
|
||||||
generan las reglas por ti, y funcionan con cualquier tema.
|
|
||||||
|
|
||||||
## Flex: filas y columnas
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn item(t: &'static str) -> Html { Html::with(move |_| html! { div { (t) } }) }
|
|
||||||
# fn f() -> Flex {
|
|
||||||
Flex::new()
|
|
||||||
.with_justify(flex::ContentJustify::SpaceBetween)
|
|
||||||
.with_align(align::Items::Center)
|
|
||||||
.with_gap(align::Gap::Both(UnitValue::RelRem(1.0)))
|
|
||||||
.with_child(item("One"))
|
|
||||||
.with_child(item("Two"))
|
|
||||||
.with_child(item("Three"))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
| Método | Controla |
|
|
||||||
|---|---|
|
|
||||||
| `with_direction()` | `Row`, `RowReverse`, `Column` o `ColumnReverse` |
|
|
||||||
| `with_justify()` | Reparto en el eje principal: `Start`, `Center`, `End`, `SpaceBetween`... |
|
|
||||||
| `with_align()` | Alineación en el eje transversal: `Start`, `Center`, `End`, `Stretch`, `Baseline` |
|
|
||||||
| `with_wrap()` | Si los elementos saltan de línea |
|
|
||||||
| `with_gap()` | Separación entre elementos |
|
|
||||||
|
|
||||||
Cada hijo puede ajustarse por separado con `FlexItem`, que se pasa a su `with_prop()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Flex {
|
|
||||||
Flex::new()
|
|
||||||
.with_child(Block::new().with_title(Lc::n("Menu")))
|
|
||||||
.with_child(
|
|
||||||
Block::new()
|
|
||||||
.with_title(Lc::n("Content"))
|
|
||||||
.with_prop(FlexItem::new().with_grow(flex::ItemGrow::Is1)),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
Block::new()
|
|
||||||
.with_title(Lc::n("Help"))
|
|
||||||
.with_prop(FlexItem::push_end()),
|
|
||||||
)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`FlexItem::push_end()` empuja el elemento al final de la fila. Es la forma habitual de alinear a
|
|
||||||
la derecha el último grupo de un menú.
|
|
||||||
|
|
||||||
## Grid: rejillas
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn item(t: &'static str) -> Html { Html::with(move |_| html! { div { (t) } }) }
|
|
||||||
# fn f() -> Grid {
|
|
||||||
Grid::new()
|
|
||||||
.with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))
|
|
||||||
.with_gap(align::Gap::Both(UnitValue::RelRem(1.0)))
|
|
||||||
.with_child(item("A"))
|
|
||||||
.with_child(item("B"))
|
|
||||||
.with_child(item("C"))
|
|
||||||
.with_child(item("D"))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Tres columnas iguales (`1fr` cada una). Las pistas se combinan a voluntad:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Grid {
|
|
||||||
// A fixed 240 px column and another one that takes the rest.
|
|
||||||
Grid::new().with_columns(
|
|
||||||
grid::Tracks::new()
|
|
||||||
.with_track(grid::AxisTrack::Fixed(UnitValue::Px(240)))
|
|
||||||
.with_track(grid::AxisTrack::Fraction(1.0)),
|
|
||||||
)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Un hijo puede ocupar varias celdas con `GridItem`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Block {
|
|
||||||
Block::new()
|
|
||||||
.with_title(Lc::n("Featured"))
|
|
||||||
.with_prop(GridItem::new().with_column(grid::ItemPlacement::Span(2)))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Diseño *responsive*
|
|
||||||
|
|
||||||
Casi todos los métodos tienen una variante `_at()` que se aplica **a partir de** un punto de
|
|
||||||
corte (el diseño es *mobile-first*: lo que no lleva `_at()` vale para todos los tamaños):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Flex {
|
|
||||||
// A column on mobile; a row from medium screens on.
|
|
||||||
Flex::new()
|
|
||||||
.with_direction(flex::Direction::Column)
|
|
||||||
.with_direction_at(Breakpoint::Md, flex::Direction::Row)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Grid {
|
|
||||||
// One column on mobile, two on tablets and four on desktop.
|
|
||||||
Grid::new()
|
|
||||||
.with_columns(grid::Tracks::repeat(1, grid::AxisTrack::Fraction(1.0)))
|
|
||||||
.with_columns_at(Breakpoint::Md, grid::Tracks::repeat(2, grid::AxisTrack::Fraction(1.0)))
|
|
||||||
.with_columns_at(Breakpoint::Xl, grid::Tracks::repeat(4, grid::AxisTrack::Fraction(1.0)))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Los puntos de corte son `Xs`, `Sm`, `Md`, `Lg`, `Xl`, `Xxl` y `Xxxl`. Sus anchos los decide el
|
|
||||||
tema; por defecto son 576, 768, 992, 1200, 1400 y 1920 píxeles a partir de `Sm` (`Xs` no tiene
|
|
||||||
mínimo).
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Estrecha la ventana del navegador: los elementos cambian de disposición al cruzar cada punto de
|
|
||||||
corte. En las herramientas de desarrollo verás que cada `_at()` se ha convertido en una regla
|
|
||||||
`@media`.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Añadir navegación](navigation.md).
|
|
||||||
- [Crear un tema](themes.md): cómo un tema fija los anchos de los puntos de corte.
|
|
||||||
|
|
@ -1,150 +0,0 @@
|
||||||
# Traducir la aplicación
|
|
||||||
|
|
||||||
**Objetivo:** mostrar cada texto en el idioma del visitante, con plurales correctos, y formatear
|
|
||||||
fechas y horas según su idioma y su zona horaria.
|
|
||||||
|
|
||||||
PageTop traduce con [Fluent](https://projectfluent.org), el sistema de Mozilla: cada idioma tiene
|
|
||||||
sus archivos `.ftl` con pares `key = text`, y las traducciones se integran en el binario al
|
|
||||||
compilar.
|
|
||||||
|
|
||||||
## 1. Crea los archivos de traducción
|
|
||||||
|
|
||||||
Por defecto viven en `src/locale/`, en un directorio por idioma:
|
|
||||||
|
|
||||||
```text
|
|
||||||
src/locale/
|
|
||||||
├── en-US/
|
|
||||||
│ └── app.ftl
|
|
||||||
└── es-ES/
|
|
||||||
└── app.ftl
|
|
||||||
```
|
|
||||||
|
|
||||||
```text
|
|
||||||
# src/locale/es-ES/app.ftl
|
|
||||||
greeting = ¡Hola!
|
|
||||||
welcome = Te damos la bienvenida, { $name }.
|
|
||||||
notices = { $total ->
|
|
||||||
[one] Tienes un aviso
|
|
||||||
*[other] Tienes { $total } avisos
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```text
|
|
||||||
# src/locale/en-US/app.ftl
|
|
||||||
greeting = Hello!
|
|
||||||
welcome = Welcome, { $name }.
|
|
||||||
notices = { $total ->
|
|
||||||
[one] You have one notice
|
|
||||||
*[other] You have { $total } notices
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Fluent resuelve los plurales y las variantes de cada idioma en el propio archivo, sin lógica en el
|
|
||||||
código.
|
|
||||||
|
|
||||||
## 2. Úsalos en el código
|
|
||||||
|
|
||||||
Declara el conjunto de traducciones una vez con `include_locales!`:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
include_locales!(LOCALES_APP);
|
|
||||||
```
|
|
||||||
|
|
||||||
Y crea textos con `Lc`:
|
|
||||||
|
|
||||||
| Constructor | Qué representa |
|
|
||||||
|---|---|
|
|
||||||
| `Lc::t("key", &LOCALES_APP)` | Traducción de tus archivos |
|
|
||||||
| `Lc::l("key")` | Traducción de los archivos de PageTop |
|
|
||||||
| `Lc::n("text")` | Texto literal, sin traducir |
|
|
||||||
| `Lc::none()` | Ningún texto |
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
include_locales!(LOCALES_APP);
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::t("greeting", &LOCALES_APP))
|
|
||||||
.with_child(Html::with(|cx| {
|
|
||||||
let welcome = Lc::t("welcome", &LOCALES_APP).with_arg("name", "Ana");
|
|
||||||
let notices = Lc::t("notices", &LOCALES_APP).with_number("total", 3);
|
|
||||||
html! {
|
|
||||||
h1 { (welcome.using(cx)) }
|
|
||||||
p { (notices.using(cx)) }
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `with_arg()` rellena una variable; `with_number()` la rellena con un número, para que Fluent
|
|
||||||
elija el plural correcto.
|
|
||||||
- `using(cx)` devuelve el texto listo para insertarlo como **contenido** en `html!`.
|
|
||||||
- `lookup(cx)` devuelve `Option<String>`. Úsalo para los **atributos** (`title`, `alt`,
|
|
||||||
`placeholder`...), donde el texto se escapa como cualquier otro valor:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# include_locales!(LOCALES_APP);
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|cx| {
|
|
||||||
let title = Lc::t("greeting", &LOCALES_APP).lookup(cx);
|
|
||||||
html! { button title=[title] { "?" } }
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Los componentes reciben `Lc`, no cadenas: así cada visitante ve el texto en su idioma.
|
|
||||||
|
|
||||||
## 3. Decide qué idioma ve cada visitante
|
|
||||||
|
|
||||||
Por defecto, PageTop decide el idioma de cada petición en este orden:
|
|
||||||
|
|
||||||
1. El parámetro `?lang=` de la URL.
|
|
||||||
2. El idioma preferido del usuario, si ha iniciado sesión y lo tiene.
|
|
||||||
3. El idioma de la configuración (`[app] language`).
|
|
||||||
4. La cabecera `Accept-Language` del navegador.
|
|
||||||
5. El idioma de respaldo, `en-US`.
|
|
||||||
|
|
||||||
La clave `lang_negotiation` de `[app]` cambia la estrategia: `"NoQuery"` ignora `?lang=` y
|
|
||||||
`"ConfigOnly"` usa sólo el idioma configurado. Los enlaces internos conservan `?lang=` solos (ver
|
|
||||||
[Navegación](navigation.md#enlaces-que-conservan-el-idioma)).
|
|
||||||
|
|
||||||
PageTop trae sus propios textos en español (`es-ES`) e inglés (`en-US` y `en-GB`).
|
|
||||||
|
|
||||||
## 4. Formatea fechas y horas
|
|
||||||
|
|
||||||
El contexto formatea fechas con las convenciones del idioma y la zona horaria del visitante:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|cx| {
|
|
||||||
let date = NaiveDate::from_ymd_opt(2026, 10, 12).unwrap();
|
|
||||||
let now = Utc::now();
|
|
||||||
html! {
|
|
||||||
p { "Published on " (cx.format_date(date, DateFormat::Long)) }
|
|
||||||
p { "Updated: " (cx.format_datetime(now, DateFormat::Short, TimeFormat::Short)) }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Los formatos son `Short`, `Medium`, `Long`, `Iso` y `Custom("...")`. La zona horaria se configura
|
|
||||||
con `[app] timezone`.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Abre una página con `?lang=es` y con `?lang=en`: los textos cambian, y los plurales cambian con el
|
|
||||||
número. Si a un idioma le falta una clave, se usa la del idioma de respaldo, `en-US`; si no existe
|
|
||||||
en ninguno, el texto sale vacío. Una [prueba](testing.md) que busque los textos en cada idioma lo
|
|
||||||
detecta antes que los usuarios.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Añadir navegación](navigation.md#enlaces-que-conservan-el-idioma): enlaces que conservan el
|
|
||||||
idioma elegido.
|
|
||||||
- [Probar rutas y componentes](testing.md): comprobar las traducciones en una prueba.
|
|
||||||
|
|
@ -1,101 +0,0 @@
|
||||||
# Registrar trazas
|
|
||||||
|
|
||||||
**Objetivo:** dejar constancia de lo que pasa en la aplicación, con el nivel de detalle adecuado
|
|
||||||
en cada entorno, por el terminal o en archivos con rotación.
|
|
||||||
|
|
||||||
PageTop usa [tracing](https://docs.rs/tracing), y lo expone en el módulo `trace` del preludio.
|
|
||||||
|
|
||||||
## 1. Escribe trazas
|
|
||||||
|
|
||||||
Hay una macro por nivel, de más a menos grave: `error!`, `warn!`, `info!`, `debug!` y `trace!`.
|
|
||||||
Admiten el formato de `format!`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f(order: u32, error: &str) {
|
|
||||||
trace::info!("Order {order} received");
|
|
||||||
trace::warn!("Low stock for order {order}");
|
|
||||||
trace::error!("Could not charge order {order}: {error}");
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y también **campos** con nombre, que en formato JSON salen como claves propias y se pueden filtrar
|
|
||||||
y buscar:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f(order: u32, total: f64) {
|
|
||||||
trace::info!(order, total, "Order received");
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Agrupa las trazas de una operación
|
|
||||||
|
|
||||||
Un *span* (intervalo) agrupa todo lo que ocurre durante una operación. Las trazas emitidas dentro
|
|
||||||
llevan sus campos, aunque vengan de otras funciones:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn charge() {}
|
|
||||||
# fn send_receipt() {}
|
|
||||||
# fn f(order: u32) {
|
|
||||||
let span = trace::info_span!("checkout", order);
|
|
||||||
let _entered = span.enter();
|
|
||||||
trace::info!("Charging"); // checkout{order=42}: Charging
|
|
||||||
charge();
|
|
||||||
send_receipt();
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
No mantengas un `span.enter()` abierto a través de un `.await`: en código asíncrono, la tarea
|
|
||||||
puede continuar en otro hilo.
|
|
||||||
|
|
||||||
## 3. Elige qué se registra
|
|
||||||
|
|
||||||
La sección `[log]` decide el nivel, la salida y el formato:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[log]
|
|
||||||
tracing = "Info,sqlx=Warn" # General level and levels per module.
|
|
||||||
rolling = "Daily" # Stdout, Daily, Hourly, Minutely or Endless.
|
|
||||||
path = "log" # Directory of the trace files.
|
|
||||||
format = "Json" # Full, Compact, Pretty or Json.
|
|
||||||
```
|
|
||||||
|
|
||||||
- **`tracing`** fija el nivel general y, separados por comas, niveles por módulo. `"Info,sqlx=Warn"`
|
|
||||||
registra todo desde `info`, salvo las sentencias SQL, que sólo aparecen si fallan.
|
|
||||||
- **`rolling`**: con `"Stdout"` (por defecto) las trazas salen por el terminal; con `"Daily"`,
|
|
||||||
`"Hourly"` o `"Minutely"` se escriben en archivos que rotan con esa frecuencia, y con
|
|
||||||
`"Endless"` en un único archivo.
|
|
||||||
- **`format`**: `"Full"` para leer en el terminal, `"Json"` para que lo procese otra herramienta.
|
|
||||||
|
|
||||||
Un filtro mal escrito no detiene la aplicación: se usa `"Info"` y se avisa al arrancar.
|
|
||||||
|
|
||||||
## 4. Un nivel por entorno
|
|
||||||
|
|
||||||
Con la [cascada de configuración](configuration.md), cada entorno tiene su nivel sin tocar el
|
|
||||||
código:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/common.toml
|
|
||||||
[log]
|
|
||||||
tracing = "Info,sqlx=Warn"
|
|
||||||
```
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/local.toml (your machine only, not versioned)
|
|
||||||
[log]
|
|
||||||
tracing = "Debug,pagetop=Info"
|
|
||||||
format = "Pretty"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Arranca con `rolling = "Daily"`: aparece el directorio `log/` con un archivo `tracing.log.<fecha>`.
|
|
||||||
Las trazas se escriben en segundo plano, sin frenar las peticiones, y PageTop vuelca las pendientes
|
|
||||||
al detenerse con `Ctrl+C` o `SIGTERM`.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Desplegar en producción](deployment.md).
|
|
||||||
- [Opciones de configuración](../reference/configuration.md#log): todas las claves de `[log]`.
|
|
||||||
|
|
@ -1,591 +0,0 @@
|
||||||
# Enviar correo electrónico
|
|
||||||
|
|
||||||
**Objetivo:** enviar correos desde la aplicación, en texto y HTML, con adjuntos, traducidos al
|
|
||||||
idioma de cada destinatario y con el mismo aspecto que los de las demás extensiones, sin enviar
|
|
||||||
nunca correo real por error mientras desarrollas.
|
|
||||||
|
|
||||||
Lo aporta la extensión `pagetop-mail`. La configuración decide **cómo** se entregan los correos
|
|
||||||
(servidor SMTP, *sendmail*, archivos, trazas o memoria), así que el código que los envía es el
|
|
||||||
mismo en desarrollo, en las pruebas y en producción.
|
|
||||||
|
|
||||||
## 1. Añade la dependencia
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop-mail = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y declara `pagetop_mail::Mail` en `dependencies()` de la extensión que envía correos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_mail::Mail]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Configura el envío
|
|
||||||
|
|
||||||
Sin configurar nada, los correos **no se envían**: se escriben en las trazas, con el remitente, los
|
|
||||||
destinatarios, el asunto y el texto. Es lo que quieres mientras desarrollas. Para enviarlos de
|
|
||||||
verdad, configura la sección `[mail]` con el transporte, el remitente y la URL pública de la
|
|
||||||
aplicación, que forma los enlaces de los correos (ver el paso 5):
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/production.toml
|
|
||||||
[mail]
|
|
||||||
transport = "smtp"
|
|
||||||
from = "Community garden <no-reply@example.com>"
|
|
||||||
base_url = "https://garden.example.com"
|
|
||||||
|
|
||||||
[mail.smtp]
|
|
||||||
host = "smtp.example.com"
|
|
||||||
username = "no-reply@example.com"
|
|
||||||
```
|
|
||||||
|
|
||||||
La contraseña no va en un archivo versionado: ponla en `config/local.toml` o en la variable de
|
|
||||||
entorno `PAGETOP_MAIL__SMTP__PASSWORD`. Por defecto la conexión exige `STARTTLS` en el puerto 587;
|
|
||||||
`security = "tls"` usa el 465.
|
|
||||||
|
|
||||||
Para ver los correos tal como llegan sin enviarlos a nadie, usa en desarrollo un servidor como
|
|
||||||
[Mailpit](https://mailpit.axllent.org), que los recoge y los muestra en el navegador:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/local.toml
|
|
||||||
[mail]
|
|
||||||
transport = "smtp"
|
|
||||||
|
|
||||||
[mail.smtp]
|
|
||||||
host = "localhost"
|
|
||||||
port = 1025
|
|
||||||
security = "none"
|
|
||||||
```
|
|
||||||
|
|
||||||
Con `transport = "file"`, cada correo se guarda como un archivo `.eml` en el directorio `mail/`,
|
|
||||||
que abre cualquier cliente de correo. Y en un entorno de pruebas con datos reales,
|
|
||||||
`redirect_to = "qa@example.com"` entrega todos los correos sólo a esa dirección. Los ajustes no
|
|
||||||
válidos detienen el arranque con un mensaje que indica el problema.
|
|
||||||
|
|
||||||
## 3. Envía un correo
|
|
||||||
|
|
||||||
Un correo se compone con `Email`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_mail::prelude::*;
|
|
||||||
|
|
||||||
async fn confirm_plot(address: String) -> Result<(), MailError> {
|
|
||||||
Email::new()
|
|
||||||
.with_to(address)
|
|
||||||
.with_subject("Your plot is booked")
|
|
||||||
.with_html(html! {
|
|
||||||
p { "Your plot " strong { "B-12" } " is booked for the whole season." }
|
|
||||||
})
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Las direcciones admiten la forma `"Ana Pérez <ana@example.com>"`, y `with_cc()`, `with_bcc()` y
|
|
||||||
`with_reply_to()` completan los destinatarios; el remitente es el de `mail.from` salvo que indiques
|
|
||||||
otro con `with_from()`. Si el correo sólo tiene HTML, al enviarlo se genera su versión en texto
|
|
||||||
plano; escríbela tú con `with_text()` sólo si la generada no queda bien.
|
|
||||||
|
|
||||||
Hay dos formas de enviarlo:
|
|
||||||
|
|
||||||
- **`send().await`** espera a que el correo se entregue y devuelve el error si falla. Úsalo cuando
|
|
||||||
necesitas saberlo para responder.
|
|
||||||
- **`send_later()`** lo entrega en segundo plano y vuelve enseguida; si falla, lo registra en las
|
|
||||||
trazas. Es lo indicado en una petición del usuario: la respuesta no espera al servidor de
|
|
||||||
correo, y su tiempo no revela nada (por ejemplo, si existe la cuenta para la que se pide
|
|
||||||
recuperar la contraseña).
|
|
||||||
|
|
||||||
## 4. Escribe una plantilla traducida
|
|
||||||
|
|
||||||
Para que el mismo correo llegue a cada destinatario en su idioma, defínelo como un tipo que
|
|
||||||
implementa `MailTemplate`. Sus métodos reciben un `Context` con el idioma del destinatario, y los
|
|
||||||
textos se escriben con `Lc`, igual que en un componente:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
include_locales!(LOCALES_APP);
|
|
||||||
|
|
||||||
struct HarvestNotice {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MailTemplate for HarvestNotice {
|
|
||||||
fn subject(&self, cx: &Context) -> String {
|
|
||||||
Lc::t("harvest-subject", &LOCALES_APP).lookup(cx).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn html(&self, cx: &Context) -> Option<Markup> {
|
|
||||||
let greeting = Lc::t("harvest-greeting", &LOCALES_APP).with_arg("name", self.name.clone());
|
|
||||||
Some(html! {
|
|
||||||
p { (greeting.using(cx)) }
|
|
||||||
p { (Lc::t("harvest-ready", &LOCALES_APP).using(cx)) }
|
|
||||||
p {
|
|
||||||
a href=(absolute_url("/harvest")) {
|
|
||||||
(Lc::t("harvest-link", &LOCALES_APP).using(cx))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Con sus traducciones en `src/locale/en-US/app.ftl`:
|
|
||||||
|
|
||||||
```ftl
|
|
||||||
harvest-subject = The tomatoes are ready to pick
|
|
||||||
harvest-greeting = Hello, { $name }:
|
|
||||||
harvest-ready = The tomatoes in the community garden are ripe. Come and pick your share this week.
|
|
||||||
harvest-link = See the harvest calendar
|
|
||||||
```
|
|
||||||
|
|
||||||
`Email::from_template()` crea el correo con el asunto y el contenido de la plantilla. El contexto
|
|
||||||
decide el idioma. Si el destinatario es quien hace la petición (por ejemplo, al apuntarse a un
|
|
||||||
aviso), usa el de la petición. Si es otra persona, crea uno con su idioma, guardado junto a su
|
|
||||||
dirección; si no es un idioma disponible, el correo sale en el idioma por defecto de la aplicación:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
# struct HarvestNotice { name: String }
|
|
||||||
# impl MailTemplate for HarvestNotice {
|
|
||||||
# fn subject(&self, _cx: &Context) -> String { String::new() }
|
|
||||||
# }
|
|
||||||
async fn notify_gardener(name: String, email: String, language: String) -> Result<(), MailError> {
|
|
||||||
let cx = Context::default().with_langid(&Locale::resolve(language));
|
|
||||||
Email::from_template(&HarvestNotice { name }, &cx)
|
|
||||||
.with_to(email)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Usa enlaces absolutos
|
|
||||||
|
|
||||||
Un enlace de un correo se abre fuera de la aplicación, así que debe ser absoluto. `absolute_url()`
|
|
||||||
antepone a la ruta la URL pública de `mail.base_url`, como en la plantilla anterior. Si no la
|
|
||||||
configuras, usa la dirección y el puerto de escucha (`http://localhost:8080`), que sólo sirve en
|
|
||||||
desarrollo.
|
|
||||||
|
|
||||||
La URL no se deduce de la petición: la cabecera `Host` la elige el cliente, y un atacante podría
|
|
||||||
conseguir que el enlace de un correo de recuperación de contraseña apuntara a su propio servidor.
|
|
||||||
|
|
||||||
## 6. Adjunta archivos
|
|
||||||
|
|
||||||
`Attachment` crea un adjunto con un contenido en memoria o leyendo un archivo, y deduce su tipo del
|
|
||||||
nombre. Con `with_content_id()` el adjunto se incrusta en el HTML, que lo muestra con `cid:`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
async fn send_report(address: String, logo_png: Vec<u8>) -> Result<(), MailError> {
|
|
||||||
Email::new()
|
|
||||||
.with_to(address)
|
|
||||||
.with_subject("October harvest report")
|
|
||||||
.with_html(html! {
|
|
||||||
img src="cid:logo" alt="Community garden";
|
|
||||||
p { "The report of the month is attached." }
|
|
||||||
})
|
|
||||||
.with_attachment(Attachment::new("logo.png", logo_png).with_content_id("logo"))
|
|
||||||
.with_attachment(Attachment::from_path("reports/october.pdf").await?)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 7. Dale tu imagen a los correos
|
|
||||||
|
|
||||||
El HTML de un correo es sólo su contenido: al enviarlo se envuelve en un diseño común, sobrio y
|
|
||||||
neutro, con el nombre de la aplicación al pie. Para dar tu propia imagen a **todos** los correos,
|
|
||||||
también a los que envían otras extensiones como `pagetop-user`, registra la acción
|
|
||||||
`RenderMailLayout`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
fn garden_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
|
|
||||||
html! {
|
|
||||||
(DOCTYPE)
|
|
||||||
html lang=(cx.langid().to_string()) {
|
|
||||||
head {
|
|
||||||
meta charset="utf-8";
|
|
||||||
title { (email.subject()) }
|
|
||||||
}
|
|
||||||
body style="margin: 0; padding: 24px; background: #f0f5ec; font-family: sans-serif;" {
|
|
||||||
div style="max-width: 600px; margin: 0 auto; padding: 24px; background: #fff;" {
|
|
||||||
(content)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_mail::Mail]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![RenderMailLayout::new(garden_layout)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si varias extensiones registran esta acción, se aplica sólo la de menor peso
|
|
||||||
(`RenderMailLayout::new(..).with_weight(..)`). Los clientes de correo ignoran las hojas de estilo
|
|
||||||
externas, y muchos también los estilos del `<head>`: escribe los estilos en línea, con `style`. Un
|
|
||||||
correo concreto puede saltarse el diseño con `with_html_document()`, que envía el documento tal
|
|
||||||
cual.
|
|
||||||
|
|
||||||
## 8. Revisa los correos en el navegador
|
|
||||||
|
|
||||||
Para ver cómo queda un correo sin enviarlo, declara una vista previa con datos de ejemplo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
# struct HarvestNotice { name: String }
|
|
||||||
# impl MailTemplate for HarvestNotice {
|
|
||||||
# fn subject(&self, _cx: &Context) -> String { String::new() }
|
|
||||||
# }
|
|
||||||
fn harvest_preview(cx: &Context) -> Email {
|
|
||||||
let notice = HarvestNotice { name: "Ana".to_string() };
|
|
||||||
Email::from_template(¬ice, cx).with_to("ana@example.com")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_previews(previews: &mut MailPreviews) {
|
|
||||||
previews.add("garden.harvest", Lc::n("Harvest notice"), harvest_preview);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_mail::Mail]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![DeclareMailPreviews::new(declare_previews)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Activa las vistas previas sólo en desarrollo, porque muestran las plantillas a quien conozca la
|
|
||||||
ruta:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/local.toml
|
|
||||||
[mail]
|
|
||||||
previews = true
|
|
||||||
```
|
|
||||||
|
|
||||||
`/mail/preview` lista los correos declarados por todas las extensiones, y cada uno se muestra
|
|
||||||
completo, con el diseño común, las cabeceras, el texto plano y los adjuntos. Añade `?lang=es` para
|
|
||||||
verlo en otro idioma.
|
|
||||||
|
|
||||||
## 9. Guarda los correos en una cola
|
|
||||||
|
|
||||||
Sin más, un correo de `send_later()` se pierde si la aplicación se detiene antes de entregarlo, y
|
|
||||||
no se reintenta si el servidor falla. Con la *feature* `queue`, los correos se guardan en la base
|
|
||||||
de datos de `pagetop-seaorm` y se reintentan:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop-mail = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["queue"] }
|
|
||||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
La cola crea su tabla al arrancar, en la base de datos de `[database]`. Con ella:
|
|
||||||
|
|
||||||
- **`send_later()`** guarda el correo y lo intenta enseguida (salvo con `transport = "log"`, que
|
|
||||||
lo escribe directamente en las trazas). Si el fallo es temporal, queda en la cola y se reintenta
|
|
||||||
más tarde, también después de un reinicio, con una espera que se duplica en cada intento. Un
|
|
||||||
rechazo definitivo del servidor o el último intento lo dejan como fallido.
|
|
||||||
- **`queue()`** sólo lo guarda: el trabajo `mail.queue` de `pagetop-cron` envía los pendientes por
|
|
||||||
lotes, uno tras otro. Es lo indicado para los envíos masivos, que así no saturan el equipo ni el
|
|
||||||
servidor de correo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
async fn announce_closure(addresses: Vec<String>) -> Result<(), MailError> {
|
|
||||||
for address in addresses {
|
|
||||||
Email::new()
|
|
||||||
.with_to(address)
|
|
||||||
.with_subject("The garden closes on Saturday")
|
|
||||||
.with_text("The garden will be closed on Saturday for the water works.")
|
|
||||||
.queue()
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El tamaño de los lotes y los reintentos se ajustan en
|
|
||||||
[`[mail.queue]`](../reference/configuration.md#mailqueue), y el ritmo en la programación del
|
|
||||||
trabajo:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[cron.jobs."mail.queue"]
|
|
||||||
schedule = "@delay 30s" # 30 s after each batch ends (1 minute by default).
|
|
||||||
```
|
|
||||||
|
|
||||||
La cola guarda los mensajes completos y sin cifrar hasta entregarlos: pueden contener datos
|
|
||||||
personales y enlaces de un solo uso, también en las copias de seguridad de la base de datos.
|
|
||||||
|
|
||||||
## 10. Comprueba el envío desde el panel
|
|
||||||
|
|
||||||
Para saber si la configuración funciona en producción no hace falta escribir nada: `pagetop-mail`
|
|
||||||
añade al [panel de administración](admin.md) la página **Configuración > Correo electrónico**
|
|
||||||
(`/admin/config/mail`). Muestra el transporte, el remitente y el servidor configurados (nunca las
|
|
||||||
credenciales) y envía un correo de prueba a la dirección que escribas. Espera al resultado, así que
|
|
||||||
al volver a la página ves si se ha enviado o el error del servidor. Con `redirect_to`, el correo
|
|
||||||
llega a esa dirección, como todos.
|
|
||||||
|
|
||||||
La página exige el permiso `mail:send_test`, que aparece en la pantalla de roles de
|
|
||||||
[`pagetop-user`](users.md) en el grupo «Correo electrónico». Los administradores lo tienen sin
|
|
||||||
asignarlo.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
Un formulario en `/harvest` donde cada visitante pide el aviso de la cosecha, que recibe por
|
|
||||||
correo en su idioma:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_mail::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
include_locales!(LOCALES_APP);
|
|
||||||
|
|
||||||
struct HarvestNotice {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MailTemplate for HarvestNotice {
|
|
||||||
fn subject(&self, cx: &Context) -> String {
|
|
||||||
Lc::t("harvest-subject", &LOCALES_APP).lookup(cx).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn html(&self, cx: &Context) -> Option<Markup> {
|
|
||||||
let greeting = Lc::t("harvest-greeting", &LOCALES_APP).with_arg("name", self.name.clone());
|
|
||||||
Some(html! {
|
|
||||||
p { (greeting.using(cx)) }
|
|
||||||
p { (Lc::t("harvest-ready", &LOCALES_APP).using(cx)) }
|
|
||||||
p {
|
|
||||||
a href=(absolute_url("/harvest")) {
|
|
||||||
(Lc::t("harvest-link", &LOCALES_APP).using(cx))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn harvest_preview(cx: &Context) -> Email {
|
|
||||||
let notice = HarvestNotice { name: "Ana".to_string() };
|
|
||||||
Email::from_template(¬ice, cx).with_to("ana@example.com")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_previews(previews: &mut MailPreviews) {
|
|
||||||
previews.add("garden.harvest", Lc::n("Harvest notice"), harvest_preview);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_mail::Mail]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![DeclareMailPreviews::new(declare_previews)]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/harvest", web::get(show).post(notify))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Gardener {
|
|
||||||
name: String,
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn notice_form() -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/harvest")
|
|
||||||
.with_method(form::Method::Post)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("name")
|
|
||||||
.with_label(Lc::n("Name"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::email()
|
|
||||||
.with_name("email")
|
|
||||||
.with_label(Lc::n("Email"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Send me the notice")))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn show(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Harvest"))
|
|
||||||
.with_child(notice_form())
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn notify(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Form(gardener): web::Form<Gardener>,
|
|
||||||
) -> Result<Response, ErrorPage> {
|
|
||||||
// The notice goes in the language of the visitor who asks for it.
|
|
||||||
let cx = Context::new(request.clone());
|
|
||||||
let notice = HarvestNotice { name: gardener.name };
|
|
||||||
let sent = Email::from_template(¬ice, &cx)
|
|
||||||
.with_to(gardener.email)
|
|
||||||
.send()
|
|
||||||
.await;
|
|
||||||
if let Err(err) = sent {
|
|
||||||
trace::warn!("Harvest notice not sent: {err}");
|
|
||||||
let mut page = Page::new(request)
|
|
||||||
.with_title(Lc::n("Harvest"))
|
|
||||||
.with_child(notice_form());
|
|
||||||
page.push_message(
|
|
||||||
MessageLevel::Error,
|
|
||||||
Lc::n("The notice could not be sent. Check the address and try again."),
|
|
||||||
);
|
|
||||||
return page.render().await.map(IntoResponse::into_response);
|
|
||||||
}
|
|
||||||
Ok(Redirect::see_other(cx.route("/harvest")).with_message(
|
|
||||||
&cx,
|
|
||||||
MessageLevel::Info,
|
|
||||||
Lc::n("We have sent you the notice. Check your inbox."),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El ejemplo usa `send().await` para avisar en el formulario si la dirección no es válida o el
|
|
||||||
servidor la rechaza. Si prefieres no hacer esperar al visitante, cambia `send().await` por
|
|
||||||
`send_later()` y avisa siempre del envío: los fallos quedarán en las trazas.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Arranca con `cargo run`, abre <http://localhost:8080/harvest> y envía el formulario: la página
|
|
||||||
confirma el envío y el terminal muestra el correo, porque sin configurar `[mail]` se escribe en las
|
|
||||||
trazas. Con `previews = true` en `config/local.toml`, <http://localhost:8080/mail/preview> lo
|
|
||||||
muestra con su diseño.
|
|
||||||
|
|
||||||
En las pruebas, el transporte `memory` guarda los correos en lugar de enviarlos, y
|
|
||||||
`pagetop_mail::outbox` los recoge. Configúralo en `config/test.toml` (ve [Usa otra configuración
|
|
||||||
para las pruebas](testing.md#5-usa-otra-configuración-para-las-pruebas)):
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/test.toml
|
|
||||||
[mail]
|
|
||||||
transport = "memory"
|
|
||||||
from = "Community garden <garden@example.com>"
|
|
||||||
base_url = "https://garden.example.com"
|
|
||||||
```
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_mail::prelude::*;
|
|
||||||
# use serde::Deserialize;
|
|
||||||
# include_locales!(LOCALES_APP);
|
|
||||||
# struct HarvestNotice { name: String }
|
|
||||||
# impl MailTemplate for HarvestNotice {
|
|
||||||
# fn subject(&self, cx: &Context) -> String {
|
|
||||||
# Lc::t("harvest-subject", &LOCALES_APP).lookup(cx).unwrap_or_default()
|
|
||||||
# }
|
|
||||||
# fn html(&self, cx: &Context) -> Option<Markup> {
|
|
||||||
# let greeting = Lc::t("harvest-greeting", &LOCALES_APP).with_arg("name", self.name.clone());
|
|
||||||
# let link = Lc::t("harvest-link", &LOCALES_APP);
|
|
||||||
# Some(html! {
|
|
||||||
# p { (greeting.using(cx)) }
|
|
||||||
# p { a href=(absolute_url("/harvest")) { (link.using(cx)) } }
|
|
||||||
# })
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
# vec![&pagetop_mail::Mail]
|
|
||||||
# }
|
|
||||||
# fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
# routes.public_route("/harvest", web::post(notify))
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[derive(Deserialize)]
|
|
||||||
# struct Gardener { name: String, email: String }
|
|
||||||
# async fn notify(
|
|
||||||
# request: HttpRequest,
|
|
||||||
# web::Form(gardener): web::Form<Gardener>,
|
|
||||||
# ) -> Result<Response, ErrorPage> {
|
|
||||||
# let cx = Context::new(request.clone());
|
|
||||||
# Email::from_template(&HarvestNotice { name: gardener.name }, &cx)
|
|
||||||
# .with_to(gardener.email)
|
|
||||||
# .send()
|
|
||||||
# .await
|
|
||||||
# .map_err(|_| ErrorPage::InternalError(Some(request)))?;
|
|
||||||
# Ok(Redirect::see_other(cx.route("/harvest")))
|
|
||||||
# }
|
|
||||||
use pagetop_mail::outbox;
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn sends_the_harvest_notice() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::post()
|
|
||||||
.uri("/harvest")
|
|
||||||
.form("name=Ana&email=ana%40example.com")
|
|
||||||
.to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER);
|
|
||||||
|
|
||||||
let sent = outbox::take_to("ana@example.com");
|
|
||||||
assert_eq!(sent.len(), 1);
|
|
||||||
assert_eq!(sent[0].email().subject(), "The tomatoes are ready to pick");
|
|
||||||
assert!(sent[0].links().contains(&"https://garden.example.com/harvest".to_string()));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`take_to()` recoge sólo los correos de esa dirección, así que las pruebas que se ejecutan en
|
|
||||||
paralelo no se roban los correos. `links()` devuelve las direcciones de los enlaces del HTML, para
|
|
||||||
seguir en la prueba, por ejemplo, un enlace de un solo uso.
|
|
||||||
|
|
||||||
Si el correo sale con `send_later()`, llega a `outbox` en segundo plano, poco después de la
|
|
||||||
respuesta. Con la *feature* `queue`, los de `queue()` sólo llegan cuando se ejecuta el trabajo, que
|
|
||||||
en las pruebas se lanza con `pagetop_cron::run_now("mail.queue")`.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Opciones de configuración](../reference/configuration.md#mail): todas las claves de `[mail]`.
|
|
||||||
- [Programar tareas periódicas](cron.md): el planificador que vacía la cola.
|
|
||||||
- [Añadir usuarios y permisos](users.md): `pagetop-user` envía con esta extensión sus correos de
|
|
||||||
recuperación de contraseña y de verificación.
|
|
||||||
|
|
@ -1,269 +0,0 @@
|
||||||
# Añadir *middleware*
|
|
||||||
|
|
||||||
**Objetivo:** aplicar a todas las peticiones lo que no es asunto de ningún *handler* concreto:
|
|
||||||
medir lo que tarda cada una, comprimir las respuestas, limitar el tamaño de lo que se envía, cortar
|
|
||||||
las que se eternizan o abrir una API a otros dominios con CORS.
|
|
||||||
|
|
||||||
Un *middleware* es una **capa** que envuelve las rutas: recibe la petición antes que el *handler*
|
|
||||||
y la respuesta después. PageTop usa las capas de Axum y de [Tower](https://docs.rs/tower), así que
|
|
||||||
tienes a mano todo su ecosistema. Cada extensión añade las suyas en `configure_middleware()`, y se
|
|
||||||
aplican a las rutas de **todas** las extensiones.
|
|
||||||
|
|
||||||
## 1. Escribe una capa propia
|
|
||||||
|
|
||||||
`web::middleware::from_fn()` convierte una función `async` en una capa. La función recibe la
|
|
||||||
petición y `next`, que ejecuta el resto de la cadena y devuelve la respuesta:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
async fn timing(request: web::Request, next: web::middleware::Next) -> Response {
|
|
||||||
let path = request.uri().path().to_owned();
|
|
||||||
let start = Instant::now();
|
|
||||||
|
|
||||||
let response = next.run(request).await;
|
|
||||||
|
|
||||||
trace::info!(
|
|
||||||
%path,
|
|
||||||
status = response.status().as_u16(),
|
|
||||||
elapsed_ms = start.elapsed().as_millis() as u64,
|
|
||||||
"Request served"
|
|
||||||
);
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
|
||||||
layers.layer(web::middleware::from_fn(timing))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Lo que va antes de `next.run()` ocurre a la ida (aquí, anotar la hora); lo que va después, a la
|
|
||||||
vuelta, con la respuesta ya hecha. Una capa también puede responder ella misma sin llamar a `next`,
|
|
||||||
por ejemplo para cerrar el sitio por mantenimiento.
|
|
||||||
|
|
||||||
## 2. Reutiliza las capas de `tower-http`
|
|
||||||
|
|
||||||
Para lo habitual no hace falta escribir nada: [`tower-http`](https://docs.rs/tower-http) trae las
|
|
||||||
capas hechas. Añádelo con las *features* de las que vayas a usar (es la misma versión que usa
|
|
||||||
PageTop):
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
tower-http = { version = "0.7", features = ["compression-gzip", "cors", "limit", "timeout"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
Y apílalas en `configure_middleware()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use tower_http::compression::CompressionLayer;
|
|
||||||
use tower_http::limit::RequestBodyLimitLayer;
|
|
||||||
use tower_http::timeout::TimeoutLayer;
|
|
||||||
|
|
||||||
# pub struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
|
||||||
layers
|
|
||||||
// Requests with a body over 1 MiB get a 413 Payload Too Large.
|
|
||||||
.layer(RequestBodyLimitLayer::new(1024 * 1024))
|
|
||||||
// Requests that take more than 30 seconds get a 408 Request Timeout.
|
|
||||||
.layer(TimeoutLayer::with_status_code(
|
|
||||||
web::http::StatusCode::REQUEST_TIMEOUT,
|
|
||||||
Duration::from_secs(30),
|
|
||||||
))
|
|
||||||
// Responses go compressed with gzip to the browsers that accept it.
|
|
||||||
.layer(CompressionLayer::new())
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
| Capa | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `CompressionLayer` | Comprime las respuestas si el navegador lo admite (*feature* `compression-gzip`, o `compression-full` para todos los formatos) |
|
|
||||||
| `RequestBodyLimitLayer` | Rechaza los cuerpos demasiado grandes (*feature* `limit`) |
|
|
||||||
| `TimeoutLayer` | Corta las peticiones que tardan demasiado (*feature* `timeout`) |
|
|
||||||
| `CorsLayer` | Permite llamadas desde otros dominios (*feature* `cors`) |
|
|
||||||
| `SetResponseHeaderLayer` | Añade una cabecera a todas las respuestas (*feature* `set-header`) |
|
|
||||||
|
|
||||||
## 3. Ten en cuenta el orden
|
|
||||||
|
|
||||||
Cada `.layer()` envuelve todo lo anterior, así que **la última capa añadida es la más externa**: la
|
|
||||||
primera que ve la petición y la última que toca la respuesta. En el ejemplo, la compresión envuelve
|
|
||||||
a las demás y comprime también el 408 del tiempo máximo, y el límite de tamaño, el más interno,
|
|
||||||
actúa justo antes del *handler*.
|
|
||||||
|
|
||||||
Lo mismo vale entre extensiones: las capas de cada una envuelven las de las extensiones que se
|
|
||||||
inicializaron antes.
|
|
||||||
|
|
||||||
## 4. Aplica una capa sólo a tus rutas
|
|
||||||
|
|
||||||
`configure_middleware()` afecta a todo. Para que una capa sólo envuelva unas rutas, crea con ellas
|
|
||||||
un `Router` propio en `configure_router()`, ponle la capa y anídalo bajo su prefijo con `nest()`,
|
|
||||||
con el acceso que compartan sus rutas. Es lo natural para CORS, que sólo debe abrirse en la API:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use serde::Serialize;
|
|
||||||
use tower_http::cors::CorsLayer;
|
|
||||||
|
|
||||||
# #[derive(Serialize)]
|
|
||||||
# struct Plot { code: &'static str }
|
|
||||||
# async fn home() -> &'static str { "" }
|
|
||||||
# async fn plots() -> Json<Vec<Plot>> { Json(vec![]) }
|
|
||||||
# pub struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
let cors = CorsLayer::new()
|
|
||||||
.allow_origin(web::http::HeaderValue::from_static("https://garden.example.org"))
|
|
||||||
.allow_methods([web::http::Method::GET]);
|
|
||||||
|
|
||||||
let api = Router::new()
|
|
||||||
.route("/plots", web::get(plots))
|
|
||||||
.layer(cors);
|
|
||||||
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.nest("/api", Access::Public, api)
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Lo que no pasa por el *middleware*
|
|
||||||
|
|
||||||
Los **archivos estáticos** que publicas con `configure_static_files()` se sirven por fuera de las
|
|
||||||
capas: no se comprimen ni se miden. Es deliberado, para que servir un estilo o una imagen sea lo más
|
|
||||||
barato posible. Si quieres comprimirlos, hazlo en el *proxy* que tengas delante (ve [Desplegar en
|
|
||||||
producción](deployment.md)).
|
|
||||||
|
|
||||||
Las **páginas de error** se pintan después, por fuera de todas las capas. Las capas sí ven la
|
|
||||||
respuesta de error (la miden, le añaden cabeceras, que se conservan), pero la página que llega al
|
|
||||||
navegador no sale comprimida. Tampoco la página mínima de un `panic!`, que PageTop atrapa en la
|
|
||||||
capa más externa de todas.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Serialize;
|
|
||||||
use tower_http::compression::CompressionLayer;
|
|
||||||
use tower_http::cors::CorsLayer;
|
|
||||||
use tower_http::limit::RequestBodyLimitLayer;
|
|
||||||
use tower_http::timeout::TimeoutLayer;
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
struct Plot {
|
|
||||||
code: &'static str,
|
|
||||||
holder: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
|
||||||
layers
|
|
||||||
.layer(web::middleware::from_fn(timing))
|
|
||||||
.layer(RequestBodyLimitLayer::new(1024 * 1024))
|
|
||||||
.layer(TimeoutLayer::with_status_code(
|
|
||||||
web::http::StatusCode::REQUEST_TIMEOUT,
|
|
||||||
Duration::from_secs(30),
|
|
||||||
))
|
|
||||||
.layer(CompressionLayer::new())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
let cors = CorsLayer::new()
|
|
||||||
.allow_origin(web::http::HeaderValue::from_static("https://garden.example.org"))
|
|
||||||
.allow_methods([web::http::Method::GET]);
|
|
||||||
|
|
||||||
let api = Router::new()
|
|
||||||
.route("/plots", web::get(plots))
|
|
||||||
.layer(cors);
|
|
||||||
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/notes", web::post(notes))
|
|
||||||
.nest("/api", Access::Public, api)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn timing(request: web::Request, next: web::middleware::Next) -> Response {
|
|
||||||
let path = request.uri().path().to_owned();
|
|
||||||
let start = Instant::now();
|
|
||||||
|
|
||||||
let response = next.run(request).await;
|
|
||||||
|
|
||||||
trace::info!(
|
|
||||||
%path,
|
|
||||||
status = response.status().as_u16(),
|
|
||||||
elapsed_ms = start.elapsed().as_millis() as u64,
|
|
||||||
"Request served"
|
|
||||||
);
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Community garden"))
|
|
||||||
.with_child(Html::with(|_| html! {
|
|
||||||
@for i in 1..=50 {
|
|
||||||
p { "Plot " (i) ": tomatoes, lettuces and courgettes." }
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn notes(body: String) -> String {
|
|
||||||
format!("Received {} bytes", body.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn plots() -> Json<Vec<Plot>> {
|
|
||||||
Json(vec![
|
|
||||||
Plot { code: "a1", holder: "Ana" },
|
|
||||||
Plot { code: "b2", holder: "Luke" },
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
```sh
|
|
||||||
# Compressed: the answer includes content-encoding: gzip.
|
|
||||||
curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' http://localhost:8080/ | grep -i encoding
|
|
||||||
|
|
||||||
# Too big: 413 Payload Too Large.
|
|
||||||
head -c 2000000 /dev/zero | curl -s -o /dev/null -w '%{http_code}\n' --data-binary @- \
|
|
||||||
http://localhost:8080/notes
|
|
||||||
|
|
||||||
# CORS: only the API answers to the allowed origin.
|
|
||||||
curl -s -o /dev/null -D - -H 'Origin: https://garden.example.org' \
|
|
||||||
http://localhost:8080/api/plots | grep -i access-control
|
|
||||||
```
|
|
||||||
|
|
||||||
Y en el terminal, una línea `Request served` por petición, con su ruta, su código y lo que ha
|
|
||||||
tardado.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear una extensión](extensions.md): el resto de lo que puede aportar una extensión.
|
|
||||||
- [Registrar trazas](logging.md): dónde acaban las líneas de `timing`.
|
|
||||||
- [Arquitectura: del arranque a la respuesta](../explanation/architecture.md): dónde encajan las
|
|
||||||
capas en el recorrido de una petición.
|
|
||||||
|
|
@ -1,203 +0,0 @@
|
||||||
# Añadir navegación
|
|
||||||
|
|
||||||
**Objetivo:** dar a la aplicación un menú en todas las páginas, con desplegables, una barra que se
|
|
||||||
pliega en móvil, migas de pan y enlaces que conservan el idioma del visitante.
|
|
||||||
|
|
||||||
## Menús con `Nav`
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Nav {
|
|
||||||
Nav::new()
|
|
||||||
.with_item(nav::Item::link(Lc::n("Home"), "/"))
|
|
||||||
.with_item(nav::Item::link(Lc::n("Blog"), "/blog"))
|
|
||||||
.with_item(nav::Item::link_blank(Lc::n("Code"), "https://git.cillero.es/manuelcillero/pagetop"))
|
|
||||||
.with_item(nav::Item::link_disabled(Lc::n("Shop"), "/shop"))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
El enlace que coincide con la ruta actual se marca solo como activo (con `aria-current="page"`).
|
|
||||||
`nav::Item::with_active()` permite forzarlo.
|
|
||||||
|
|
||||||
## Desplegables
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Nav {
|
|
||||||
Nav::new().with_item(nav::Item::dropdown(
|
|
||||||
Dropdown::new()
|
|
||||||
.with_title(Lc::n("Products"))
|
|
||||||
.with_item(dropdown::Item::header(Lc::n("Software")))
|
|
||||||
.with_item(dropdown::Item::link(Lc::n("Desktop"), "/products/desktop"))
|
|
||||||
.with_item(dropdown::Item::link(Lc::n("Mobile"), "/products/mobile"))
|
|
||||||
.with_item(dropdown::Item::divider())
|
|
||||||
.with_item(dropdown::Item::link(Lc::n("See all"), "/products")),
|
|
||||||
))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Enlaces según el acceso
|
|
||||||
|
|
||||||
Un enlace a una ruta declarada con `Endpoint` no se muestra a quien no tiene acceso a ella, y un
|
|
||||||
`Nav` o un `Dropdown` sin nada que mostrar tampoco se pinta. Funciona con cualquier tema, y el
|
|
||||||
enlace no repite el permiso de la ruta:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum GardenPermission { SeeHarvest, ManageBeds }
|
|
||||||
# impl Permission for GardenPermission {
|
|
||||||
# fn key(&self) -> CowStr { "garden:permission".into() }
|
|
||||||
# }
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum GardenRoute {
|
|
||||||
Harvest,
|
|
||||||
Beds,
|
|
||||||
BedEdit,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Endpoint for GardenRoute {
|
|
||||||
fn path(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::Harvest => "/harvest".into(),
|
|
||||||
Self::Beds => "/beds".into(),
|
|
||||||
Self::BedEdit => "/beds/{id}/edit".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn access(&self) -> Access {
|
|
||||||
match self {
|
|
||||||
Self::Harvest => Access::Permission(&GardenPermission::SeeHarvest),
|
|
||||||
Self::Beds | Self::BedEdit => Access::Permission(&GardenPermission::ManageBeds),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# fn f(bed: i32) -> Nav {
|
|
||||||
Nav::new()
|
|
||||||
.with_item(nav::Item::link(Lc::n("Harvest"), GardenRoute::Harvest))
|
|
||||||
.with_item(nav::Item::dropdown(
|
|
||||||
Dropdown::new()
|
|
||||||
.with_title(Lc::n("Beds"))
|
|
||||||
.with_item(dropdown::Item::link(Lc::n("All the beds"), GardenRoute::Beds))
|
|
||||||
.with_item(dropdown::Item::link(Lc::n("This bed"), GardenRoute::BedEdit.to(bed))),
|
|
||||||
))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Las rutas se montan con `routes.endpoint(GardenRoute::Harvest, web::get(...))`. Los encabezados y
|
|
||||||
separadores de un `Dropdown` sólo se muestran si separan elementos visibles: si se ocultan todos los
|
|
||||||
enlaces de un grupo, su encabezado desaparece con ellos.
|
|
||||||
Más sobre `Endpoint` en
|
|
||||||
[Proteger rutas y adaptar la interfaz](users.md#5-protege-rutas-y-adapta-la-interfaz).
|
|
||||||
|
|
||||||
## Barra de navegación
|
|
||||||
|
|
||||||
`Navbar` combina marca, menús y otros elementos. Con `brand_left()`, en pantallas estrechas los
|
|
||||||
menús se pliegan tras un botón de despliegue:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Navbar {
|
|
||||||
let brand = Brand::new()
|
|
||||||
.with_title(Lc::n("Urban Garden"))
|
|
||||||
.with_route(Route::from("/"));
|
|
||||||
|
|
||||||
let menu = Nav::new()
|
|
||||||
.with_item(nav::Item::link(Lc::n("Gardens"), "/gardens"))
|
|
||||||
.with_item(nav::Item::link(Lc::n("Events"), "/events"));
|
|
||||||
|
|
||||||
let account = Nav::new()
|
|
||||||
.with_prop(FlexItem::push_end())
|
|
||||||
.with_item(nav::Item::link(Lc::n("Sign in"), "/login"));
|
|
||||||
|
|
||||||
Navbar::brand_left(brand)
|
|
||||||
.with_item(navbar::Item::nav(menu))
|
|
||||||
.with_item(navbar::Item::nav(account))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Otras formas de empezar:
|
|
||||||
|
|
||||||
| Constructor | Marca | Botón de despliegue |
|
|
||||||
|---|---|---|
|
|
||||||
| `Navbar::simple()` | No | No |
|
|
||||||
| `Navbar::simple_toggle()` | No | Sí |
|
|
||||||
| `Navbar::simple_brand_left(brand)` | A la izquierda | No |
|
|
||||||
| `Navbar::brand_left(brand)` | A la izquierda | Sí |
|
|
||||||
| `Navbar::brand_right(brand)` | A la derecha | Sí |
|
|
||||||
|
|
||||||
## Un menú en todas las páginas
|
|
||||||
|
|
||||||
Registra el menú una sola vez al arrancar, en la región de cabecera, con `InRegion`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct MyApp;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for MyApp {
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
let menu = Navbar::simple().with_item(navbar::Item::nav(
|
|
||||||
Nav::new()
|
|
||||||
.with_item(nav::Item::link(Lc::n("Home"), "/"))
|
|
||||||
.with_item(nav::Item::link(Lc::n("Contact"), "/contact")),
|
|
||||||
));
|
|
||||||
InRegion::Global(&CoreRegions::Header).add(menu);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Migas de pan
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Breadcrumb {
|
|
||||||
Breadcrumb::new()
|
|
||||||
.with_crumb(breadcrumb::Crumb::new(Lc::n("Home"), "/"))
|
|
||||||
.with_crumb(breadcrumb::Crumb::new(Lc::n("Blog"), "/blog"))
|
|
||||||
.with_crumb(breadcrumb::Crumb::current(Lc::n("My first post")))
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Enlaces que conservan el idioma
|
|
||||||
|
|
||||||
Si el visitante eligió idioma con `?lang=en`, los enlaces internos deben conservarlo. PageTop lo
|
|
||||||
hace por ti siempre que no construyas las URL a mano:
|
|
||||||
|
|
||||||
- Los componentes aceptan rutas como `Route`: un literal como `"/blog"` ya se convierte solo,
|
|
||||||
y la URL definitiva se calcula al renderizar, con el idioma de cada petición.
|
|
||||||
- Las URL externas (`https://...`, `mailto:`...) se detectan y se dejan tal cual.
|
|
||||||
- Dentro de un componente o de `Html::with()`, usa `cx.route()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|cx| {
|
|
||||||
let post = cx.route("/blog/my-first-post");
|
|
||||||
html! { a href=(post) { "Read the post" } }
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
- Cuando la ruta depende del contexto, `Route::with()` recibe un cierre que se evalúa en cada
|
|
||||||
petición:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> nav::Item {
|
|
||||||
nav::Item::link(
|
|
||||||
Lc::n("My profile"),
|
|
||||||
Route::with(|cx| match cx.current_user().id() {
|
|
||||||
Some(id) => cx.route(util::join!("/users/", id.to_string())),
|
|
||||||
None => cx.route("/login"),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear una extensión](extensions.md): más sobre `InRegion` e `initialize()`.
|
|
||||||
- [Traducir la aplicación](localization.md): de dónde sale el `?lang=` que conservan los enlaces.
|
|
||||||
|
|
@ -1,155 +0,0 @@
|
||||||
# Construir páginas
|
|
||||||
|
|
||||||
**Objetivo:** montar una página completa: título y metadatos, contenido en las regiones del tema,
|
|
||||||
estilos y *scripts* propios, y datos compartidos con sus componentes.
|
|
||||||
|
|
||||||
## 1. Crea la página
|
|
||||||
|
|
||||||
`Page` es un documento HTML completo. Se crea a partir de la petición, se configura con métodos
|
|
||||||
encadenados y termina con `render()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn about(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("About us"))
|
|
||||||
.with_description(Lc::n("Who we are and what we do"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "We are a small team." } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El tema activo se encarga del resto: el `<head>`, la estructura del `<body>`, sus estilos y
|
|
||||||
*scripts*.
|
|
||||||
|
|
||||||
## 2. Reparte el contenido en regiones
|
|
||||||
|
|
||||||
Un tema reparte la página en **regiones**. PageTop define cuatro que cualquier tema respeta:
|
|
||||||
|
|
||||||
| Región | Uso habitual |
|
|
||||||
|---|---|
|
|
||||||
| `CoreRegions::Header` | Cabecera: logotipo, menú principal |
|
|
||||||
| `CoreRegions::Content` | Contenido principal |
|
|
||||||
| `CoreRegions::Aside` | Barra lateral |
|
|
||||||
| `CoreRegions::Footer` | Pie de página |
|
|
||||||
|
|
||||||
`with_child()` añade al contenido principal; `with_child_in()` elige la región:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn news(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(|_| html! { h1 { "News" } }))
|
|
||||||
.with_child_in(
|
|
||||||
&CoreRegions::Aside,
|
|
||||||
Block::new()
|
|
||||||
.with_title(Lc::n("Archive"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "October, September..." } })),
|
|
||||||
)
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`Content` empieza siempre por los avisos al usuario (ver [Mensajes al
|
|
||||||
usuario](components.md#mensajes-al-usuario)): no hace falta añadir el componente `Messages`.
|
|
||||||
|
|
||||||
Los componentes añadidos así sólo existen en esa página. Para que algo aparezca en **todas** (un
|
|
||||||
menú, un pie...), regístralo una vez con `InRegion`, como se explica en [Crear una
|
|
||||||
extensión](extensions.md#4-pon-componentes-en-todas-las-páginas).
|
|
||||||
|
|
||||||
## 3. Añade metadatos
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# async fn h(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_metadata("author", "PageTop Team")
|
|
||||||
.with_property("og:title", "PageTop")
|
|
||||||
.with_assets(Favicon::new().with_icon("/static/favicon.ico"))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`with_metadata()` genera `<meta name="..." content="...">` y `with_property()` genera
|
|
||||||
`<meta property="...">`, la forma que usa Open Graph.
|
|
||||||
|
|
||||||
Título, descripción y metadatos se guardan en el contexto de la página, así que también un
|
|
||||||
componente puede fijarlos mientras se renderiza (por ejemplo, un artículo con su propia
|
|
||||||
descripción), con `cx.alter_description()`, `cx.alter_metadata()` o `cx.alter_property()`: el
|
|
||||||
`<head>` se genera después del `<body>`.
|
|
||||||
|
|
||||||
## 4. Añade estilos y *scripts*
|
|
||||||
|
|
||||||
Una página puede pedir sus propios recursos. PageTop los ordena, evita duplicados y los añade al
|
|
||||||
`<head>`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# async fn h(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_assets(StyleSheet::from("/static/css/catalog.css"))
|
|
||||||
.with_assets(JavaScript::defer("/static/js/catalog.js").with_version("1.2"))
|
|
||||||
.with_assets(JavaScript::on_load("greeting", |_| "console.log('Ready!');".to_string()))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
- `StyleSheet::from()` enlaza una hoja de estilos; `.for_media(TargetMedia::Print)` la limita
|
|
||||||
a la impresión.
|
|
||||||
- `JavaScript::defer()` carga el *script* sin bloquear la página; `JavaScript::from()` lo carga de
|
|
||||||
forma normal y `asynchronous()` con `async`.
|
|
||||||
- `JavaScript::inline()` y `on_load()` incrustan código; el segundo lo ejecuta cuando el DOM está
|
|
||||||
listo.
|
|
||||||
- `with_version()` añade `?v=...` a la URL para que el navegador descargue la nueva versión.
|
|
||||||
- `with_weight()` ordena los recursos: los de menor peso van antes.
|
|
||||||
|
|
||||||
Cómo publicar esos archivos se explica en [Recursos estáticos](assets.md).
|
|
||||||
|
|
||||||
## 5. Páginas de administración
|
|
||||||
|
|
||||||
`Page::admin()` crea la página con la plantilla de administración en lugar de la estándar. El tema
|
|
||||||
puede maquetar ambas de forma distinta:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::admin(request)
|
|
||||||
.with_title(Lc::n("Dashboard"))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 6. Comparte datos con los componentes
|
|
||||||
|
|
||||||
Una página puede guardar valores en su contexto para que cualquier componente los lea durante el
|
|
||||||
renderizado:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn shop(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_param("currency", "EUR")
|
|
||||||
.with_child(Html::with(|cx| {
|
|
||||||
let currency = cx.param_or("currency", "USD");
|
|
||||||
html! { p { "Prices in " (currency) } }
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Abre la página y mira su código fuente (`Ctrl+U`): el `<title>`, las etiquetas `<meta>` y los
|
|
||||||
`<link>` y `<script>` están en el `<head>`, sin duplicados, en el orden de sus pesos.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Escribir HTML con `html!`](html.md).
|
|
||||||
- [Usar componentes](components.md).
|
|
||||||
- [Componentes, temas y renderizado](../explanation/rendering.md): qué hace `render()` por dentro.
|
|
||||||
|
|
@ -1,227 +0,0 @@
|
||||||
# Añadir rutas
|
|
||||||
|
|
||||||
**Objetivo:** registrar las rutas de tu extensión, leer los datos de cada petición y responder con
|
|
||||||
una página, un error, una redirección o JSON.
|
|
||||||
|
|
||||||
## 1. Registra las rutas
|
|
||||||
|
|
||||||
Cada extensión registra sus rutas en `configure_router()`. Recibe las rutas acumuladas por las
|
|
||||||
extensiones anteriores, añade las suyas y las devuelve.
|
|
||||||
|
|
||||||
Cada ruta lleva su acceso (`Access`), que PageTop comprueba antes de llegar al *handler*:
|
|
||||||
|
|
||||||
| Acceso | Quién llega al *handler* |
|
|
||||||
|---|---|
|
|
||||||
| `Access::Public` | Cualquiera, también un visitante anónimo |
|
|
||||||
| `Access::Authenticated` | Cualquier usuario con la sesión iniciada |
|
|
||||||
| `Access::Permission(&P)` | Quien tenga el permiso `P` (ver [Añadir usuarios y permisos](users.md)) |
|
|
||||||
|
|
||||||
No hay forma de registrar una ruta sin indicarlo, así que una página no queda abierta por olvido.
|
|
||||||
Como casi todas las rutas son públicas, `routes.public_route(path, ...)` equivale a
|
|
||||||
`routes.route(path, Access::Public, ...)` y se lee mejor. A quien no cumple el acceso se le
|
|
||||||
responde con un 403, salvo a un visitante anónimo, al que una extensión de autenticación como
|
|
||||||
`pagetop-user` le ofrece antes iniciar sesión.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# struct BlogPermission;
|
|
||||||
# impl Permission for BlogPermission {
|
|
||||||
# fn key(&self) -> CowStr { "blog:publish".into() }
|
|
||||||
# }
|
|
||||||
# async fn list() -> &'static str { "" }
|
|
||||||
# async fn view() -> &'static str { "" }
|
|
||||||
# async fn create() -> &'static str { "" }
|
|
||||||
pub struct Blog;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Blog {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/posts", web::get(list))
|
|
||||||
.public_route("/posts/{id}", web::get(view))
|
|
||||||
.route(
|
|
||||||
"/posts/new",
|
|
||||||
Access::Permission(&BlogPermission),
|
|
||||||
web::get(create).post(create),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Los métodos disponibles son `web::get`, `web::post`, `web::put`, `web::patch` y `web::delete`, y se
|
|
||||||
encadenan para atender varios en la misma ruta. Si cada método necesita un acceso distinto (leer
|
|
||||||
para todos y guardar con un permiso, por ejemplo), registra la misma ruta dos veces, cada una con
|
|
||||||
su método y su acceso.
|
|
||||||
|
|
||||||
Si enlazas a una ruta protegida desde otras páginas, declárala con `Endpoint` y móntala con
|
|
||||||
`routes.endpoint()`, para que [sus enlaces](navigation.md#enlaces-según-el-acceso) se oculten solos
|
|
||||||
a quien no pueda entrar.
|
|
||||||
|
|
||||||
## 2. Agrupa rutas bajo un prefijo
|
|
||||||
|
|
||||||
Para agrupar rutas bajo un prefijo común, crea un `Router` aparte y anídalo con `nest()`. Todas
|
|
||||||
sus rutas comparten el acceso que indiques:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# async fn beds() -> &'static str { "" }
|
|
||||||
# async fn crops() -> &'static str { "" }
|
|
||||||
# pub struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
let garden = Router::new()
|
|
||||||
.route("/beds", web::get(beds))
|
|
||||||
.route("/crops", web::get(crops));
|
|
||||||
routes.nest("/garden", Access::Authenticated, garden)
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Las rutas del panel de administración no se registran así, sino con `routes.admin_route()`, que
|
|
||||||
exige el permiso de su página (ver [Añadir páginas al panel de administración](admin.md)).
|
|
||||||
|
|
||||||
## 3. Lee los datos de la petición
|
|
||||||
|
|
||||||
Un *handler* es una función `async` que recibe lo que necesite de la petición y devuelve algo que
|
|
||||||
se pueda convertir en respuesta. PageTop reexporta los extractores de [Axum](https://docs.rs/axum)
|
|
||||||
en `web`:
|
|
||||||
|
|
||||||
| Extractor | Qué obtiene |
|
|
||||||
|---|---|
|
|
||||||
| `HttpRequest` | La petición completa; la necesita `Page::new()` |
|
|
||||||
| `web::Path<T>` | Segmentos de la ruta, como `{id}` |
|
|
||||||
| `web::Query<T>` | Parámetros de la URL (`?page=2`) |
|
|
||||||
| `web::Form<T>` | Campos de un formulario enviado |
|
|
||||||
| `web::RawForm` | El cuerpo del formulario sin interpretar |
|
|
||||||
| `Json<T>` | Cuerpo JSON |
|
|
||||||
|
|
||||||
Para `Query`, `Form` y `Json` define una estructura con `serde::Deserialize` (añade `serde` con la
|
|
||||||
*feature* `derive` a tu `Cargo.toml`):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Search {
|
|
||||||
q: String,
|
|
||||||
page: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn search(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Query(search): web::Query<Search>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
let page = search.page.unwrap_or(1);
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| {
|
|
||||||
html! { p { "Searching for “" (search.q) "”, page " (page) } }
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Una ruta puede tener varios segmentos variables. Recógelos en una tupla, en el mismo orden en que
|
|
||||||
aparecen:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
// Registered as .route("/plots/{zone}/{number}", web::get(plot))
|
|
||||||
async fn plot(web::Path((zone, number)): web::Path<(String, u32)>) -> String {
|
|
||||||
format!("Plot {number} in zone {zone}")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`/plots/north/7` responde «Plot 7 in zone north». Si un segmento no se puede convertir al tipo
|
|
||||||
pedido (`/plots/north/seven`), el *handler* no llega a ejecutarse: Axum responde por su cuenta con
|
|
||||||
un 400 y un texto explicando el motivo.
|
|
||||||
|
|
||||||
Para recoger **todo** lo que sigue a un prefijo, por muchos segmentos que tenga, usa un comodín con
|
|
||||||
asterisco:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
// Registered as .route("/files/{*path}", web::get(file))
|
|
||||||
async fn file(web::Path(path): web::Path<String>) -> String {
|
|
||||||
format!("You asked for {path}")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`/files/seeds/2026/list.txt` da `path = "seeds/2026/list.txt"`. El comodín tiene que ir al final de
|
|
||||||
la ruta y no coincide con `/files/` a secas.
|
|
||||||
|
|
||||||
## 4. Elige la respuesta
|
|
||||||
|
|
||||||
**Páginas HTML.** Lo habitual: `Result<Markup, ErrorPage>`, que es lo que devuelve
|
|
||||||
`Page::render()`.
|
|
||||||
|
|
||||||
**Errores.** `ErrorPage` se renderiza con el tema activo, para que el usuario no pierda la
|
|
||||||
navegación del sitio (todos los casos en [Mostrar páginas de error](error-pages.md)):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn view(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(id): web::Path<u32>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
if id == 0 {
|
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
}
|
|
||||||
Page::new(request).render().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Las variantes son `BadRequest` (400), `AccessDenied` (403), `NotFound` (404), `InternalError`
|
|
||||||
(500), `ServiceUnavailable` (503) y `GatewayTimeout` (504). Las rutas que no existen responden
|
|
||||||
solas con la página 404.
|
|
||||||
|
|
||||||
**Redirecciones.** `Redirect` crea la respuesta con el código adecuado:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn save() -> Response {
|
|
||||||
// ... save the data ...
|
|
||||||
Redirect::see_other("/posts")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Hay también `Redirect::found()`, `temporary()`, `permanent()` y `moved()`.
|
|
||||||
|
|
||||||
**JSON.** Para una API, devuelve `Json<T>` con cualquier tipo que implemente `serde::Serialize`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
struct Status {
|
|
||||||
version: &'static str,
|
|
||||||
active: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn status() -> Json<Status> {
|
|
||||||
Json(Status { version: "1.0", active: true })
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Texto plano.** Cualquier tipo que Axum sepa convertir en respuesta también sirve, como
|
|
||||||
`&'static str` o `String`.
|
|
||||||
|
|
||||||
Para una página o un fragmento de HTML para HTMX, mira también [Una ruta, dos
|
|
||||||
respuestas](htmx-setup.md#6-una-ruta-dos-respuestas).
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
```sh
|
|
||||||
curl -i http://localhost:8080/posts/0 # HTTP/1.1 404 Not Found, with the error page
|
|
||||||
curl -i http://localhost:8080/nope # Also 404: unknown routes get the same error page
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Construir páginas](pages.md): lo que va dentro de `Page::new(request)`.
|
|
||||||
- [Crear y procesar formularios](forms.md): `web::Form` en acción.
|
|
||||||
- [Mostrar páginas de error](error-pages.md): cuándo usar cada `ErrorPage`.
|
|
||||||
- [Probar rutas y componentes](testing.md).
|
|
||||||
|
|
@ -1,373 +0,0 @@
|
||||||
# Compartir un servicio entre rutas
|
|
||||||
|
|
||||||
**Objetivo:** crear una sola vez, a partir de los ajustes, un objeto que usan muchas rutas y
|
|
||||||
componentes (un contador, un catálogo cargado al arrancar, el cliente de un servicio externo), y
|
|
||||||
llegar a él desde cualquier sitio sin pasarlo de mano en mano.
|
|
||||||
|
|
||||||
En otros *frameworks* este objeto se registra en un contenedor y se pide en cada *handler* (en
|
|
||||||
Axum, con `State<T>`). En PageTop no hace falta: una extensión lo guarda en un **estático** y
|
|
||||||
ofrece una función para obtenerlo, igual que hace `pagetop-seaorm` con `dbconn()`. Así lo usan
|
|
||||||
igual un *handler*, un componente o un tema, que no reciben el estado de Axum.
|
|
||||||
|
|
||||||
## 1. Define el servicio
|
|
||||||
|
|
||||||
Un contador de visitas por ruta. Guarda su estado tras un `Mutex`, porque lo usarán a la vez
|
|
||||||
peticiones de varios hilos, y toma de los ajustes cuántas rutas distintas recuerda como mucho:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
pub struct Visits {
|
|
||||||
max_paths: usize,
|
|
||||||
counts: Mutex<HashMap<String, u64>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Visits {
|
|
||||||
fn new(max_paths: usize) -> Self {
|
|
||||||
Visits { max_paths, counts: Mutex::new(HashMap::new()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Counts a visit to `path` and returns its total.
|
|
||||||
pub fn record(&self, path: &str) -> u64 {
|
|
||||||
let mut counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
if !counts.contains_key(path) && counts.len() >= self.max_paths {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let total = counts.entry(path.to_string()).or_insert(0);
|
|
||||||
*total += 1;
|
|
||||||
*total
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the `n` most visited paths.
|
|
||||||
pub fn top(&self, n: usize) -> Vec<(String, u64)> {
|
|
||||||
let counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
let mut top: Vec<_> = counts.iter().map(|(p, c)| (p.clone(), *c)).collect();
|
|
||||||
top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
|
||||||
top.truncate(n);
|
|
||||||
top
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`unwrap_or_else(|poisoned| poisoned.into_inner())` sigue adelante aunque otra petición haya
|
|
||||||
fallado con el `Mutex` tomado: un contador a medias no justifica dejar de responder.
|
|
||||||
|
|
||||||
## 2. Créalo con los ajustes
|
|
||||||
|
|
||||||
Los ajustes de la extensión, como en [Ajustes de tu
|
|
||||||
extensión](configuration.md#5-ajustes-de-tu-extensión):
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
|
||||||
|
|
||||||
#[settings(section = "stats")]
|
|
||||||
pub struct StatsSettings {
|
|
||||||
/// Maximum number of different paths that are counted.
|
|
||||||
#[default = 100]
|
|
||||||
pub max_paths: usize,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si crearlo es inmediato y no puede fallar, basta con un `LazyLock`: se construye la primera vez que
|
|
||||||
alguien lo pide, ya con los ajustes cargados:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use std::sync::LazyLock;
|
|
||||||
# static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
|
||||||
# #[settings(section = "stats")]
|
|
||||||
# pub struct StatsSettings {
|
|
||||||
# #[default = 100]
|
|
||||||
# pub max_paths: usize,
|
|
||||||
# }
|
|
||||||
# pub struct Visits;
|
|
||||||
# impl Visits {
|
|
||||||
# fn new(_max_paths: usize) -> Self { Visits }
|
|
||||||
# }
|
|
||||||
static VISITS: LazyLock<Visits> = LazyLock::new(|| Visits::new(SETTINGS.max_paths));
|
|
||||||
|
|
||||||
/// The visit counter of the application.
|
|
||||||
pub fn visits() -> &'static Visits {
|
|
||||||
&VISITS
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
No lo uses antes de que arranque la aplicación: hasta entonces los ajustes no están cargados.
|
|
||||||
|
|
||||||
## 3. Úsalo en *handlers* y componentes
|
|
||||||
|
|
||||||
Cualquier código lo pide con `visits()`. Un *handler* cuenta la visita:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# pub struct Visits;
|
|
||||||
# impl Visits { pub fn record(&self, _: &str) -> u64 { 0 } }
|
|
||||||
# static VISITS: Visits = Visits;
|
|
||||||
# fn visits() -> &'static Visits { &VISITS }
|
|
||||||
async fn page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let total = visits().record(request.path());
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| html! { p { "Visits to this page: " (total) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Y un componente puesto en el pie de todas las páginas muestra las más visitadas, sin que nadie le
|
|
||||||
pase el contador:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# pub struct Visits;
|
|
||||||
# impl Visits { pub fn top(&self, _: usize) -> Vec<(String, u64)> { vec![] } }
|
|
||||||
# static VISITS: Visits = Visits;
|
|
||||||
# fn visits() -> &'static Visits { &VISITS }
|
|
||||||
# fn f() {
|
|
||||||
InRegion::Global(&CoreRegions::Footer).add(Html::with(|_| {
|
|
||||||
let top = visits().top(3);
|
|
||||||
html! {
|
|
||||||
p { "Most visited: "
|
|
||||||
@for (path, total) in top {
|
|
||||||
a href=(path) { (path) } " (" (total) ") "
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Si crearlo puede fallar, hazlo al arrancar
|
|
||||||
|
|
||||||
Cuando crear el servicio es asíncrono o puede fallar (conectar con un servidor, leer un archivo),
|
|
||||||
hazlo en `initialize()` y guárdalo en un `OnceLock`. Si devuelve un error, la aplicación **no
|
|
||||||
arranca** y explica por qué, en lugar de fallar más tarde en mitad de una petición:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use std::sync::OnceLock;
|
|
||||||
# pub struct Station;
|
|
||||||
# impl Station {
|
|
||||||
# async fn connect(_url: &str) -> Result<Self, std::io::Error> { Ok(Station) }
|
|
||||||
# }
|
|
||||||
# static SETTINGS: LazySettings<WeatherSettings> = LazySettings::new();
|
|
||||||
# #[settings(section = "weather")]
|
|
||||||
# pub struct WeatherSettings {
|
|
||||||
# #[default = "http://localhost:9000"]
|
|
||||||
# pub url: String,
|
|
||||||
# }
|
|
||||||
static STATION: OnceLock<Station> = OnceLock::new();
|
|
||||||
|
|
||||||
/// The weather station, connected when the application starts.
|
|
||||||
pub fn station() -> &'static Station {
|
|
||||||
STATION.get().expect("Weather station not connected: is the extension a dependency?")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Weather;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Weather {
|
|
||||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
|
||||||
Some(&SETTINGS)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
if STATION.get().is_none() {
|
|
||||||
let station = Station::connect(&SETTINGS.url).await?;
|
|
||||||
let _ = STATION.set(station);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`initialize()` se ejecuta cada vez que se prepara la aplicación, y en las pruebas eso ocurre varias
|
|
||||||
veces en el mismo proceso: por eso comprueba primero si el servicio ya existe.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::{LazyLock, Mutex};
|
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
|
||||||
|
|
||||||
#[settings(section = "stats")]
|
|
||||||
pub struct StatsSettings {
|
|
||||||
/// Maximum number of different paths that are counted.
|
|
||||||
#[default = 100]
|
|
||||||
pub max_paths: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Visits {
|
|
||||||
max_paths: usize,
|
|
||||||
counts: Mutex<HashMap<String, u64>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Visits {
|
|
||||||
fn new(max_paths: usize) -> Self {
|
|
||||||
Visits { max_paths, counts: Mutex::new(HashMap::new()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Counts a visit to `path` and returns its total.
|
|
||||||
pub fn record(&self, path: &str) -> u64 {
|
|
||||||
let mut counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
if !counts.contains_key(path) && counts.len() >= self.max_paths {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
let total = counts.entry(path.to_string()).or_insert(0);
|
|
||||||
*total += 1;
|
|
||||||
*total
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the `n` most visited paths.
|
|
||||||
pub fn top(&self, n: usize) -> Vec<(String, u64)> {
|
|
||||||
let counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
let mut top: Vec<_> = counts.iter().map(|(p, c)| (p.clone(), *c)).collect();
|
|
||||||
top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
|
||||||
top.truncate(n);
|
|
||||||
top
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static VISITS: LazyLock<Visits> = LazyLock::new(|| Visits::new(SETTINGS.max_paths));
|
|
||||||
|
|
||||||
/// The visit counter of the application.
|
|
||||||
pub fn visits() -> &'static Visits {
|
|
||||||
&VISITS
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
|
||||||
Some(&SETTINGS)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
InRegion::Global(&CoreRegions::Footer).add(Html::with(|_| {
|
|
||||||
let top = visits().top(3);
|
|
||||||
html! {
|
|
||||||
p { "Most visited: "
|
|
||||||
@for (path, total) in top {
|
|
||||||
a href=(path) { (path) } " (" (total) ") "
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(page))
|
|
||||||
.public_route("/plots", web::get(page))
|
|
||||||
.public_route("/harvest", web::get(page))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let total = visits().record(request.path());
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| html! { p { "Visits to this page: " (total) } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Arranca con `cargo run` y visita varias veces `/`, `/plots` y `/harvest`: cada página dice cuántas
|
|
||||||
veces la has visto, y el pie de todas ordena las tres por visitas. Con `max_paths = 2` en la
|
|
||||||
sección `[stats]` de `config/local.toml`, la tercera ruta distinta deja de contarse.
|
|
||||||
|
|
||||||
En una prueba, todas comparten el mismo contador, porque es un estático del proceso: escribe una
|
|
||||||
sola prueba por flujo (ve [Probar rutas y componentes](testing.md)).
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use std::collections::HashMap;
|
|
||||||
# use std::sync::{LazyLock, Mutex};
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
|
||||||
# #[settings(section = "stats")]
|
|
||||||
# pub struct StatsSettings {
|
|
||||||
# #[default = 100]
|
|
||||||
# pub max_paths: usize,
|
|
||||||
# }
|
|
||||||
# pub struct Visits {
|
|
||||||
# max_paths: usize,
|
|
||||||
# counts: Mutex<HashMap<String, u64>>,
|
|
||||||
# }
|
|
||||||
# impl Visits {
|
|
||||||
# fn new(max_paths: usize) -> Self {
|
|
||||||
# Visits { max_paths, counts: Mutex::new(HashMap::new()) }
|
|
||||||
# }
|
|
||||||
# pub fn record(&self, path: &str) -> u64 {
|
|
||||||
# let mut counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
# if !counts.contains_key(path) && counts.len() >= self.max_paths {
|
|
||||||
# return 0;
|
|
||||||
# }
|
|
||||||
# let total = counts.entry(path.to_string()).or_insert(0);
|
|
||||||
# *total += 1;
|
|
||||||
# *total
|
|
||||||
# }
|
|
||||||
# pub fn top(&self, n: usize) -> Vec<(String, u64)> {
|
|
||||||
# let counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
# let mut top: Vec<_> = counts.iter().map(|(p, c)| (p.clone(), *c)).collect();
|
|
||||||
# top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
|
||||||
# top.truncate(n);
|
|
||||||
# top
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# static VISITS: LazyLock<Visits> = LazyLock::new(|| Visits::new(SETTINGS.max_paths));
|
|
||||||
# pub fn visits() -> &'static Visits {
|
|
||||||
# &VISITS
|
|
||||||
# }
|
|
||||||
# struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
# fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
|
||||||
# Some(&SETTINGS)
|
|
||||||
# }
|
|
||||||
# fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
# routes.public_route("/plots", web::get(page)).public_route("/harvest", web::get(page))
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# async fn page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
# let total = visits().record(request.path());
|
|
||||||
# Page::new(request)
|
|
||||||
# .with_child(Html::with(move |_| html! { p { "Visits to this page: " (total) } }))
|
|
||||||
# .render()
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn visits_are_counted_by_path() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
|
||||||
|
|
||||||
for uri in ["/plots", "/plots", "/harvest"] {
|
|
||||||
let request = web::test::TestRequest::get().uri(uri).to_request();
|
|
||||||
web::test::send_request(&app, request).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
visits().top(2),
|
|
||||||
[("/plots".to_string(), 2), ("/harvest".to_string(), 1)]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Configurar la aplicación](configuration.md#5-ajustes-de-tu-extensión): los ajustes del servicio.
|
|
||||||
- [Crear una extensión](extensions.md): el servicio es parte de una extensión.
|
|
||||||
- [Si vienes de Axum](../explanation/coming-from-axum.md#el-estado-de-la-aplicación): por qué no se
|
|
||||||
usa `State<T>`.
|
|
||||||
|
|
@ -1,99 +0,0 @@
|
||||||
# Mostrar tablas ordenables y paginadas
|
|
||||||
|
|
||||||
**Objetivo:** mostrar datos en una tabla con cabeceras que ordenan y un paginador, usando enlaces
|
|
||||||
normales que funcionan en cualquier navegador.
|
|
||||||
|
|
||||||
## 1. Construye la tabla
|
|
||||||
|
|
||||||
`Table` se construye columna a columna y fila a fila. Cada celda acepta texto, un `Lc` o
|
|
||||||
cualquier componente:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
struct Book {
|
|
||||||
title: &'static str,
|
|
||||||
author: &'static str,
|
|
||||||
available: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn books_table(books: &[Book]) -> Table {
|
|
||||||
let mut table = Table::new()
|
|
||||||
.with_column(table::Column::new(Lc::n("Title")))
|
|
||||||
.with_column(table::Column::new(Lc::n("Author")))
|
|
||||||
.with_column(table::Column::new(Lc::n("Status")))
|
|
||||||
.with_empty(Lc::n("There are no books in the catalog."));
|
|
||||||
|
|
||||||
for book in books {
|
|
||||||
let status = if book.available {
|
|
||||||
Badge::success(Lc::n("Available"))
|
|
||||||
} else {
|
|
||||||
Badge::warning(Lc::n("On loan"))
|
|
||||||
};
|
|
||||||
table = table.with_row(
|
|
||||||
table::Row::new()
|
|
||||||
.with_cell(book.title)
|
|
||||||
.with_cell(book.author)
|
|
||||||
.with_cell(table::Cell::new(status)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
table
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si no hay filas, se muestra el texto de `with_empty()` (o uno genérico, si no lo indicas).
|
|
||||||
|
|
||||||
## 2. Ordena por columnas
|
|
||||||
|
|
||||||
Una columna se hace ordenable con un `SortLink`: la URL a la que lleva y, si la tabla ya está
|
|
||||||
ordenada por ella, en qué dirección. `Table` marca la cabecera con `aria-sort` y con clases que el
|
|
||||||
tema usa para dibujar la flecha:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f(sort: &str, dir: SortDir) -> table::Column {
|
|
||||||
table::Column::new(Lc::n("Title")).with_sort(
|
|
||||||
table::SortLink::new("/books?sort=title")
|
|
||||||
.with_dir((sort == "title").then_some(dir)),
|
|
||||||
)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Tu *handler* lee los parámetros (con `web::Query`) y consulta los datos en ese orden.
|
|
||||||
|
|
||||||
## 3. Pagina el listado
|
|
||||||
|
|
||||||
`Pager` genera los enlaces de un listado paginado. Sólo se muestra si hay más de una página:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f(page: u64, total: u64) -> Pager {
|
|
||||||
Pager::new()
|
|
||||||
.with_base_path("/books")
|
|
||||||
.with_extra_query("sort", "title")
|
|
||||||
.with_current_page(page)
|
|
||||||
.with_items_per_page(20)
|
|
||||||
.with_total_items(total)
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Cada enlace lleva el parámetro `page` con el número de página, más los que añadas con
|
|
||||||
`with_extra_query()` (para conservar el orden o la búsqueda). Coloca el paginador junto a la tabla:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn table() -> Table { Table::new() }
|
|
||||||
# fn pager() -> Pager { Pager::new() }
|
|
||||||
# fn f() -> Container {
|
|
||||||
Container::new()
|
|
||||||
.with_child(table())
|
|
||||||
.with_child(pager())
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
La guía [Ordenar y paginar sin recargar](htmx-tables.md) tiene un ejemplo completo con su *handler*,
|
|
||||||
que lee `sort`, `dir` y `page` de la URL.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Ordenar y paginar sin recargar](htmx-tables.md): la misma tabla, sustituida con HTMX.
|
|
||||||
- [Borrar con confirmación](htmx-delete.md): botones de acción en cada fila.
|
|
||||||
|
|
@ -1,228 +0,0 @@
|
||||||
# Probar rutas y componentes
|
|
||||||
|
|
||||||
**Objetivo:** comprobar con `cargo test` lo que devuelve cada ruta y cada componente, sin arrancar
|
|
||||||
el servidor ni abrir un navegador.
|
|
||||||
|
|
||||||
Las pruebas detectan lo que se rompe antes de que lo vean tus usuarios, te dejan reorganizar el
|
|
||||||
código con la tranquilidad de que todo sigue funcionando y, de paso, muestran cómo se usa cada ruta.
|
|
||||||
En PageTop son baratas: la aplicación entera se prepara en memoria y responde en milisegundos.
|
|
||||||
|
|
||||||
## 1. Prepara la aplicación sin servidor
|
|
||||||
|
|
||||||
`Application::prepare()` hace lo mismo que al arrancar (registra las extensiones, carga los ajustes,
|
|
||||||
las inicializa...), y `test()` devuelve sus rutas sin abrir ningún puerto. Con
|
|
||||||
`web::test::send_request()` se le envían peticiones:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
struct MyApp;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for MyApp {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/hello/{name}", web::get(hello))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn hello(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(name): web::Path<String>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(move |_| html! { h1 { "Hello, " (name) "!" } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn greets_by_name() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&MyApp).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get().uri("/hello/Ana").to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::OK);
|
|
||||||
let body = web::test::read_body_text(response).await;
|
|
||||||
assert!(body.contains("<h1>Hello, Ana!</h1>"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn unknown_routes_answer_with_404() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&MyApp).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get().uri("/nope").to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::NOT_FOUND);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`#[pagetop::test]` ejecuta cada prueba en el mismo *runtime* asíncrono multihilo que usa la
|
|
||||||
aplicación real. Las pruebas que sólo usan la API pública van en `tests/`; si la aplicación vive
|
|
||||||
en `src/lib.rs`, cada archivo de `tests/` la importa como una biblioteca más.
|
|
||||||
|
|
||||||
## 2. Envía formularios y otros métodos
|
|
||||||
|
|
||||||
`TestRequest` tiene un constructor por método (`get()`, `post()`, `put()`, `patch()` y
|
|
||||||
`delete()`), y `form()` envía los campos de un formulario, ya codificados, como lo hace el
|
|
||||||
navegador:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
struct Contact;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Contact {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/contact", web::post(send))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Message {
|
|
||||||
text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send(web::Form(message): web::Form<Message>) -> Response {
|
|
||||||
if message.text.trim().is_empty() {
|
|
||||||
return web::http::StatusCode::UNPROCESSABLE_ENTITY.into_response();
|
|
||||||
}
|
|
||||||
Redirect::see_other("/contact/thanks")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn a_message_redirects_to_the_thanks_page() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&Contact).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::post()
|
|
||||||
.uri("/contact")
|
|
||||||
.form("text=Hello")
|
|
||||||
.to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER);
|
|
||||||
assert_eq!(response.headers()["location"], "/contact/thanks");
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. Prueba un componente suelto
|
|
||||||
|
|
||||||
Un componente se renderiza con un `Context`, sin aplicación ni rutas. `Context::default()` usa el
|
|
||||||
idioma por defecto; para probar otro idioma o una ruta concreta, créalo a partir de una petición de
|
|
||||||
prueba:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn a_badge_shows_its_label() {
|
|
||||||
let mut cx = Context::default();
|
|
||||||
let mut badge = Badge::success(Lc::n("Active"));
|
|
||||||
|
|
||||||
let html = badge.render(&mut cx).await.into_string();
|
|
||||||
|
|
||||||
assert!(html.contains("Active"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn internal_links_keep_the_language() {
|
|
||||||
let request = web::test::TestRequest::get().uri("/?lang=es").to_http_request();
|
|
||||||
let cx = Context::new(request);
|
|
||||||
|
|
||||||
assert_eq!(cx.route("/blog").to_string(), "/blog?lang=es");
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Prueba las rutas de HTMX
|
|
||||||
|
|
||||||
Una ruta para HTMX es una ruta normal que devuelve un fragmento. Envía la cabecera `HX-Request`,
|
|
||||||
como hace HTMX, y comprueba el fragmento y las cabeceras `HX-*` de la respuesta:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
struct Clock;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Clock {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/time", web::get(time))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn time(request: HttpRequest) -> Response {
|
|
||||||
if !request.is_htmx() {
|
|
||||||
return Redirect::see_other("/");
|
|
||||||
}
|
|
||||||
HtmxResponse::new(html! { span { "12:00" } })
|
|
||||||
.trigger("timeShown")
|
|
||||||
.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn time_answers_htmx_with_a_fragment_and_an_event() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&Clock).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get()
|
|
||||||
.uri("/time")
|
|
||||||
.header("hx-request", "true")
|
|
||||||
.to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
|
|
||||||
assert_eq!(response.headers()["hx-trigger"], "timeShown");
|
|
||||||
assert_eq!(web::test::read_body_text(response).await, "<span>12:00</span>");
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Lo que HTMX haga después con el fragmento lo deciden los atributos `hx-*` de la página, que son
|
|
||||||
HTML: no hay lógica de cliente que probar.
|
|
||||||
|
|
||||||
## 5. Usa otra configuración para las pruebas
|
|
||||||
|
|
||||||
Las pruebas leen la misma cascada de configuración que la aplicación. Para que usen sus propios
|
|
||||||
ajustes (otra base de datos, menos trazas...), créalos en `config/test.toml` y ejecuta las pruebas
|
|
||||||
en ese modo:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/test.toml
|
|
||||||
[log]
|
|
||||||
tracing = "Warn"
|
|
||||||
|
|
||||||
[database]
|
|
||||||
db_name = "tests?mode=memory"
|
|
||||||
max_pool_size = 1
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
PAGETOP_RUN_MODE=test cargo test
|
|
||||||
```
|
|
||||||
|
|
||||||
Una base de datos SQLite en memoria es nueva en cada ejecución. Con `max_pool_size = 1` todas las
|
|
||||||
consultas comparten la misma conexión, y por tanto las mismas tablas.
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo test
|
|
||||||
```
|
|
||||||
|
|
||||||
```text
|
|
||||||
running 2 tests
|
|
||||||
test greets_by_name ... ok
|
|
||||||
test unknown_routes_answer_with_404 ... ok
|
|
||||||
|
|
||||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Tareas del huerto con HTMX](../tutorials/htmx-tasks.md#8-prueba-la-aplicación): pruebas de una
|
|
||||||
aplicación completa.
|
|
||||||
- [Registrar trazas](logging.md).
|
|
||||||
|
|
@ -1,198 +0,0 @@
|
||||||
# Crear un tema
|
|
||||||
|
|
||||||
**Objetivo:** elegir el aspecto de la aplicación y, si hace falta, crear un tema propio que herede
|
|
||||||
de otro y cambie sólo lo necesario.
|
|
||||||
|
|
||||||
El tema es la **piel** de la aplicación: maqueta la página por regiones, aporta estilos y
|
|
||||||
*scripts*, y decide cómo se ve cada componente. Cambiar de tema no obliga a tocar las páginas.
|
|
||||||
|
|
||||||
## 1. Elige un tema
|
|
||||||
|
|
||||||
PageTop trae el tema `Basic`. Hay otros como extensiones:
|
|
||||||
|
|
||||||
| Tema | *Crate* | Estilo |
|
|
||||||
|---|---|---|
|
|
||||||
| Basic | `pagetop` | Sobrio, sin dependencias |
|
|
||||||
| Bootsier | `pagetop-bootsier` | [Bootstrap 5](https://getbootstrap.com) |
|
|
||||||
| Aliner | `pagetop-aliner` | Muestra la estructura de la página, para pruebas |
|
|
||||||
|
|
||||||
Para usar uno, declara su extensión como dependencia y selecciónalo en la configuración:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct MyApp;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for MyApp {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[app]
|
|
||||||
theme = "Bootsier"
|
|
||||||
```
|
|
||||||
|
|
||||||
Si el tema configurado no está disponible, PageTop usa `Basic` y avisa al arrancar.
|
|
||||||
|
|
||||||
## 2. Crea un tema
|
|
||||||
|
|
||||||
Un tema es una extensión que además implementa `Theme`. Todos los métodos de `Theme` tienen
|
|
||||||
implementación por defecto, así que el mínimo es éste:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct Earth;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Earth {
|
|
||||||
fn theme(&self) -> Option<ThemeRef> {
|
|
||||||
Some(&Self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Theme for Earth {}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. Hereda de otro tema
|
|
||||||
|
|
||||||
Lo más práctico es partir de un tema existente y cambiar sólo lo necesario. Un **tema hijo**
|
|
||||||
hereda todo de su padre:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct Earth;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Earth {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn theme(&self) -> Option<ThemeRef> {
|
|
||||||
Some(&Self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Theme for Earth {
|
|
||||||
fn parent(&self) -> Option<ThemeRef> {
|
|
||||||
Some(&pagetop_bootsier::Bootsier)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Adds its own style sheet to every page.
|
|
||||||
fn before_render_page_body(&self, page: &mut Page) {
|
|
||||||
if let Some(parent) = self.parent() {
|
|
||||||
parent.before_render_page_body(page);
|
|
||||||
}
|
|
||||||
page.alter_assets(StyleSheet::from("/static/css/earth.css").with_weight(10));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`before_render_page_body()` es donde un tema añade sus recursos. Al sobrescribirlo, llama al del
|
|
||||||
padre para no perder los suyos.
|
|
||||||
|
|
||||||
No olvides seleccionarlo en la configuración (`theme = "Earth"`) y declararlo como dependencia
|
|
||||||
de la aplicación.
|
|
||||||
|
|
||||||
## 4. Ajusta componentes
|
|
||||||
|
|
||||||
`setup_component()` permite retocar cualquier componente antes de pintarlo. La macro
|
|
||||||
`setup_component!` lo distingue por tipo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# pub struct Earth;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Earth {}
|
|
||||||
#[async_trait]
|
|
||||||
impl Theme for Earth {
|
|
||||||
fn setup_component(&self, component: &mut dyn Component, _cx: &mut Context) {
|
|
||||||
setup_component!(component, {
|
|
||||||
Button => |button| { button.alter_prop(PropsOp::add_classes("earth-button")); },
|
|
||||||
Block => |block| { block.alter_prop(PropsOp::add_classes("earth-block")); },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Reescribe componentes
|
|
||||||
|
|
||||||
Para cambiar el HTML entero de un componente, usa `render_component()` con la macro
|
|
||||||
`render_component!`. Lo que no captures se pinta como siempre:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# pub struct Earth;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Earth {}
|
|
||||||
#[async_trait]
|
|
||||||
impl Theme for Earth {
|
|
||||||
async fn render_component(
|
|
||||||
&self,
|
|
||||||
component: &dyn Component,
|
|
||||||
cx: &mut Context,
|
|
||||||
) -> Option<Result<Markup, ComponentError>> {
|
|
||||||
render_component!(component, {
|
|
||||||
Badge => |badge| Ok(html! {
|
|
||||||
span class="earth-label" { (badge.label().using(cx)) }
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Como el componente expone sus datos con *getters* (`badge.label()`), el tema no depende de sus
|
|
||||||
detalles internos.
|
|
||||||
|
|
||||||
Si capturas `layout::Region` para maquetar la región de contenido a tu manera, incluye al
|
|
||||||
principio `Messages::new().with_deferred(true)`, que es lo que pone PageTop: sin él, los avisos al
|
|
||||||
usuario no se ven. Es también la forma de llevarlos a otro lugar de la página, por ejemplo a la
|
|
||||||
cabecera.
|
|
||||||
|
|
||||||
## 6. Cambia las páginas de error
|
|
||||||
|
|
||||||
Las páginas 403, 404 y de error grave se pintan con la plantilla activa, para no perder la
|
|
||||||
navegación. Un tema puede cambiar su contenido:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# pub struct Earth;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Earth {}
|
|
||||||
#[async_trait]
|
|
||||||
impl Theme for Earth {
|
|
||||||
fn error_404(&self, page: &mut Page) {
|
|
||||||
page.alter_title(Lc::n("Not found")).alter_child_in(
|
|
||||||
&CoreRegions::Content,
|
|
||||||
ChildOp::Prepend(
|
|
||||||
Html::with(|_| {
|
|
||||||
html! {
|
|
||||||
h1 { "This page has gone off to plant tomatoes" }
|
|
||||||
p { a href="/" { "Back to home" } }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.into(),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Más allá
|
|
||||||
|
|
||||||
Un tema también puede definir **regiones** y **plantillas** propias, fijar los anchos de los
|
|
||||||
puntos de corte (`breakpoint_entry()`) o traducir las intenciones a su paleta de colores
|
|
||||||
(`intent_color()`). La documentación del módulo `core::theme` en
|
|
||||||
[docs.rs](https://docs.rs/pagetop) recorre los seis pasos para personalizar un tema por completo.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Intervenir con acciones](actions.md): retocar componentes desde una extensión que no es un tema.
|
|
||||||
- [Componentes, temas y renderizado](../explanation/rendering.md).
|
|
||||||
|
|
@ -1,486 +0,0 @@
|
||||||
# Subir y descargar archivos
|
|
||||||
|
|
||||||
**Objetivo:** recibir archivos desde un formulario, guardarlos en el servidor con límites de tamaño
|
|
||||||
y de tipo, y servirlos después sólo a quien pueda verlos.
|
|
||||||
|
|
||||||
Todo lo necesario está en el núcleo de PageTop: el campo `form::File`, `web::Upload` para recibir
|
|
||||||
y guardar los archivos, y `web::Download` para servirlos.
|
|
||||||
|
|
||||||
## 1. Define la subida
|
|
||||||
|
|
||||||
`web::Upload` describe qué se admite y dónde se guarda. Defínelo una sola vez, en una función, para
|
|
||||||
que el formulario y el servidor compartan las mismas reglas:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
fn photo_upload() -> web::Upload {
|
|
||||||
web::Upload::new()
|
|
||||||
.with_subdir("photos")
|
|
||||||
.with_extensions(["jpg", "jpeg", "png"])
|
|
||||||
.with_file_fields(["photo"])
|
|
||||||
.with_max_size(2 * 1024 * 1024)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Método | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `with_subdir("photos")` | Subdirectorio, dentro del de archivos subidos (`[upload] dir`) |
|
|
||||||
| `with_extensions(["jpg", "png"])` | Extensiones admitidas; un archivo con otra se rechaza |
|
|
||||||
| `with_file_fields(["photo"])` | Campos del formulario que pueden traer archivos; uno en otro campo se rechaza |
|
|
||||||
| `with_max_size(bytes)` | Tamaño máximo de cada archivo, en lugar del de la configuración |
|
|
||||||
| `with_max_files(n)` | Número máximo de archivos de un envío, en lugar del de la configuración |
|
|
||||||
|
|
||||||
Restringe siempre las extensiones: es la defensa más sencilla contra quien sube una página HTML o un
|
|
||||||
programa en lugar de una foto.
|
|
||||||
|
|
||||||
## 2. Construye el formulario
|
|
||||||
|
|
||||||
Un formulario con archivos necesita la codificación `multipart/form-data`, que se indica con
|
|
||||||
`form::Enctype::Multipart`. El campo es `form::File`, y con `accept()` ofrece al usuario los mismos
|
|
||||||
tipos que admite el servidor:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn photo_upload() -> web::Upload { web::Upload::new() }
|
|
||||||
fn photo_form() -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/photos")
|
|
||||||
.with_method(form::Method::Post)
|
|
||||||
.with_enctype(form::Enctype::Multipart)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("title")
|
|
||||||
.with_label(Lc::n("Title"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::File::new()
|
|
||||||
.with_name("photo")
|
|
||||||
.with_label(Lc::n("Photo"))
|
|
||||||
.with_accept(photo_upload().accept())
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Upload")))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para elegir varios archivos en el mismo campo, añade `with_multiple(true)`.
|
|
||||||
|
|
||||||
## 3. Recibe el envío
|
|
||||||
|
|
||||||
El *handler* recibe el cuerpo con el extractor `web::Multipart`, siempre como **último** parámetro.
|
|
||||||
`receive()` guarda los archivos según las reglas del paso 1 y deserializa los campos de texto en una
|
|
||||||
estructura, como hace `web::Form` en un formulario sin archivos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn photo_upload() -> web::Upload { web::Upload::new() }
|
|
||||||
# async fn show_form(_request: HttpRequest, _error: Lc) -> Result<Response, ErrorPage> { todo!() }
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct PhotoData {
|
|
||||||
title: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn upload(request: HttpRequest, multipart: web::Multipart) -> Result<Response, ErrorPage> {
|
|
||||||
let sent = match photo_upload().receive::<PhotoData>(multipart).await {
|
|
||||||
Ok(sent) => sent,
|
|
||||||
// Too large, a type not allowed...: shows the form again with the reason.
|
|
||||||
Err(err) if err.is_client_error() => return show_form(request, err.message()).await,
|
|
||||||
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
|
||||||
};
|
|
||||||
let Some(photo) = sent.file("photo") else {
|
|
||||||
return show_form(request, Lc::n("Choose a photo to upload.")).await;
|
|
||||||
};
|
|
||||||
// Save `sent.form().title`, `photo.path()` and `photo.original_name()`, for example in the
|
|
||||||
// database. If anything fails before `keep()`, the file is deleted.
|
|
||||||
sent.keep();
|
|
||||||
let cx = Context::new(request);
|
|
||||||
Ok(Redirect::see_other(cx.route("/photos")).with_message(
|
|
||||||
&cx,
|
|
||||||
MessageLevel::Info,
|
|
||||||
Lc::n("Photo uploaded."),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Fíjate en tres cosas:
|
|
||||||
|
|
||||||
- **Los errores del usuario se distinguen de los del servidor.** `is_client_error()` es cierto si
|
|
||||||
el archivo es demasiado grande, de un tipo no admitido o el envío está mal formado, y
|
|
||||||
`message()` explica el motivo, ya traducido, con el nombre del archivo y el límite superado.
|
|
||||||
- **Los archivos se borran si no llamas a `keep()`.** El envío recibido conserva sus archivos sólo
|
|
||||||
si llegas a `keep()`, cuando ya está todo guardado. Si la validación o la base de datos fallan y
|
|
||||||
sales antes, con `return` o con `?`, no quedan archivos huérfanos en el disco.
|
|
||||||
- **El nombre que envía el navegador nunca llega al disco.** Cada archivo se guarda con un nombre
|
|
||||||
aleatorio y la extensión del original, y `path()` devuelve su ruta relativa
|
|
||||||
(`photos/3f9c2a7d1b4e8a60.jpg`): es lo que se guarda en la base de datos. El nombre original,
|
|
||||||
saneado, queda en `original_name()`, sólo para mostrarlo.
|
|
||||||
|
|
||||||
`content_type()` devuelve el tipo que declara el navegador, pero no se comprueba contra el
|
|
||||||
contenido: no lo tomes como garantía de que el archivo es lo que dice.
|
|
||||||
|
|
||||||
## 4. Sirve el archivo con permisos
|
|
||||||
|
|
||||||
Los archivos subidos no se publican como estáticos. Se sirven desde un *handler*, que antes
|
|
||||||
comprueba si quien los pide puede verlos y busca su ruta, con `web::Download`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn find_photo(_index: usize) -> Option<(String, String)> { None }
|
|
||||||
async fn photo(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(index): web::Path<usize>,
|
|
||||||
) -> Result<Response, ErrorPage> {
|
|
||||||
// Check the permissions here, as in any other handler...
|
|
||||||
let Some((path, original_name)) = find_photo(index) else {
|
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
};
|
|
||||||
web::Download::new(path)
|
|
||||||
.with_file_name(original_name)
|
|
||||||
.serve(&request)
|
|
||||||
.await
|
|
||||||
.map_err(|err| match err {
|
|
||||||
web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)),
|
|
||||||
_ => ErrorPage::InternalError(Some(request)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`Download` envía el tipo que corresponde a la extensión del archivo guardado, y el nombre original
|
|
||||||
para guardarlo. Las imágenes (salvo SVG), el audio, el vídeo, los PDF y el texto plano se muestran
|
|
||||||
en el navegador; el resto se descarga, para que un `.html` o un `.svg` subido no se ejecute como una
|
|
||||||
página más de tu sitio. `with_attachment(true)` obliga a descargar también los primeros. Atiende
|
|
||||||
las descargas parciales (para reanudar o avanzar en un vídeo), y el navegador vuelve a preguntar
|
|
||||||
antes de reutilizar el archivo, así que cada visita pasa por tu *handler* y sus permisos.
|
|
||||||
|
|
||||||
La ruta debe salir de tu aplicación (la que guardaste en la base de datos), nunca directamente de la
|
|
||||||
petición: aunque `Download` no sale del directorio de archivos subidos, daría acceso a cualquiera de
|
|
||||||
ellos.
|
|
||||||
|
|
||||||
## 5. Borra los archivos que ya no se usan
|
|
||||||
|
|
||||||
Al borrar o sustituir el registro que apunta a un archivo, borra también el archivo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
async fn delete_photo_file(path: &str) -> Result<(), web::UploadError> {
|
|
||||||
web::Upload::remove(path).await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
No es un error que el archivo ya no exista, y una ruta que intente salir del directorio de
|
|
||||||
archivos subidos (con `..`, por ejemplo) se rechaza.
|
|
||||||
|
|
||||||
## 6. Ajusta los límites
|
|
||||||
|
|
||||||
Los valores por defecto sirven para la mayoría de las aplicaciones:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[upload]
|
|
||||||
dir = "uploads" # Where files are saved (relative to the working directory).
|
|
||||||
max_file_size = 8388608 # 8 MiB per file (0 = only max_request_size).
|
|
||||||
max_files = 20 # Files per submission (0 = no limit).
|
|
||||||
max_request_size = 33554432 # 32 MiB for a whole multipart/form-data request (0 = no limit).
|
|
||||||
```
|
|
||||||
|
|
||||||
Las peticiones `multipart/form-data` pueden llegar a `max_request_size`, porque sus archivos se
|
|
||||||
escriben en disco según llegan. El resto de cuerpos (`web::Form`, JSON) se leen enteros en memoria
|
|
||||||
y se limitan con `max_body_size` de `[server]` (2 MiB): uno mayor se rechaza con `413`. Ese límite
|
|
||||||
acota también la suma de los campos de texto de un formulario con archivos.
|
|
||||||
|
|
||||||
Un envío con archivos que supera cualquiera de estos límites llega a `receive()` como un error del
|
|
||||||
usuario, así que el formulario vuelve con el motivo («El envío supera el tamaño máximo de 32 MiB»,
|
|
||||||
por ejemplo) en lugar de mostrar una página de error.
|
|
||||||
|
|
||||||
En producción, el directorio `dir` debe sobrevivir a los despliegues: fuera del directorio de la
|
|
||||||
aplicación, o en un volumen si usas contenedores. Y si un proxy inverso va delante, su límite de
|
|
||||||
tamaño también debe admitir los envíos: nginx rechaza por defecto los cuerpos de más de 1 MiB, así
|
|
||||||
que añade `client_max_body_size 32m;` a su configuración (ve [Detrás de un proxy
|
|
||||||
inverso](deployment.md#5-detrás-de-un-proxy-inverso)).
|
|
||||||
|
|
||||||
## 7. Con HTMX
|
|
||||||
|
|
||||||
Un formulario con `form::Enctype::Multipart` se envía igual con HTMX: HTMX respeta su `enctype`.
|
|
||||||
Sólo si la petición sale de otro elemento que no es el formulario, indícalo con el atributo
|
|
||||||
`hx::ENCODING` de `pagetop-htmx` y el valor `"multipart/form-data"`.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
Un tablón de fotos del huerto: el formulario sube una foto con su título, y la lista enlaza cada
|
|
||||||
una, servida por su *handler*. Las fotos se guardan en memoria para no depender de una base de
|
|
||||||
datos:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
use std::sync::{Mutex, MutexGuard};
|
|
||||||
|
|
||||||
struct Photo {
|
|
||||||
title: String,
|
|
||||||
path: String,
|
|
||||||
original_name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
static PHOTOS: Mutex<Vec<Photo>> = Mutex::new(Vec::new());
|
|
||||||
|
|
||||||
fn photos() -> MutexGuard<'static, Vec<Photo>> {
|
|
||||||
PHOTOS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn photo_upload() -> web::Upload {
|
|
||||||
web::Upload::new()
|
|
||||||
.with_subdir("photos")
|
|
||||||
.with_extensions(["jpg", "jpeg", "png"])
|
|
||||||
.with_file_fields(["photo"])
|
|
||||||
.with_max_size(2 * 1024 * 1024)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/photos", web::get(gallery).post(upload))
|
|
||||||
.public_route("/photos/{index}", web::get(photo))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn photo_form() -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/photos")
|
|
||||||
.with_method(form::Method::Post)
|
|
||||||
.with_enctype(form::Enctype::Multipart)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("title")
|
|
||||||
.with_label(Lc::n("Title"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::File::new()
|
|
||||||
.with_name("photo")
|
|
||||||
.with_label(Lc::n("Photo"))
|
|
||||||
.with_accept(photo_upload().accept())
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Upload")))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn gallery_page(request: HttpRequest) -> Page {
|
|
||||||
let list = html! {
|
|
||||||
ul {
|
|
||||||
@for (index, photo) in photos().iter().enumerate() {
|
|
||||||
li { a href=(util::join!("/photos/", index.to_string())) { (photo.title) } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden photos"))
|
|
||||||
.with_child(photo_form())
|
|
||||||
.with_child(Html::with(move |_| list.clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn gallery(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
gallery_page(request).render().await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn show_form(request: HttpRequest, error: Lc) -> Result<Response, ErrorPage> {
|
|
||||||
let mut page = gallery_page(request);
|
|
||||||
page.push_message(MessageLevel::Error, error);
|
|
||||||
page.render().await.map(IntoResponse::into_response)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct PhotoData {
|
|
||||||
title: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn upload(request: HttpRequest, multipart: web::Multipart) -> Result<Response, ErrorPage> {
|
|
||||||
let sent = match photo_upload().receive::<PhotoData>(multipart).await {
|
|
||||||
Ok(sent) => sent,
|
|
||||||
Err(err) if err.is_client_error() => return show_form(request, err.message()).await,
|
|
||||||
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
|
||||||
};
|
|
||||||
let Some(file) = sent.file("photo") else {
|
|
||||||
return show_form(request, Lc::n("Choose a photo to upload.")).await;
|
|
||||||
};
|
|
||||||
let photo = Photo {
|
|
||||||
title: sent.form().title.clone(),
|
|
||||||
path: file.path().to_string(),
|
|
||||||
original_name: file.original_name().to_string(),
|
|
||||||
};
|
|
||||||
photos().push(photo);
|
|
||||||
sent.keep();
|
|
||||||
let cx = Context::new(request);
|
|
||||||
Ok(Redirect::see_other(cx.route("/photos")).with_message(
|
|
||||||
&cx,
|
|
||||||
MessageLevel::Info,
|
|
||||||
Lc::n("Photo uploaded."),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn photo(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(index): web::Path<usize>,
|
|
||||||
) -> Result<Response, ErrorPage> {
|
|
||||||
let found = photos()
|
|
||||||
.get(index)
|
|
||||||
.map(|photo| (photo.path.clone(), photo.original_name.clone()));
|
|
||||||
let Some((path, original_name)) = found else {
|
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
};
|
|
||||||
web::Download::new(path)
|
|
||||||
.with_file_name(original_name)
|
|
||||||
.serve(&request)
|
|
||||||
.await
|
|
||||||
.map_err(|err| match err {
|
|
||||||
web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)),
|
|
||||||
_ => ErrorPage::InternalError(Some(request)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Garden).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
Arranca con `cargo run` y abre <http://localhost:8080/photos>:
|
|
||||||
|
|
||||||
1. Sube una foto `.jpg` o `.png` con un título: vuelves a la lista con el aviso «Photo uploaded.»,
|
|
||||||
y el archivo está en `uploads/photos/` con un nombre aleatorio.
|
|
||||||
2. Pulsa su enlace: el navegador muestra la foto.
|
|
||||||
3. Intenta subir otro tipo de archivo (el selector propone sólo fotos, pero la mayoría de los
|
|
||||||
navegadores permite elegir cualquier archivo): el formulario vuelve con el motivo del rechazo, y
|
|
||||||
no se guarda nada.
|
|
||||||
|
|
||||||
En las pruebas, un envío `multipart/form-data` se escribe a mano con `body()` y su cabecera
|
|
||||||
`Content-Type`. Para no llenar de archivos el directorio del proyecto, apunta `dir` de `[upload]` a
|
|
||||||
otro lugar en `config/test.toml` (por ejemplo, `"target/test-uploads"`):
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use serde::Deserialize;
|
|
||||||
# use std::sync::{Mutex, MutexGuard};
|
|
||||||
# struct Photo { path: String, original_name: String }
|
|
||||||
# static PHOTOS: Mutex<Vec<Photo>> = Mutex::new(Vec::new());
|
|
||||||
# fn photos() -> MutexGuard<'static, Vec<Photo>> {
|
|
||||||
# PHOTOS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
||||||
# }
|
|
||||||
# fn photo_upload() -> web::Upload {
|
|
||||||
# web::Upload::new()
|
|
||||||
# .with_subdir("photos")
|
|
||||||
# .with_extensions(["jpg", "jpeg", "png"])
|
|
||||||
# .with_file_fields(["photo"])
|
|
||||||
# }
|
|
||||||
# struct Garden;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Garden {
|
|
||||||
# fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
# routes
|
|
||||||
# .public_route("/photos", web::post(upload))
|
|
||||||
# .public_route("/photos/{index}", web::get(photo))
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[derive(Deserialize)]
|
|
||||||
# struct PhotoData {
|
|
||||||
# #[allow(dead_code)]
|
|
||||||
# title: String,
|
|
||||||
# }
|
|
||||||
# async fn show_form(request: HttpRequest, error: Lc) -> Result<Response, ErrorPage> {
|
|
||||||
# let mut page = Page::new(request);
|
|
||||||
# page.push_message(MessageLevel::Error, error);
|
|
||||||
# page.render().await.map(IntoResponse::into_response)
|
|
||||||
# }
|
|
||||||
# async fn upload(request: HttpRequest, multipart: web::Multipart) -> Result<Response, ErrorPage> {
|
|
||||||
# let sent = match photo_upload().receive::<PhotoData>(multipart).await {
|
|
||||||
# Ok(sent) => sent,
|
|
||||||
# Err(err) if err.is_client_error() => return show_form(request, err.message()).await,
|
|
||||||
# Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
|
||||||
# };
|
|
||||||
# let Some(file) = sent.file("photo") else {
|
|
||||||
# return show_form(request, Lc::n("Choose a photo to upload.")).await;
|
|
||||||
# };
|
|
||||||
# let photo = Photo {
|
|
||||||
# path: file.path().to_string(),
|
|
||||||
# original_name: file.original_name().to_string(),
|
|
||||||
# };
|
|
||||||
# photos().push(photo);
|
|
||||||
# sent.keep();
|
|
||||||
# Ok(Redirect::see_other("/photos"))
|
|
||||||
# }
|
|
||||||
# async fn photo(
|
|
||||||
# request: HttpRequest,
|
|
||||||
# web::Path(index): web::Path<usize>,
|
|
||||||
# ) -> Result<Response, ErrorPage> {
|
|
||||||
# let found = photos()
|
|
||||||
# .get(index)
|
|
||||||
# .map(|photo| (photo.path.clone(), photo.original_name.clone()));
|
|
||||||
# let Some((path, original_name)) = found else {
|
|
||||||
# return Err(ErrorPage::NotFound(Some(request)));
|
|
||||||
# };
|
|
||||||
# web::Download::new(path)
|
|
||||||
# .with_file_name(original_name)
|
|
||||||
# .serve(&request)
|
|
||||||
# .await
|
|
||||||
# .map_err(|_| ErrorPage::NotFound(Some(request)))
|
|
||||||
# }
|
|
||||||
// A submission with a title and one file, as a browser sends it.
|
|
||||||
fn photo_body(file_name: &str, content: &str) -> String {
|
|
||||||
format!(
|
|
||||||
"--boundary\r\n\
|
|
||||||
Content-Disposition: form-data; name=\"title\"\r\n\r\n\
|
|
||||||
First tomatoes\r\n\
|
|
||||||
--boundary\r\n\
|
|
||||||
Content-Disposition: form-data; name=\"photo\"; filename=\"{file_name}\"\r\n\
|
|
||||||
Content-Type: application/octet-stream\r\n\r\n\
|
|
||||||
{content}\r\n\
|
|
||||||
--boundary--\r\n"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_photo(file_name: &str, content: &str) -> web::test::TestRequest {
|
|
||||||
web::test::TestRequest::post()
|
|
||||||
.uri("/photos")
|
|
||||||
.header("content-type", "multipart/form-data; boundary=boundary")
|
|
||||||
.body(photo_body(file_name, content))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn uploads_and_serves_a_photo() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
|
||||||
|
|
||||||
// A file of a type not allowed is rejected with the reason, and nothing is saved.
|
|
||||||
let request = send_photo("tomatoes.exe", "MZ").to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
let body = web::test::read_body_text(response).await;
|
|
||||||
assert!(body.contains("is not an allowed file type"), "{body}");
|
|
||||||
assert!(photos().is_empty());
|
|
||||||
|
|
||||||
// A photo is saved under a random name and served with its original one.
|
|
||||||
let request = send_photo("tomatoes.png", "PNG data").to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER);
|
|
||||||
let saved = photos()[0].path.clone();
|
|
||||||
assert!(saved.starts_with("photos/") && saved.ends_with(".png"), "{saved}");
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get().uri("/photos/0").to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
assert_eq!(response.status(), web::http::StatusCode::OK);
|
|
||||||
assert_eq!(response.headers()["content-type"], "image/png");
|
|
||||||
assert_eq!(web::test::read_body_text(response).await, "PNG data");
|
|
||||||
|
|
||||||
web::Upload::remove(saved).await.unwrap();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Crear y procesar formularios](forms.md): campos, validación y avisos tras redirigir.
|
|
||||||
- [Opciones de configuración](../reference/configuration.md#upload): todas las claves de
|
|
||||||
`[upload]`.
|
|
||||||
- [Desplegar en producción](deployment.md): el proxy inverso delante de la aplicación.
|
|
||||||
|
|
@ -1,522 +0,0 @@
|
||||||
# Añadir usuarios y permisos
|
|
||||||
|
|
||||||
**Objetivo:** que los visitantes puedan iniciar sesión y que algunas páginas o acciones sólo estén
|
|
||||||
al alcance de quien tenga el permiso adecuado.
|
|
||||||
|
|
||||||
La extensión `pagetop-user` aporta las cuentas, el inicio de sesión, las sesiones (guardadas en la
|
|
||||||
base de datos), las contraseñas cifradas con Argon2 y el control de acceso por roles, con su
|
|
||||||
interfaz de administración en `/admin`. Necesita una base de datos: mira antes [Conectar una base
|
|
||||||
de datos](database.md).
|
|
||||||
|
|
||||||
## 1. Añade la extensión
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop-user = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
pub struct Board;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Board {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_user::User]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`User` declara por su cuenta lo que necesita: `pagetop-seaorm`, `pagetop-htmx` y `pagetop-mail`, y
|
|
||||||
sus páginas de usuarios, roles y permisos en el panel de administración. Al arrancar crea sus tablas
|
|
||||||
y registra sus rutas, entre ellas `/user/login`, `/user/register`, `/user` (el perfil), `/user/email`
|
|
||||||
(cambiar el email) y `/user/password/reset` (recuperar la contraseña).
|
|
||||||
|
|
||||||
La recuperación de contraseña envía un correo con un enlace, como el cambio de email, que no se
|
|
||||||
aplica hasta que se confirma desde la nueva dirección. Además, la cuenta recibe un aviso cuando
|
|
||||||
cambia su contraseña o se pide cambiar su dirección. Mientras no configures la sección
|
|
||||||
`[mail]`, los correos se escriben en las trazas en lugar de enviarse; para enviarlos, indica al menos
|
|
||||||
el transporte, el remitente y la URL pública de la aplicación, que forma los enlaces:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/production.toml
|
|
||||||
[mail]
|
|
||||||
transport = "smtp"
|
|
||||||
from = "Garden board <no-reply@example.com>"
|
|
||||||
base_url = "https://board.example.com"
|
|
||||||
|
|
||||||
[mail.smtp]
|
|
||||||
host = "smtp.example.com"
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2. Configura la base de datos y el primer administrador
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/common.toml
|
|
||||||
[database]
|
|
||||||
db_type = "sqlite"
|
|
||||||
db_name = "board.db?mode=rwc"
|
|
||||||
```
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/local.toml (not versioned)
|
|
||||||
[user.seed]
|
|
||||||
admin_password = "choose-a-long-one"
|
|
||||||
```
|
|
||||||
|
|
||||||
Con la base de datos vacía, el primer arranque crea la cuenta `admin` con esa contraseña. Si no la
|
|
||||||
indicas, genera una aleatoria y la muestra **una sola vez** en el terminal:
|
|
||||||
|
|
||||||
```text
|
|
||||||
pagetop-user: admin account created.
|
|
||||||
username: admin
|
|
||||||
password: ...
|
|
||||||
```
|
|
||||||
|
|
||||||
Las demás opciones (registro abierto, bloqueo tras intentos fallidos, límites por IP, duración de
|
|
||||||
las sesiones...) están en la [referencia de configuración](../reference/configuration.md#user).
|
|
||||||
|
|
||||||
### Elige qué nombres de usuario se aceptan
|
|
||||||
|
|
||||||
Cada cuenta tiene un nombre de usuario y un email, los dos obligatorios y únicos, y se puede
|
|
||||||
iniciar sesión con cualquiera de ellos. Qué nombres de usuario se admiten lo decide
|
|
||||||
`identity_policy`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
# config/common.toml
|
|
||||||
[user]
|
|
||||||
identity_policy = "unicode"
|
|
||||||
```
|
|
||||||
|
|
||||||
| Valor | Caracteres | Longitud |
|
|
||||||
|---|---|---|
|
|
||||||
| `"strict"` (por defecto) | Letras ASCII sin tildes, dígitos, `.`, `_` y `-` | 3 a 32 |
|
|
||||||
| `"unicode"` | Letras y dígitos de cualquier alfabeto, sin mezclarlos, `.`, `_` y `-` | 3 a 32 |
|
|
||||||
| `"permissive"` | Los de `"unicode"`, más espacios simples, `'` y `+` | 3 a 60 |
|
|
||||||
|
|
||||||
Cada nivel admite todo lo del anterior, y los tres comparten tres reglas:
|
|
||||||
|
|
||||||
- **Nunca se admite `@`**, así que un nombre de usuario no puede coincidir con el email de otra
|
|
||||||
cuenta, que también sirve para entrar.
|
|
||||||
- **No se distinguen mayúsculas**: `Ana` y `ana` son el mismo usuario. El nombre se muestra tal
|
|
||||||
como se escribió.
|
|
||||||
- **No se admiten nombres que se confunden a simple vista con otro existente**: si existe `maria`,
|
|
||||||
no se puede crear `rnaria`, ni `сосо` (escrito con letras cirílicas) si existe `coco`. Se
|
|
||||||
comprueba con la tabla de caracteres confusables de Unicode.
|
|
||||||
|
|
||||||
Para elegir, piensa en quién crea los nombres más que en dónde se publica la aplicación. Con el
|
|
||||||
registro abierto, cualquiera escoge un nombre que verán los demás y que aparecerá en el saludo de
|
|
||||||
sus correos en cuanto verifique su dirección; si las cuentas sólo las crea un administrador, el
|
|
||||||
riesgo es mucho menor.
|
|
||||||
|
|
||||||
| Situación | Política |
|
|
||||||
|---|---|
|
|
||||||
| Aplicación en Internet con registro abierto | `"strict"` |
|
|
||||||
| Comunidad en Internet cuyos usuarios escriben su nombre en su alfabeto | `"unicode"` |
|
|
||||||
| Aplicación interna con cuentas creadas por administradores | `"strict"` o `"unicode"` |
|
|
||||||
| Importar cuentas de un sistema con espacios en los nombres (Drupal...) | `"permissive"` |
|
|
||||||
|
|
||||||
`"strict"` basta casi siempre: los nombres con tildes o en otros alfabetos tienen su sitio en el
|
|
||||||
nombre visible de la cuenta. Evita `"permissive"` con el registro abierto, porque los espacios
|
|
||||||
permiten escribir frases («Soporte técnico», «Llama al 900...») que luego se muestran como nombre.
|
|
||||||
|
|
||||||
Puedes cambiar de política cuando quieras, y nadie pierde el acceso:
|
|
||||||
|
|
||||||
- **A una más abierta**, las cuentas existentes no cambian.
|
|
||||||
- **A una más estricta**, los nombres que ya no la cumplen se conservan y sus titulares pueden
|
|
||||||
seguir entrando y guardando su perfil; sólo un nombre nuevo, o uno que se cambia, debe cumplirla.
|
|
||||||
Nada se renombra automáticamente.
|
|
||||||
- **El administrador inicial** (`[user.seed] admin_username`) se comprueba en cada arranque: si no
|
|
||||||
cumple la política nueva, la aplicación no arranca hasta que pongas uno válido. Cambiarlo no
|
|
||||||
renombra al administrador que ya existe, y con el valor por defecto, `admin`, no ocurre nunca.
|
|
||||||
|
|
||||||
## 3. Pon el menú de cuenta en la cabecera
|
|
||||||
|
|
||||||
`account_menu(cx)` construye el menú: «Iniciar sesión» para los anónimos, y el nombre del usuario
|
|
||||||
con su perfil, la administración (si tiene acceso) y «Cerrar sesión» para los demás. Depende de
|
|
||||||
quién pide la página, así que se construye al renderizar, dentro de un componente:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use pagetop_user::prelude::*;
|
|
||||||
|
|
||||||
#[derive(AutoDefault, Clone, Debug)]
|
|
||||||
struct TopBar;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Component for TopBar {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
let brand = Brand::new()
|
|
||||||
.with_title(Lc::n("Garden board"))
|
|
||||||
.with_route(Route::from("/"));
|
|
||||||
Ok(Navbar::brand_left(brand)
|
|
||||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
|
||||||
.render(cx)
|
|
||||||
.await)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Regístralo una vez en `initialize()`, para todas las páginas:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Define tus permisos
|
|
||||||
|
|
||||||
Un permiso es un valor de un `enum` propio con una clave única. Su nombre y su grupo son los que
|
|
||||||
verá el administrador al asignarlo:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum BoardPermission {
|
|
||||||
PostNotices,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permission for BoardPermission {
|
|
||||||
fn key(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::PostNotices => "board:post_notices".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn label(&self) -> Lc {
|
|
||||||
Lc::n("Post notices on the board")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group(&self) -> &'static str {
|
|
||||||
"board"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group_label(&self) -> Lc {
|
|
||||||
Lc::n("Garden board")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Para que aparezca en la pantalla de roles, decláralo con la acción `DeclarePermissions` de
|
|
||||||
PageTop:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum BoardPermission { PostNotices }
|
|
||||||
# impl Permission for BoardPermission {
|
|
||||||
# fn key(&self) -> CowStr { "board:post_notices".into() }
|
|
||||||
# }
|
|
||||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
|
||||||
registry.register(&BoardPermission::PostNotices);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Board;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Board {
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![action::auth::DeclarePermissions::new(declare_permissions)]
|
|
||||||
}
|
|
||||||
|
|
||||||
// ... dependencies(), initialize() and configure_router() ...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si una ruta o una página del panel exige un permiso que no has declarado, PageTop lo avisa en las
|
|
||||||
trazas al arrancar: nadie podría concederlo, y sólo entrarían los administradores.
|
|
||||||
|
|
||||||
## 5. Protege rutas y adapta la interfaz
|
|
||||||
|
|
||||||
Cada ruta se registra con su acceso. Con `Access::Permission`, PageTop comprueba el permiso antes de
|
|
||||||
llegar al *handler*; a quien no lo tiene le responde con un 403 y, si no ha iniciado sesión,
|
|
||||||
`pagetop-user` le lleva antes al formulario de inicio de sesión y le devuelve después a la ruta que
|
|
||||||
pedía:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum BoardPermission { PostNotices }
|
|
||||||
# impl Permission for BoardPermission {
|
|
||||||
# fn key(&self) -> CowStr { "board:post_notices".into() }
|
|
||||||
# }
|
|
||||||
# async fn board() -> &'static str { "" }
|
|
||||||
# async fn new_notice() -> &'static str { "" }
|
|
||||||
# pub struct Board;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Board {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(board))
|
|
||||||
.route(
|
|
||||||
"/notices/new",
|
|
||||||
Access::Permission(&BoardPermission::PostNotices),
|
|
||||||
web::get(new_notice),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Para una comprobación más concreta que la de la ruta (que sólo el autor pueda editar su aviso, por
|
|
||||||
ejemplo), `require_permission()` corta la petición con un 403 desde el propio *handler*.
|
|
||||||
|
|
||||||
`has_permission()` devuelve un `bool`, para mostrar u ocultar lo que no se puede usar:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum BoardPermission { PostNotices }
|
|
||||||
# impl Permission for BoardPermission {
|
|
||||||
# fn key(&self) -> CowStr { "board:post_notices".into() }
|
|
||||||
# }
|
|
||||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let can_post = has_permission(&request, &BoardPermission::PostNotices);
|
|
||||||
let mut page = Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden board"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }));
|
|
||||||
if can_post {
|
|
||||||
page = page.with_child(Button::anchor(Lc::n("Post a notice"), "/notices/new"));
|
|
||||||
}
|
|
||||||
page.render().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Y dentro de un componente, `cx.current_user()` dice quién está viendo la página:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|cx| {
|
|
||||||
let user = cx.current_user();
|
|
||||||
html! {
|
|
||||||
@if let Some(name) = user.display_name() {
|
|
||||||
p { "Hello, " (name) "." }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
Ocultar el botón no basta: la ruta debe comprobar el permiso igualmente, porque cualquiera puede
|
|
||||||
escribir la URL.
|
|
||||||
|
|
||||||
Con `has_permission()`, el permiso queda escrito en dos sitios, en la ruta y en el enlace. PageTop
|
|
||||||
no permite preguntar después qué acceso tiene una ruta, de modo que, si cambias uno y olvidas el
|
|
||||||
otro, el enlace llevará a un 403 o se ocultará a quien sí podría entrar. Para los enlaces hay una
|
|
||||||
forma mejor: declara las rutas con su acceso en un `enum`, como los permisos, implementando
|
|
||||||
`Endpoint`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(Clone, Copy, Debug)]
|
|
||||||
# enum BoardPermission { PostNotices }
|
|
||||||
# impl Permission for BoardPermission {
|
|
||||||
# fn key(&self) -> CowStr { "board:post_notices".into() }
|
|
||||||
# }
|
|
||||||
# async fn new_notice() -> &'static str { "" }
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum BoardRoute {
|
|
||||||
Home,
|
|
||||||
NewNotice,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Endpoint for BoardRoute {
|
|
||||||
fn path(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::Home => "/".into(),
|
|
||||||
Self::NewNotice => "/notices/new".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn access(&self) -> Access {
|
|
||||||
match self {
|
|
||||||
Self::Home => Access::Public,
|
|
||||||
Self::NewNotice => Access::Permission(&BoardPermission::PostNotices),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# pub struct Board;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Board {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.endpoint(BoardRoute::Home, web::get(board))
|
|
||||||
.endpoint(BoardRoute::NewNotice, web::get(new_notice))
|
|
||||||
}
|
|
||||||
# }
|
|
||||||
|
|
||||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden board"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }))
|
|
||||||
.with_child(Button::anchor(Lc::n("Post a notice"), BoardRoute::NewNotice))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`routes.endpoint()` monta la ruta con su acceso, y `Button::anchor()` y los enlaces de los menús
|
|
||||||
([`nav::Item` y `dropdown::Item`](navigation.md#enlaces-según-el-acceso)) no se muestran a quien no
|
|
||||||
lo cumple. El enlace nunca nombra el permiso, así que no puede desalinearse de la ruta, y una ruta
|
|
||||||
nueva sin acceso no compila. Una ruta con parámetro se enlaza con `to()`:
|
|
||||||
`BoardRoute::EditNotice.to(7)` lleva a `/notices/7/edit` si la ruta es `/notices/{id}/edit`.
|
|
||||||
|
|
||||||
`Endpoint` sólo responde por el acceso de la ruta, no por lo que compruebe además su *handler*, y
|
|
||||||
lo aplican esos enlaces, no todo lo que muestre la página. Para el resto, y cuando un permiso decide
|
|
||||||
varias cosas dentro de una misma página, sigue estando `has_permission()`.
|
|
||||||
|
|
||||||
## 6. Asigna el permiso
|
|
||||||
|
|
||||||
Inicia sesión como `admin` y entra en **Administración** desde el menú de cuenta. En la lista de
|
|
||||||
roles, abre los permisos de uno de ellos: verás el grupo «Garden board» con su permiso. Puedes
|
|
||||||
concederlo:
|
|
||||||
|
|
||||||
- al rol **authenticated**, para todos los usuarios que inicien sesión;
|
|
||||||
- o a un rol nuevo («Gardeners», por ejemplo), y asignar ese rol a las cuentas que quieras.
|
|
||||||
|
|
||||||
Los administradores tienen todos los permisos sin necesidad de asignarlos.
|
|
||||||
|
|
||||||
## El ejemplo completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_user::prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum BoardPermission {
|
|
||||||
PostNotices,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permission for BoardPermission {
|
|
||||||
fn key(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::PostNotices => "board:post_notices".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn label(&self) -> Lc {
|
|
||||||
Lc::n("Post notices on the board")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group(&self) -> &'static str {
|
|
||||||
"board"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group_label(&self) -> Lc {
|
|
||||||
Lc::n("Garden board")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
|
||||||
registry.register(&BoardPermission::PostNotices);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum BoardRoute {
|
|
||||||
Home,
|
|
||||||
NewNotice,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Endpoint for BoardRoute {
|
|
||||||
fn path(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::Home => "/".into(),
|
|
||||||
Self::NewNotice => "/notices/new".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn access(&self) -> Access {
|
|
||||||
match self {
|
|
||||||
Self::Home => Access::Public,
|
|
||||||
Self::NewNotice => Access::Permission(&BoardPermission::PostNotices),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Board;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Board {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_user::User]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![action::auth::DeclarePermissions::new(declare_permissions)]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.endpoint(BoardRoute::Home, web::get(board))
|
|
||||||
.endpoint(BoardRoute::NewNotice, web::get(new_notice))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(AutoDefault, Clone, Debug)]
|
|
||||||
struct TopBar;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Component for TopBar {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
let brand = Brand::new()
|
|
||||||
.with_title(Lc::n("Garden board"))
|
|
||||||
.with_route(Route::from("/"));
|
|
||||||
Ok(Navbar::brand_left(brand)
|
|
||||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
|
||||||
.render(cx)
|
|
||||||
.await)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden board"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }))
|
|
||||||
.with_child(Button::anchor(Lc::n("Post a notice"), BoardRoute::NewNotice))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn new_notice(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("New notice"))
|
|
||||||
.with_child(Html::with(|_| html! { p { "Write your notice here." } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&Board).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comprueba
|
|
||||||
|
|
||||||
1. Sin iniciar sesión, la portada no muestra *Post a notice*, y <http://localhost:8080/notices/new>
|
|
||||||
te lleva al formulario de inicio de sesión.
|
|
||||||
2. Inicia sesión como `admin`: aparece el botón y la página se abre.
|
|
||||||
3. Crea una cuenta con el enlace «Crear una cuenta» del menú, concede el permiso al rol
|
|
||||||
**authenticated** e inicia sesión con ella: también puede publicar.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Opciones de configuración](../reference/configuration.md#user): registro, sesiones y
|
|
||||||
contraseñas.
|
|
||||||
- [Extensiones oficiales](../reference/extensions.md): lo que aportan `pagetop-user` y
|
|
||||||
`pagetop-admin`, y el panel de administración.
|
|
||||||
- [Conectar tu propia autenticación](auth.md): si los usuarios vienen de otro sistema.
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
# PageTop
|
|
||||||
|
|
||||||
> **La web clásica, con la potencia de Rust.**
|
|
||||||
> HTML generado en el servidor, componentes reutilizables y un único binario que lo lleva todo
|
|
||||||
> dentro.
|
|
||||||
|
|
||||||
PageTop es un entorno de desarrollo para crear soluciones web **modulares, extensibles y
|
|
||||||
configurables** en [Rust](https://www.rust-lang.org/es). Las páginas se generan en el servidor
|
|
||||||
(SSR) con HTML, CSS y JavaScript de toda la vida, sin compilar un *frontend* aparte ni mantener dos
|
|
||||||
aplicaciones que se hablan por una API.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
struct HelloWorld;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for HelloWorld {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/", web::get(home))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(|_| html! { h1 { "Hello, world!" } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&HelloWorld).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Veinte líneas, un `cargo run`, y tienes un servidor web sirviendo una página completa en
|
|
||||||
`http://localhost:8080`.
|
|
||||||
|
|
||||||
## Lo que te llevas
|
|
||||||
|
|
||||||
- **Un solo lenguaje, de principio a fin.** Rutas, lógica, componentes y plantillas son código
|
|
||||||
Rust. El compilador revisa tu HTML igual que revisa el resto del programa.
|
|
||||||
- **Componentes de verdad.** Botones, formularios, tablas, menús o rejillas son tipos Rust que
|
|
||||||
se configuran con métodos encadenados, se reutilizan entre proyectos y se adaptan al tema activo.
|
|
||||||
- **Temas intercambiables.** El aspecto se cambia sin tocar el código de las páginas: el tema
|
|
||||||
puede reescribir cómo se pinta cualquier componente.
|
|
||||||
- **Extensiones como piezas de LEGO.** Cada funcionalidad es una extensión que declara sus
|
|
||||||
dependencias, sus rutas, sus ajustes y sus traducciones. Las aplicaciones se componen sumando
|
|
||||||
extensiones.
|
|
||||||
- **Interactividad sin escribir JavaScript.** Con [HTMX](explanation/htmx.md), un atributo en un
|
|
||||||
botón basta para actualizar una parte de la página con HTML generado en el servidor: búsquedas en
|
|
||||||
vivo, edición en línea, *scroll* infinito...
|
|
||||||
- **Multilingüe desde el primer día.** Traducciones con [Fluent](https://projectfluent.org/),
|
|
||||||
integradas en el binario.
|
|
||||||
- **Despliegue trivial.** Estilos, *scripts* y traducciones viajan dentro del ejecutable. Copias
|
|
||||||
un archivo, añades la configuración y listo.
|
|
||||||
- **Rendimiento y seguridad de Rust.** Sin recolector de basura, con *async* sobre Tokio y
|
|
||||||
Axum, y con los errores de memoria descartados por el compilador.
|
|
||||||
|
|
||||||
## ¿Para quién es?
|
|
||||||
|
|
||||||
Para quien quiere construir aplicaciones web de gestión, portales, intranets o sitios con
|
|
||||||
contenido, y prefiere **HTML servido desde el servidor** (con un toque de
|
|
||||||
[HTMX](https://htmx.org) cuando haga falta interactividad) a montar un *frontend* JavaScript
|
|
||||||
completo. Si conoces lo básico de Rust, puedes empezar hoy; si aún no, [El libro de
|
|
||||||
Rust](https://doc.rust-lang.org/book/) es el mejor punto de partida.
|
|
||||||
|
|
||||||
¿Dudas entre PageTop y otro *framework*? [PageTop frente a otros
|
|
||||||
*frameworks*](explanation/comparison.md) los compara con franqueza.
|
|
||||||
|
|
||||||
## Cómo está organizada esta guía
|
|
||||||
|
|
||||||
| | Para... | Empieza por |
|
|
||||||
|---|---|---|
|
|
||||||
| **[Tutoriales](tutorials/first-app.md)** | Aprender haciendo, de principio a fin | [Tu primera aplicación](tutorials/first-app.md), en 10 minutos |
|
|
||||||
| **Guías prácticas** | Resolver una tarea concreta | [Añadir rutas](how-to/routes.md), [Buscar mientras se escribe](how-to/htmx-search.md)... |
|
|
||||||
| **[Referencia](reference/configuration.md)** | Consultar opciones, componentes y atributos | [Referencia rápida](reference/cheatsheet.md) |
|
|
||||||
| **[Explicación](explanation/why.md)** | Entender el porqué | [Arquitectura](explanation/architecture.md) |
|
|
||||||
|
|
||||||
Si es tu primera vez, sigue los tutoriales en orden: en algo más de una hora pasas de no tener nada
|
|
||||||
instalado a una aplicación interactiva con base de datos y pruebas.
|
|
||||||
|
|
||||||
Todos los ejemplos están escritos contra la versión actual de PageTop, y se compilan (y, los que
|
|
||||||
pueden, se ejecutan) cada vez que PageTop cambia.
|
|
||||||
|
|
||||||
> **Aviso:** PageTop está en desarrollo activo y su API puede cambiar hasta la versión **1.0.0**.
|
|
||||||
> Pruébalo, constrúyelo y cuéntanos qué tal, pero piénsalo dos veces antes de llevarlo a
|
|
||||||
> producción.
|
|
||||||
|
|
@ -1,151 +0,0 @@
|
||||||
# Referencia rápida
|
|
||||||
|
|
||||||
Lo esencial de PageTop en una página. Cada línea enlaza con la guía que lo explica.
|
|
||||||
|
|
||||||
## Aplicación
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Arrancar](../tutorials/first-app.md) | `Application::prepare(&MyApp).await.run().await` |
|
|
||||||
| [Declarar dependencias](../how-to/extensions.md) | `fn dependencies(&self) -> Vec<ExtensionRef> { vec![&Other] }` |
|
|
||||||
| [Ejecutar código al arrancar](../how-to/extensions.md#3-inicialízala-al-arrancar) | `async fn initialize(&self) -> Result<(), BoxError>` |
|
|
||||||
| [Lanzar una tarea en segundo plano](../how-to/extensions.md#3-inicialízala-al-arrancar) | `async fn start(&self) -> Result<(), BoxError>` (y `shutdown()`) |
|
|
||||||
| [Programar una tarea periódica](../how-to/cron.md) | `Job::new("app.key", Schedule::cron("0 3 * * *"), job_fn)` |
|
|
||||||
| [Ejecutar una tarea programada ya](../how-to/cron.md#comprueba) | `pagetop_cron::run_now("app.key").await` |
|
|
||||||
| [Añadir rutas](../how-to/routes.md) | `routes.public_route("/path", web::get(handler))` |
|
|
||||||
| [Servir archivos](../how-to/assets.md) | `serve_static_files!(files, ["./static", app] => "/static")` |
|
|
||||||
| [Leer un ajuste](../how-to/configuration.md) | `global::SETTINGS.app.name` |
|
|
||||||
| [Escribir una traza](../how-to/logging.md) | `trace::info!("...")` |
|
|
||||||
| [Compartir un servicio](../how-to/services.md) | `static X: LazyLock<Service> = LazyLock::new(...)` |
|
|
||||||
| [Añadir *middleware*](../how-to/middleware.md) | `fn configure_middleware(&self, layers: Layers) -> Layers` |
|
|
||||||
|
|
||||||
## *Handlers*
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Una página](../how-to/pages.md) | `Page::new(request).with_child(...).render().await` |
|
|
||||||
| [Un segmento de la URL](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Path(id): web::Path<u32>` |
|
|
||||||
| [Parámetros de consulta](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Query(q): web::Query<T>` |
|
|
||||||
| [Un formulario](../how-to/forms.md#3-recibe-y-valida-los-datos) | `web::Form(data): web::Form<T>` (el último parámetro) |
|
|
||||||
| [Un formulario con archivos](../how-to/uploads.md#3-recibe-el-envío) | `upload.receive::<T>(multipart).await` con `multipart: web::Multipart` (el último parámetro) |
|
|
||||||
| [Servir un archivo subido](../how-to/uploads.md#4-sirve-el-archivo-con-permisos) | `web::Download::new(path).with_file_name(name).serve(&request).await` |
|
|
||||||
| [Un error 404](../how-to/error-pages.md) | `Err(ErrorPage::NotFound(Some(request)))` |
|
|
||||||
| [Redirigir](../how-to/routes.md#4-elige-la-respuesta) | `Redirect::see_other("/target")` |
|
|
||||||
| [Responder JSON](../how-to/routes.md#4-elige-la-respuesta) | `Json(value)` |
|
|
||||||
| [Un error de API en JSON](../how-to/error-pages.md#7-errores-de-una-api-json) | `impl IntoResponse for ApiError` |
|
|
||||||
| [Exigir un permiso en una ruta](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `routes.route("/path", Access::Permission(&MyPermission::X), web::get(handler))` |
|
|
||||||
| [Declarar una ruta con su acceso](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `impl Endpoint for MyRoute` y `routes.endpoint(MyRoute::X, web::get(handler))` |
|
|
||||||
| [Un enlace que se oculta sin acceso](../how-to/navigation.md#enlaces-según-el-acceso) | `nav::Item::link(Lc::n("..."), MyRoute::X)`, o `MyRoute::X.to(id)` con parámetro |
|
|
||||||
| [Conceder permisos desde tu autenticación](../how-to/auth.md#2-concede-los-permisos) | `action::auth::CheckPermission::new(grant)` con `fn grant(&HttpRequest, PermissionRef, &mut bool)` |
|
|
||||||
| [Llevar al anónimo al inicio de sesión](../how-to/auth.md#3-ofrece-el-inicio-de-sesión-al-anónimo) | `action::auth::AnonymousDenied::new(offer_login)` con `fn offer_login(&HttpRequest) -> Option<Response>` |
|
|
||||||
| [Montar una página del panel](../how-to/admin.md#5-añade-una-página-con-tu-propio-contenido) | `routes.admin_route("reports/harvest", web::get(handler))` |
|
|
||||||
| [Exigir un permiso en el *handler*](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `require_permission(&request, &MyPermission::X)?` |
|
|
||||||
|
|
||||||
## Páginas
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Título](../how-to/pages.md) | `.with_title(Lc::n("..."))` |
|
|
||||||
| [Contenido en una región](../how-to/pages.md#2-reparte-el-contenido-en-regiones) | `.with_child_in(&CoreRegions::Aside, component)` |
|
|
||||||
| [Una hoja de estilos](../how-to/pages.md#4-añade-estilos-y-scripts) | `.with_assets(StyleSheet::from("/static/app.css"))` |
|
|
||||||
| [Un *script*](../how-to/pages.md#4-añade-estilos-y-scripts) | `.with_assets(JavaScript::defer("/static/app.js"))` |
|
|
||||||
| [Un aviso al usuario](../how-to/components.md#mensajes-al-usuario) | `page.push_message(MessageLevel::Info, Lc::n("..."))` |
|
|
||||||
| [Un aviso tras redirigir](../how-to/forms.md#3-recibe-y-valida-los-datos) | `Redirect::see_other(cx.route("/")).with_message(&cx, MessageLevel::Info, Lc::n("..."))` |
|
|
||||||
| [Algo en todas las páginas](../how-to/extensions.md#4-pon-componentes-en-todas-las-páginas) | `InRegion::Global(&CoreRegions::Footer).add(component)` |
|
|
||||||
|
|
||||||
## Textos
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Cargar traducciones](../how-to/localization.md) | `include_locales!(LOCALES_APP);` |
|
|
||||||
| [Texto traducido](../how-to/localization.md) | `Lc::t("key", &LOCALES_APP)` |
|
|
||||||
| [Texto literal](../how-to/localization.md) | `Lc::n("text")` |
|
|
||||||
| [Con una variable](../how-to/localization.md) | `.with_arg("name", "Ana")` |
|
|
||||||
| [Con plural](../how-to/localization.md) | `.with_number("total", 3)` |
|
|
||||||
| [Como contenido HTML](../how-to/localization.md) | `(text.using(cx))` |
|
|
||||||
| [Como atributo HTML](../how-to/localization.md) | `title=[text.lookup(cx)]` |
|
|
||||||
| [Un enlace interno](../how-to/navigation.md#enlaces-que-conservan-el-idioma) | `a href=(cx.route("/path")) { ... }` |
|
|
||||||
|
|
||||||
## Componentes
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Marcado puntual](../how-to/html.md) | `Html::with(\|cx\| html! { ... })` |
|
|
||||||
| [Agrupar](../how-to/components.md#contenedores) | `Container::new().with_child(...)` |
|
|
||||||
| [Un botón-enlace](../how-to/components.md#botones) | `Button::anchor(Lc::n("..."), "/path")` |
|
|
||||||
| [Una clase CSS](../how-to/components.md#identificadores-clases-y-estilos) | `.with_prop(PropsOp::add_classes("..."))` |
|
|
||||||
| [Una fila o columna](../how-to/layout.md) | `Flex::new().with_direction(flex::Direction::Row)` |
|
|
||||||
| [Una rejilla](../how-to/layout.md#grid-rejillas) | `Grid::new().with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))` |
|
|
||||||
| [Un menú](../how-to/navigation.md) | `Nav::new().with_item(nav::Item::link(Lc::n("..."), "/path"))` |
|
|
||||||
| [Una tabla](../how-to/tables.md) | `Table::new().with_column(...).with_row(...)` |
|
|
||||||
|
|
||||||
## HTMX
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Cargar HTMX en todas las páginas](../how-to/htmx-setup.md) | `vec![&pagetop_htmx::Htmx]` en `dependencies()` |
|
|
||||||
| [Pedir un fragmento al pulsar](../how-to/htmx-setup.md) | `button hx-get="/path" hx-target="#id" { ... }` |
|
|
||||||
| [Atributos en un componente](../how-to/htmx-setup.md#3-ponlos-en-componentes-con-with_prop) | `.with_prop(PropsOp::set(hx::POST, "/path"))` |
|
|
||||||
| [Saber si llama HTMX](../how-to/htmx-setup.md#6-una-ruta-dos-respuestas) | `request.is_htmx()` |
|
|
||||||
| [Responder un fragmento](../how-to/htmx-setup.md#4-responde-con-un-fragmento) | `HtmxResponse::new(html! { ... })` |
|
|
||||||
| [Renderizar un componente suelto](../how-to/htmx-setup.md#5-renderiza-componentes-en-un-fragmento) | `component.render(&mut Context::new(request)).await` |
|
|
||||||
| [Actualizar otra zona a la vez](../how-to/htmx-delete.md) | `.oob(html! { span id="x" hx-swap-oob="true" { ... } })` |
|
|
||||||
| [Avisar a otras partes](../how-to/htmx-responses.md#2-avisar-a-otras-partes-de-la-página) | `.trigger("event")` y `hx-trigger="event from:body"` |
|
|
||||||
| [Redirigir tras una acción](../how-to/htmx-responses.md#3-redirigir) | `HtmxResponse::empty().redirect("/path")` |
|
|
||||||
|
|
||||||
## Datos, usuarios y pruebas
|
|
||||||
|
|
||||||
| Quiero... | Código |
|
|
||||||
|---|---|
|
|
||||||
| [Aplicar migraciones](../how-to/database.md#4-aplícalas-al-arrancar) | `install_migrations!(m20261015_000001_create_plots)?` |
|
|
||||||
| [Consultar](../how-to/database.md#6-consulta-los-datos) | `plot::Entity::find().filter(..).all(dbconn()).await?` |
|
|
||||||
| [Paginar](../how-to/database.md#6-consulta-los-datos) | `paginate(plot::Entity::find(), page, 20).await?` |
|
|
||||||
| [Traer lo relacionado](../how-to/database.md#7-relaciona-tablas) | `harvest::Entity::find().find_also_related(plot::Entity)` |
|
|
||||||
| [SQL a mano](../how-to/database.md#8-escribe-sql-a-mano) | `fetch_all(&stmt).await?` / `execute("...").await?` |
|
|
||||||
| [Saber quién pide la página](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `cx.current_user()` |
|
|
||||||
| [Comprobar un permiso](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `has_permission(&request, &MyPermission::X)` |
|
|
||||||
| [Una página en el panel](../how-to/admin.md) | `action::admin::DeclareAdminPages::new(declare_pages)` |
|
|
||||||
| [Leer un ajuste del panel](../how-to/admin.md#4-lee-los-ajustes-guardados) | `pagetop_admin::settings::get_or("app.key", default).await` |
|
|
||||||
| [Enviar un correo](../how-to/mail.md#3-envía-un-correo) | `Email::new().with_to(addr).with_subject("...").with_html(markup).send().await` |
|
|
||||||
| [Un correo traducido](../how-to/mail.md#4-escribe-una-plantilla-traducida) | `Email::from_template(&template, &cx)` |
|
|
||||||
| [Probar una ruta](../how-to/testing.md) | `web::test::send_request(&app, request).await` |
|
|
||||||
| [Comprobar un correo enviado](../how-to/mail.md#comprueba) | `pagetop_mail::outbox::take_to("ana@example.com")` |
|
|
||||||
|
|
||||||
## Crear un componente
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
|
||||||
pub struct MyComponent {
|
|
||||||
/// Returns the text.
|
|
||||||
text: Lc,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Component for MyComponent {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
Ok(html! { div class="my-component" { (self.text().using(cx)) } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[builder_impl]
|
|
||||||
impl MyComponent {
|
|
||||||
/// Sets the text.
|
|
||||||
pub fn with_text(mut self, text: Lc) -> Self {
|
|
||||||
self.text = text;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Más información
|
|
||||||
|
|
||||||
- La API completa, con ejemplos, en [docs.rs/pagetop](https://docs.rs/pagetop).
|
|
||||||
- El código y los ejemplos ejecutables, en el
|
|
||||||
[repositorio oficial](https://git.cillero.es/manuelcillero/pagetop).
|
|
||||||
- Todas las opciones de configuración, en [Opciones de configuración](configuration.md).
|
|
||||||
|
|
@ -1,94 +0,0 @@
|
||||||
# Catálogo de componentes
|
|
||||||
|
|
||||||
Los componentes que trae PageTop, con sus constructores. Todos funcionan con cualquier tema, que
|
|
||||||
decide cómo se ven. Para aprender a usarlos, empieza por [Usar componentes](../how-to/components.md).
|
|
||||||
|
|
||||||
## Lo común a todos
|
|
||||||
|
|
||||||
| Método | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `with_id(id)` | Fija el `id` del elemento raíz |
|
|
||||||
| `with_prop(op)` | Añade o quita clases, atributos y estilos (`PropsOp`), o ajustes de maquetación (`FlexItem`, `GridItem`, `Margin`, `Padding`) |
|
|
||||||
| `with_*()` / `alter_*()` | Configuran el componente: los primeros al construirlo, los segundos sobre uno ya creado |
|
|
||||||
| `render(cx)` | Lo renderiza con un `Context`; dentro de una página lo hace `Page` por ti |
|
|
||||||
|
|
||||||
Los textos se pasan como [`Lc`](../how-to/localization.md), y las rutas como `Route`, que conserva
|
|
||||||
el idioma del visitante.
|
|
||||||
|
|
||||||
## Contenido
|
|
||||||
|
|
||||||
| Componente | Qué genera | Constructores |
|
|
||||||
|---|---|---|
|
|
||||||
| `Html` | Marcado puntual con `html!` | `Html::with(\|cx\| html! { ... })` |
|
|
||||||
| `Block` | Bloque con título opcional y contenido | `Block::new()` |
|
|
||||||
| `Intro` | Portada con título, eslogan, botón y contenido | `Intro::new()`, `Intro::custom()` |
|
|
||||||
| `Image` | Imagen, a su tamaño, adaptable o en miniatura | `Image::with(image::Source::plain(..))`, `responsive(..)`, `thumbnail(..)` |
|
|
||||||
| `Badge` | Etiqueta pequeña de estado | `Badge::labeled()`, `primary()`, `neutral()`, `success()`, `info()`, `warning()`, `severe()` |
|
|
||||||
| `Button` | Botón o enlace con aspecto de botón | `Button::submit()`, `reset()`, `plain()`, `anchor(label, ruta)` |
|
|
||||||
| `Messages` | Avisos acumulados en el contexto; la región de contenido ya empieza por uno | `Messages::new()`, `.with_deferred(true)` |
|
|
||||||
| `Dialog` | Ventana modal con título, cuerpo y pie | `Dialog::new()` |
|
|
||||||
| `PoweredBy` | Pie con el crédito de PageTop | `PoweredBy::new()` |
|
|
||||||
|
|
||||||
## Estructura y maquetación
|
|
||||||
|
|
||||||
| Componente | Qué genera | Constructores |
|
|
||||||
|---|---|---|
|
|
||||||
| `Container` | Agrupa componentes en una etiqueta | `Container::new()` (`<div>`), `main()`, `header()`, `footer()`, `section()`, `article()` |
|
|
||||||
| `Flex` | Filas o columnas | `Flex::new()`, `inline()`, `at(punto)`, `inline_at(punto)` |
|
|
||||||
| `Grid` | Rejillas | `Grid::new()`, `columns(..)`, `rows(..)`, `inline()`, `at(punto)`, `inline_at(punto)` |
|
|
||||||
|
|
||||||
Los ajustes de cada hijo se pasan a su `with_prop()`: `FlexItem` para `Flex`, `GridItem` para
|
|
||||||
`Grid`. Ver [Maquetar con Flex y Grid](../how-to/layout.md).
|
|
||||||
|
|
||||||
## Navegación
|
|
||||||
|
|
||||||
| Componente | Qué genera | Constructores |
|
|
||||||
|---|---|---|
|
|
||||||
| `Brand` | Logotipo y nombre del sitio | `Brand::new()` |
|
|
||||||
| `Nav` | Menú de enlaces | `Nav::new()`, con `nav::Item::link()`, `link_blank()`, `link_disabled()`, `dropdown()`, `html()`, `label()` |
|
|
||||||
| `Dropdown` | Menú desplegable | `Dropdown::new()`, con `dropdown::Item::link()`, `button()`, `header()`, `label()`, `divider()` |
|
|
||||||
| `Navbar` | Barra con marca y menús, plegable | `Navbar::simple()`, `simple_toggle()`, `simple_brand_left(..)`, `brand_left(..)`, `brand_right(..)`, con `navbar::Item::nav()`, `brand()`, `form()`, `text()` |
|
|
||||||
| `Breadcrumb` | Migas de pan | `Breadcrumb::new()`, con `breadcrumb::Crumb::new()`, `text()`, `current()` |
|
|
||||||
|
|
||||||
Ver [Añadir navegación](../how-to/navigation.md).
|
|
||||||
|
|
||||||
## Formularios
|
|
||||||
|
|
||||||
| Componente | Qué genera | Constructores |
|
|
||||||
|---|---|---|
|
|
||||||
| `Form` | El formulario | `Form::new()` |
|
|
||||||
| `form::Fieldset` | Grupo de campos con leyenda | `form::Fieldset::new()` |
|
|
||||||
| `form::input::Field` | Campos de texto | `text()`, `email()`, `url()`, `telephone()`, `search()`, `password()` |
|
|
||||||
| `form::Textarea` | Área de texto | `form::Textarea::new()` |
|
|
||||||
| `form::Number`, `form::Range` | Números y deslizadores | `new()` |
|
|
||||||
| `form::Checkbox` | Casilla o interruptor | `check()`, `switch()` |
|
|
||||||
| `form::check::Field` | Grupo de casillas | `new()`, con `form::check::Item` |
|
|
||||||
| `form::radio::Field` | Opciones excluyentes | `new()`, con `form::radio::Item` |
|
|
||||||
| `form::select::Field` | Lista desplegable | `new()`, con `form::select::Item` |
|
|
||||||
| `form::date::Field` | Fecha, hora, o las dos | `date()`, `time()`, `datetime()` |
|
|
||||||
| `form::Hidden` | Campo oculto | `form::Hidden::field(name, value)` |
|
|
||||||
| `form::SelectLanguage`, `SelectTheme`, `SelectTimezone` | Selectores de idioma, tema y zona horaria | `new()` |
|
|
||||||
|
|
||||||
Ver [Crear y procesar formularios](../how-to/forms.md).
|
|
||||||
|
|
||||||
## Datos
|
|
||||||
|
|
||||||
| Componente | Qué genera | Constructores |
|
|
||||||
|---|---|---|
|
|
||||||
| `Table` | Tabla con cabeceras ordenables | `Table::new()`, con `table::Column::new()`, `table::Row::new()`, `table::Cell::new()` y `table::SortLink::new()` |
|
|
||||||
| `Pager` | Paginador de un listado | `Pager::new()` |
|
|
||||||
|
|
||||||
Ver [Mostrar tablas ordenables y paginadas](../how-to/tables.md).
|
|
||||||
|
|
||||||
## De las extensiones
|
|
||||||
|
|
||||||
| Componente | Extensión | Qué genera |
|
|
||||||
|---|---|---|
|
|
||||||
| `LoginForm` | `pagetop-user` | Formulario de inicio de sesión |
|
|
||||||
| `AccountMenu` | `pagetop-user` | Menú de cuenta; también como función, `account_menu(cx)` |
|
|
||||||
| `UserName` | `pagetop-user` | Nombre visible de un usuario |
|
|
||||||
| `bs::Offcanvas` | `pagetop-bootsier` | Panel lateral deslizante (sólo con Bootsier) |
|
|
||||||
| `bs::Icon` | `pagetop-bootsier` | Iconos de Bootstrap Icons (sólo con Bootsier) |
|
|
||||||
|
|
||||||
Los componentes de un tema sólo funcionan con ese tema: úsalos en la aplicación, no en extensiones
|
|
||||||
que deban servir para cualquier tema.
|
|
||||||
|
|
@ -1,330 +0,0 @@
|
||||||
# Opciones de configuración
|
|
||||||
|
|
||||||
Todas las opciones que leen PageTop y sus extensiones oficiales, sección a sección. Para aprender a
|
|
||||||
usarlas, empieza por [Configurar la aplicación](../how-to/configuration.md).
|
|
||||||
|
|
||||||
## Carga y precedencia
|
|
||||||
|
|
||||||
Los archivos se leen del directorio `config/`, en este orden; cada uno sobrescribe a los anteriores
|
|
||||||
sólo en las claves que define:
|
|
||||||
|
|
||||||
| Orden | Archivo | Uso habitual |
|
|
||||||
|---|---|---|
|
|
||||||
| 1 | `config/common.toml` | Ajustes comunes a todos los entornos |
|
|
||||||
| 2 | `config/{modo}.toml` | Ajustes del modo de ejecución |
|
|
||||||
| 3 | `config/local.{modo}.toml` | Ajustes locales de ese modo (no se versiona) |
|
|
||||||
| 4 | `config/local.toml` | Ajustes locales para cualquier modo (no se versiona) |
|
|
||||||
|
|
||||||
Todos son opcionales. Dos variables de entorno eligen qué archivos se cargan:
|
|
||||||
|
|
||||||
| Variable | Efecto |
|
|
||||||
|---|---|
|
|
||||||
| `PAGETOP_RUN_MODE` | El modo de ejecución, `{modo}` en la tabla anterior. Por defecto, `default` |
|
|
||||||
| `CONFIG_DIR` | Otro directorio de configuración en lugar de `config/` |
|
|
||||||
|
|
||||||
Por último, las variables `PAGETOP_<SECCIÓN>__<CLAVE>` sobrescriben cualquier clave de los
|
|
||||||
archivos. La sección y la clave van en mayúsculas, con cada nivel separado por dos guiones bajos:
|
|
||||||
|
|
||||||
| Variable | Clave |
|
|
||||||
|---|---|
|
|
||||||
| `PAGETOP_SERVER__BIND_PORT=80` | `bind_port` de `[server]` |
|
|
||||||
| `PAGETOP_DATABASE__DB_PASS=secret` | `db_pass` de `[database]` |
|
|
||||||
| `PAGETOP_MAIL__SMTP__PASSWORD=secret` | `password` de `[mail.smtp]` |
|
|
||||||
|
|
||||||
- El valor se escribe sin comillas: los números en decimal (`80`) y los booleanos como `true` o
|
|
||||||
`false`.
|
|
||||||
- Una variable vacía equivale a no definirla, así que no sirve para vaciar un valor de los archivos.
|
|
||||||
- No sirven para listas ni para claves con punto, como la del trabajo `mail.queue` en
|
|
||||||
`[cron.jobs."mail.queue"]`. Un trabajo sin punto en la clave sí:
|
|
||||||
`PAGETOP_CRON__JOBS__CLEANUP__ENABLED=false`.
|
|
||||||
- Con la *feature* `testing` se ignoran, para que no cambien el resultado de las pruebas.
|
|
||||||
- Al arrancar, las trazas indican qué claves vienen del entorno (nunca sus valores).
|
|
||||||
|
|
||||||
Reglas comunes a todas las secciones:
|
|
||||||
|
|
||||||
- Una **clave desconocida** o un **valor no válido** impiden arrancar, con un mensaje que indica la
|
|
||||||
sección y la clave. También si vienen de una variable de entorno: el mensaje nombra entonces las
|
|
||||||
variables de esa sección.
|
|
||||||
- Una **sección** que no corresponde a PageTop ni a ninguna extensión habilitada se ignora, con un
|
|
||||||
aviso al arrancar.
|
|
||||||
- En los valores fijos del núcleo (`"Full"`, `"Daily"`...) da igual escribir mayúsculas o
|
|
||||||
minúsculas.
|
|
||||||
|
|
||||||
## `[app]`
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[app]
|
|
||||||
name = "Urban Garden"
|
|
||||||
theme = "Bootsier"
|
|
||||||
language = "es-ES"
|
|
||||||
lang_negotiation = "Full"
|
|
||||||
timezone = "Europe/Madrid"
|
|
||||||
startup_banner = "Slant"
|
|
||||||
```
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `name` | Texto | `"PageTop App"` | Nombre de la aplicación: título de las páginas, pie, banner |
|
|
||||||
| `theme` | Texto | `"Basic"` | Tema predeterminado. Si no está habilitado, se usa `"Basic"` y se avisa |
|
|
||||||
| `language` | Texto | Ninguno | Idioma predeterminado, en BCP 47 (`"es-ES"`). Sin él, se negocia |
|
|
||||||
| `lang_negotiation` | `Full`, `NoQuery`, `ConfigOnly` | `"Full"` | Cómo se decide el idioma de cada petición (ver abajo) |
|
|
||||||
| `timezone` | Texto | `"UTC"` | Zona horaria del sitio, en formato IANA (`"Europe/Madrid"`) |
|
|
||||||
| `timezone_regions` | Texto | `""` (todas) | Regiones ofrecidas al elegir zona horaria, separadas por comas (`"Europe, America"`) |
|
|
||||||
| `timezone_order` | `Nearest`, `Alphabetical`, `Listed` | `"Nearest"` | Orden de esas regiones en el selector |
|
|
||||||
| `timezone_per_user` | Booleano | `true` | Si cada usuario puede tener su propia zona horaria |
|
|
||||||
| `admin_path` | Texto | `"/admin"` | Raíz del panel de administración: empieza por `/`, sin `/` final; una no válida impide arrancar |
|
|
||||||
| `startup_banner` | `Off`, `Slant`, `Small`, `Speed`, `Starwars` | `"Slant"` | Banner al arrancar |
|
|
||||||
|
|
||||||
`lang_negotiation`:
|
|
||||||
|
|
||||||
| Valor | El idioma de cada petición sale de... |
|
|
||||||
|---|---|
|
|
||||||
| `Full` | `?lang=` de la URL, idioma del usuario, `language`, `Accept-Language` y respaldo (`en-US`) |
|
|
||||||
| `NoQuery` | Lo mismo, sin `?lang=` |
|
|
||||||
| `ConfigOnly` | Sólo `language` o el idioma de respaldo. No se ofrece elegir idioma |
|
|
||||||
|
|
||||||
## `[server]`
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[server]
|
|
||||||
bind_address = "0.0.0.0"
|
|
||||||
bind_port = 8080
|
|
||||||
```
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `bind_address` | Texto | `"localhost"` | Dirección en la que escucha. `"0.0.0.0"` acepta conexiones de fuera |
|
|
||||||
| `bind_port` | Entero | `8080` | Puerto |
|
|
||||||
| `max_body_size` | Entero | `2097152` | Tamaño máximo en bytes (2 MiB) de los cuerpos que se leen enteros en memoria (`web::Form`, JSON) y de la suma de los campos de texto de un formulario con archivos; `0`, sin límite. Un cuerpo mayor se rechaza con `413`; en un formulario con archivos, `receive()` devuelve un error del usuario |
|
|
||||||
| `client_ip_header` | Texto | `""` | Cabecera con la IP del cliente detrás de un proxy inverso (`"X-Forwarded-For"`, `"X-Real-IP"`...); con varias direcciones vale la última; `"Forwarded"` no se admite. Vacía, la de la conexión. Un nombre no válido impide arrancar. Ver [Detrás de un proxy inverso](../how-to/deployment.md#5-detrás-de-un-proxy-inverso) |
|
|
||||||
| `trusted_origins` | Lista | `[]` | Orígenes de otras aplicaciones (`"https://shop.example.com"`) desde los que un navegador puede enviar peticiones que cambian estado (`POST`, `PUT`...); las demás que lleguen de otro origen se rechazan con `403` (protección CSRF). Formato `esquema://servidor[:puerto]`; uno no válido impide arrancar. Ver [Sin *tokens* contra CSRF](../how-to/forms.md#6-sin-tokens-contra-csrf) |
|
|
||||||
|
|
||||||
## `[upload]`
|
|
||||||
|
|
||||||
Archivos subidos con `web::Upload` (ver [Subir y descargar archivos](../how-to/uploads.md)).
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `dir` | Texto | `"uploads"` | Directorio de los archivos subidos, absoluto o relativo al de trabajo. Se crea al guardar el primer archivo |
|
|
||||||
| `max_file_size` | Entero | `8388608` | Tamaño máximo en bytes (8 MiB) de cada archivo; `0`, sólo limita `max_request_size`. Cada subida puede cambiarlo con `with_max_size()` |
|
|
||||||
| `max_files` | Entero | `20` | Archivos de un mismo envío; `0`, sin límite. Cada subida puede cambiarlo con `with_max_files()` |
|
|
||||||
| `max_request_size` | Entero | `33554432` | Tamaño máximo en bytes (32 MiB) de una petición `multipart/form-data` completa, en lugar de `max_body_size` de `[server]`; `0`, sin límite. Si se supera, `receive()` devuelve un error del usuario con el límite |
|
|
||||||
|
|
||||||
## `[log]`
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[log]
|
|
||||||
tracing = "Info,sqlx=Warn"
|
|
||||||
rolling = "Daily"
|
|
||||||
format = "Json"
|
|
||||||
```
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `enabled` | Booleano | `true` | Activa o desactiva las trazas |
|
|
||||||
| `tracing` | Texto | `"Info"` | Nivel (`Error`, `Warn`, `Info`, `Debug`, `Trace`) y niveles por módulo. Si no es válido, se usa `"Info"` y se avisa |
|
|
||||||
| `rolling` | `Stdout`, `Daily`, `Hourly`, `Minutely`, `Endless` | `"Stdout"` | Terminal, archivos con rotación o un único archivo |
|
|
||||||
| `path` | Texto | `"log"` | Directorio de los archivos de traza |
|
|
||||||
| `prefix` | Texto | `"tracing.log"` | Prefijo de esos archivos |
|
|
||||||
| `format` | `Full`, `Compact`, `Pretty`, `Json` | `"Full"` | Formato de cada traza |
|
|
||||||
|
|
||||||
## `[dev]`
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `pagetop_static_dir` | Texto | `""` | Directorio `static/` de PageTop para servir sus archivos desde disco, editables sin recompilar. Vacío: los del binario |
|
|
||||||
|
|
||||||
## `[database]`
|
|
||||||
|
|
||||||
De [`pagetop-seaorm`](extensions.md#seaorm). Ver [Conectar una base de
|
|
||||||
datos](../how-to/database.md).
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[database]
|
|
||||||
db_type = "postgres"
|
|
||||||
db_name = "garden"
|
|
||||||
db_user = "garden"
|
|
||||||
db_host = "localhost"
|
|
||||||
```
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `db_type` | `mysql`, `postgres`, `sqlite` | Ninguno | **Obligatorio.** También valen `mariadb` y `postgresql` |
|
|
||||||
| `db_name` | Texto | `""` | Nombre de la base de datos; en SQLite, el archivo (admite parámetros como `?mode=rwc`) |
|
|
||||||
| `db_user` | Texto | `""` | Usuario (MySQL y PostgreSQL) |
|
|
||||||
| `db_pass` | Texto | `""` | Contraseña (MySQL y PostgreSQL). Mejor en `local.toml` |
|
|
||||||
| `db_host` | Texto | `"localhost"` | Servidor (MySQL y PostgreSQL) |
|
|
||||||
| `db_port` | Entero | 3306 / 5432 | Puerto, si no es el del motor |
|
|
||||||
| `max_pool_size` | Entero | `5` | Conexiones simultáneas como máximo |
|
|
||||||
|
|
||||||
## `[mail]`
|
|
||||||
|
|
||||||
De [`pagetop-mail`](extensions.md#correo). Sin configurar, los correos se escriben en las trazas en
|
|
||||||
lugar de enviarse, así que una aplicación en desarrollo nunca envía correo real por error.
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[mail]
|
|
||||||
transport = "smtp"
|
|
||||||
from = "Garden board <no-reply@example.com>"
|
|
||||||
base_url = "https://board.example.com"
|
|
||||||
|
|
||||||
[mail.smtp]
|
|
||||||
host = "smtp.example.com"
|
|
||||||
username = "no-reply@example.com"
|
|
||||||
password = "secret" # Better in config/local.toml.
|
|
||||||
```
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `transport` | `smtp`, `sendmail`, `file`, `log`, `memory` | `log` | Cómo se entregan: servidor SMTP, programa *sendmail*, un `.eml` por correo, en las trazas, o en memoria (pruebas) |
|
|
||||||
| `from` | Texto | Ninguno | Remitente por defecto, con o sin nombre. Necesario para enviar los correos de `pagetop-user` |
|
|
||||||
| `reply_to` | Texto | Ninguno | Dirección de respuesta por defecto |
|
|
||||||
| `redirect_to` | Texto | Ninguno | Entrega todos los correos sólo a esta dirección (entornos de pruebas) |
|
|
||||||
| `base_url` | Texto | `http://{bind_address}:{bind_port}` | URL pública para los enlaces de los correos. **Indícala en producción** |
|
|
||||||
| `previews` | Booleano | `false` | Vistas previas de los correos en `/mail/preview`. Sólo en desarrollo |
|
|
||||||
| `delivery_timeout_secs` | Entero | `300` | Tiempo máximo de cada entrega completa, incluida la espera de su turno (1 a 86400). Se recomienda el valor por defecto |
|
|
||||||
| `max_waiting` | Entero | `100` | Correos que pueden esperar turno por cada envío simultáneo; con más, la entrega falla enseguida en lugar de acumularlos en memoria. No se recomiendan valores mayores |
|
|
||||||
|
|
||||||
### `[mail.smtp]`
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `host` | Texto | `"localhost"` | Servidor SMTP |
|
|
||||||
| `port` | Entero | Según `security` | 465 con `tls`, 587 con `starttls` y 25 con los demás |
|
|
||||||
| `security` | `none`, `opportunistic`, `starttls`, `tls` | `starttls` | Cifrado de la conexión |
|
|
||||||
| `username`, `password` | Texto | Ninguno | Credenciales. Sin usuario, no se autentica |
|
|
||||||
| `hello_name` | Texto | Nombre del equipo | Nombre para `EHLO` |
|
|
||||||
| `timeout_secs` | Entero | `60` | Espera máxima de cada orden al servidor |
|
|
||||||
| `pool_max_size` | Entero | `10` | Conexiones abiertas como máximo, reutilizadas entre envíos |
|
|
||||||
| `accept_invalid_certs` | Booleano | `false` | Acepta certificados no válidos. **Sólo para pruebas** |
|
|
||||||
|
|
||||||
Con `transport = "sendmail"`, `[mail.sendmail] command` indica el programa (por defecto,
|
|
||||||
`sendmail` del `PATH`); con `transport = "file"`, `[mail.file] dir` el directorio de los `.eml`
|
|
||||||
(por defecto, `"mail"`). En las dos subsecciones, `max_concurrent` (por defecto, `10`) limita los
|
|
||||||
correos que se entregan a la vez; no se recomiendan valores mayores.
|
|
||||||
|
|
||||||
### `[mail.queue]`
|
|
||||||
|
|
||||||
Sólo con la *feature* `queue` de `pagetop-mail`, que guarda los correos en la base de datos y
|
|
||||||
reintenta los que fallan. La envía el trabajo `mail.queue` de `pagetop-cron`, un minuto después de
|
|
||||||
terminar la ejecución anterior; su ritmo se cambia en `[cron.jobs."mail.queue"]`.
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `batch_size` | Entero | `50` | Correos que envía cada ejecución del trabajo, uno tras otro |
|
|
||||||
| `max_attempts` | Entero | `5` | Intentos de cada correo, contando el primero; agotados, o ante un rechazo definitivo del servidor (SMTP 5xx), queda como fallido |
|
|
||||||
| `retry_base_secs` | Entero | `60` | Espera tras el primer fallo temporal; se duplica en cada intento |
|
|
||||||
| `max_retry_secs` | Entero | `86400` | Espera máxima entre dos intentos (1 a un año) |
|
|
||||||
| `keep_failed_days` | Entero | `30` | Días que se conservan los correos fallidos; `0`, siempre. Los enviados se borran al entregarse |
|
|
||||||
|
|
||||||
## `[cron]`
|
|
||||||
|
|
||||||
De [`pagetop-cron`](extensions.md#tareas-programadas). Decide cómo se ejecutan los trabajos
|
|
||||||
programados y permite ajustar cada uno por su clave.
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[cron]
|
|
||||||
mode = "internal"
|
|
||||||
|
|
||||||
[cron.jobs."garden.water"]
|
|
||||||
schedule = "0 7 * * *"
|
|
||||||
timeout_secs = 600
|
|
||||||
```
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `mode` | `internal`, `external`, `off` | `internal` | Quién ejecuta los trabajos: la propia aplicación, una llamada externa a `POST /cron`, o nadie (sólo bajo demanda) |
|
|
||||||
| `trigger_token` | Texto | Ninguno | Clave secreta del modo `external`, en la cabecera `Authorization: Bearer <clave>`: 16 o más letras, dígitos, `-` o `_`. Obligatoria en ese modo |
|
|
||||||
| `trigger_interval_secs` | Entero | `60` | Cada cuántos segundos llama el programa externo en el modo `external`; cada llamada ejecuta lo programado en el último intervalo |
|
|
||||||
| `shutdown_timeout_secs` | Entero | `30` | Espera máxima, al detener la aplicación, a que terminen los trabajos en curso |
|
|
||||||
|
|
||||||
Con varias instancias de la aplicación, usa `internal` en una sola y `off` en las demás, o
|
|
||||||
`external` en todas (ve [Con varias instancias, elige el
|
|
||||||
modo](../how-to/cron.md#6-con-varias-instancias-elige-el-modo)).
|
|
||||||
|
|
||||||
### `[cron.jobs."clave"]`
|
|
||||||
|
|
||||||
Ajustes de un trabajo, por su clave (entre comillas, porque suele llevar un punto). Lo que no se
|
|
||||||
indica mantiene lo declarado en el código; una clave que no corresponde a ningún trabajo sólo
|
|
||||||
produce un aviso.
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `enabled` | Booleano | `true` | Con `false`, el trabajo sólo se ejecuta bajo demanda |
|
|
||||||
| `schedule` | Texto | La del código | Expresión cron, `"@daily"`, `"@every 10m"` (cada 10 min desde que empieza) o `"@delay 30s"` (30 s después de terminar) |
|
|
||||||
| `timeout_secs` | Entero | El del código | Tiempo máximo de cada ejecución; `0` quita el límite |
|
|
||||||
|
|
||||||
## `[user]`
|
|
||||||
|
|
||||||
De [`pagetop-user`](extensions.md#usuarios-y-permisos). Ver [Añadir usuarios y
|
|
||||||
permisos](../how-to/users.md).
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `allow_registration` | Booleano | `true` | Los visitantes pueden crear su propia cuenta |
|
|
||||||
| `require_email_verification` | Booleano | `false` | Las cuentas nuevas quedan pendientes hasta confirmar su dirección desde el enlace del correo de verificación que reciben al registrarse |
|
|
||||||
| `identity_policy` | Texto | `"strict"` | Nombres de usuario que se aceptan: `"strict"`, `"unicode"` o `"permissive"`. Ver [Elige qué nombres de usuario se aceptan](../how-to/users.md#elige-qué-nombres-de-usuario-se-aceptan) |
|
|
||||||
| `max_failed_logins` | Entero | `5` | Intentos fallidos seguidos que bloquean la cuenta, también los de la contraseña actual al cambiar la contraseña o el email; `0`, nunca |
|
|
||||||
| `failed_login_window_secs` | Entero | `900` | Segundos desde el último fallo en los que el siguiente se suma al recuento |
|
|
||||||
| `locked_for_secs` | Entero | `600` | Segundos que dura el bloqueo |
|
|
||||||
| `max_password_resets` | Entero | `3` | Máximo de solicitudes de recuperación de contraseña de una misma cuenta en un periodo de `password_reset_window_secs` segundos; las siguientes no envían correo; `0`, sin límite |
|
|
||||||
| `password_reset_window_secs` | Entero | `3600` | Duración del periodo |
|
|
||||||
| `max_email_changes` | Entero | `3` | Máximo de cambios de email que puede pedir una misma cuenta en un periodo de `email_change_window_secs` segundos; `0`, sin límite |
|
|
||||||
| `email_change_window_secs` | Entero | `3600` | Duración del periodo |
|
|
||||||
| `max_ip_requests` | Entero | `20` | Máximo de registros, recuperaciones de contraseña y cambios de email desde una misma IP en un periodo de `ip_request_window_secs` segundos; `0`, sin límite. Tras un proxy inverso requiere `client_ip_header` de `[server]` |
|
|
||||||
| `ip_request_window_secs` | Entero | `3600` | Duración del periodo |
|
|
||||||
| `max_ip_failed_logins` | Entero | `30` | Máximo de inicios de sesión fallidos desde una misma IP en un periodo de `ip_failed_login_window_secs` segundos; los siguientes se rechazan sin comprobar la contraseña. Frena probar unas pocas contraseñas en muchas cuentas. `0`, sin límite. Tras un proxy inverso requiere `client_ip_header` de `[server]` |
|
|
||||||
| `ip_failed_login_window_secs` | Entero | `900` | Duración del periodo |
|
|
||||||
| `login_strict` | Booleano | `false` | Dificulta que el navegador recuerde las credenciales |
|
|
||||||
|
|
||||||
### `[user.session]`
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `cookie_name` | Texto | `"pagetop"` | Nombre de la *cookie* de sesión |
|
|
||||||
| `secure_cookie` | Booleano | `false` | Sólo por HTTPS. **Actívalo en producción** |
|
|
||||||
| `idle_secs` | Entero | `7200` | Inactividad tras la que caduca la sesión (2 horas) |
|
|
||||||
| `remember_idle_secs` | Entero | `1209600` | Lo mismo, si se marcó «recordarme» (14 días) |
|
|
||||||
| `write_interval_secs` | Entero | `60` | Mínimo entre dos escrituras de la misma sesión para prorrogarla |
|
|
||||||
|
|
||||||
### `[user.password]`
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `argon2_m_cost` | Entero | `19456` | Memoria de Argon2id, en KiB |
|
|
||||||
| `argon2_t_cost` | Entero | `2` | Iteraciones |
|
|
||||||
| `argon2_p_cost` | Entero | `1` | Hilos |
|
|
||||||
| `min_length` | Entero | `8` | Longitud mínima de una contraseña, en caracteres |
|
|
||||||
|
|
||||||
Si cambia cualquiera de los tres costes, cada contraseña se vuelve a cifrar con los nuevos en el
|
|
||||||
siguiente acceso de su usuario.
|
|
||||||
|
|
||||||
### `[user.seed]`
|
|
||||||
|
|
||||||
El primer administrador, que se crea si no existe ningún usuario.
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `admin_username` | Texto | `"admin"` | Nombre de usuario. Si no cumple `identity_policy`, la aplicación no arranca |
|
|
||||||
| `admin_email` | Texto | `"admin@example.com"` | Correo. Si no es válido, la aplicación no arranca |
|
|
||||||
| `admin_password` | Texto | Ninguno | Sin valor, se genera una y se muestra una sola vez en el terminal |
|
|
||||||
|
|
||||||
### `[user.admin]`
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `list_page_size` | Entero | `20` | Filas por página en los listados de administración |
|
|
||||||
|
|
||||||
## `[bootsier]`
|
|
||||||
|
|
||||||
De [`pagetop-bootsier`](extensions.md#bootsier).
|
|
||||||
|
|
||||||
| Clave | Tipo | Por defecto | Notas |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `max_width` | Texto | `"1440px"` | Ancho máximo de la página (`"100%"`, `"90rem"`...) |
|
|
||||||
| `static_dir` | Texto | `""` | Como `pagetop_static_dir`, para los archivos de Bootsier |
|
|
||||||
|
|
||||||
## El archivo de referencia
|
|
||||||
|
|
||||||
El repositorio de PageTop incluye `config/reference.toml`, con todas estas opciones comentadas y su
|
|
||||||
valor por defecto. No se carga nunca: sirve para copiar de él lo que necesites.
|
|
||||||
|
|
@ -1,307 +0,0 @@
|
||||||
# Extensiones oficiales
|
|
||||||
|
|
||||||
PageTop mantiene un núcleo pequeño. Lo demás llega como extensiones que se suman a tu aplicación
|
|
||||||
con una línea en `dependencies()`.
|
|
||||||
|
|
||||||
| Extensión | Qué aporta | Basada en |
|
|
||||||
|---|---|---|
|
|
||||||
| [`pagetop-bootsier`](#bootsier) | Tema completo para cualquier aplicación | [Bootstrap 5](https://getbootstrap.com) |
|
|
||||||
| [`pagetop-htmx`](#htmx) | Interactividad sin escribir JavaScript | [HTMX 2](https://htmx.org) |
|
|
||||||
| [`pagetop-seaorm`](#seaorm) | Bases de datos PostgreSQL, MySQL y SQLite | [SeaORM](https://www.sea-ql.org/SeaORM) |
|
|
||||||
| [`pagetop-mail`](#correo) | Envío de correo con plantillas, HTML y adjuntos | [lettre](https://lettre.rs) |
|
|
||||||
| [`pagetop-cron`](#tareas-programadas) | Tareas periódicas con expresiones cron o intervalos | [croner](https://github.com/hexagon/croner-rust) |
|
|
||||||
| [`pagetop-user`](#usuarios-y-permisos) | Usuarios, sesiones, roles y permisos | [Argon2](https://docs.rs/argon2) para las contraseñas |
|
|
||||||
| [`pagetop-admin`](#administración) | Páginas de ajustes del panel, guardados en la base de datos | [SeaORM](https://www.sea-ql.org/SeaORM) |
|
|
||||||
| [`pagetop-aliner`](../how-to/themes.md) | Tema de pruebas que muestra la estructura de la página | Componentes del núcleo |
|
|
||||||
| [`pagetop-mdbook`](#documentación-con-mdbook) | Libros de mdBook servidos como páginas PageTop | [mdBook](https://rust-lang.github.io/mdBook/) |
|
|
||||||
|
|
||||||
## Dependencias y *features*
|
|
||||||
|
|
||||||
Todas se añaden igual al `Cargo.toml`, y casi ninguna tiene *features*:
|
|
||||||
|
|
||||||
| *Crate* | *Features* | Dónde se activan |
|
|
||||||
|---|---|---|
|
|
||||||
| `pagetop-seaorm` | `postgres`, `mysql`, `sqlite`: el motor de base de datos | Sólo en la **aplicación**; vale para todas sus extensiones (ve [Elige el motor](../how-to/database.md#1-elige-el-motor)) |
|
|
||||||
| `pagetop-user` | `demo-data`: siembra roles y usuarios ficticios para explorar la administración | En la aplicación, sólo para desarrollo o demostraciones |
|
|
||||||
| El resto | Ninguna | |
|
|
||||||
|
|
||||||
## Bootsier
|
|
||||||
|
|
||||||
Tema completo sobre [Bootstrap 5.3](https://getbootstrap.com): adapta los componentes del núcleo
|
|
||||||
a Bootstrap y añade los suyos (como `Offcanvas`) y un selector de modo claro/oscuro.
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[app]
|
|
||||||
theme = "Bootsier"
|
|
||||||
|
|
||||||
[bootsier]
|
|
||||||
max_width = "90rem" # Maximum width of the content.
|
|
||||||
```
|
|
||||||
|
|
||||||
Recuerda declarar `&pagetop_bootsier::Bootsier` como dependencia de tu aplicación. Más en [Crear un
|
|
||||||
tema](../how-to/themes.md).
|
|
||||||
|
|
||||||
## HTMX
|
|
||||||
|
|
||||||
Con `pagetop-htmx`, todas las páginas incluyen [HTMX 2](https://htmx.org): basta con añadir
|
|
||||||
atributos `hx-*` para que un enlace o un formulario actualice sólo una parte de la página.
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct Clock;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Clock {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/time", web::get(time))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(|_| html! {
|
|
||||||
button hx-get="/time" hx-target="#result" { "What time is it?" }
|
|
||||||
div id="result" {}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns only the HTML fragment that HTMX places in #result.
|
|
||||||
async fn time() -> Markup {
|
|
||||||
html! { p { "It is " (Utc::now().format("%H:%M")) " UTC" } }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
También ofrece constantes para los atributos (`hx::GET`, `hx::TARGET`...), que se aplican a
|
|
||||||
cualquier componente con `with_prop()`, y ayudas para leer y responder a peticiones HTMX. Diez
|
|
||||||
guías prácticas, empezando por [Añadir HTMX a una aplicación](../how-to/htmx-setup.md), y la
|
|
||||||
[referencia](htmx.md) lo cuentan todo.
|
|
||||||
|
|
||||||
## SeaORM
|
|
||||||
|
|
||||||
Conecta tu aplicación a una base de datos con [SeaORM](https://www.sea-ql.org/SeaORM) y aplica las
|
|
||||||
migraciones al arrancar. Elige el motor con una *feature* en tu `Cargo.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[features]
|
|
||||||
default = ["postgres"]
|
|
||||||
postgres = ["pagetop-seaorm/postgres"]
|
|
||||||
mysql = ["pagetop-seaorm/mysql"]
|
|
||||||
sqlite = ["pagetop-seaorm/sqlite"]
|
|
||||||
```
|
|
||||||
|
|
||||||
Configura la conexión (la contraseña, mejor en `config/local.toml`):
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[database]
|
|
||||||
db_type = "postgres"
|
|
||||||
db_name = "garden"
|
|
||||||
db_user = "garden"
|
|
||||||
db_pass = "secret"
|
|
||||||
db_host = "localhost"
|
|
||||||
```
|
|
||||||
|
|
||||||
Y declara la extensión, instalando tus migraciones en `initialize()`:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_seaorm::install_migrations;
|
|
||||||
|
|
||||||
mod migration;
|
|
||||||
|
|
||||||
struct MyApp;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for MyApp {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_seaorm::SeaORM]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
install_migrations!(m20240101_000001_create_users)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si la base de datos no responde o una migración falla, la aplicación no arranca y lo explica. Más
|
|
||||||
en [Conectar una base de datos](../how-to/database.md).
|
|
||||||
|
|
||||||
## Correo
|
|
||||||
|
|
||||||
`pagetop-mail` envía correos en texto y HTML, con adjuntos, por SMTP, con *sendmail* o a archivos
|
|
||||||
`.eml`, según la sección [`[mail]`](configuration.md#mail). Sin configurar, los escribe en las
|
|
||||||
trazas. Un correo se compone con `Email`, o con una plantilla (`MailTemplate`) que traduce sus
|
|
||||||
textos al idioma del destinatario:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_mail::prelude::*;
|
|
||||||
|
|
||||||
async fn notify() -> Result<(), MailError> {
|
|
||||||
Email::new()
|
|
||||||
.with_to("Ana Pérez <ana@example.com>")
|
|
||||||
.with_subject("Your order has shipped")
|
|
||||||
.with_html(html! { p { "Order " strong { "1234" } " left today." } })
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`send()` espera a la entrega; `send_later()` envía en segundo plano y registra los fallos en las
|
|
||||||
trazas. Con la *feature* `queue`, `send_later()` guarda antes el correo en una cola en la base de
|
|
||||||
datos (con `pagetop-seaorm`), que sobrevive a un reinicio y reintenta los fallos temporales, y
|
|
||||||
`queue()` lo deja en la cola para enviarlo por lotes con `pagetop-cron` (ver
|
|
||||||
[`[mail.queue]`](configuration.md#mailqueue)). Los enlaces de un correo se construyen con
|
|
||||||
`absolute_url()`, sobre `mail.base_url`. En el panel de administración, la página
|
|
||||||
**Configuración > Correo electrónico** muestra la configuración y envía un correo de prueba (permiso
|
|
||||||
`mail:send_test`). Paso a paso en [Enviar correo electrónico](../how-to/mail.md).
|
|
||||||
|
|
||||||
## Tareas programadas
|
|
||||||
|
|
||||||
`pagetop-cron` ejecuta trabajos en segundo plano mientras la aplicación está en marcha, según una
|
|
||||||
expresión cron o a intervalos. Cada extensión los declara con la acción `DeclareCronJobs`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_cron::prelude::*;
|
|
||||||
|
|
||||||
async fn purge_old_tasks(_cx: JobContext) -> JobResult {
|
|
||||||
// Deletes the tasks completed more than a year ago...
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare_jobs(jobs: &mut CronJobs) {
|
|
||||||
jobs.add(Job::new("garden.purge", Schedule::cron("0 3 * * SUN"), purge_old_tasks));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Garden;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Garden {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_cron::Cron]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![DeclareCronJobs::new(declare_jobs)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
La sección [`[cron]`](configuration.md#cron) elige si los ejecuta la propia aplicación, una llamada
|
|
||||||
externa (para varias instancias) o nadie, y permite cambiar o desactivar cada trabajo por su clave.
|
|
||||||
`pagetop_cron::run_now()` ejecuta un trabajo bajo demanda, también en las pruebas, donde el
|
|
||||||
planificador no arranca. Paso a paso en [Programar tareas periódicas](../how-to/cron.md).
|
|
||||||
|
|
||||||
## Usuarios y permisos
|
|
||||||
|
|
||||||
`pagetop-user` aporta inicio de sesión, perfiles, sesiones guardadas en la base de datos,
|
|
||||||
contraseñas con Argon2 y control de acceso por roles (RBAC), con su interfaz de administración. Se
|
|
||||||
apoya en `pagetop-seaorm`, y en `pagetop-mail` para los correos de recuperación de contraseña y de
|
|
||||||
verificación de las cuentas nuevas.
|
|
||||||
|
|
||||||
Frena los ataques a las cuentas sin configurar nada: bloquea una cuenta tras varios intentos
|
|
||||||
fallidos y limita por dirección IP los inicios de sesión fallidos y las solicitudes que envían
|
|
||||||
correo (registros, recuperaciones de contraseña, cambios de email). Detrás de un proxy inverso,
|
|
||||||
los límites por IP necesitan `client_ip_header` de `[server]`. Tras sus acciones (cuenta creada,
|
|
||||||
contraseña cambiada...) deja un aviso para la página siguiente.
|
|
||||||
|
|
||||||
El núcleo de PageTop define cómo se **expresa** un permiso; la extensión decide quién lo tiene:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum BlogPermission {
|
|
||||||
Publish,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permission for BlogPermission {
|
|
||||||
fn key(&self) -> CowStr {
|
|
||||||
match self {
|
|
||||||
Self::Publish => "blog:publish".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn new_post(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request).with_title(Lc::n("New post")).render().await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Blog;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Blog {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
// Without the permission, a 403; without a session, pagetop-user offers to sign in first.
|
|
||||||
routes.route(
|
|
||||||
"/posts/new",
|
|
||||||
Access::Permission(&BlogPermission::Publish),
|
|
||||||
web::get(new_post),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Dentro de cualquier componente, `cx.current_user()` indica quién hace la petición:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# fn f() -> Html {
|
|
||||||
Html::with(|cx| {
|
|
||||||
let user = cx.current_user();
|
|
||||||
html! {
|
|
||||||
@if user.is_authenticated() {
|
|
||||||
p { "Welcome back." }
|
|
||||||
} @else {
|
|
||||||
a href=(cx.route("/user/login")) { "Sign in" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
La extensión declara sus permisos con la acción `DeclarePermissions` de PageTop; con `pagetop-user`
|
|
||||||
activo, aparecen en la pantalla de roles y se pueden asignar. Paso a paso en [Añadir usuarios y
|
|
||||||
permisos](../how-to/users.md).
|
|
||||||
|
|
||||||
`pagetop-user` es una extensión de autenticación más: cualquier otra se conecta igual, con un
|
|
||||||
*middleware* que deja el `CurrentUser` en la petición y las acciones `CheckPermission` (concede los
|
|
||||||
permisos) y `AnonymousDenied` (qué responder a un anónimo sin acceso). Paso a paso en [Conectar tu
|
|
||||||
propia autenticación](../how-to/auth.md).
|
|
||||||
|
|
||||||
## Administración
|
|
||||||
|
|
||||||
El panel de administración es de PageTop. Las extensiones declaran sus secciones y páginas con
|
|
||||||
acciones, con rutas relativas a su raíz (`/admin` por defecto, ajuste `admin_path` de `[app]`);
|
|
||||||
`pagetop-user` declara, por ejemplo, la gestión de usuarios y roles. Si hay alguna página, PageTop
|
|
||||||
monta la página de inicio del panel y la de cada sección, y la plantilla de administración pinta la
|
|
||||||
navegación, las migas y el título con los componentes del núcleo (funciona con cualquier tema).
|
|
||||||
`pagetop-admin` añade los formularios de ajustes que se guardan en la base de datos. Paso a paso en
|
|
||||||
[Añadir páginas al panel de administración](../how-to/admin.md).
|
|
||||||
|
|
||||||
| Pieza | Qué hace |
|
|
||||||
|---|---|
|
|
||||||
| `DeclareAdminSections` | Acción de PageTop para añadir secciones al panel |
|
|
||||||
| `DeclareAdminPages` | Acción de PageTop para añadir páginas a una sección, cada una con su permiso |
|
|
||||||
| `DeclareAdminTasks`, `DeclareAdminActions` | Acciones de PageTop para añadir pestañas y botones a una página |
|
|
||||||
| `routes.admin_route()` | Monta una ruta del panel, relativa a su raíz, con el permiso de su página |
|
|
||||||
| `admin_path()` | Ruta completa de una ruta relativa a la raíz del panel, para enlazar |
|
|
||||||
| `DeclareConfigForms` | Página de ajustes que `pagetop-admin` pinta y guarda por sí solo |
|
|
||||||
| `Page::admin()` | Página del panel: la plantilla de administración añade la navegación, las migas, el título, las pestañas y los botones |
|
|
||||||
| `settings::get_or()` | Lee un ajuste guardado (`<ámbito>.<campo>`) |
|
|
||||||
|
|
||||||
## Documentación con mdBook
|
|
||||||
|
|
||||||
[`pagetop-mdbook`](https://git.cillero.es/manuelcillero/pagetop-mdbook) compila libros de
|
|
||||||
[mdBook](https://rust-lang.github.io/mdBook/) al construir la aplicación y los sirve como páginas
|
|
||||||
PageTop, dentro del tema activo. Esta misma guía se publica así.
|
|
||||||
|
|
@ -1,130 +0,0 @@
|
||||||
# HTMX: atributos, cabeceras y respuestas
|
|
||||||
|
|
||||||
Lo que ofrece `pagetop-htmx`, en tablas. Para aprender a usarlo, empieza por [Añadir HTMX a una
|
|
||||||
aplicación](../how-to/htmx-setup.md); la documentación completa de cada atributo está en
|
|
||||||
[htmx.org](https://htmx.org/reference/).
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop_htmx::prelude::*; // hx, hx_table, hx_pager, HtmxRequestExt, HtmxResponse
|
|
||||||
```
|
|
||||||
|
|
||||||
## Atributos
|
|
||||||
|
|
||||||
Cada atributo tiene su constante en `hx`, para usarla con `PropsOp::set()` en cualquier
|
|
||||||
componente. En `html!` se escriben tal cual.
|
|
||||||
|
|
||||||
| Constante | Atributo | Para qué |
|
|
||||||
|---|---|---|
|
|
||||||
| `hx::GET`, `POST`, `PUT`, `PATCH`, `DELETE` | `hx-get`... | Método y URL de la petición |
|
|
||||||
| `hx::TRIGGER` | `hx-trigger` | Evento que la lanza |
|
|
||||||
| `hx::TARGET` | `hx-target` | Dónde va la respuesta: selector CSS, `this`, `closest tr`, `next`, `previous`, `find .x` |
|
|
||||||
| `hx::SWAP` | `hx-swap` | Cómo se coloca la respuesta |
|
|
||||||
| `hx::SWAP_OOB` | `hx-swap-oob` | En la respuesta: este fragmento va a su propio `id`, fuera de banda |
|
|
||||||
| `hx::SELECT`, `SELECT_OOB` | `hx-select`... | Usa sólo una parte de la respuesta |
|
|
||||||
| `hx::BOOST` | `hx-boost` | Convierte los enlaces y formularios contenidos en peticiones HTMX |
|
|
||||||
| `hx::PUSH_URL`, `REPLACE_URL` | `hx-push-url`... | Añade o cambia la entrada del historial |
|
|
||||||
| `hx::CONFIRM` | `hx-confirm` | Pide confirmación antes de enviar |
|
|
||||||
| `hx::PROMPT` | `hx-prompt` | Pide un texto antes de enviar (llega en la cabecera `HX-Prompt`) |
|
|
||||||
| `hx::INDICATOR` | `hx-indicator` | Elemento que se muestra durante la petición |
|
|
||||||
| `hx::DISABLED_ELT` | `hx-disabled-elt` | Elementos que se desactivan durante la petición |
|
|
||||||
| `hx::INCLUDE`, `PARAMS`, `VALS` | `hx-include`... | Qué valores se envían |
|
|
||||||
| `hx::HEADERS`, `ENCODING` | `hx-headers`... | Cabeceras extra; `multipart/form-data` para archivos |
|
|
||||||
| `hx::SYNC` | `hx-sync` | Coordina peticiones simultáneas (`this:replace`, `#form:abort`...) |
|
|
||||||
| `hx::VALIDATE` | `hx-validate` | Valida el formulario con las reglas del navegador antes de enviar |
|
|
||||||
| `hx::PRESERVE` | `hx-preserve` | Mantiene el elemento intacto al sustituir lo que lo rodea |
|
|
||||||
| `hx::DISINHERIT`, `INHERIT` | `hx-disinherit`... | Controla qué atributos heredan los descendientes |
|
|
||||||
| `hx::on("click")` | `hx-on:click` | JavaScript en línea ante un evento del DOM |
|
|
||||||
| `hx::on_htmx("after-request")` | `hx-on::after-request` | JavaScript en línea ante un evento de HTMX |
|
|
||||||
|
|
||||||
### `hx-swap`
|
|
||||||
|
|
||||||
| Constante | Valor | Coloca la respuesta... |
|
|
||||||
|---|---|---|
|
|
||||||
| `hx::swap::INNER_HTML` | `innerHTML` | Dentro del destino, sustituyendo su contenido (por defecto) |
|
|
||||||
| `hx::swap::OUTER_HTML` | `outerHTML` | En lugar del destino |
|
|
||||||
| `hx::swap::OUTER_HTML_SCROLL_TOP` | `outerHTML scroll:top` | En lugar del destino, y vuelve arriba |
|
|
||||||
| `hx::swap::BEFORE_BEGIN` | `beforebegin` | Justo antes del destino |
|
|
||||||
| `hx::swap::AFTER_BEGIN` | `afterbegin` | Al principio de su contenido |
|
|
||||||
| `hx::swap::BEFORE_END` | `beforeend` | Al final de su contenido |
|
|
||||||
| `hx::swap::AFTER_END` | `afterend` | Justo después del destino |
|
|
||||||
| `hx::swap::DELETE` | `delete` | Borra el destino, sea cual sea la respuesta |
|
|
||||||
| `hx::swap::NONE` | `none` | En ningún sitio (sólo cuentan las cabeceras y los fragmentos fuera de banda) |
|
|
||||||
|
|
||||||
Admite modificadores tras el valor: `swap:300ms` retrasa la sustitución, `settle:...` el asentado,
|
|
||||||
`scroll:top` y `show:top` mueven la vista.
|
|
||||||
|
|
||||||
### `hx-trigger`
|
|
||||||
|
|
||||||
| Constante | Evento |
|
|
||||||
|---|---|
|
|
||||||
| `hx::trigger::CLICK` | `click` (por defecto en botones y enlaces) |
|
|
||||||
| `hx::trigger::CHANGE` | `change` (por defecto en campos) |
|
|
||||||
| `hx::trigger::SUBMIT` | `submit` (por defecto en formularios) |
|
|
||||||
| `hx::trigger::KEYUP` | `keyup` |
|
|
||||||
| `hx::trigger::LOAD` | `load`: nada más cargarse el elemento |
|
|
||||||
| `hx::trigger::REVEALED` | `revealed`: al entrar en la pantalla |
|
|
||||||
| `hx::trigger::INTERSECT` | `intersect`: al cruzar el área visible, en cualquier contenedor |
|
|
||||||
|
|
||||||
Modificadores y formas habituales: `delay:300ms` (espera a que paren los eventos), `throttle:1s`
|
|
||||||
(como mucho uno por intervalo), `changed` (sólo si cambió el valor), `once`, `from:body` (escucha
|
|
||||||
eventos de otro elemento), `every 2s` (sondeo) y varios eventos separados por comas
|
|
||||||
(`input delay:300ms, submit`).
|
|
||||||
|
|
||||||
## Cabeceras de la petición
|
|
||||||
|
|
||||||
Lo que HTMX envía, y cómo leerlo con `HtmxRequestExt` sobre `HttpRequest`:
|
|
||||||
|
|
||||||
| Método | Cabecera | Devuelve |
|
|
||||||
|---|---|---|
|
|
||||||
| `is_htmx()` | `HX-Request` | Si la petición viene de HTMX |
|
|
||||||
| `is_boosted()` | `HX-Boosted` | Si viene de un enlace o formulario con `hx-boost` |
|
|
||||||
| `is_history_restore()` | `HX-History-Restore-Request` | Si HTMX está reconstruyendo el historial |
|
|
||||||
| `hx_current_url()` | `HX-Current-URL` | La URL que se ve en el navegador |
|
|
||||||
| `hx_target()` | `HX-Target` | El `id` del destino |
|
|
||||||
| `hx_trigger_id()` | `HX-Trigger` | El `id` del elemento que lanzó la petición |
|
|
||||||
| `hx_trigger_name()` | `HX-Trigger-Name` | Su `name` |
|
|
||||||
| `hx_prompt()` | `HX-Prompt` | Lo que el usuario escribió en un `hx-prompt` |
|
|
||||||
|
|
||||||
Los nombres, como constantes, están en `hx::request`.
|
|
||||||
|
|
||||||
## Respuestas
|
|
||||||
|
|
||||||
`HtmxResponse` devuelve un fragmento de HTML (`Content-Type: text/html`) con las cabeceras que se
|
|
||||||
le añadan. Implementa `IntoResponse`.
|
|
||||||
|
|
||||||
| Método | Cabecera | Efecto |
|
|
||||||
|---|---|---|
|
|
||||||
| `HtmxResponse::new(markup)` | - | Respuesta con un fragmento |
|
|
||||||
| `HtmxResponse::empty()` | - | Respuesta sin cuerpo, sólo cabeceras |
|
|
||||||
| `oob(markup)` | - | Añade un fragmento fuera de banda (lleva su `id` y `hx-swap-oob`) |
|
|
||||||
| `retarget(selector)` | `HX-Retarget` | Cambia el destino |
|
|
||||||
| `reswap(estrategia)` | `HX-Reswap` | Cambia la forma de colocarla |
|
|
||||||
| `reselect(selector)` | `HX-Reselect` | Usa sólo una parte de la respuesta |
|
|
||||||
| `trigger(eventos)` | `HX-Trigger` | Dispara eventos en el cliente |
|
|
||||||
| `trigger_after_swap(eventos)` | `HX-Trigger-After-Swap` | ...tras colocar la respuesta |
|
|
||||||
| `trigger_after_settle(eventos)` | `HX-Trigger-After-Settle` | ...tras asentarla |
|
|
||||||
| `push_url(url)`, `replace_url(url)` | `HX-Push-Url`... | Cambia la URL del navegador |
|
|
||||||
| `redirect(url)` | `HX-Redirect` | Navegación completa |
|
|
||||||
| `location(url)`, `location_json(json)` | `HX-Location` | Navegación con HTMX, sin recargar la página |
|
|
||||||
| `refresh()` | `HX-Refresh` | Recarga la página |
|
|
||||||
|
|
||||||
Un `Markup` también es una respuesta válida para HTMX cuando no hacen falta cabeceras.
|
|
||||||
|
|
||||||
## Ayudas para tablas y paginadores
|
|
||||||
|
|
||||||
| Ayuda | Para qué |
|
|
||||||
|---|---|
|
|
||||||
| `hx_table::sort_link(href, destino, dirección)` | Cabecera ordenable que sustituye el destino, vuelve arriba y actualiza la URL |
|
|
||||||
| `hx_pager` | Documenta el patrón para `Pager`: `hx::BOOST`, `TARGET`, `SWAP` y `PUSH_URL` en su `with_prop()` |
|
|
||||||
|
|
||||||
Ver [Ordenar y paginar sin recargar](../how-to/htmx-tables.md).
|
|
||||||
|
|
||||||
## Comportamientos de HTMX que conviene recordar
|
|
||||||
|
|
||||||
| Comportamiento | Consecuencia |
|
|
||||||
|---|---|
|
|
||||||
| Las respuestas 4xx y 5xx **no se colocan** | Responde con 200 a los errores de validación que el usuario deba ver |
|
|
||||||
| Los atributos `hx-*` **se heredan** | Un `hx-swap` en un formulario afecta a los campos que hacen sus propias peticiones |
|
|
||||||
| Una petición que no es `GET` envía el formulario que la contiene | Un campo dentro de un formulario envía también los demás campos |
|
|
||||||
| El código **286** detiene el sondeo | Alternativa a sustituir el elemento que sondea |
|
|
||||||
| Una redirección `3xx` la sigue HTMX por su cuenta | Para cambiar de página, usa `HtmxResponse::redirect()` |
|
|
||||||
|
|
@ -1,986 +0,0 @@
|
||||||
# Guarda las tareas en una base de datos
|
|
||||||
|
|
||||||
Las tareas del [tutorial anterior](htmx-tasks.md) viven en memoria: al reiniciar el servidor, se
|
|
||||||
pierden. En éste las guardas en [SQLite](https://sqlite.org) con la extensión `pagetop-seaorm`, que
|
|
||||||
integra [SeaORM](https://www.sea-ql.org/SeaORM) en PageTop. Lo interesante es lo que **no**
|
|
||||||
cambia: las rutas, los fragmentos y los atributos `hx-*` siguen igual.
|
|
||||||
|
|
||||||
- **Tiempo:** unos 20 minutos.
|
|
||||||
- **Necesitas:** el proyecto `garden-tasks` del tutorial anterior.
|
|
||||||
- **Al terminar tendrás:** tareas persistentes, una migración que crea la tabla al arrancar y una
|
|
||||||
prueba contra una base de datos en memoria.
|
|
||||||
|
|
||||||
## 1. Añade SeaORM
|
|
||||||
|
|
||||||
En `Cargo.toml`, añade la extensión con el motor que vas a usar:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
pagetop-htmx = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
Los motores disponibles son `sqlite`, `postgres` y `mysql`. El código que vas a escribir es el mismo
|
|
||||||
para los tres; sólo cambian la *feature* y la configuración.
|
|
||||||
|
|
||||||
Crea `config/common.toml`, junto a `Cargo.toml`, con la conexión:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[database]
|
|
||||||
db_type = "sqlite"
|
|
||||||
db_name = "garden.db?mode=rwc"
|
|
||||||
```
|
|
||||||
|
|
||||||
`mode=rwc` le pide a SQLite que cree el archivo `garden.db` si no existe.
|
|
||||||
|
|
||||||
## 2. La migración
|
|
||||||
|
|
||||||
Una **migración** describe un cambio en el esquema de la base de datos. PageTop las aplica al
|
|
||||||
arrancar, en orden, y anota en la tabla `seaql_migrations` las que ya aplicó para no repetirlas.
|
|
||||||
|
|
||||||
Cada migración es un módulo dentro de `migration`, con un nombre que empieza por la fecha. En un
|
|
||||||
proyecto grande irían en `src/migration/`; aquí caben en `src/main.rs`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
mod migration {
|
|
||||||
pub mod m20261015_000001_create_tasks {
|
|
||||||
use pagetop_seaorm::migration::*;
|
|
||||||
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[pagetop::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
table_auto(Tasks::Table)
|
|
||||||
.col(pk_auto(Tasks::Id))
|
|
||||||
.col(string(Tasks::Title))
|
|
||||||
.col(boolean(Tasks::Done).default(false))
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Tasks {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
Title,
|
|
||||||
Done,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`table_auto()` crea la tabla `tasks` (si no existe) con dos columnas de regalo, `created_at` y
|
|
||||||
`updated_at`. `pk_auto()` es una clave primaria autoincremental; `string()` y `boolean()`,
|
|
||||||
columnas obligatorias.
|
|
||||||
|
|
||||||
## 3. La entidad
|
|
||||||
|
|
||||||
La **entidad** es el tipo Rust que representa una fila. Sustituye al `struct Task` del tutorial
|
|
||||||
anterior:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
mod task {
|
|
||||||
use pagetop_seaorm::db::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
#[sea_orm(table_name = "tasks")]
|
|
||||||
pub struct Model {
|
|
||||||
#[sea_orm(primary_key)]
|
|
||||||
pub id: i32,
|
|
||||||
pub title: String,
|
|
||||||
pub done: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
pub enum Relation {}
|
|
||||||
|
|
||||||
impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
El *struct* debe llamarse `Model`. A partir de él, `DeriveEntityModel` genera el resto: `Entity`
|
|
||||||
para consultar, `Column` para filtrar y ordenar, y `ActiveModel` para insertar y modificar.
|
|
||||||
|
|
||||||
Borra el `struct Task`, el `struct Store`, `STORE` y `store()`: ya no los necesitas. En
|
|
||||||
`task_url()`, `task_item()` y `edit_item()`, cambia `&Task` por `&task::Model`; los campos se llaman
|
|
||||||
igual.
|
|
||||||
|
|
||||||
## 4. Conecta y migra al arrancar
|
|
||||||
|
|
||||||
Declara `pagetop_seaorm::SeaORM` como dependencia: abrirá la conexión con los ajustes de
|
|
||||||
`[database]` antes de que se inicialice tu extensión. Después, en `initialize()`, aplica la
|
|
||||||
migración y siembra las dos tareas de ejemplo si la tabla está vacía:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
use pagetop_seaorm::install_migrations;
|
|
||||||
# mod migration {
|
|
||||||
# pub mod m20261015_000001_create_tasks {
|
|
||||||
# use pagetop_seaorm::migration::*;
|
|
||||||
# pub struct Migration;
|
|
||||||
# #[pagetop::async_trait]
|
|
||||||
# impl MigrationTrait for Migration {
|
|
||||||
# async fn up(&self, _: &SchemaManager) -> Result<(), DbErr> { Ok(()) }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# mod task {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "tasks")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub title: String,
|
|
||||||
# pub done: bool,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# async fn add_task(_: &str) -> Result<task::Model, DbErr> { todo!() }
|
|
||||||
# struct GardenTasks;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for GardenTasks {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx, &pagetop_seaorm::SeaORM]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
install_migrations!(m20261015_000001_create_tasks)?;
|
|
||||||
if task::Entity::find().count(dbconn()).await? == 0 {
|
|
||||||
add_task("Water the tomatoes").await?;
|
|
||||||
add_task("Turn the compost").await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ... configure_router() as before ...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Si la base de datos no responde o la migración falla, `?` devuelve el error y la aplicación **no
|
|
||||||
arranca**: lo explica en el terminal y termina. Nunca funciona a medias con un esquema incompleto.
|
|
||||||
|
|
||||||
## 5. Las consultas
|
|
||||||
|
|
||||||
Las operaciones del almacén pasan a ser funciones `async` que hablan con la base de datos.
|
|
||||||
`dbconn()` devuelve el *pool* de conexiones que abrió la extensión:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod task {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "tasks")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub title: String,
|
|
||||||
# pub done: bool,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
async fn all_tasks() -> Result<Vec<task::Model>, DbErr> {
|
|
||||||
task::Entity::find()
|
|
||||||
.order_by_asc(task::Column::Id)
|
|
||||||
.all(dbconn())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn find_task(id: i32) -> Result<Option<task::Model>, DbErr> {
|
|
||||||
task::Entity::find_by_id(id).one(dbconn()).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn add_task(title: &str) -> Result<task::Model, DbErr> {
|
|
||||||
task::ActiveModel {
|
|
||||||
title: Set(title.to_string()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
.insert(dbconn())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn pending() -> Result<u64, DbErr> {
|
|
||||||
task::Entity::find()
|
|
||||||
.filter(task::Column::Done.eq(false))
|
|
||||||
.count(dbconn())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`pending_update()` recibe ahora un `u64`, que es lo que devuelve `count()`.
|
|
||||||
|
|
||||||
## 6. Los *handlers*
|
|
||||||
|
|
||||||
Una consulta puede fallar, así que los *handlers* devuelven un `Result`. Para no repetir el
|
|
||||||
tratamiento del error en cada uno, define un tipo que lo convierta en respuesta: un error 500 y una
|
|
||||||
traza con la causa. Gracias a `From<DbErr>`, el operador `?` hace el resto:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
// Ends the request with a 500 error, and leaves a trace with the cause.
|
|
||||||
struct DbFailure(DbErr);
|
|
||||||
|
|
||||||
impl From<DbErr> for DbFailure {
|
|
||||||
fn from(error: DbErr) -> Self {
|
|
||||||
Self(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoResponse for DbFailure {
|
|
||||||
fn into_response(self) -> Response {
|
|
||||||
trace::error!("Database error: {}", self.0);
|
|
||||||
web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Con eso, cada *handler* cambia muy poco. Por ejemplo, `toggle` lee la tarea, la convierte en un
|
|
||||||
`ActiveModel`, cambia el campo y la guarda:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod task {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "tasks")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub title: String,
|
|
||||||
# pub done: bool,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# struct DbFailure(DbErr);
|
|
||||||
# impl From<DbErr> for DbFailure { fn from(error: DbErr) -> Self { Self(error) } }
|
|
||||||
# impl IntoResponse for DbFailure { fn into_response(self) -> Response { todo!() } }
|
|
||||||
# async fn find_task(_: i32) -> Result<Option<task::Model>, DbErr> { todo!() }
|
|
||||||
# async fn pending() -> Result<u64, DbErr> { todo!() }
|
|
||||||
# fn task_item(_: &task::Model) -> Markup { html! {} }
|
|
||||||
# fn pending_update(_: u64) -> Markup { html! {} }
|
|
||||||
# fn not_found() -> Response { todo!() }
|
|
||||||
async fn toggle(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
let Some(task) = find_task(id).await? else {
|
|
||||||
return Ok(not_found());
|
|
||||||
};
|
|
||||||
let done = !task.done;
|
|
||||||
let mut task = task.into_active_model();
|
|
||||||
task.done = Set(done);
|
|
||||||
let task = task.update(dbconn()).await?;
|
|
||||||
Ok(HtmxResponse::new(task_item(&task))
|
|
||||||
.oob(pending_update(pending().await?))
|
|
||||||
.into_response())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Fíjate en la última parte: **la respuesta es idéntica** a la del tutorial anterior. El navegador
|
|
||||||
no nota ningún cambio.
|
|
||||||
|
|
||||||
Borrar es una sola llamada:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod task {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "tasks")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub title: String,
|
|
||||||
# pub done: bool,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# struct DbFailure(DbErr);
|
|
||||||
# impl From<DbErr> for DbFailure { fn from(error: DbErr) -> Self { Self(error) } }
|
|
||||||
# impl IntoResponse for DbFailure { fn into_response(self) -> Response { todo!() } }
|
|
||||||
# async fn pending() -> Result<u64, DbErr> { todo!() }
|
|
||||||
# fn pending_update(_: u64) -> Markup { html! {} }
|
|
||||||
async fn remove(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
task::Entity::delete_by_id(id).exec(dbconn()).await?;
|
|
||||||
Ok(HtmxResponse::empty()
|
|
||||||
.oob(pending_update(pending().await?))
|
|
||||||
.into_response())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
La página principal devuelve una página de error si la consulta falla, para no dejar al usuario
|
|
||||||
ante una pantalla en blanco:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# mod task {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "tasks")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub title: String,
|
|
||||||
# pub done: bool,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# async fn all_tasks() -> Result<Vec<task::Model>, DbErr> { todo!() }
|
|
||||||
# async fn pending() -> Result<u64, DbErr> { todo!() }
|
|
||||||
# fn add_form() -> Form { Form::new() }
|
|
||||||
# fn task_item(_: &task::Model) -> Markup { html! {} }
|
|
||||||
async fn load_list() -> Result<(Vec<task::Model>, u64), DbErr> {
|
|
||||||
Ok((all_tasks().await?, pending().await?))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let Ok((tasks, pending)) = load_list().await else {
|
|
||||||
return Err(ErrorPage::InternalError(Some(request)));
|
|
||||||
};
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden tasks"))
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
h1 { "Garden tasks" }
|
|
||||||
p { "Pending: " strong id="pending" { (pending) } }
|
|
||||||
}))
|
|
||||||
.with_child(add_form())
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
ul id="tasks" {
|
|
||||||
@for task in &tasks {
|
|
||||||
(task_item(task))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Los demás *handlers* siguen el mismo patrón; los tienes todos en [el código
|
|
||||||
completo](#el-código-completo). Los identificadores de las rutas pasan de `u32` a `i32`, el tipo de
|
|
||||||
la clave primaria.
|
|
||||||
|
|
||||||
## 7. Pruébalo
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo run
|
|
||||||
```
|
|
||||||
|
|
||||||
Al arrancar verás en el terminal la conexión y, una a una, las sentencias SQL de la migración.
|
|
||||||
Si te sobran, baja el nivel de las trazas de `sqlx` en `config/common.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[log]
|
|
||||||
tracing = "Info,sqlx=Warn"
|
|
||||||
```
|
|
||||||
|
|
||||||
Añade un par de tareas, marca alguna como hecha y **reinicia el servidor**: siguen ahí. El archivo `garden.db` ha aparecido junto a
|
|
||||||
`Cargo.toml`; puedes abrirlo con cualquier cliente de SQLite.
|
|
||||||
|
|
||||||
Reinicia otra vez: la migración ya no se aplica, porque `seaql_migrations` la tiene anotada.
|
|
||||||
|
|
||||||
## 8. Pruebas con una base de datos en memoria
|
|
||||||
|
|
||||||
Las pruebas no deberían tocar `garden.db`. Crea `config/test.toml` para el modo de ejecución
|
|
||||||
`test`, con una base de datos SQLite **en memoria**, nueva en cada ejecución:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[database]
|
|
||||||
db_name = "garden?mode=memory"
|
|
||||||
max_pool_size = 1
|
|
||||||
```
|
|
||||||
|
|
||||||
`db_type` llega de `common.toml`. Una base de datos en memoria vive dentro de su conexión: con
|
|
||||||
`max_pool_size = 1` todas las consultas usan la misma y ven las mismas tablas.
|
|
||||||
|
|
||||||
La prueba es la del tutorial anterior. La tabla parte vacía y `initialize()` siembra dos tareas,
|
|
||||||
así que la nueva es la tercera.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use pagetop_htmx::prelude::*;
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# use pagetop_seaorm::install_migrations;
|
|
||||||
# use serde::Deserialize;
|
|
||||||
# mod migration {
|
|
||||||
# pub mod m20261015_000001_create_tasks {
|
|
||||||
# use pagetop_seaorm::migration::*;
|
|
||||||
# pub struct Migration;
|
|
||||||
# #[pagetop::async_trait]
|
|
||||||
# impl MigrationTrait for Migration {
|
|
||||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
# manager
|
|
||||||
# .create_table(
|
|
||||||
# table_auto(Tasks::Table)
|
|
||||||
# .col(pk_auto(Tasks::Id))
|
|
||||||
# .col(string(Tasks::Title))
|
|
||||||
# .col(boolean(Tasks::Done).default(false))
|
|
||||||
# .to_owned(),
|
|
||||||
# )
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[derive(DeriveIden)]
|
|
||||||
# enum Tasks { Table, Id, Title, Done }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# mod task {
|
|
||||||
# use pagetop_seaorm::db::*;
|
|
||||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
# #[sea_orm(table_name = "tasks")]
|
|
||||||
# pub struct Model {
|
|
||||||
# #[sea_orm(primary_key)]
|
|
||||||
# pub id: i32,
|
|
||||||
# pub title: String,
|
|
||||||
# pub done: bool,
|
|
||||||
# }
|
|
||||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
# pub enum Relation {}
|
|
||||||
# impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
# }
|
|
||||||
# struct GardenTasks;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for GardenTasks {
|
|
||||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
# vec![&pagetop_htmx::Htmx, &pagetop_seaorm::SeaORM]
|
|
||||||
# }
|
|
||||||
# async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
# install_migrations!(m20261015_000001_create_tasks)?;
|
|
||||||
# if task::Entity::find().count(dbconn()).await? == 0 {
|
|
||||||
# add_task("Water the tomatoes").await?;
|
|
||||||
# add_task("Turn the compost").await?;
|
|
||||||
# }
|
|
||||||
# Ok(())
|
|
||||||
# }
|
|
||||||
# fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
# routes
|
|
||||||
# .public_route("/", web::get(home))
|
|
||||||
# .public_route("/tasks", web::post(create))
|
|
||||||
# .public_route("/tasks/{id}", web::get(show).put(update).delete(remove))
|
|
||||||
# .public_route("/tasks/{id}/edit", web::get(edit))
|
|
||||||
# .public_route("/tasks/{id}/toggle", web::patch(toggle))
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# async fn all_tasks() -> Result<Vec<task::Model>, DbErr> {
|
|
||||||
# task::Entity::find().order_by_asc(task::Column::Id).all(dbconn()).await
|
|
||||||
# }
|
|
||||||
# async fn find_task(id: i32) -> Result<Option<task::Model>, DbErr> {
|
|
||||||
# task::Entity::find_by_id(id).one(dbconn()).await
|
|
||||||
# }
|
|
||||||
# async fn add_task(title: &str) -> Result<task::Model, DbErr> {
|
|
||||||
# task::ActiveModel { title: Set(title.to_string()), ..Default::default() }
|
|
||||||
# .insert(dbconn())
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# async fn pending() -> Result<u64, DbErr> {
|
|
||||||
# task::Entity::find().filter(task::Column::Done.eq(false)).count(dbconn()).await
|
|
||||||
# }
|
|
||||||
# fn add_form() -> Form {
|
|
||||||
# Form::new()
|
|
||||||
# .with_action("/tasks")
|
|
||||||
# .with_method(form::Method::Post)
|
|
||||||
# .with_prop(PropsOp::set(hx::POST, "/tasks"))
|
|
||||||
# .with_prop(PropsOp::set(hx::TARGET, "#tasks"))
|
|
||||||
# .with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END))
|
|
||||||
# .with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()"))
|
|
||||||
# .with_child(
|
|
||||||
# form::input::Field::text()
|
|
||||||
# .with_name("title")
|
|
||||||
# .with_label(Lc::n("New task"))
|
|
||||||
# .with_required(true),
|
|
||||||
# )
|
|
||||||
# .with_child(Button::submit(Lc::n("Add")))
|
|
||||||
# }
|
|
||||||
# fn task_url(task: &task::Model) -> String {
|
|
||||||
# util::join!("/tasks/", task.id.to_string())
|
|
||||||
# }
|
|
||||||
# fn task_item(task: &task::Model) -> Markup {
|
|
||||||
# let url = task_url(task);
|
|
||||||
# html! {
|
|
||||||
# li hx-target="this" hx-swap="outerHTML" {
|
|
||||||
# input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle"));
|
|
||||||
# " "
|
|
||||||
# @if task.done { s { (task.title) } } @else { (task.title) }
|
|
||||||
# " "
|
|
||||||
# button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" }
|
|
||||||
# button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# fn edit_item(task: &task::Model) -> Markup {
|
|
||||||
# let url = task_url(task);
|
|
||||||
# html! {
|
|
||||||
# li hx-target="this" hx-swap="outerHTML" {
|
|
||||||
# form hx-put=(url) {
|
|
||||||
# input type="text" name="title" value=(task.title) required autofocus;
|
|
||||||
# button type="submit" { "Save" }
|
|
||||||
# button type="button" hx-get=(url) { "Cancel" }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# fn pending_update(pending: u64) -> Markup {
|
|
||||||
# html! { strong id="pending" hx-swap-oob="true" { (pending) } }
|
|
||||||
# }
|
|
||||||
# struct DbFailure(DbErr);
|
|
||||||
# impl From<DbErr> for DbFailure { fn from(error: DbErr) -> Self { Self(error) } }
|
|
||||||
# impl IntoResponse for DbFailure {
|
|
||||||
# fn into_response(self) -> Response {
|
|
||||||
# trace::error!("Database error: {}", self.0);
|
|
||||||
# web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# fn not_found() -> Response {
|
|
||||||
# web::http::StatusCode::NOT_FOUND.into_response()
|
|
||||||
# }
|
|
||||||
# async fn load_list() -> Result<(Vec<task::Model>, u64), DbErr> {
|
|
||||||
# Ok((all_tasks().await?, pending().await?))
|
|
||||||
# }
|
|
||||||
# async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
# let Ok((tasks, pending)) = load_list().await else {
|
|
||||||
# return Err(ErrorPage::InternalError(Some(request)));
|
|
||||||
# };
|
|
||||||
# Page::new(request)
|
|
||||||
# .with_child(Html::with(move |_| html! {
|
|
||||||
# p { "Pending: " strong id="pending" { (pending) } }
|
|
||||||
# }))
|
|
||||||
# .with_child(add_form())
|
|
||||||
# .with_child(Html::with(move |_| html! {
|
|
||||||
# ul id="tasks" { @for task in &tasks { (task_item(task)) } }
|
|
||||||
# }))
|
|
||||||
# .render()
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# #[derive(Deserialize)]
|
|
||||||
# struct TaskForm { title: String }
|
|
||||||
# async fn create(
|
|
||||||
# request: HttpRequest,
|
|
||||||
# web::Form(form): web::Form<TaskForm>,
|
|
||||||
# ) -> Result<Response, DbFailure> {
|
|
||||||
# let title = form.title.trim();
|
|
||||||
# let added = if title.is_empty() { None } else { Some(add_task(title).await?) };
|
|
||||||
# if !request.is_htmx() {
|
|
||||||
# return Ok(Redirect::see_other("/"));
|
|
||||||
# }
|
|
||||||
# Ok(match added {
|
|
||||||
# Some(task) => HtmxResponse::new(task_item(&task))
|
|
||||||
# .oob(pending_update(pending().await?))
|
|
||||||
# .into_response(),
|
|
||||||
# None => HtmxResponse::empty().into_response(),
|
|
||||||
# })
|
|
||||||
# }
|
|
||||||
# async fn toggle(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
# let Some(task) = find_task(id).await? else { return Ok(not_found()) };
|
|
||||||
# let done = !task.done;
|
|
||||||
# let mut task = task.into_active_model();
|
|
||||||
# task.done = Set(done);
|
|
||||||
# let task = task.update(dbconn()).await?;
|
|
||||||
# Ok(HtmxResponse::new(task_item(&task)).oob(pending_update(pending().await?)).into_response())
|
|
||||||
# }
|
|
||||||
# async fn remove(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
# task::Entity::delete_by_id(id).exec(dbconn()).await?;
|
|
||||||
# Ok(HtmxResponse::empty().oob(pending_update(pending().await?)).into_response())
|
|
||||||
# }
|
|
||||||
# async fn edit(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
# Ok(match find_task(id).await? {
|
|
||||||
# Some(task) => HtmxResponse::new(edit_item(&task)).into_response(),
|
|
||||||
# None => not_found(),
|
|
||||||
# })
|
|
||||||
# }
|
|
||||||
# async fn show(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
# Ok(match find_task(id).await? {
|
|
||||||
# Some(task) => HtmxResponse::new(task_item(&task)).into_response(),
|
|
||||||
# None => not_found(),
|
|
||||||
# })
|
|
||||||
# }
|
|
||||||
# async fn update(
|
|
||||||
# web::Path(id): web::Path<i32>,
|
|
||||||
# web::Form(form): web::Form<TaskForm>,
|
|
||||||
# ) -> Result<Response, DbFailure> {
|
|
||||||
# let Some(task) = find_task(id).await? else { return Ok(not_found()) };
|
|
||||||
# let title = form.title.trim().to_string();
|
|
||||||
# if title.is_empty() {
|
|
||||||
# return Ok(HtmxResponse::new(task_item(&task)).into_response());
|
|
||||||
# }
|
|
||||||
# let mut task = task.into_active_model();
|
|
||||||
# task.title = Set(title);
|
|
||||||
# let task = task.update(dbconn()).await?;
|
|
||||||
# Ok(HtmxResponse::new(task_item(&task)).into_response())
|
|
||||||
# }
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
// Sends a request as HTMX does: with the `HX-Request` header.
|
|
||||||
fn htmx(request: web::test::TestRequest) -> web::Request {
|
|
||||||
request.header("hx-request", "true").to_request()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn tasks_are_stored_in_the_database() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&GardenTasks).await.test());
|
|
||||||
|
|
||||||
let request = htmx(web::test::TestRequest::post().uri("/tasks").form("title=Plant+lettuces"));
|
|
||||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
|
||||||
assert!(body.contains("Plant lettuces"));
|
|
||||||
assert!(body.contains(r#"<strong id="pending" hx-swap-oob="true">3</strong>"#));
|
|
||||||
|
|
||||||
let request = htmx(web::test::TestRequest::patch().uri("/tasks/3/toggle"));
|
|
||||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
|
||||||
assert!(body.contains("<s>Plant lettuces</s>"));
|
|
||||||
|
|
||||||
// The change is in the database, not only in the response.
|
|
||||||
let stored = task::Entity::find_by_id(3).one(dbconn()).await.unwrap().unwrap();
|
|
||||||
assert!(stored.done);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Ejecútala en el modo `test`:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
PAGETOP_RUN_MODE=test cargo test
|
|
||||||
```
|
|
||||||
|
|
||||||
## El código completo
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
use pagetop_seaorm::db::*;
|
|
||||||
use pagetop_seaorm::install_migrations;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
// **< Database >***********************************************************************************
|
|
||||||
|
|
||||||
mod migration {
|
|
||||||
pub mod m20261015_000001_create_tasks {
|
|
||||||
use pagetop_seaorm::migration::*;
|
|
||||||
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[pagetop::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
table_auto(Tasks::Table)
|
|
||||||
.col(pk_auto(Tasks::Id))
|
|
||||||
.col(string(Tasks::Title))
|
|
||||||
.col(boolean(Tasks::Done).default(false))
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Tasks {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
Title,
|
|
||||||
Done,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mod task {
|
|
||||||
use pagetop_seaorm::db::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
|
||||||
#[sea_orm(table_name = "tasks")]
|
|
||||||
pub struct Model {
|
|
||||||
#[sea_orm(primary_key)]
|
|
||||||
pub id: i32,
|
|
||||||
pub title: String,
|
|
||||||
pub done: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
|
||||||
pub enum Relation {}
|
|
||||||
|
|
||||||
impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn all_tasks() -> Result<Vec<task::Model>, DbErr> {
|
|
||||||
task::Entity::find()
|
|
||||||
.order_by_asc(task::Column::Id)
|
|
||||||
.all(dbconn())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn find_task(id: i32) -> Result<Option<task::Model>, DbErr> {
|
|
||||||
task::Entity::find_by_id(id).one(dbconn()).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn add_task(title: &str) -> Result<task::Model, DbErr> {
|
|
||||||
task::ActiveModel {
|
|
||||||
title: Set(title.to_string()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
.insert(dbconn())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn pending() -> Result<u64, DbErr> {
|
|
||||||
task::Entity::find()
|
|
||||||
.filter(task::Column::Done.eq(false))
|
|
||||||
.count(dbconn())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< The application >****************************************************************************
|
|
||||||
|
|
||||||
struct GardenTasks;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for GardenTasks {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_htmx::Htmx, &pagetop_seaorm::SeaORM]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
install_migrations!(m20261015_000001_create_tasks)?;
|
|
||||||
if task::Entity::find().count(dbconn()).await? == 0 {
|
|
||||||
add_task("Water the tomatoes").await?;
|
|
||||||
add_task("Turn the compost").await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/tasks", web::post(create))
|
|
||||||
.public_route("/tasks/{id}", web::get(show).put(update).delete(remove))
|
|
||||||
.public_route("/tasks/{id}/edit", web::get(edit))
|
|
||||||
.public_route("/tasks/{id}/toggle", web::patch(toggle))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&GardenTasks).await.run().await
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< Markup >*************************************************************************************
|
|
||||||
|
|
||||||
fn add_form() -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/tasks")
|
|
||||||
.with_method(form::Method::Post)
|
|
||||||
.with_prop(PropsOp::set(hx::POST, "/tasks"))
|
|
||||||
.with_prop(PropsOp::set(hx::TARGET, "#tasks"))
|
|
||||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END))
|
|
||||||
.with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()"))
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("title")
|
|
||||||
.with_label(Lc::n("New task"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Add")))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn task_url(task: &task::Model) -> String {
|
|
||||||
util::join!("/tasks/", task.id.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn task_item(task: &task::Model) -> Markup {
|
|
||||||
let url = task_url(task);
|
|
||||||
html! {
|
|
||||||
li hx-target="this" hx-swap="outerHTML" {
|
|
||||||
input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle"));
|
|
||||||
" "
|
|
||||||
@if task.done {
|
|
||||||
s { (task.title) }
|
|
||||||
} @else {
|
|
||||||
(task.title)
|
|
||||||
}
|
|
||||||
" "
|
|
||||||
button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" }
|
|
||||||
button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edit_item(task: &task::Model) -> Markup {
|
|
||||||
let url = task_url(task);
|
|
||||||
html! {
|
|
||||||
li hx-target="this" hx-swap="outerHTML" {
|
|
||||||
form hx-put=(url) {
|
|
||||||
input type="text" name="title" value=(task.title) required autofocus;
|
|
||||||
button type="submit" { "Save" }
|
|
||||||
button type="button" hx-get=(url) { "Cancel" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pending_update(pending: u64) -> Markup {
|
|
||||||
html! { strong id="pending" hx-swap-oob="true" { (pending) } }
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< Handlers >***********************************************************************************
|
|
||||||
|
|
||||||
// Ends the request with a 500 error, and leaves a trace with the cause.
|
|
||||||
struct DbFailure(DbErr);
|
|
||||||
|
|
||||||
impl From<DbErr> for DbFailure {
|
|
||||||
fn from(error: DbErr) -> Self {
|
|
||||||
Self(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoResponse for DbFailure {
|
|
||||||
fn into_response(self) -> Response {
|
|
||||||
trace::error!("Database error: {}", self.0);
|
|
||||||
web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn not_found() -> Response {
|
|
||||||
web::http::StatusCode::NOT_FOUND.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn load_list() -> Result<(Vec<task::Model>, u64), DbErr> {
|
|
||||||
Ok((all_tasks().await?, pending().await?))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let Ok((tasks, pending)) = load_list().await else {
|
|
||||||
return Err(ErrorPage::InternalError(Some(request)));
|
|
||||||
};
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Garden tasks"))
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
h1 { "Garden tasks" }
|
|
||||||
p { "Pending: " strong id="pending" { (pending) } }
|
|
||||||
}))
|
|
||||||
.with_child(add_form())
|
|
||||||
.with_child(Html::with(move |_| html! {
|
|
||||||
ul id="tasks" {
|
|
||||||
@for task in &tasks {
|
|
||||||
(task_item(task))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct TaskForm {
|
|
||||||
title: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn create(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Form(form): web::Form<TaskForm>,
|
|
||||||
) -> Result<Response, DbFailure> {
|
|
||||||
let title = form.title.trim();
|
|
||||||
let added = if title.is_empty() { None } else { Some(add_task(title).await?) };
|
|
||||||
if !request.is_htmx() {
|
|
||||||
// Without JavaScript the browser posts the form: back to the list.
|
|
||||||
return Ok(Redirect::see_other("/"));
|
|
||||||
}
|
|
||||||
Ok(match added {
|
|
||||||
Some(task) => HtmxResponse::new(task_item(&task))
|
|
||||||
.oob(pending_update(pending().await?))
|
|
||||||
.into_response(),
|
|
||||||
None => HtmxResponse::empty().into_response(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn toggle(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
let Some(task) = find_task(id).await? else {
|
|
||||||
return Ok(not_found());
|
|
||||||
};
|
|
||||||
let done = !task.done;
|
|
||||||
let mut task = task.into_active_model();
|
|
||||||
task.done = Set(done);
|
|
||||||
let task = task.update(dbconn()).await?;
|
|
||||||
Ok(HtmxResponse::new(task_item(&task))
|
|
||||||
.oob(pending_update(pending().await?))
|
|
||||||
.into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn remove(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
task::Entity::delete_by_id(id).exec(dbconn()).await?;
|
|
||||||
Ok(HtmxResponse::empty()
|
|
||||||
.oob(pending_update(pending().await?))
|
|
||||||
.into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn edit(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
Ok(match find_task(id).await? {
|
|
||||||
Some(task) => HtmxResponse::new(edit_item(&task)).into_response(),
|
|
||||||
None => not_found(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn show(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
|
||||||
Ok(match find_task(id).await? {
|
|
||||||
Some(task) => HtmxResponse::new(task_item(&task)).into_response(),
|
|
||||||
None => not_found(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn update(
|
|
||||||
web::Path(id): web::Path<i32>,
|
|
||||||
web::Form(form): web::Form<TaskForm>,
|
|
||||||
) -> Result<Response, DbFailure> {
|
|
||||||
let Some(task) = find_task(id).await? else {
|
|
||||||
return Ok(not_found());
|
|
||||||
};
|
|
||||||
let title = form.title.trim().to_string();
|
|
||||||
if title.is_empty() {
|
|
||||||
return Ok(HtmxResponse::new(task_item(&task)).into_response());
|
|
||||||
}
|
|
||||||
let mut task = task.into_active_model();
|
|
||||||
task.title = Set(title);
|
|
||||||
let task = task.update(dbconn()).await?;
|
|
||||||
Ok(HtmxResponse::new(task_item(&task)).into_response())
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Lo que has construido
|
|
||||||
|
|
||||||
- Una aplicación con **datos persistentes** en SQLite, que cambia de motor con una *feature* y dos
|
|
||||||
líneas de configuración.
|
|
||||||
- Una **migración** que se aplica sola al arrancar, una sola vez.
|
|
||||||
- Una **entidad** con consultas tipadas: si te equivocas de columna, no compila.
|
|
||||||
- Un tipo de error que convierte cualquier fallo de la base de datos en una respuesta 500 con su
|
|
||||||
traza, sin repetir código.
|
|
||||||
- Pruebas aisladas con una base de datos **en memoria**.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Conectar una base de datos](../how-to/database.md): PostgreSQL, MySQL, más migraciones y
|
|
||||||
consultas.
|
|
||||||
- [Añadir usuarios y permisos](../how-to/users.md): que sólo quien inicia sesión pueda borrar
|
|
||||||
tareas.
|
|
||||||
- [Ordenar y paginar sin recargar](../how-to/htmx-tables.md), para cuando la lista crezca.
|
|
||||||
|
|
@ -1,206 +0,0 @@
|
||||||
# Tu primera aplicación
|
|
||||||
|
|
||||||
En este tutorial pasas de no tener nada instalado a un servidor web propio con dos páginas, una
|
|
||||||
de ellas con parámetros en la URL, y un ajuste que cambias sin recompilar.
|
|
||||||
|
|
||||||
- **Tiempo:** unos 10 minutos (más lo que tarde la primera compilación).
|
|
||||||
- **Necesitas:** conocer lo básico de Rust y tener una terminal a mano.
|
|
||||||
- **Al terminar tendrás:** una aplicación PageTop que entiendes línea a línea.
|
|
||||||
|
|
||||||
## 1. Instala Rust
|
|
||||||
|
|
||||||
PageTop necesita **Rust 1.88** o posterior. Si no lo tienes, instálalo con
|
|
||||||
[rustup](https://rustup.rs) y comprueba la versión:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
rustc --version
|
|
||||||
```
|
|
||||||
|
|
||||||
```text
|
|
||||||
rustc 1.90.0 (1159e78c4 2025-09-14)
|
|
||||||
```
|
|
||||||
|
|
||||||
Cualquier versión igual o superior sirve. Un editor con *rust-analyzer* (VS Code, Zed, RustRover...)
|
|
||||||
te ahorrará muchos viajes a la documentación.
|
|
||||||
|
|
||||||
## 2. Crea el proyecto
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo new hello-pagetop
|
|
||||||
cd hello-pagetop
|
|
||||||
```
|
|
||||||
|
|
||||||
Añade PageTop a `Cargo.toml`. Esta guía describe la versión en desarrollo, que se obtiene del
|
|
||||||
repositorio oficial:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
```
|
|
||||||
|
|
||||||
No necesitas añadir Tokio ni Axum: PageTop ya los trae y los expone a través de su **preludio**,
|
|
||||||
`pagetop::prelude::*`.
|
|
||||||
|
|
||||||
## 3. Arranca el servidor
|
|
||||||
|
|
||||||
Sustituye el contenido de `src/main.rs`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::new().await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Y ejecútalo:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo run
|
|
||||||
```
|
|
||||||
|
|
||||||
La primera compilación tarda unos minutos; las siguientes, segundos. Cuando termine, verás algo así:
|
|
||||||
|
|
||||||
```text
|
|
||||||
PageTop App
|
|
||||||
Powered by PageTop 0.5.0
|
|
||||||
|
|
||||||
INFO pagetop::core::extension::all: Loading settings for all extensions
|
|
||||||
INFO pagetop::core::extension::all: Calling application bootstrap
|
|
||||||
```
|
|
||||||
|
|
||||||
En un terminal de 80 columnas o más, el nombre aparece en letras grandes. Abre
|
|
||||||
<http://localhost:8080>: es la página de bienvenida de PageTop. Para el servidor con `Ctrl+C`.
|
|
||||||
|
|
||||||
`Application::new()` arranca una aplicación vacía, útil para comprobar que todo funciona. Para hacer
|
|
||||||
algo propio necesitas una **extensión raíz**.
|
|
||||||
|
|
||||||
## 4. Tu primera página
|
|
||||||
|
|
||||||
Todo en PageTop es una extensión, empezando por tu aplicación. Cambia `src/main.rs`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
struct HelloPageTop;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for HelloPageTop {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/", web::get(home))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Home"))
|
|
||||||
.with_child(Html::with(|_| html! {
|
|
||||||
h1 { "Hello, PageTop!" }
|
|
||||||
p { "This page is generated by the server." }
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&HelloPageTop).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Arranca de nuevo y recarga <http://localhost:8080>. Qué está pasando:
|
|
||||||
|
|
||||||
1. `HelloPageTop` es una extensión: un *struct* vacío que implementa `Extension`. Todos sus
|
|
||||||
métodos son opcionales; aquí sólo usa uno.
|
|
||||||
2. `configure_router()` registra la ruta `/` y la asocia al *handler* `home`.
|
|
||||||
3. `home` recibe la petición, construye una `Page`, le pone título y contenido, y la **renderiza**:
|
|
||||||
el tema activo añade el `<head>`, la estructura de la página, los estilos y el pie.
|
|
||||||
4. `Application::prepare()` arranca la aplicación con `HelloPageTop` como **extensión raíz**.
|
|
||||||
|
|
||||||
El contenido se escribe con la macro `html!`: HTML con sintaxis de Rust, comprobado al compilar. Si
|
|
||||||
olvidas cerrar una llave, no compila. La verás a fondo en [Escribir HTML con
|
|
||||||
`html!`](../how-to/html.md).
|
|
||||||
|
|
||||||
## 5. Una ruta con parámetros
|
|
||||||
|
|
||||||
Las rutas pueden capturar segmentos de la URL. Añade una segunda ruta:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
struct HelloPageTop;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for HelloPageTop {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes
|
|
||||||
.public_route("/", web::get(home))
|
|
||||||
.public_route("/hello/{name}", web::get(hello))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
# Page::new(request).render().await
|
|
||||||
# }
|
|
||||||
async fn hello(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Path(name): web::Path<String>,
|
|
||||||
) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Greeting"))
|
|
||||||
.with_child(Html::with(move |_| html! { h1 { "Hello, " (name) "!" } }))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&HelloPageTop).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Visita <http://localhost:8080/hello/Ana>. Ahora prueba
|
|
||||||
<http://localhost:8080/hello/%3Cscript%3E>: verás `<script>` como texto, porque `html!` **escapa**
|
|
||||||
todo lo que insertas. No tienes que acordarte de hacerlo.
|
|
||||||
|
|
||||||
Y una ruta que no existe, como <http://localhost:8080/nope>, responde con una página 404 que
|
|
||||||
mantiene el aspecto del sitio.
|
|
||||||
|
|
||||||
## 6. Cambia un ajuste sin recompilar
|
|
||||||
|
|
||||||
El título de la pestaña dice «PageTop App | Greeting». Ese nombre es un **ajuste** de la
|
|
||||||
aplicación. Crea `config/common.toml`, junto a `Cargo.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[app]
|
|
||||||
name = "Hello PageTop"
|
|
||||||
```
|
|
||||||
|
|
||||||
Para el servidor y arráncalo con `cargo run`: no se recompila nada, sólo se lee la configuración.
|
|
||||||
La pestaña dice ahora «Hello PageTop | Greeting», y el pie de página también usa el nuevo nombre.
|
|
||||||
|
|
||||||
Prueba a escribir mal la clave (`nmae = ...`): la aplicación no arranca y te dice qué clave no
|
|
||||||
reconoce, y cuáles admite:
|
|
||||||
|
|
||||||
```text
|
|
||||||
Invalid settings in section [app]: unknown field `nmae`, expected one of `name`, `theme`, ...
|
|
||||||
```
|
|
||||||
|
|
||||||
Las erratas en la configuración no pasan desapercibidas.
|
|
||||||
|
|
||||||
## Lo que has construido
|
|
||||||
|
|
||||||
- Un servidor web completo en un solo archivo, sin añadir Tokio ni Axum a mano.
|
|
||||||
- Una **extensión raíz** con dos rutas, una de ellas con parámetros.
|
|
||||||
- Páginas completas que el tema rodea de cabecera, estilos y pie.
|
|
||||||
- HTML comprobado al compilar y escapado automáticamente.
|
|
||||||
- Un ajuste en `config/common.toml` que cambia la aplicación sin recompilar.
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Recorrido por PageTop](tour.md): componentes, formularios, traducciones y pruebas en un solo
|
|
||||||
paseo.
|
|
||||||
- [Tareas del huerto con HTMX](htmx-tasks.md), si prefieres ir directo a la interactividad.
|
|
||||||
- [Arquitectura: del arranque a la respuesta](../explanation/architecture.md), para entender qué
|
|
||||||
hace `Application::prepare()` por dentro.
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,525 +0,0 @@
|
||||||
# Recorrido por PageTop
|
|
||||||
|
|
||||||
Este recorrido va más rápido que [Tu primera aplicación](first-app.md). En una sola aplicación, un
|
|
||||||
directorio de huertos vecinales, tocas las piezas que usarás a diario: un **tema**, un
|
|
||||||
**componente** propio, una **rejilla**, un **formulario**, **traducciones**, **ajustes** propios y
|
|
||||||
una **prueba**. Cada sección termina con un enlace a la guía que la explica a fondo.
|
|
||||||
|
|
||||||
- **Tiempo:** unos 20 minutos.
|
|
||||||
- **Necesitas:** haber hecho [Tu primera aplicación](first-app.md).
|
|
||||||
|
|
||||||
## Prepara el proyecto
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo new gardens
|
|
||||||
cd gardens
|
|
||||||
```
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[dependencies]
|
|
||||||
pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
pagetop-bootsier = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
```
|
|
||||||
|
|
||||||
Esta vez la aplicación vive en `src/lib.rs` y `src/main.rs` sólo la arranca. Así las pruebas, y
|
|
||||||
cualquier otro programa, pueden usar la aplicación como una biblioteca:
|
|
||||||
|
|
||||||
```rust,ignore
|
|
||||||
// src/main.rs
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
#[pagetop::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
Application::prepare(&gardens::Gardens).await.run().await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
// src/lib.rs
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
pub struct Gardens;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Gardens {
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`pagetop_bootsier::Bootsier` es un **tema** basado en Bootstrap 5. Declararlo como dependencia lo
|
|
||||||
pone a disposición de la aplicación; elegirlo es cosa de la configuración. Crea
|
|
||||||
`config/common.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[app]
|
|
||||||
name = "Urban Garden"
|
|
||||||
theme = "Bootsier"
|
|
||||||
```
|
|
||||||
|
|
||||||
Más en [Crear un tema](../how-to/themes.md) y [Extensiones oficiales](../reference/extensions.md).
|
|
||||||
|
|
||||||
## Un componente propio
|
|
||||||
|
|
||||||
Cada huerto se muestra en una tarjeta. Como la tarjeta se repite, se convierte en un
|
|
||||||
**componente**: un tipo Rust con sus datos, sus métodos `with_*()` y su HTML. Añádelo a
|
|
||||||
`src/lib.rs`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
|
||||||
pub struct GardenCard {
|
|
||||||
/// Returns the name of the garden.
|
|
||||||
name: Lc,
|
|
||||||
/// Returns the number of free plots.
|
|
||||||
#[getters(copy)]
|
|
||||||
free_plots: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Component for GardenCard {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
let plots = Lc::n(util::join!(self.free_plots().to_string(), " free plots"));
|
|
||||||
let mut badge = if self.free_plots() > 0 {
|
|
||||||
Badge::success(plots)
|
|
||||||
} else {
|
|
||||||
Badge::neutral(plots)
|
|
||||||
};
|
|
||||||
Ok(html! {
|
|
||||||
article class="garden-card" {
|
|
||||||
h3 { (self.name().using(cx)) }
|
|
||||||
(badge.render(cx).await)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[builder_impl]
|
|
||||||
impl GardenCard {
|
|
||||||
/// Sets the name of the garden.
|
|
||||||
pub fn with_name(mut self, name: Lc) -> Self {
|
|
||||||
self.name = name;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the number of free plots.
|
|
||||||
pub fn with_free_plots(mut self, free_plots: u32) -> Self {
|
|
||||||
self.free_plots = free_plots;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Tres cosas a retener:
|
|
||||||
|
|
||||||
- Los textos son `Lc`, no cadenas: se resuelven al renderizar, en el idioma de cada visitante.
|
|
||||||
- `prepare()` es `async` y puede usar otros componentes: aquí, un `Badge` verde o gris según
|
|
||||||
queden parcelas libres. El tema decide cómo se ve cada intención.
|
|
||||||
- `#[builder_impl]` genera, junto a cada `with_*()`, un `alter_*()` que modifica la tarjeta ya
|
|
||||||
creada. Un tema o una extensión pueden usarlo para retocarla.
|
|
||||||
|
|
||||||
Más en [Crear un componente](../how-to/custom-components.md).
|
|
||||||
|
|
||||||
## Una página con rejilla
|
|
||||||
|
|
||||||
Los datos son una lista fija y la página los coloca en una rejilla de tres columnas con `Grid`, sin
|
|
||||||
escribir CSS:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# #[derive(AutoDefault, Clone, Debug)]
|
|
||||||
# pub struct GardenCard;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Component for GardenCard {
|
|
||||||
# fn new() -> Self { Self }
|
|
||||||
# async fn prepare(&self, _: &mut Context) -> Result<Markup, ComponentError> { Ok(html! {}) }
|
|
||||||
# }
|
|
||||||
# impl GardenCard {
|
|
||||||
# pub fn with_name(self, _: Lc) -> Self { self }
|
|
||||||
# pub fn with_free_plots(self, _: u32) -> Self { self }
|
|
||||||
# }
|
|
||||||
const GARDENS: &[(&str, u32)] = &[("Benimaclet", 4), ("Russafa", 0), ("Natzaret", 2)];
|
|
||||||
|
|
||||||
async fn list(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
let mut grid = Grid::new()
|
|
||||||
.with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))
|
|
||||||
.with_gap(align::Gap::Both(UnitValue::RelRem(1.0)));
|
|
||||||
for (name, free_plots) in GARDENS {
|
|
||||||
grid = grid.with_child(
|
|
||||||
GardenCard::new()
|
|
||||||
.with_name(Lc::n(*name))
|
|
||||||
.with_free_plots(*free_plots),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Community gardens"))
|
|
||||||
.with_child(Html::with(|_| html! { h1 { "Community gardens" } }))
|
|
||||||
.with_child(grid)
|
|
||||||
.with_child(Button::anchor(Lc::n("Propose a garden"), "/propose"))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Regístrala en la extensión con `routes.public_route("/", web::get(list))`, arranca y abre
|
|
||||||
<http://localhost:8080>. Con Bootsier, las tarjetas, las etiquetas y el botón ya tienen el aspecto
|
|
||||||
de Bootstrap. Cambia `theme = "Basic"` en la configuración, reinicia y verás el mismo contenido con
|
|
||||||
otra piel.
|
|
||||||
|
|
||||||
Más en [Maquetar con Flex y Grid](../how-to/layout.md) y [Usar componentes](../how-to/components.md).
|
|
||||||
|
|
||||||
## Un formulario
|
|
||||||
|
|
||||||
Ahora, un formulario para proponer huertos nuevos. `Form` y sus campos generan las etiquetas, la
|
|
||||||
marca de obligatorio y los atributos de accesibilidad:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
fn proposal_form() -> Form {
|
|
||||||
Form::new()
|
|
||||||
.with_action("/propose")
|
|
||||||
.with_method(form::Method::Post)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::text()
|
|
||||||
.with_name("name")
|
|
||||||
.with_label(Lc::n("Garden name"))
|
|
||||||
.with_required(true),
|
|
||||||
)
|
|
||||||
.with_child(
|
|
||||||
form::input::Field::email()
|
|
||||||
.with_name("email")
|
|
||||||
.with_label(Lc::n("Your email"))
|
|
||||||
.with_help_text(Lc::n("Only to tell you how it goes.")),
|
|
||||||
)
|
|
||||||
.with_child(Button::submit(Lc::n("Send")))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Proposal {
|
|
||||||
name: String,
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn propose(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_title(Lc::n("Propose a garden"))
|
|
||||||
.with_child(proposal_form())
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn receive(
|
|
||||||
request: HttpRequest,
|
|
||||||
web::Form(proposal): web::Form<Proposal>,
|
|
||||||
) -> Result<Response, ErrorPage> {
|
|
||||||
if proposal.name.trim().is_empty() {
|
|
||||||
let mut page = Page::new(request)
|
|
||||||
.with_title(Lc::n("Propose a garden"))
|
|
||||||
.with_child(proposal_form());
|
|
||||||
page.push_message(MessageLevel::Error, Lc::n("The garden needs a name."));
|
|
||||||
return page.render().await.map(IntoResponse::into_response);
|
|
||||||
}
|
|
||||||
trace::info!("New garden proposed: {} ({})", proposal.name, proposal.email);
|
|
||||||
let cx = Context::new(request);
|
|
||||||
Ok(Redirect::see_other(cx.route("/")).with_message(
|
|
||||||
&cx,
|
|
||||||
MessageLevel::Info,
|
|
||||||
Lc::n("Thank you! We will review your proposal."),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Las dos funciones atienden la misma ruta, una por método:
|
|
||||||
`routes.public_route("/propose", web::get(propose).post(receive))`.
|
|
||||||
|
|
||||||
El navegador ya impide enviar el nombre vacío (`required`), pero el servidor lo comprueba igual:
|
|
||||||
cualquiera puede saltarse el navegador. Si falta, la página se repite con un aviso, que aparece al
|
|
||||||
principio del contenido sin hacer nada más. Si todo va bien, redirige con `see_other()`, para que
|
|
||||||
recargar no reenvíe el formulario, y `with_message()` deja un aviso de agradecimiento para la
|
|
||||||
portada. La propuesta queda en las trazas del terminal.
|
|
||||||
|
|
||||||
Más en [Crear y procesar formularios](../how-to/forms.md).
|
|
||||||
|
|
||||||
## Traducciones
|
|
||||||
|
|
||||||
Los textos de la interfaz se traducen con [Fluent](https://projectfluent.org). Crea un archivo por
|
|
||||||
idioma en `src/locale/`:
|
|
||||||
|
|
||||||
```text
|
|
||||||
# src/locale/en-US/app.ftl
|
|
||||||
gardens = Community gardens
|
|
||||||
free-plots = { $count ->
|
|
||||||
[0] No free plots
|
|
||||||
[one] One free plot
|
|
||||||
*[other] { $count } free plots
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```text
|
|
||||||
# src/locale/es-ES/app.ftl
|
|
||||||
gardens = Huertos vecinales
|
|
||||||
free-plots = { $count ->
|
|
||||||
[0] Sin parcelas libres
|
|
||||||
[one] Una parcela libre
|
|
||||||
*[other] { $count } parcelas libres
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Fluent resuelve los plurales en el propio archivo, cada idioma con sus reglas. En `src/lib.rs`,
|
|
||||||
declara las traducciones una vez y usa `Lc::t()` donde antes había `Lc::n()`:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
include_locales!(LOCALES_APP);
|
|
||||||
|
|
||||||
# struct Card { free_plots: u32 }
|
|
||||||
# impl Card { fn free_plots(&self) -> u32 { self.free_plots } fn f(&self) {
|
|
||||||
// In GardenCard::prepare():
|
|
||||||
let plots = Lc::t("free-plots", &LOCALES_APP).with_number("count", self.free_plots());
|
|
||||||
# }}
|
|
||||||
# fn g() {
|
|
||||||
// In list():
|
|
||||||
let title = Lc::t("gardens", &LOCALES_APP);
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
`include_locales!` mete los archivos en el binario al compilar. Abre
|
|
||||||
<http://localhost:8080/?lang=es>: el título y las etiquetas salen en español. Sin `?lang=`,
|
|
||||||
PageTop usa el idioma configurado o el que pida el navegador.
|
|
||||||
|
|
||||||
Más en [Traducir la aplicación](../how-to/localization.md).
|
|
||||||
|
|
||||||
## Ajustes propios
|
|
||||||
|
|
||||||
La aplicación muestra los huertos de una ciudad, y la ciudad debería poder cambiarse sin
|
|
||||||
recompilar. Declara una sección propia de configuración, con sus valores por defecto:
|
|
||||||
|
|
||||||
```rust,no_run
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
/// Settings of the `[gardens]` section.
|
|
||||||
pub static SETTINGS: LazySettings<GardensSettings> = LazySettings::new();
|
|
||||||
|
|
||||||
/// The **`[gardens]`** section of the configuration.
|
|
||||||
#[settings(section = "gardens")]
|
|
||||||
pub struct GardensSettings {
|
|
||||||
/// City whose gardens are listed.
|
|
||||||
#[default = "Valencia"]
|
|
||||||
pub city: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Gardens;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Gardens {
|
|
||||||
// ... dependencies() and configure_router() as before ...
|
|
||||||
|
|
||||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
|
||||||
Some(&SETTINGS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Úsala en la página, por ejemplo bajo el título, con `SETTINGS.city`. Y cámbiala en
|
|
||||||
`config/common.toml`:
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[gardens]
|
|
||||||
city = "Alicante"
|
|
||||||
```
|
|
||||||
|
|
||||||
`settings()` hace que la sección se cargue y se **valide al arrancar**: una clave desconocida o un
|
|
||||||
valor del tipo equivocado detienen la aplicación antes de servir una sola página.
|
|
||||||
|
|
||||||
Más en [Configurar la aplicación](../how-to/configuration.md).
|
|
||||||
|
|
||||||
## Una prueba
|
|
||||||
|
|
||||||
Las pruebas preparan la aplicación sin abrir ningún puerto y le envían peticiones. Crea
|
|
||||||
`tests/gardens.rs`:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
# use pagetop::prelude::*;
|
|
||||||
# use serde::Deserialize;
|
|
||||||
# include_locales!(LOCALES_APP);
|
|
||||||
# pub static SETTINGS: LazySettings<GardensSettings> = LazySettings::new();
|
|
||||||
# #[settings(section = "gardens")]
|
|
||||||
# pub struct GardensSettings {
|
|
||||||
# #[default = "Valencia"]
|
|
||||||
# pub city: String,
|
|
||||||
# }
|
|
||||||
# #[derive(AutoDefault, Clone, Debug, Getters)]
|
|
||||||
# pub struct GardenCard {
|
|
||||||
# name: Lc,
|
|
||||||
# #[getters(copy)]
|
|
||||||
# free_plots: u32,
|
|
||||||
# }
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Component for GardenCard {
|
|
||||||
# fn new() -> Self {
|
|
||||||
# Self::default()
|
|
||||||
# }
|
|
||||||
# async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
# let plots = Lc::t("free-plots", &LOCALES_APP).with_number("count", self.free_plots());
|
|
||||||
# let mut badge = if self.free_plots() > 0 {
|
|
||||||
# Badge::success(plots)
|
|
||||||
# } else {
|
|
||||||
# Badge::neutral(plots)
|
|
||||||
# };
|
|
||||||
# Ok(html! {
|
|
||||||
# article class="garden-card" {
|
|
||||||
# h3 { (self.name().using(cx)) }
|
|
||||||
# (badge.render(cx).await)
|
|
||||||
# }
|
|
||||||
# })
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# #[builder_impl]
|
|
||||||
# impl GardenCard {
|
|
||||||
# pub fn with_name(mut self, name: Lc) -> Self {
|
|
||||||
# self.name = name;
|
|
||||||
# self
|
|
||||||
# }
|
|
||||||
# pub fn with_free_plots(mut self, free_plots: u32) -> Self {
|
|
||||||
# self.free_plots = free_plots;
|
|
||||||
# self
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# const GARDENS: &[(&str, u32)] = &[("Benimaclet", 4), ("Russafa", 0), ("Natzaret", 2)];
|
|
||||||
# pub struct Gardens;
|
|
||||||
# #[async_trait]
|
|
||||||
# impl Extension for Gardens {
|
|
||||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
# vec![&pagetop_bootsier::Bootsier]
|
|
||||||
# }
|
|
||||||
# fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
|
||||||
# Some(&SETTINGS)
|
|
||||||
# }
|
|
||||||
# fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
# routes
|
|
||||||
# .public_route("/", web::get(list))
|
|
||||||
# .public_route("/propose", web::get(propose).post(receive))
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
# async fn list(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
# let mut grid = Grid::new()
|
|
||||||
# .with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))
|
|
||||||
# .with_gap(align::Gap::Both(UnitValue::RelRem(1.0)));
|
|
||||||
# for (name, free_plots) in GARDENS {
|
|
||||||
# grid = grid.with_child(
|
|
||||||
# GardenCard::new()
|
|
||||||
# .with_name(Lc::n(*name))
|
|
||||||
# .with_free_plots(*free_plots),
|
|
||||||
# );
|
|
||||||
# }
|
|
||||||
# let title = Lc::t("gardens", &LOCALES_APP);
|
|
||||||
# Page::new(request)
|
|
||||||
# .with_title(title.clone())
|
|
||||||
# .with_child(Html::with(move |cx| html! {
|
|
||||||
# h1 { (title.using(cx)) }
|
|
||||||
# p { (SETTINGS.city) }
|
|
||||||
# }))
|
|
||||||
# .with_child(grid)
|
|
||||||
# .with_child(Button::anchor(Lc::n("Propose a garden"), "/propose"))
|
|
||||||
# .render()
|
|
||||||
# .await
|
|
||||||
# }
|
|
||||||
# fn proposal_form() -> Form {
|
|
||||||
# Form::new()
|
|
||||||
# .with_action("/propose")
|
|
||||||
# .with_method(form::Method::Post)
|
|
||||||
# .with_child(
|
|
||||||
# form::input::Field::text()
|
|
||||||
# .with_name("name")
|
|
||||||
# .with_label(Lc::n("Garden name"))
|
|
||||||
# .with_required(true),
|
|
||||||
# )
|
|
||||||
# .with_child(Button::submit(Lc::n("Send")))
|
|
||||||
# }
|
|
||||||
# #[derive(Deserialize)]
|
|
||||||
# struct Proposal {
|
|
||||||
# name: String,
|
|
||||||
# }
|
|
||||||
# async fn propose(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
# Page::new(request).with_child(proposal_form()).render().await
|
|
||||||
# }
|
|
||||||
# async fn receive(
|
|
||||||
# request: HttpRequest,
|
|
||||||
# web::Form(proposal): web::Form<Proposal>,
|
|
||||||
# ) -> Result<Response, ErrorPage> {
|
|
||||||
# if proposal.name.trim().is_empty() {
|
|
||||||
# let mut page = Page::new(request).with_child(proposal_form());
|
|
||||||
# page.push_message(MessageLevel::Error, Lc::n("The garden needs a name."));
|
|
||||||
# return page.render().await.map(IntoResponse::into_response);
|
|
||||||
# }
|
|
||||||
# Ok(Redirect::see_other("/"))
|
|
||||||
# }
|
|
||||||
# mod gardens {
|
|
||||||
# pub use super::Gardens;
|
|
||||||
# }
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn lists_the_gardens_in_both_languages() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&gardens::Gardens).await.test());
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get().uri("/").to_request();
|
|
||||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
|
||||||
assert!(body.contains("Community gardens"));
|
|
||||||
assert!(body.contains("4 free plots"));
|
|
||||||
assert!(body.contains("No free plots"));
|
|
||||||
|
|
||||||
let request = web::test::TestRequest::get().uri("/?lang=es").to_request();
|
|
||||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
|
||||||
assert!(body.contains("Huertos vecinales"));
|
|
||||||
assert!(body.contains("Sin parcelas libres"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn a_proposal_without_name_is_rejected() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&gardens::Gardens).await.test());
|
|
||||||
|
|
||||||
// The form is sent as a browser does, with an empty name.
|
|
||||||
let request = web::test::TestRequest::post()
|
|
||||||
.uri("/propose")
|
|
||||||
.form("name=+&email=ana%40example.com")
|
|
||||||
.to_request();
|
|
||||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
|
||||||
assert!(body.contains("The garden needs a name."));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cargo test
|
|
||||||
```
|
|
||||||
|
|
||||||
`#[pagetop::test]` ejecuta cada prueba en el mismo *runtime* asíncrono que usa la aplicación real.
|
|
||||||
|
|
||||||
Más en [Probar rutas y componentes](../how-to/testing.md).
|
|
||||||
|
|
||||||
## Lo que has recorrido
|
|
||||||
|
|
||||||
| Pieza | Lo que hace | Para profundizar |
|
|
||||||
|---|---|---|
|
|
||||||
| Extensión | Declara dependencias, rutas y ajustes | [Crear una extensión](../how-to/extensions.md) |
|
|
||||||
| Tema | Da el aspecto; se elige en la configuración | [Crear un tema](../how-to/themes.md) |
|
|
||||||
| Componente | Interfaz reutilizable con datos y HTML propios | [Crear un componente](../how-to/custom-components.md) |
|
|
||||||
| `Grid` | Rejillas sin CSS | [Maquetar con Flex y Grid](../how-to/layout.md) |
|
|
||||||
| `Form` | Formularios accesibles | [Crear y procesar formularios](../how-to/forms.md) |
|
|
||||||
| `Lc` y Fluent | Textos traducidos, con plurales | [Traducir la aplicación](../how-to/localization.md) |
|
|
||||||
| `#[settings]` | Ajustes propios validados al arrancar | [Configurar la aplicación](../how-to/configuration.md) |
|
|
||||||
| `#[pagetop::test]` | Pruebas sin servidor | [Probar rutas y componentes](../how-to/testing.md) |
|
|
||||||
|
|
||||||
## Siguiente
|
|
||||||
|
|
||||||
- [Tareas del huerto con HTMX](htmx-tasks.md): la misma forma de trabajar, ahora sin recargar la
|
|
||||||
página.
|
|
||||||
- [Componentes, temas y renderizado](../explanation/rendering.md): qué pasa entre `with_child()` y
|
|
||||||
el HTML final.
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
edition = "2024"
|
|
||||||
119
src/lib.rs
119
src/lib.rs
|
|
@ -1,119 +0,0 @@
|
||||||
/*!
|
|
||||||
Official [PageTop](https://pagetop.cillero.es) website.
|
|
||||||
|
|
||||||
It introduces PageTop to the community and publishes its guides, written with mdBook under `doc/`
|
|
||||||
and served with [`pagetop_mdbook`].
|
|
||||||
|
|
||||||
Built on the [PageTop](https://docs.rs/pagetop) framework.
|
|
||||||
*/
|
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
include_locales!(LOCALES_WEBSITE);
|
|
||||||
|
|
||||||
// Version of the guides that `/doc/latest/{lang}` redirects to.
|
|
||||||
const LATEST_DOC: &str = "v0.6";
|
|
||||||
|
|
||||||
// Languages of the guides; the first one is used for any other language.
|
|
||||||
const DOC_LANGUAGES: &[&str] = &["es"];
|
|
||||||
|
|
||||||
/// Root extension of the PageTop website.
|
|
||||||
pub struct Website;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for Website {
|
|
||||||
fn name(&self) -> Lc {
|
|
||||||
Lc::t("app_name", &LOCALES_WEBSITE)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn description(&self) -> Lc {
|
|
||||||
Lc::t("app_description", &LOCALES_WEBSITE)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
|
||||||
vec![
|
|
||||||
&pagetop_bootsier::Bootsier,
|
|
||||||
&pagetop_mdbook::MdBook,
|
|
||||||
// PageTop welcome page at `/`, until the website has a home page of its own.
|
|
||||||
&pagetop::base::extension::Welcome,
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
|
||||||
InRegion::Global(&CoreRegions::Header).add(main_menu());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
let routes = routes.public_route("/doc/latest/{lang}", web::get(doc_latest));
|
|
||||||
pagetop_mdbook::serve_mdbook!(routes, [doc] => "/doc", Access::Public);
|
|
||||||
routes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main_menu() -> Navbar {
|
|
||||||
let brand = Brand::new()
|
|
||||||
.with_title(Lc::n(global::SETTINGS.app.name.clone()))
|
|
||||||
.with_route(Route::from("/"));
|
|
||||||
let nav = Nav::new()
|
|
||||||
.with_prop(FlexItem::push_end())
|
|
||||||
.with_item(nav::Item::link(Lc::t("menu_home", &LOCALES_WEBSITE), "/"))
|
|
||||||
.with_item(nav::Item::link(
|
|
||||||
Lc::t("menu_documentation", &LOCALES_WEBSITE),
|
|
||||||
Route::with(|cx| RoutePath::new(util::join!("/doc/latest/", doc_language(cx)))),
|
|
||||||
))
|
|
||||||
.with_item(nav::Item::link_blank(
|
|
||||||
Lc::t("menu_api", &LOCALES_WEBSITE),
|
|
||||||
"https://docs.rs/pagetop",
|
|
||||||
))
|
|
||||||
.with_item(nav::Item::link_blank(
|
|
||||||
Lc::t("menu_code", &LOCALES_WEBSITE),
|
|
||||||
"https://github.com/manuelcillero/pagetop",
|
|
||||||
))
|
|
||||||
.with_item(nav::Item::dropdown(
|
|
||||||
Dropdown::new()
|
|
||||||
.with_title(Lc::t("menu_language", &LOCALES_WEBSITE))
|
|
||||||
.with_menu_end(true)
|
|
||||||
.with_item(dropdown::Item::link(
|
|
||||||
Lc::n("English"),
|
|
||||||
Route::with(|cx| switch_language(cx, "en")),
|
|
||||||
))
|
|
||||||
.with_item(dropdown::Item::link(
|
|
||||||
Lc::n("Español"),
|
|
||||||
Route::with(|cx| switch_language(cx, "es")),
|
|
||||||
)),
|
|
||||||
));
|
|
||||||
Navbar::brand_left(brand).with_item(navbar::Item::nav(nav))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn doc_language(cx: &Context) -> &'static str {
|
|
||||||
available_doc_language(cx.langid().language.as_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn available_doc_language(lang: &str) -> &'static str {
|
|
||||||
DOC_LANGUAGES
|
|
||||||
.iter()
|
|
||||||
.find(|available| **available == lang)
|
|
||||||
.unwrap_or(&DOC_LANGUAGES[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
// Same page in another language: in the guides (`/doc/<version>/<lang>/...`) the language is part
|
|
||||||
// of the path, if the guides exist in that language; elsewhere it is requested with `?lang=`.
|
|
||||||
fn switch_language(cx: &Context, lang: &str) -> RoutePath {
|
|
||||||
let path = cx.request().map_or("/", |request| request.path());
|
|
||||||
if let Some(rest) = path.strip_prefix("/doc/")
|
|
||||||
&& DOC_LANGUAGES.contains(&lang)
|
|
||||||
{
|
|
||||||
let mut segments = rest.splitn(3, '/');
|
|
||||||
if let (Some(version), Some(_)) = (segments.next(), segments.next()) {
|
|
||||||
let page = segments.next().unwrap_or_default();
|
|
||||||
return RoutePath::new(util::join!("/doc/", version, "/", lang, "/", page));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
RoutePath::new(path.to_string()).with_param("lang", lang)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn doc_latest(web::Path(lang): web::Path<String>) -> Response {
|
|
||||||
let lang = available_doc_language(&lang);
|
|
||||||
Redirect::see_other(util::join!("/doc/", LATEST_DOC, "/", lang, "/index.html"))
|
|
||||||
}
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
app_name = PageTop Landing Page
|
|
||||||
app_description = Discover PageTop with helpful user guides, tutorials, and practical examples.
|
|
||||||
app_slogan = Modular web solutions made simple
|
|
||||||
|
|
||||||
menu_home = Home
|
|
||||||
menu_documentation = Documentation
|
|
||||||
menu_api = API
|
|
||||||
menu_code = Code
|
|
||||||
menu_language = Language
|
|
||||||
|
|
||||||
under_construction = <strong>This website is under construction</strong>. If you're curious, you can read the <a href="/doc/latest/es">latest Spanish version of the PageTop documentation</a>.
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
app_name = Presentación de PageTop
|
|
||||||
app_description = Descubre PageTop con guías útiles para el usuario, tutoriales y ejemplos prácticos.
|
|
||||||
app_slogan = Crea fácilmente soluciones web modulares
|
|
||||||
|
|
||||||
menu_home = Inicio
|
|
||||||
menu_documentation = Documentación
|
|
||||||
menu_api = API
|
|
||||||
menu_code = Código
|
|
||||||
menu_language = Idioma
|
|
||||||
|
|
||||||
under_construction = <strong>Este sitio web está en construcción</strong>. Si tienes curiosidad, puedes leer la <a href="/doc/latest/es">versión más reciente de la documentación de PageTop en español</a>.
|
|
||||||
|
|
@ -2,8 +2,5 @@ use pagetop::prelude::*;
|
||||||
|
|
||||||
#[pagetop::main]
|
#[pagetop::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
Application::prepare(&pagetop_website::Website)
|
Application::new().run()?.await
|
||||||
.await
|
|
||||||
.run()
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
#!/bin/bash
|
|
||||||
# Checks a book of the guides against the current PageTop code: its links, and that every Rust
|
|
||||||
# example compiles (and runs, if it is not marked `no_run`). See "Checking the guides" in README.md.
|
|
||||||
#
|
|
||||||
# Usage: tools/doccheck.sh [book dir] (default: the latest Spanish guide)
|
|
||||||
|
|
||||||
set -u
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|
||||||
BOOK="$(cd "${1:-$ROOT/doc/v0.6/es}" && pwd)"
|
|
||||||
CRATE="$ROOT/tools/doccheck"
|
|
||||||
OUT="$CRATE/target/book"
|
|
||||||
FAILED=0
|
|
||||||
|
|
||||||
echo "== Links"
|
|
||||||
rm -rf "$OUT"
|
|
||||||
if mdbook build "$BOOK" -d "$OUT" >/dev/null 2>&1; then
|
|
||||||
python3 "$CRATE/check_links.py" "$OUT" || FAILED=1
|
|
||||||
else
|
|
||||||
echo "mdbook build failed"; FAILED=1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "== Examples"
|
|
||||||
python3 "$CRATE/extract.py" "$BOOK/src" "$CRATE"
|
|
||||||
cd "$CRATE" || exit 1
|
|
||||||
if ! cargo build -j 2 --examples; then
|
|
||||||
FAILED=1
|
|
||||||
else
|
|
||||||
for example in examples/*_run.rs; do
|
|
||||||
[ -e "$example" ] || continue
|
|
||||||
name="$(basename "$example" .rs)"
|
|
||||||
if ! "./target/debug/examples/$name" >/dev/null; then
|
|
||||||
echo "run failed: $name"; FAILED=1
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "== Tests"
|
|
||||||
cargo test -j 2 --tests || FAILED=1
|
|
||||||
|
|
||||||
if [ "$FAILED" -eq 0 ]; then echo "OK: the guide matches the current PageTop code"; fi
|
|
||||||
exit "$FAILED"
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "doccheck"
|
|
||||||
version = "0.0.0"
|
|
||||||
edition = "2024"
|
|
||||||
description = "Compiles and runs the Rust examples of the PageTop guides (see tools/doccheck.sh)."
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
# Independent of the website package: it only exists to check the guides.
|
|
||||||
[workspace]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
pagetop = { path = "../../../pagetop" }
|
|
||||||
pagetop-bootsier = { path = "../../../pagetop/extensions/pagetop-bootsier" }
|
|
||||||
pagetop-build = { path = "../../../pagetop/helpers/pagetop-build" }
|
|
||||||
pagetop-cron = { path = "../../../pagetop/extensions/pagetop-cron" }
|
|
||||||
pagetop-htmx = { path = "../../../pagetop/extensions/pagetop-htmx" }
|
|
||||||
pagetop-mail = { path = "../../../pagetop/extensions/pagetop-mail", features = ["queue"] }
|
|
||||||
pagetop-seaorm = { path = "../../../pagetop/extensions/pagetop-seaorm", features = ["sqlite"] }
|
|
||||||
pagetop-admin = { path = "../../../pagetop/extensions/pagetop-admin" }
|
|
||||||
pagetop-user = { path = "../../../pagetop/extensions/pagetop-user" }
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
thiserror = "2"
|
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
tower-http = { version = "0.7", features = ["compression-gzip", "cors", "limit", "timeout"] }
|
|
||||||
|
|
||||||
[build-dependencies]
|
|
||||||
pagetop-build = { path = "../../../pagetop/helpers/pagetop-build" }
|
|
||||||
|
|
||||||
# The examples are only compiled and run to check them: without debug info or incremental caches
|
|
||||||
# they take far less disk.
|
|
||||||
[profile.dev]
|
|
||||||
debug = 0
|
|
||||||
incremental = false
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
// Bundle named "app", so that the examples using `serve_static_files!(router, [app] => ...)`
|
|
||||||
// compile like they would in an application.
|
|
||||||
fn main() -> std::io::Result<()> {
|
|
||||||
pagetop_build::StaticFilesBundle::from_dir("./bundle", None)
|
|
||||||
.with_name("app")
|
|
||||||
.build()
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
body {}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
"""Checks the internal links (pages and anchors) of a book built by mdBook.
|
|
||||||
|
|
||||||
Usage: check_links.py <built book dir>. Exits with 1 if any link is broken.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import pathlib
|
|
||||||
import posixpath
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
import urllib.parse
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
out = pathlib.Path(sys.argv[1])
|
|
||||||
pages = {p.relative_to(out).as_posix(): p.read_text() for p in out.rglob("*.html")}
|
|
||||||
ids = {name: set(re.findall(r'id="([^"]+)"', html)) for name, html in pages.items()}
|
|
||||||
broken = 0
|
|
||||||
for name, html in pages.items():
|
|
||||||
content = html[html.find("<main>") : html.find("</main>")]
|
|
||||||
for link, anchor in re.findall(r'href="([^"#:]*\.html)(?:#([^"]*))?"', content):
|
|
||||||
page = posixpath.normpath(posixpath.join(posixpath.dirname(name), link))
|
|
||||||
if page not in ids:
|
|
||||||
print(f"{name}: missing page {page}")
|
|
||||||
broken += 1
|
|
||||||
elif anchor and urllib.parse.unquote(anchor) not in ids[page]:
|
|
||||||
print(f"{name}: missing anchor {page}#{urllib.parse.unquote(anchor)}")
|
|
||||||
broken += 1
|
|
||||||
for anchor in re.findall(r'href="#([^"]+)"', content):
|
|
||||||
if urllib.parse.unquote(anchor) not in ids[name]:
|
|
||||||
print(f"{name}: missing anchor #{anchor}")
|
|
||||||
broken += 1
|
|
||||||
print(f"{broken} broken links")
|
|
||||||
sys.exit(1 if broken else 0)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
# Settings for the examples and tests of the guides that start an application. Those that use a
|
|
||||||
# database get a new in-memory SQLite one on every run (one connection, so all queries share it).
|
|
||||||
[database]
|
|
||||||
db_type = "sqlite"
|
|
||||||
db_name = "doccheck?mode=memory"
|
|
||||||
max_pool_size = 1
|
|
||||||
|
|
||||||
# Only errors: the expected warnings (such as [database] in an application without a database)
|
|
||||||
# would hide the result of the checks.
|
|
||||||
[log]
|
|
||||||
tracing = "Error"
|
|
||||||
|
|
||||||
# Mail is kept in memory (see how-to/mail.md), and its links point to a fixed public URL.
|
|
||||||
[mail]
|
|
||||||
transport = "memory"
|
|
||||||
from = "Community garden <garden@example.com>"
|
|
||||||
base_url = "https://garden.example.com"
|
|
||||||
|
|
||||||
# Uploaded files go to the build directory, which git ignores (see how-to/uploads.md).
|
|
||||||
[upload]
|
|
||||||
dir = "target/doccheck-uploads"
|
|
||||||
|
|
@ -1,72 +0,0 @@
|
||||||
"""Extracts the Rust code blocks of an mdBook book into the doccheck crate.
|
|
||||||
|
|
||||||
Usage: extract.py <book src dir> <doccheck dir>
|
|
||||||
|
|
||||||
Every ```rust block becomes a file, after removing the `# ` prefix of the lines that mdBook hides:
|
|
||||||
|
|
||||||
- Blocks marked `ignore` are skipped (loose fragments that are not meant to compile).
|
|
||||||
- Blocks with `#[pagetop::test]` go to `tests/generated_*.rs` and run with `cargo test`.
|
|
||||||
- The rest go to `examples/*.rs`. Those not marked `no_run` end in `_run` and are executed, so
|
|
||||||
their `assert!` are checked. Blocks without `fn main` get one: statements are wrapped in it, like
|
|
||||||
rustdoc does; items get an empty one.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import pathlib
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
|
|
||||||
STATEMENT = re.compile(r"(let |assert|[A-Za-z_:]+::[a-z_]+\(|[a-z_]+\.)")
|
|
||||||
HEADER = re.compile(r"(use |#!|include_locales!)")
|
|
||||||
|
|
||||||
|
|
||||||
def unhide(code):
|
|
||||||
lines = []
|
|
||||||
for line in code.splitlines():
|
|
||||||
if line.startswith("# "):
|
|
||||||
line = line[2:]
|
|
||||||
elif line == "#":
|
|
||||||
line = ""
|
|
||||||
lines.append(line)
|
|
||||||
return lines
|
|
||||||
|
|
||||||
|
|
||||||
def with_main(lines):
|
|
||||||
code = "\n".join(lines)
|
|
||||||
if "fn main" in code:
|
|
||||||
return code
|
|
||||||
if any(STATEMENT.match(line) for line in lines):
|
|
||||||
head = [line for line in lines if HEADER.match(line)]
|
|
||||||
body = [line for line in lines if not HEADER.match(line)]
|
|
||||||
return "\n".join(head) + "\nfn main() {\n" + "\n".join(body) + "\n}\n"
|
|
||||||
return code + "\n\nfn main() {}\n"
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
book, crate = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
|
|
||||||
examples, tests = crate / "examples", crate / "tests"
|
|
||||||
examples.mkdir(exist_ok=True)
|
|
||||||
for old in list(examples.glob("*.rs")) + list(tests.glob("generated_*.rs")):
|
|
||||||
old.unlink()
|
|
||||||
|
|
||||||
count = {"examples": 0, "tests": 0}
|
|
||||||
for md in sorted(book.rglob("*.md")):
|
|
||||||
blocks = re.finditer(r"```rust([^\n]*)\n(.*?)```", md.read_text(), re.S)
|
|
||||||
for i, block in enumerate(blocks):
|
|
||||||
attrs, lines = block.group(1), unhide(block.group(2))
|
|
||||||
if "ignore" in attrs:
|
|
||||||
continue
|
|
||||||
name = md.relative_to(book).with_suffix("").as_posix()
|
|
||||||
stem = re.sub(r"[^a-z0-9]", "_", name.lower()) + f"_{i:02d}"
|
|
||||||
prelude = "#![allow(dead_code, unused)]\n"
|
|
||||||
if any("#[pagetop::test]" in line for line in lines):
|
|
||||||
(tests / f"generated_{stem}.rs").write_text(prelude + "\n".join(lines) + "\n")
|
|
||||||
count["tests"] += 1
|
|
||||||
else:
|
|
||||||
suffix = "" if "no_run" in attrs else "_run"
|
|
||||||
(examples / f"{stem}{suffix}.rs").write_text(prelude + with_main(lines))
|
|
||||||
count["examples"] += 1
|
|
||||||
print(f"{count['examples']} examples and {count['tests']} tests extracted")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
//! Empty on purpose: the examples of the guides are extracted into `examples/` and `tests/` by
|
|
||||||
//! `tools/doccheck.sh`. The translations in `src/locale` are the ones the localization chapter uses.
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
greeting = Hello!
|
|
||||||
welcome = Welcome, { $name }.
|
|
||||||
notices = { $total ->
|
|
||||||
[one] You have one notice
|
|
||||||
*[other] You have { $total } notices
|
|
||||||
}
|
|
||||||
|
|
||||||
# Used by the tour (tutorials/tour.md).
|
|
||||||
gardens = Community gardens
|
|
||||||
free-plots = { $count ->
|
|
||||||
[0] No free plots
|
|
||||||
[one] One free plot
|
|
||||||
*[other] { $count } free plots
|
|
||||||
}
|
|
||||||
|
|
||||||
# Used by the mail guide (how-to/mail.md).
|
|
||||||
harvest-subject = The tomatoes are ready to pick
|
|
||||||
harvest-greeting = Hello, { $name }:
|
|
||||||
harvest-ready = The tomatoes in the community garden are ripe. Come and pick your share this week.
|
|
||||||
harvest-link = See the harvest calendar
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
greeting = ¡Hola!
|
|
||||||
welcome = Te damos la bienvenida, { $name }.
|
|
||||||
notices = { $total ->
|
|
||||||
[one] Tienes un aviso
|
|
||||||
*[other] Tienes { $total } avisos
|
|
||||||
}
|
|
||||||
|
|
||||||
# Used by the tour (tutorials/tour.md).
|
|
||||||
gardens = Huertos vecinales
|
|
||||||
free-plots = { $count ->
|
|
||||||
[0] Sin parcelas libres
|
|
||||||
[one] Una parcela libre
|
|
||||||
*[other] { $count } parcelas libres
|
|
||||||
}
|
|
||||||
|
|
||||||
# Used by the mail guide (how-to/mail.md).
|
|
||||||
harvest-subject = Ya se pueden recoger los tomates
|
|
||||||
harvest-greeting = Hola, { $name }:
|
|
||||||
harvest-ready = Los tomates del huerto vecinal ya están maduros. Ven a recoger tu parte esta semana.
|
|
||||||
harvest-link = Ver el calendario de cosecha
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
// Runtime check of the localization chapter: translations, arguments and plurals in both languages.
|
|
||||||
use pagetop::prelude::*;
|
|
||||||
|
|
||||||
include_locales!(LOCALES_APP);
|
|
||||||
|
|
||||||
struct App;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Extension for App {
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
|
||||||
routes.public_route("/", web::get(home))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|
||||||
Page::new(request)
|
|
||||||
.with_child(Html::with(|cx| {
|
|
||||||
let welcome = Lc::t("welcome", &LOCALES_APP).with_arg("name", "Ana");
|
|
||||||
let many = Lc::t("notices", &LOCALES_APP).with_number("total", 3);
|
|
||||||
let one = Lc::t("notices", &LOCALES_APP).with_number("total", 1);
|
|
||||||
html! { p { (welcome.using(cx)) } p { (many.using(cx)) } p { (one.using(cx)) } }
|
|
||||||
}))
|
|
||||||
.render()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[pagetop::test]
|
|
||||||
async fn translates_with_arguments_and_plurals() {
|
|
||||||
let app = web::test::init_router(Application::prepare(&App).await.test());
|
|
||||||
for (lang, expected) in [
|
|
||||||
("es", ["Te damos la bienvenida, Ana.", "Tienes 3 avisos", "Tienes un aviso"]),
|
|
||||||
("en", ["Welcome, Ana.", "You have 3 notices", "You have one notice"]),
|
|
||||||
] {
|
|
||||||
let request = web::test::TestRequest::get().uri(format!("/?lang={lang}")).to_request();
|
|
||||||
let response = web::test::send_request(&app, request).await;
|
|
||||||
let body = web::test::read_body_text(response).await;
|
|
||||||
for text in expected {
|
|
||||||
assert!(body.contains(text), "{lang}: {text:?} not found in the page");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue