diff --git a/Cargo.toml b/Cargo.toml index c59b1452..083b903a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ members = [ repository = "https://git.cillero.es/manuelcillero/pagetop" homepage = "https://pagetop.cillero.es" edition = "2024" +rust-version = "1.88" license = "MIT OR Apache-2.0" authors = ["Manuel Cillero "] @@ -101,6 +102,7 @@ keywords = ["pagetop", "web", "framework", "frontend", "ssr"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-admin/Cargo.toml b/extensions/pagetop-admin/Cargo.toml index 662c62b9..c61c2550 100644 --- a/extensions/pagetop-admin/Cargo.toml +++ b/extensions/pagetop-admin/Cargo.toml @@ -8,6 +8,7 @@ keywords = ["pagetop", "admin", "cms", "settings", "ssr"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-admin/src/lib.rs b/extensions/pagetop-admin/src/lib.rs index 1c868c6a..86f5c7b8 100644 --- a/extensions/pagetop-admin/src/lib.rs +++ b/extensions/pagetop-admin/src/lib.rs @@ -9,11 +9,11 @@ ## 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 [dependencies] -pagetop-admin = { version = "...", features = ["sqlite"] } +pagetop-admin = "..." ``` Añade `&pagetop_admin::Admin` a las dependencias de tu extensión y declara tus diff --git a/extensions/pagetop-aliner/Cargo.toml b/extensions/pagetop-aliner/Cargo.toml index 072324e3..6c459877 100644 --- a/extensions/pagetop-aliner/Cargo.toml +++ b/extensions/pagetop-aliner/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["pagetop", "theme", "css"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-bootsier/Cargo.toml b/extensions/pagetop-bootsier/Cargo.toml index 47766c52..0bfc051b 100644 --- a/extensions/pagetop-bootsier/Cargo.toml +++ b/extensions/pagetop-bootsier/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["pagetop", "theme", "bootstrap", "css", "js"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-htmx/Cargo.toml b/extensions/pagetop-htmx/Cargo.toml index d1159b5b..eb51d853 100644 --- a/extensions/pagetop-htmx/Cargo.toml +++ b/extensions/pagetop-htmx/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["pagetop", "htmx", "ajax", "ssr"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-seaorm/Cargo.toml b/extensions/pagetop-seaorm/Cargo.toml index 26016a76..4ee76a29 100644 --- a/extensions/pagetop-seaorm/Cargo.toml +++ b/extensions/pagetop-seaorm/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["pagetop", "database", "sql", "orm", "ssr"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-seaorm/src/db.rs b/extensions/pagetop-seaorm/src/db.rs index 57f6f8ee..2d984f22 100644 --- a/extensions/pagetop-seaorm/src/db.rs +++ b/extensions/pagetop-seaorm/src/db.rs @@ -27,7 +27,8 @@ //! - **Transacciones**: [`TransactionTrait`], [`DatabaseTransaction`], [`flatten_txn_err`] //! (para convertir [`TransactionError`] a `E`). //! - **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`], //! [`DeriveRelation`], [`EnumIter`]. //! - **Errores**: [`DbErr`], [`TransactionError`]. @@ -167,8 +168,8 @@ pub use sea_orm::prelude::*; pub use sea_orm; pub use sea_orm::{ - ActiveValue, Condition, DatabaseTransaction, DbBackend, ExecResult, NotSet, Order, QueryOrder, - QuerySelect, Set, TransactionError, TransactionTrait, Unchanged, + ActiveValue, Condition, DatabaseTransaction, DbBackend, ExecResult, IntoActiveModel, NotSet, + Order, QueryOrder, QuerySelect, Set, TransactionError, TransactionTrait, Unchanged, }; /// Re-exporta `sea_query` para construir sentencias SQL en tiempo de ejecución. diff --git a/extensions/pagetop-user/Cargo.toml b/extensions/pagetop-user/Cargo.toml index 76870d99..8acf19c1 100644 --- a/extensions/pagetop-user/Cargo.toml +++ b/extensions/pagetop-user/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["pagetop", "auth", "users", "session", "rbac"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/extensions/pagetop-user/src/auth.rs b/extensions/pagetop-user/src/auth.rs index 04712964..7ba951d2 100644 --- a/extensions/pagetop-user/src/auth.rs +++ b/extensions/pagetop-user/src/auth.rs @@ -2,8 +2,8 @@ use pagetop::prelude::*; use pagetop_seaorm::db::{ - ActiveModelTrait, ActiveValue, ColumnTrait, Condition, EntityTrait, PaginatorTrait, - QueryFilter, Set, dbconn, + ActiveModelTrait, ActiveValue, ColumnTrait, Condition, EntityTrait, IntoActiveModel, + PaginatorTrait, QueryFilter, Set, dbconn, }; use crate::account::UserStatus; @@ -61,7 +61,7 @@ pub async fn login( // Actualizar last_login_at y resetear contador de fallos. let user_id = user_model.id; 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_access_at = Set(Some(now)); active.failed_login_count = Set(0); diff --git a/extensions/pagetop-user/src/lib.rs b/extensions/pagetop-user/src/lib.rs index e810bd4f..911aba0d 100644 --- a/extensions/pagetop-user/src/lib.rs +++ b/extensions/pagetop-user/src/lib.rs @@ -9,13 +9,11 @@ ## Guía rápida -Declara la dependencia en tu `Cargo.toml`, activando en `pagetop-seaorm` el motor de base de -datos que vayas a usar: +Declara la dependencia en tu `Cargo.toml`: ```toml [dependencies] pagetop-user = "..." -pagetop-seaorm = { version = "...", features = ["postgres"] } ``` Añade `&pagetop_user::User` a las dependencias de tu extensión. El usuario actual se inyecta diff --git a/extensions/pagetop-user/src/token.rs b/extensions/pagetop-user/src/token.rs index 8dba8418..8f343d8f 100644 --- a/extensions/pagetop-user/src/token.rs +++ b/extensions/pagetop-user/src/token.rs @@ -3,7 +3,8 @@ use pagetop::prelude::*; use pagetop_seaorm::db::{ - ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn, + ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set, + dbconn, }; use crate::entity::user_token; @@ -116,7 +117,7 @@ pub async fn consume_token(token: &str, kind: TokenKind) -> Result, 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. let literal_attr_names: Vec = { @@ -170,21 +170,54 @@ impl Generator { if !classes.is_empty() { 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(" "); self.name(parse_quote!(class), build); 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 { - toggle_class_exprs.push((i > 0, name, toggler)); + toggle_class_exprs.push((name, toggler)); } else { - if i > 0 { + if written { build.push_str(" "); } 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 mut build = self.builder(); if not_first { diff --git a/helpers/pagetop-minimal/Cargo.toml b/helpers/pagetop-minimal/Cargo.toml index c67e7587..a55136ac 100644 --- a/helpers/pagetop-minimal/Cargo.toml +++ b/helpers/pagetop-minimal/Cargo.toml @@ -12,6 +12,7 @@ keywords = ["pagetop", "build", "assets", "resources", "static"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/helpers/pagetop-statics/Cargo.toml b/helpers/pagetop-statics/Cargo.toml index 503511eb..de037588 100644 --- a/helpers/pagetop-statics/Cargo.toml +++ b/helpers/pagetop-statics/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["pagetop", "build", "static", "resources", "file"] repository.workspace = true homepage.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true authors.workspace = true diff --git a/rustfmt.toml b/rustfmt.toml index 5d6e629c..f216078d 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,8 +1 @@ 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" diff --git a/src/app.rs b/src/app.rs index ebd1cb22..9a24f45b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -72,6 +72,11 @@ impl Application { // Secuencia de arranque común a new() y prepare(). async fn internal_prepare(root_extension: Option) -> 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. Self::show_banner(); diff --git a/src/base/component/pager.rs b/src/base/component/pager.rs index 976103d1..e210edf7 100644 --- a/src/base/component/pager.rs +++ b/src/base/component/pager.rs @@ -250,7 +250,7 @@ impl Component for Pager { } ul class="pagination" { @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" href=[(!first_disabled).then(|| Self::page_route(&route, page - 1))] aria-disabled=[first_disabled.then_some("true")] @@ -265,7 +265,7 @@ impl Component for Pager { @match item { PageItem::Number(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" href=(href) aria-current=[(n == page).then_some("page")] { @@ -281,7 +281,7 @@ impl Component for Pager { } } @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" href=[(!last_disabled).then(|| Self::page_route(&route, page + 1))] aria-disabled=[last_disabled.then_some("true")] diff --git a/src/config.rs b/src/config.rs index b311a653..03532550 100644 --- a/src/config.rs +++ b/src/config.rs @@ -144,9 +144,10 @@ const DEFAULT_CONFIG_DIR: &str = "config"; 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 -// (`app.run_mode`). Se construye una sola vez, en el primer acceso, y sólo la leen las funciones de -// este módulo: así ningún ajuste se salta las comprobaciones de `#[settings]`. -static CONFIG_VALUES: LazyLock = LazyLock::new(|| { +// (`app.run_mode`), o el texto del error si no se pudieron leer (`ConfigError` no implementa +// `Clone`). Se construye una sola vez, en el primer acceso, y sólo la leen las funciones de este +// módulo: así ningún ajuste se salta las comprobaciones de `#[settings]`. +static CONFIG_VALUES: LazyLock> = LazyLock::new(|| { // 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 // 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 = LazyLock::new(|| { // Guarda el modo de ejecución explícitamente. .set_override("app.run_mode", rm) .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() -> Result<(), ConfigError> { + section_from::(config_values()?).map(|_| ()) +} + // Secciones del primer nivel de la configuración. pub(crate) fn sections() -> Vec { - CONFIG_VALUES - .clone() - .try_deserialize::>() + config_values() + .ok() + .and_then(|config| { + config + .clone() + .try_deserialize::>() + .ok() + }) .map(|sections| sections.into_keys().collect()) .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 -// valor por defecto, y si falta la sección entera se usan los de todos los campos. Si la sección no -// puede deserializarse (un valor no válido o una clave desconocida), lanza `panic!` con un mensaje -// que indica la sección y el problema. +// valor por defecto, y si falta la sección entera se usan los de todos los campos. Si los archivos +// no se pueden leer o la sección no puede deserializarse (un valor no válido o una clave +// 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 { - 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)) } @@ -318,7 +346,7 @@ impl LoadSettings for LazySettings { // mismos. fn load(&self) -> Result<(), BoxError> { if self.0.get().is_none() { - let _ = self.0.set(section_from::(&CONFIG_VALUES)?); + let _ = self.0.set(section_from::(config_values()?)?); } Ok(()) } diff --git a/src/core/extension/all.rs b/src/core/extension/all.rs index a2f7b958..641fb097 100644 --- a/src/core/extension/all.rs +++ b/src/core/extension/all.rs @@ -12,6 +12,9 @@ static EXTENSIONS: OnceLock> = OnceLock::new(); /// Errores de las extensiones que detienen el arranque de la aplicación. #[derive(Debug, thiserror::Error)] 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: /// cada una la leería con su propia estructura de ajustes. #[error("Settings section [{0}] is already claimed by PageTop or another extension")] diff --git a/src/global.rs b/src/global.rs index a1f21d38..920c7992 100644 --- a/src/global.rs +++ b/src/global.rs @@ -1,5 +1,6 @@ //! Ajustes de configuración globales de PageTop. +use crate::core::extension::all::StartupError; use crate::{config, settings}; use std::sync::LazyLock; @@ -31,6 +32,23 @@ pub static SETTINGS: LazyLock = LazyLock::new(|| Settings { 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::()?; + check_section::()?; + check_section::()?; + check_section::() +} + +fn check_section() -> Result<(), StartupError> { + config::check::().map_err(|err| StartupError::InvalidSettings { + section: T::SECTION, + source: err.into(), + }) +} + // **< Settings >*********************************************************************************** /// Ajustes globales de [`SETTINGS`]. diff --git a/src/html/props/definition.rs b/src/html/props/definition.rs index 85806238..b8574f2f 100644 --- a/src/html/props/definition.rs +++ b/src/html/props/definition.rs @@ -124,6 +124,25 @@ use std::sync::Arc; /// assert_eq!(markup.into_string(), r#"OK"#); /// ``` /// +/// 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#"
"#); +/// +/// let props = props.with_prop(PropsOp::prepend_classes("card")); +/// let markup = html! { div (props.unpack(&mut cx)) {} }; +/// assert_eq!(markup.into_string(), r#"
"#); +/// ``` +/// /// # Valores extra /// /// Las variantes [`SetExtra`](PropsOp::SetExtra) y [`RemoveExtra`](PropsOp::RemoveExtra), usando diff --git a/src/web.rs b/src/web.rs index beb1a2b1..33a65610 100644 --- a/src/web.rs +++ b/src/web.rs @@ -438,26 +438,42 @@ pub mod test { uri: String, headers: http::HeaderMap, extensions: http::Extensions, + body: String, } impl TestRequest { /// Crea una petición GET. pub fn get() -> Self { - Self { - method: http::Method::GET, - uri: "/".to_owned(), - headers: http::HeaderMap::new(), - extensions: http::Extensions::new(), - } + Self::with_method(http::Method::GET) } /// Crea una petición POST. 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 { - method: http::Method::POST, + method, uri: "/".to_owned(), headers: http::HeaderMap::new(), extensions: http::Extensions::new(), + body: String::new(), } } @@ -481,6 +497,14 @@ pub mod test { 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) -> Self { + self.body = fields.into(); + self.header("content-type", "application/x-www-form-urlencoded") + } + /// 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 @@ -495,7 +519,7 @@ pub mod test { let mut req = http::Request::builder() .method(self.method) .uri(self.uri) - .body(Body::empty()) + .body(Body::from(self.body)) .unwrap(); *req.headers_mut() = self.headers; *req.extensions_mut() = self.extensions; diff --git a/tests/html_class.rs b/tests/html_class.rs new file mode 100644 index 00000000..89736b00 --- /dev/null +++ b/tests/html_class.rs @@ -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#"
"# + ); +} + +#[pagetop::test] +async fn literal_class_attribute_from_expression_is_escaped() { + let value = "a\"b"; + assert_eq!( + html! { div class=(value) {} }.into_string(), + r#"
"# + ); +} + +#[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#"
"# + ); + assert_eq!(html! { div class=[none] {} }.into_string(), "
"); +} + +// **< Shorthand classes >************************************************************************** + +#[pagetop::test] +async fn shorthand_classes() { + assert_eq!( + html! { div.a.b {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_classes_without_element_name_are_a_div() { + assert_eq!( + html! { .a.b {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_toggled_classes() { + assert_eq!( + html! { div.a.b[true].c[false] {} }.into_string(), + r#"
"# + ); +} + +#[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#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_only_toggled_classes() { + assert_eq!( + html! { div.a[true].b[true] {} }.into_string(), + r#"
"# + ); + // 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#"
"# + ); + assert_eq!( + html! { div.a[false] {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn shorthand_class_from_expression() { + let name = "dynamic"; + assert_eq!( + html! { div.a.(name) {} }.into_string(), + r#"
"# + ); + assert_eq!( + html! { div.a.(name)[false] {} }.into_string(), + r#"
"# + ); +} + +// **< 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#"
"# + ); + assert_eq!( + html! { div class="a b" .c.d {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn literal_class_goes_first_whatever_its_position() { + assert_eq!( + html! { div.b class="a" {} }.into_string(), + r#"
"# + ); +} + +#[pagetop::test] +async fn literal_and_toggled_classes_merge() { + assert_eq!( + html! { li class="item" .active[true] {} }.into_string(), + r#"
  • "# + ); + assert_eq!( + html! { li class="item" .active[false] {} }.into_string(), + r#"
  • "# + ); + assert_eq!( + html! { li class="item" .active[true].disabled[false].first {} }.into_string(), + r#"
  • "# + ); +} + +#[pagetop::test] +async fn class_from_expression_and_shorthand_classes_merge() { + let base = "card"; + assert_eq!( + html! { div class=(base) .shadow {} }.into_string(), + r#"
    "# + ); + let escaped = "a\"b"; + assert_eq!( + html! { div class=(escaped) .c[true] {} }.into_string(), + r#"
    "# + ); +} + +#[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#"
    "# + ); + // A leading space when the optional value is missing: harmless, browsers ignore it. + assert_eq!( + html! { div class=[none] .b {} }.into_string(), + r#"
    "# + ); +} + +#[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#"x"# + ); +} + +#[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#"
    • a
    • b
    • c
    "# + ); +} + +// **< 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#"
    "# + ); +} + +#[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#"
    "# + ); +} + +#[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#"
    "# + ); +} + +#[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#"
    "# + ); + // Even if every shorthand class is toggled off. + assert_eq!( + html! { div.literal[false] (props.unpack(&mut cx)) {} }.into_string(), + r#"
    "# + ); +} + +#[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#"
    "# + ); +} + +#[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#"
    "# + ); +} + +#[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#"
    "# + ); +} + +#[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(), + "
    " + ); +} + +// **< 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> = 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}"); + } +} diff --git a/tests/web_test_request.rs b/tests/web_test_request.rs new file mode 100644 index 00000000..014c8b7e --- /dev/null +++ b/tests/web_test_request.rs @@ -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) -> 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()); +}