Compare commits

...

7 commits

27 changed files with 587 additions and 48 deletions

View file

@ -19,6 +19,7 @@ members = [
repository = "https://git.cillero.es/manuelcillero/pagetop" repository = "https://git.cillero.es/manuelcillero/pagetop"
homepage = "https://pagetop.cillero.es" homepage = "https://pagetop.cillero.es"
edition = "2024" edition = "2024"
rust-version = "1.88"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
authors = ["Manuel Cillero <manuel@cillero.es>"] authors = ["Manuel Cillero <manuel@cillero.es>"]
@ -101,6 +102,7 @@ keywords = ["pagetop", "web", "framework", "frontend", "ssr"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -8,6 +8,7 @@ keywords = ["pagetop", "admin", "cms", "settings", "ssr"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -9,11 +9,11 @@
## Guía rápida ## Guía rápida
Declara la dependencia en tu `Cargo.toml` activando el motor de base de datos: Declara la dependencia en tu `Cargo.toml`:
```toml ```toml
[dependencies] [dependencies]
pagetop-admin = { version = "...", features = ["sqlite"] } pagetop-admin = "..."
``` ```
Añade `&pagetop_admin::Admin` a las dependencias de tu extensión y declara tus Añade `&pagetop_admin::Admin` a las dependencias de tu extensión y declara tus

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "theme", "css"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "theme", "bootstrap", "css", "js"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "htmx", "ajax", "ssr"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "database", "sql", "orm", "ssr"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -27,7 +27,8 @@
//! - **Transacciones**: [`TransactionTrait`], [`DatabaseTransaction`], [`flatten_txn_err`] //! - **Transacciones**: [`TransactionTrait`], [`DatabaseTransaction`], [`flatten_txn_err`]
//! (para convertir [`TransactionError<E>`] a `E`). //! (para convertir [`TransactionError<E>`] a `E`).
//! - **Modelos activos**: [`ActiveModelTrait`], [`ActiveValue`] ([`ActiveValue::Set`], //! - **Modelos activos**: [`ActiveModelTrait`], [`ActiveValue`] ([`ActiveValue::Set`],
//! [`ActiveValue::Unchanged`], [`ActiveValue::NotSet`]). //! [`ActiveValue::Unchanged`], [`ActiveValue::NotSet`]), [`IntoActiveModel`] (para modificar un
//! modelo leído: `model.into_active_model()`).
//! - **Macros de derivación**: [`DeriveEntityModel`], [`DeriveColumn`], [`DerivePrimaryKey`], //! - **Macros de derivación**: [`DeriveEntityModel`], [`DeriveColumn`], [`DerivePrimaryKey`],
//! [`DeriveRelation`], [`EnumIter`]. //! [`DeriveRelation`], [`EnumIter`].
//! - **Errores**: [`DbErr`], [`TransactionError`]. //! - **Errores**: [`DbErr`], [`TransactionError`].
@ -167,8 +168,8 @@ pub use sea_orm::prelude::*;
pub use sea_orm; pub use sea_orm;
pub use sea_orm::{ pub use sea_orm::{
ActiveValue, Condition, DatabaseTransaction, DbBackend, ExecResult, NotSet, Order, QueryOrder, ActiveValue, Condition, DatabaseTransaction, DbBackend, ExecResult, IntoActiveModel, NotSet,
QuerySelect, Set, TransactionError, TransactionTrait, Unchanged, Order, QueryOrder, QuerySelect, Set, TransactionError, TransactionTrait, Unchanged,
}; };
/// Re-exporta `sea_query` para construir sentencias SQL en tiempo de ejecución. /// Re-exporta `sea_query` para construir sentencias SQL en tiempo de ejecución.

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "auth", "users", "session", "rbac"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -2,8 +2,8 @@
use pagetop::prelude::*; use pagetop::prelude::*;
use pagetop_seaorm::db::{ use pagetop_seaorm::db::{
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, EntityTrait, PaginatorTrait, ActiveModelTrait, ActiveValue, ColumnTrait, Condition, EntityTrait, IntoActiveModel,
QueryFilter, Set, dbconn, PaginatorTrait, QueryFilter, Set, dbconn,
}; };
use crate::account::UserStatus; use crate::account::UserStatus;
@ -61,7 +61,7 @@ pub async fn login(
// Actualizar last_login_at y resetear contador de fallos. // Actualizar last_login_at y resetear contador de fallos.
let user_id = user_model.id; let user_id = user_model.id;
let needs_rehash = password::needs_rehash(&user_model.password_hash); let needs_rehash = password::needs_rehash(&user_model.password_hash);
let mut active: user::ActiveModel = user_model.into(); let mut active = user_model.into_active_model();
active.last_login_at = Set(Some(now)); active.last_login_at = Set(Some(now));
active.last_access_at = Set(Some(now)); active.last_access_at = Set(Some(now));
active.failed_login_count = Set(0); active.failed_login_count = Set(0);

View file

@ -9,13 +9,11 @@
## Guía rápida ## Guía rápida
Declara la dependencia en tu `Cargo.toml`, activando en `pagetop-seaorm` el motor de base de Declara la dependencia en tu `Cargo.toml`:
datos que vayas a usar:
```toml ```toml
[dependencies] [dependencies]
pagetop-user = "..." pagetop-user = "..."
pagetop-seaorm = { version = "...", features = ["postgres"] }
``` ```
Añade `&pagetop_user::User` a las dependencias de tu extensión. El usuario actual se inyecta Añade `&pagetop_user::User` a las dependencias de tu extensión. El usuario actual se inyecta

View file

@ -3,7 +3,8 @@
use pagetop::prelude::*; use pagetop::prelude::*;
use pagetop_seaorm::db::{ use pagetop_seaorm::db::{
ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn, ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set,
dbconn,
}; };
use crate::entity::user_token; use crate::entity::user_token;
@ -116,7 +117,7 @@ pub async fn consume_token(token: &str, kind: TokenKind) -> Result<i32, AuthErro
} }
let user_id = row.user_id; let user_id = row.user_id;
let mut active: user_token::ActiveModel = row.into(); let mut active = row.into_active_model();
active.consumed_at = Set(Some(now)); active.consumed_at = Set(Some(now));
active.updated_at = Set(now); active.updated_at = Set(now);
active.update(dbconn()).await?; active.update(dbconn()).await?;

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "build", "assets", "resources", "static"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "macros", "proc-macros", "codegen"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -150,7 +150,7 @@ impl Generator {
} }
fn attrs(&self, attrs: Vec<Attribute>, build: &mut Builder) { fn attrs(&self, attrs: Vec<Attribute>, build: &mut Builder) {
let (classes, id, named_attrs, spliced) = split_attrs(attrs); let (classes, id, mut named_attrs, spliced) = split_attrs(attrs);
// Must run before `classes`/`id`/`named_attrs` are consumed below. // Must run before `classes`/`id`/`named_attrs` are consumed below.
let literal_attr_names: Vec<LitStr> = { let literal_attr_names: Vec<LitStr> = {
@ -170,21 +170,54 @@ impl Generator {
if !classes.is_empty() { if !classes.is_empty() {
let mut toggle_class_exprs = vec![]; let mut toggle_class_exprs = vec![];
// A `class="..."` (or `class=[...]`) next to shorthand classes (`.a`, `.a[cond]`) is
// merged with them into a single attribute, with its value first; otherwise the
// element would end up with two `class` attributes.
let class_value = named_attrs
.iter()
.position(|(name, attr_type)| {
name.to_string() == "class" && !matches!(attr_type, AttributeType::Empty(_))
})
.map(|i| named_attrs.remove(i).1);
let has_value = class_value.is_some();
build.push_str(" "); build.push_str(" ");
self.name(parse_quote!(class), build); self.name(parse_quote!(class), build);
build.push_str("=\""); build.push_str("=\"");
for (i, (name, toggler)) in classes.into_iter().enumerate() { match class_value {
Some(AttributeType::Normal { value, .. }) => self.markup(value, build),
Some(AttributeType::Optional {
toggler: Toggler { cond, .. },
..
}) => {
let inner_value: Expr = parse_quote!(inner_value);
let body = {
let mut build = self.builder();
self.splice(inner_value.clone(), &mut build);
build.finish()
};
build.push_tokens(quote!(if let Some(#inner_value) = (#cond) { #body }));
}
_ => {}
}
// Static classes are written before toggled ones, so the separator depends on the
// writing order, not on the position in the source: a toggled class gets a leading
// space if the `class` value, a static class or another toggled class precedes it.
let mut written = has_value;
for (name, toggler) in classes {
if let Some(toggler) = toggler { if let Some(toggler) = toggler {
toggle_class_exprs.push((i > 0, name, toggler)); toggle_class_exprs.push((name, toggler));
} else { } else {
if i > 0 { if written {
build.push_str(" "); build.push_str(" ");
} }
self.name_or_markup(name, build); self.name_or_markup(name, build);
written = true;
} }
} }
for (not_first, name, toggler) in toggle_class_exprs { for (i, (name, toggler)) in toggle_class_exprs.into_iter().enumerate() {
let not_first = written || i > 0;
let body = { let body = {
let mut build = self.builder(); let mut build = self.builder();
if not_first { if not_first {

View file

@ -12,6 +12,7 @@ keywords = ["pagetop", "build", "assets", "resources", "static"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -11,6 +11,7 @@ keywords = ["pagetop", "build", "static", "resources", "file"]
repository.workspace = true repository.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View file

@ -1,8 +1 @@
edition = "2024" edition = "2024"
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
# Heurísticas por defecto: evitar reformateo agresivo
use_small_heuristics = "Default"

View file

@ -72,6 +72,11 @@ impl Application {
// Secuencia de arranque común a new() y prepare(). // Secuencia de arranque común a new() y prepare().
async fn internal_prepare(root_extension: Option<ExtensionRef>) -> Self { async fn internal_prepare(root_extension: Option<ExtensionRef>) -> Self {
// Comprueba la configuración global antes de usarla. Un error detiene aquí el arranque.
if let Err(err) = global::check_settings() {
Self::abort_startup(None, err);
}
// Al arrancar muestra una cabecera para la aplicación. // Al arrancar muestra una cabecera para la aplicación.
Self::show_banner(); Self::show_banner();

View file

@ -250,7 +250,7 @@ impl Component for Pager {
} }
ul class="pagination" { ul class="pagination" {
@if show_prev_next { @if show_prev_next {
li.page-item.page-previous.disabled[first_disabled] { li class="page-item page-previous" .disabled[first_disabled] {
a class="page-link" a class="page-link"
href=[(!first_disabled).then(|| Self::page_route(&route, page - 1))] href=[(!first_disabled).then(|| Self::page_route(&route, page - 1))]
aria-disabled=[first_disabled.then_some("true")] aria-disabled=[first_disabled.then_some("true")]
@ -265,7 +265,7 @@ impl Component for Pager {
@match item { @match item {
PageItem::Number(n) => { PageItem::Number(n) => {
@let href = Self::page_route(&route, n); @let href = Self::page_route(&route, n);
li.page-item.active[n == page] { li class="page-item" .active[n == page] {
a class="page-link" a class="page-link"
href=(href) href=(href)
aria-current=[(n == page).then_some("page")] { aria-current=[(n == page).then_some("page")] {
@ -281,7 +281,7 @@ impl Component for Pager {
} }
} }
@if show_prev_next { @if show_prev_next {
li.page-item.page-next.disabled[last_disabled] { li class="page-item page-next" .disabled[last_disabled] {
a class="page-link" a class="page-link"
href=[(!last_disabled).then(|| Self::page_route(&route, page + 1))] href=[(!last_disabled).then(|| Self::page_route(&route, page + 1))]
aria-disabled=[last_disabled.then_some("true")] aria-disabled=[last_disabled.then_some("true")]

View file

@ -144,9 +144,10 @@ const DEFAULT_CONFIG_DIR: &str = "config";
const DEFAULT_RUN_MODE: &str = "default"; const DEFAULT_RUN_MODE: &str = "default";
// Configuración combinada de los archivos TOML en el orden de carga, más el modo de ejecución // Configuración combinada de los archivos TOML en el orden de carga, más el modo de ejecución
// (`app.run_mode`). Se construye una sola vez, en el primer acceso, y sólo la leen las funciones de // (`app.run_mode`), o el texto del error si no se pudieron leer (`ConfigError` no implementa
// este módulo: así ningún ajuste se salta las comprobaciones de `#[settings]`. // `Clone`). Se construye una sola vez, en el primer acceso, y sólo la leen las funciones de este
static CONFIG_VALUES: LazyLock<Config> = LazyLock::new(|| { // módulo: así ningún ajuste se salta las comprobaciones de `#[settings]`.
static CONFIG_VALUES: LazyLock<Result<Config, String>> = LazyLock::new(|| {
// CONFIG_DIR (si existe) o DEFAULT_CONFIG_DIR. Si no se puede resolver, se usa tal cual. Sólo // CONFIG_DIR (si existe) o DEFAULT_CONFIG_DIR. Si no se puede resolver, se usa tal cual. Sólo
// se avisa si CONFIG_DIR está definida: que falte el directorio predeterminado es normal en una // se avisa si CONFIG_DIR está definida: que falte el directorio predeterminado es normal en una
// aplicación sin configuración propia, pero un CONFIG_DIR erróneo podría dejar la aplicación // aplicación sin configuración propia, pero un CONFIG_DIR erróneo podría dejar la aplicación
@ -189,14 +190,38 @@ static CONFIG_VALUES: LazyLock<Config> = LazyLock::new(|| {
// Guarda el modo de ejecución explícitamente. // Guarda el modo de ejecución explícitamente.
.set_override("app.run_mode", rm) .set_override("app.run_mode", rm)
.and_then(|builder| builder.build()) .and_then(|builder| builder.build())
.unwrap_or_else(|err| panic!("Failed to read the configuration files: {err}")) .map_err(|err| err.to_string())
}); });
// Configuración combinada, o el error que impidió leer los archivos.
fn config_values() -> Result<&'static Config, ConfigError> {
CONFIG_VALUES
.as_ref()
.map_err(|message| ConfigError::Message(message.clone()))
}
// Comprueba que los archivos de configuración se pueden leer (p. ej. que ningún TOML está mal
// formado), para detener el arranque con un error en lugar del `panic!` del primer acceso.
pub(crate) fn check_files() -> Result<(), ConfigError> {
config_values().map(|_| ())
}
// Comprueba, sin guardarlos, que los ajustes de la sección de `T` se pueden cargar. Sirve para los
// ajustes que se guardan en otra variable, como los globales de PageTop.
pub(crate) fn check<T: SettingsSection>() -> Result<(), ConfigError> {
section_from::<T>(config_values()?).map(|_| ())
}
// Secciones del primer nivel de la configuración. // Secciones del primer nivel de la configuración.
pub(crate) fn sections() -> Vec<String> { pub(crate) fn sections() -> Vec<String> {
CONFIG_VALUES config_values()
.clone() .ok()
.try_deserialize::<HashMap<String, IgnoredAny>>() .and_then(|config| {
config
.clone()
.try_deserialize::<HashMap<String, IgnoredAny>>()
.ok()
})
.map(|sections| sections.into_keys().collect()) .map(|sections| sections.into_keys().collect())
.unwrap_or_default() .unwrap_or_default()
} }
@ -213,11 +238,14 @@ pub trait SettingsSection: DeserializeOwned + Default + Send + Sync + 'static {
} }
// Carga los ajustes de la sección `T::SECTION` de la configuración. Las claves ausentes toman su // Carga los ajustes de la sección `T::SECTION` de la configuración. Las claves ausentes toman su
// valor por defecto, y si falta la sección entera se usan los de todos los campos. Si la sección no // valor por defecto, y si falta la sección entera se usan los de todos los campos. Si los archivos
// puede deserializarse (un valor no válido o una clave desconocida), lanza `panic!` con un mensaje // no se pueden leer o la sección no puede deserializarse (un valor no válido o una clave
// que indica la sección y el problema. // desconocida), lanza `panic!` con un mensaje que indica el problema. Al arrancar no llega a
// ocurrir: la aplicación lo comprueba antes y se detiene con un error.
pub(crate) fn load<T: SettingsSection>() -> T { pub(crate) fn load<T: SettingsSection>() -> T {
section_from(&CONFIG_VALUES) let config = config_values()
.unwrap_or_else(|err| panic!("Failed to read the configuration files: {err}"));
section_from(config)
.unwrap_or_else(|err| panic!("Invalid settings in section [{}]: {err}", T::SECTION)) .unwrap_or_else(|err| panic!("Invalid settings in section [{}]: {err}", T::SECTION))
} }
@ -318,7 +346,7 @@ impl<T: SettingsSection> LoadSettings for LazySettings<T> {
// mismos. // mismos.
fn load(&self) -> Result<(), BoxError> { fn load(&self) -> Result<(), BoxError> {
if self.0.get().is_none() { if self.0.get().is_none() {
let _ = self.0.set(section_from::<T>(&CONFIG_VALUES)?); let _ = self.0.set(section_from::<T>(config_values()?)?);
} }
Ok(()) Ok(())
} }

View file

@ -12,6 +12,9 @@ static EXTENSIONS: OnceLock<Vec<ExtensionRef>> = OnceLock::new();
/// Errores de las extensiones que detienen el arranque de la aplicación. /// Errores de las extensiones que detienen el arranque de la aplicación.
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum StartupError { pub enum StartupError {
/// Los archivos de configuración no se pueden leer (p. ej. un TOML mal formado).
#[error("Failed to read the configuration files")]
ReadConfig(#[source] BoxError),
/// Dos extensiones, o una extensión y PageTop, reclaman la misma sección de la configuración: /// Dos extensiones, o una extensión y PageTop, reclaman la misma sección de la configuración:
/// cada una la leería con su propia estructura de ajustes. /// cada una la leería con su propia estructura de ajustes.
#[error("Settings section [{0}] is already claimed by PageTop or another extension")] #[error("Settings section [{0}] is already claimed by PageTop or another extension")]

View file

@ -1,5 +1,6 @@
//! Ajustes de configuración globales de PageTop. //! Ajustes de configuración globales de PageTop.
use crate::core::extension::all::StartupError;
use crate::{config, settings}; use crate::{config, settings};
use std::sync::LazyLock; use std::sync::LazyLock;
@ -31,6 +32,23 @@ pub static SETTINGS: LazyLock<Settings> = LazyLock::new(|| Settings {
server: config::load(), server: config::load(),
}); });
// Comprueba que los archivos de configuración se pueden leer y que los ajustes globales son válidos.
// La aplicación lo llama al arrancar, antes del primer acceso a `SETTINGS`, que lanzaría `panic!`.
pub(crate) fn check_settings() -> Result<(), StartupError> {
config::check_files().map_err(|err| StartupError::ReadConfig(err.into()))?;
check_section::<AppSettings>()?;
check_section::<DevSettings>()?;
check_section::<LogSettings>()?;
check_section::<ServerSettings>()
}
fn check_section<T: config::SettingsSection>() -> Result<(), StartupError> {
config::check::<T>().map_err(|err| StartupError::InvalidSettings {
section: T::SECTION,
source: err.into(),
})
}
// **< Settings >*********************************************************************************** // **< Settings >***********************************************************************************
/// Ajustes globales de [`SETTINGS`]. /// Ajustes globales de [`SETTINGS`].

View file

@ -124,6 +124,25 @@ use std::sync::Arc;
/// assert_eq!(markup.into_string(), r#"<span title="literal">OK</span>"#); /// assert_eq!(markup.into_string(), r#"<span title="literal">OK</span>"#);
/// ``` /// ```
/// ///
/// Con `class` ocurre lo mismo. Si el elemento escribe alguna clase propia, con `class="..."` o con
/// la forma abreviada (`.clase`, `.clase[cond]`), se omiten **todas** las clases de `Props`. Para
/// combinar las clases del componente con las que se añadan con `with_prop()`, el componente debe
/// incorporarlas a sus `Props` en su `setup()`, por ejemplo con [`PropsOp::prepend_classes()`], y
/// no las escribe en el elemento.
///
/// ```rust
/// # use pagetop::prelude::*;
/// # let mut cx = Context::default();
/// let props = Props::classes("extra");
///
/// let markup = html! { div class="card" (props.unpack(&mut cx)) {} };
/// assert_eq!(markup.into_string(), r#"<div class="card"></div>"#);
///
/// let props = props.with_prop(PropsOp::prepend_classes("card"));
/// let markup = html! { div (props.unpack(&mut cx)) {} };
/// assert_eq!(markup.into_string(), r#"<div class="card extra"></div>"#);
/// ```
///
/// # Valores extra /// # Valores extra
/// ///
/// Las variantes [`SetExtra`](PropsOp::SetExtra) y [`RemoveExtra`](PropsOp::RemoveExtra), usando /// Las variantes [`SetExtra`](PropsOp::SetExtra) y [`RemoveExtra`](PropsOp::RemoveExtra), usando

View file

@ -438,26 +438,42 @@ pub mod test {
uri: String, uri: String,
headers: http::HeaderMap, headers: http::HeaderMap,
extensions: http::Extensions, extensions: http::Extensions,
body: String,
} }
impl TestRequest { impl TestRequest {
/// Crea una petición GET. /// Crea una petición GET.
pub fn get() -> Self { pub fn get() -> Self {
Self { Self::with_method(http::Method::GET)
method: http::Method::GET,
uri: "/".to_owned(),
headers: http::HeaderMap::new(),
extensions: http::Extensions::new(),
}
} }
/// Crea una petición POST. /// Crea una petición POST.
pub fn post() -> Self { pub fn post() -> Self {
Self::with_method(http::Method::POST)
}
/// Crea una petición PUT.
pub fn put() -> Self {
Self::with_method(http::Method::PUT)
}
/// Crea una petición PATCH.
pub fn patch() -> Self {
Self::with_method(http::Method::PATCH)
}
/// Crea una petición DELETE.
pub fn delete() -> Self {
Self::with_method(http::Method::DELETE)
}
fn with_method(method: http::Method) -> Self {
Self { Self {
method: http::Method::POST, method,
uri: "/".to_owned(), uri: "/".to_owned(),
headers: http::HeaderMap::new(), headers: http::HeaderMap::new(),
extensions: http::Extensions::new(), extensions: http::Extensions::new(),
body: String::new(),
} }
} }
@ -481,6 +497,14 @@ pub mod test {
self self
} }
/// Envía como cuerpo los campos de un formulario, ya codificados (p. ej.
/// `"title=Plant+lettuces&done=on"`), con la cabecera
/// `Content-Type: application/x-www-form-urlencoded`, como lo envía un navegador.
pub fn form(mut self, fields: impl Into<String>) -> Self {
self.body = fields.into();
self.header("content-type", "application/x-www-form-urlencoded")
}
/// Inserta un valor en las extensiones de la petición. /// Inserta un valor en las extensiones de la petición.
/// ///
/// Útil para simular lo que un middleware haría en producción antes de que el handler /// Útil para simular lo que un middleware haría en producción antes de que el handler
@ -495,7 +519,7 @@ pub mod test {
let mut req = http::Request::builder() let mut req = http::Request::builder()
.method(self.method) .method(self.method)
.uri(self.uri) .uri(self.uri)
.body(Body::empty()) .body(Body::from(self.body))
.unwrap(); .unwrap();
*req.headers_mut() = self.headers; *req.headers_mut() = self.headers;
*req.extensions_mut() = self.extensions; *req.extensions_mut() = self.extensions;

332
tests/html_class.rs Normal file
View file

@ -0,0 +1,332 @@
use pagetop::prelude::*;
// Every way an element of `html!` gets its `class` attribute: literal `class="..."`, shorthand
// classes (`.a`, `.a[cond]`, `.(expr)`), both together, and the classes of a `Props` splice.
// **< Literal class attribute >********************************************************************
#[pagetop::test]
async fn literal_class_attribute() {
assert_eq!(
html! { div class="a b" {} }.into_string(),
r#"<div class="a b"></div>"#
);
}
#[pagetop::test]
async fn literal_class_attribute_from_expression_is_escaped() {
let value = "a\"b";
assert_eq!(
html! { div class=(value) {} }.into_string(),
r#"<div class="a&quot;b"></div>"#
);
}
#[pagetop::test]
async fn optional_class_attribute() {
let some = Some("a");
let none: Option<&str> = None;
assert_eq!(
html! { div class=[some] {} }.into_string(),
r#"<div class="a"></div>"#
);
assert_eq!(html! { div class=[none] {} }.into_string(), "<div></div>");
}
// **< Shorthand classes >**************************************************************************
#[pagetop::test]
async fn shorthand_classes() {
assert_eq!(
html! { div.a.b {} }.into_string(),
r#"<div class="a b"></div>"#
);
}
#[pagetop::test]
async fn shorthand_classes_without_element_name_are_a_div() {
assert_eq!(
html! { .a.b {} }.into_string(),
r#"<div class="a b"></div>"#
);
}
#[pagetop::test]
async fn shorthand_toggled_classes() {
assert_eq!(
html! { div.a.b[true].c[false] {} }.into_string(),
r#"<div class="a b"></div>"#
);
}
#[pagetop::test]
async fn shorthand_toggled_classes_go_after_the_fixed_ones() {
// Toggled classes are written after all the fixed ones, whatever their order in the source.
assert_eq!(
html! { div.a[true].b {} }.into_string(),
r#"<div class="b a"></div>"#
);
}
#[pagetop::test]
async fn shorthand_only_toggled_classes() {
assert_eq!(
html! { div.a[true].b[true] {} }.into_string(),
r#"<div class="a b"></div>"#
);
// A leading space when the first toggled class is off: harmless, browsers ignore it.
assert_eq!(
html! { div.a[false].b[true] {} }.into_string(),
r#"<div class=" b"></div>"#
);
assert_eq!(
html! { div.a[false] {} }.into_string(),
r#"<div class=""></div>"#
);
}
#[pagetop::test]
async fn shorthand_class_from_expression() {
let name = "dynamic";
assert_eq!(
html! { div.a.(name) {} }.into_string(),
r#"<div class="a dynamic"></div>"#
);
assert_eq!(
html! { div.a.(name)[false] {} }.into_string(),
r#"<div class="a"></div>"#
);
}
// **< Literal and shorthand classes together >*****************************************************
#[pagetop::test]
async fn literal_and_shorthand_classes_merge_into_one_attribute() {
assert_eq!(
html! { div class="a" .b {} }.into_string(),
r#"<div class="a b"></div>"#
);
assert_eq!(
html! { div class="a b" .c.d {} }.into_string(),
r#"<div class="a b c d"></div>"#
);
}
#[pagetop::test]
async fn literal_class_goes_first_whatever_its_position() {
assert_eq!(
html! { div.b class="a" {} }.into_string(),
r#"<div class="a b"></div>"#
);
}
#[pagetop::test]
async fn literal_and_toggled_classes_merge() {
assert_eq!(
html! { li class="item" .active[true] {} }.into_string(),
r#"<li class="item active"></li>"#
);
assert_eq!(
html! { li class="item" .active[false] {} }.into_string(),
r#"<li class="item"></li>"#
);
assert_eq!(
html! { li class="item" .active[true].disabled[false].first {} }.into_string(),
r#"<li class="item first active"></li>"#
);
}
#[pagetop::test]
async fn class_from_expression_and_shorthand_classes_merge() {
let base = "card";
assert_eq!(
html! { div class=(base) .shadow {} }.into_string(),
r#"<div class="card shadow"></div>"#
);
let escaped = "a\"b";
assert_eq!(
html! { div class=(escaped) .c[true] {} }.into_string(),
r#"<div class="a&quot;b c"></div>"#
);
}
#[pagetop::test]
async fn optional_class_and_shorthand_classes_merge() {
let some = Some("a");
let none: Option<&str> = None;
assert_eq!(
html! { div class=[some] .b {} }.into_string(),
r#"<div class="a b"></div>"#
);
// A leading space when the optional value is missing: harmless, browsers ignore it.
assert_eq!(
html! { div class=[none] .b {} }.into_string(),
r#"<div class=" b"></div>"#
);
}
#[pagetop::test]
async fn merged_class_keeps_the_order_of_the_other_attributes() {
// `class` is written first, then `id`, then the rest in source order, as always.
assert_eq!(
html! { a href="/" class="link" #home .active[true] title="Home" { "x" } }.into_string(),
r#"<a class="link active" id="home" href="/" title="Home">x</a>"#
);
}
#[pagetop::test]
async fn merged_class_works_with_conditional_markup() {
let items = ["a", "b", "c"];
let current = 1;
let markup = html! {
ul {
@for (i, item) in items.iter().enumerate() {
li class="item" .current[i == current] { (item) }
}
}
};
assert_eq!(
markup.into_string(),
r#"<ul><li class="item">a</li><li class="item current">b</li><li class="item">c</li></ul>"#
);
}
// **< Classes from Props >*************************************************************************
#[pagetop::test]
async fn props_classes() {
let props = Props::classes("from-props-a from-props-b");
let mut cx = Context::default();
assert_eq!(
html! { div (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class="from-props-a from-props-b"></div>"#
);
}
#[pagetop::test]
async fn props_classes_with_other_literal_attributes_are_kept() {
// Only a literal `class` collides with the classes of `Props`.
let props = Props::classes("from-props");
let mut cx = Context::default();
assert_eq!(
html! { div #fixed style="color: red" (props.unpack(&mut cx)) {} }.into_string(),
r#"<div id="fixed" style="color: red" class="from-props"></div>"#
);
}
#[pagetop::test]
async fn literal_class_attribute_prevails_over_props_classes() {
let props = Props::classes("from-props");
let mut cx = Context::default();
assert_eq!(
html! { div class="literal" (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class="literal"></div>"#
);
}
#[pagetop::test]
async fn shorthand_classes_prevail_over_props_classes() {
let props = Props::classes("from-props");
let mut cx = Context::default();
assert_eq!(
html! { div.literal (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class="literal"></div>"#
);
// Even if every shorthand class is toggled off.
assert_eq!(
html! { div.literal[false] (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class=""></div>"#
);
}
#[pagetop::test]
async fn merged_literal_classes_prevail_over_props_classes() {
let props = Props::classes("from-props");
let mut cx = Context::default();
assert_eq!(
html! { div class="a" .b[true] (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class="a b"></div>"#
);
}
#[pagetop::test]
async fn props_keep_their_id_when_only_the_class_collides() {
let props = Props::classes("from-props").with_id("from-props-id");
let mut cx = Context::default();
assert_eq!(
html! { div class="literal" (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class="literal" id="from-props-id"></div>"#
);
}
#[pagetop::test]
async fn props_classes_after_class_operations() {
let props = Props::classes("b c")
.with_prop(PropsOp::prepend_classes("a"))
.with_prop(PropsOp::add_classes("d"))
.with_prop(PropsOp::remove_classes("c"))
.with_prop(PropsOp::replace_classes("b", "beta"));
let mut cx = Context::default();
assert_eq!(
html! { div (props.unpack(&mut cx)) {} }.into_string(),
r#"<div class="a beta d"></div>"#
);
}
#[pagetop::test]
async fn empty_props_write_no_class_attribute() {
let props = Props::default();
let mut cx = Context::default();
assert_eq!(
html! { div (props.unpack(&mut cx)) {} }.into_string(),
"<div></div>"
);
}
// **< Classes of components >**********************************************************************
#[pagetop::test]
async fn component_merges_its_own_classes_with_the_added_ones() {
// A component writes its own classes and the ones added with `with_prop()` in one attribute.
let mut container = Container::new()
.with_prop(PropsOp::add_classes("extra-a extra-b"))
.with_child(Lc::n("x"));
let markup = container
.render(&mut Context::default())
.await
.into_string();
let class = markup
.split("class=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.expect("the container has a class attribute");
assert!(class.split(' ').any(|c| c == "extra-a"), "{markup}");
assert!(class.split(' ').any(|c| c == "extra-b"), "{markup}");
assert_eq!(markup.matches("class=").count(), 1, "{markup}");
}
#[pagetop::test]
async fn component_with_added_classes_never_duplicates_the_class_attribute() {
// Every component has some content: empty ones are not rendered.
let mut cx = Context::default();
let components: Vec<Box<dyn Component>> = vec![
Box::new(
Block::new()
.with_prop(PropsOp::add_classes("extra"))
.with_child(Lc::n("x")),
),
Box::new(Badge::info(Lc::n("x")).with_prop(PropsOp::add_classes("extra"))),
Box::new(Button::plain(Lc::n("x")).with_prop(PropsOp::add_classes("extra"))),
Box::new(
Nav::new()
.with_prop(PropsOp::add_classes("extra"))
.with_item(nav::Item::link(Lc::n("x"), "/")),
),
];
for mut component in components {
let markup = component.render(&mut cx).await.into_string();
let first_tag = &markup[..markup.find('>').unwrap_or(markup.len())];
assert!(first_tag.contains("extra"), "{markup}");
assert_eq!(first_tag.matches("class=").count(), 1, "{markup}");
}
}

72
tests/web_test_request.rs Normal file
View file

@ -0,0 +1,72 @@
use pagetop::prelude::*;
use serde::Deserialize;
// Every method of `web::test::TestRequest` reaches the route registered for it, and `form()` sends
// the fields as a browser does.
#[derive(Deserialize)]
struct Item {
name: String,
}
async fn echo(web::Form(item): web::Form<Item>) -> String {
item.name
}
struct Echo;
#[async_trait]
impl Extension for Echo {
fn configure_router(&self, router: Router) -> Router {
router.route(
"/item",
web::get(|| async { "get" })
.post(echo)
.put(echo)
.patch(echo)
.delete(|| async { "delete" }),
)
}
}
async fn send(request: web::test::TestRequest) -> (web::http::StatusCode, String) {
let app = web::test::init_router(Application::prepare(&Echo).await.test());
let response = web::test::send_request(&app, request.uri("/item").to_request()).await;
let status = response.status();
(status, web::test::read_body_text(response).await)
}
#[pagetop::test]
async fn get_and_delete_reach_their_routes() {
let (status, body) = send(web::test::TestRequest::get()).await;
assert_eq!((status, body.as_str()), (web::http::StatusCode::OK, "get"));
let (status, body) = send(web::test::TestRequest::delete()).await;
assert_eq!(
(status, body.as_str()),
(web::http::StatusCode::OK, "delete")
);
}
#[pagetop::test]
async fn post_put_and_patch_send_the_form_fields() {
for request in [
web::test::TestRequest::post(),
web::test::TestRequest::put(),
web::test::TestRequest::patch(),
] {
let (status, body) = send(request.form("name=Plant+lettuces")).await;
assert_eq!(
(status, body.as_str()),
(web::http::StatusCode::OK, "Plant lettuces")
);
}
}
#[pagetop::test]
async fn a_form_request_without_fields_is_rejected() {
// No `form()`: no body and no form content type, so the form extractor refuses it.
let (status, _) = send(web::test::TestRequest::post()).await;
assert!(status.is_client_error());
}