From 947aef2f9117aa90578002b465b957ed028c6451 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sun, 8 Nov 2026 13:51:35 +0100 Subject: [PATCH 01/11] =?UTF-8?q?=F0=9F=94=A5=20Simplifica=20startup=5Fban?= =?UTF-8?q?ner=20a=20booleano?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- {src/app => assets/figfonts}/slant.flf | 0 {src/app => assets/figfonts}/small.flf | 0 {src/app => assets/figfonts}/speed.flf | 0 config/reference.toml | 4 +- src/app.rs | 10 +- src/app/figfont.rs | 20 - src/app/starwars.flf | 719 ------------------------- src/global.rs | 10 +- src/global/startup_banner.rs | 45 -- 9 files changed, 11 insertions(+), 797 deletions(-) rename {src/app => assets/figfonts}/slant.flf (100%) rename {src/app => assets/figfonts}/small.flf (100%) rename {src/app => assets/figfonts}/speed.flf (100%) delete mode 100644 src/app/figfont.rs delete mode 100644 src/app/starwars.flf delete mode 100644 src/global/startup_banner.rs diff --git a/src/app/slant.flf b/assets/figfonts/slant.flf similarity index 100% rename from src/app/slant.flf rename to assets/figfonts/slant.flf diff --git a/src/app/small.flf b/assets/figfonts/small.flf similarity index 100% rename from src/app/small.flf rename to assets/figfonts/small.flf diff --git a/src/app/speed.flf b/assets/figfonts/speed.flf similarity index 100% rename from src/app/speed.flf rename to assets/figfonts/speed.flf diff --git a/config/reference.toml b/config/reference.toml index 189ebf6b..83c2b9ff 100644 --- a/config/reference.toml +++ b/config/reference.toml @@ -80,8 +80,8 @@ admin_path = "/admin" # Ruta raíz del panel de administración # "/", sin "/" final; cada tramo sólo admite letras y dígitos # ASCII, "-", "_", "." y "~" (sin ser "." ni ".."). Una no # válida impide arrancar. -startup_banner = "Slant" # Banner ASCII al arrancar: "Off", "Slant", "Small", "Speed" - # o "Starwars". +startup_banner = true # Muestra al arrancar un banner ASCII con el nombre de la + # aplicación (true) o no (false). [dev] pagetop_static_dir = "" # Directorio static/ de PageTop para servir sus archivos diff --git a/src/app.rs b/src/app.rs index 1dd9eeda..ef9d51a5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,7 +1,5 @@ //! Prepara y ejecuta una aplicación creada con PageTop. -mod figfont; - use crate::admin; use crate::core::extension; use crate::core::extension::ExtensionRef; @@ -16,6 +14,7 @@ use crate::{PAGETOP_VERSION, global, trace}; use axum::extract::DefaultBodyLimit; use axum::middleware::Next; +use figlet_rs::FIGlet; use tower::{Layer, ServiceExt}; use tower_http::catch_panic::CatchPanicLayer; use tracing_appender::non_blocking::WorkerGuard; @@ -146,7 +145,7 @@ impl Application { use colored::Colorize; use terminal_size::{Width, terminal_size}; - if global::SETTINGS.app.startup_banner != global::StartupBanner::Off { + if global::SETTINGS.app.startup_banner { // Nombre de la aplicación, ajustado al ancho del terminal si es necesario. let mut app_ff = String::new(); let app_name = &global::SETTINGS.app.name; @@ -158,7 +157,10 @@ impl Application { if app_name.chars().count() > maxlen { app = format!("{app}..."); } - if let Some(ff) = figfont::FIGFONT.convert(&app) { + // Esta fuente incluye la `ñ` y las vocales con tilde. + if let Ok(font) = FIGlet::from_content(include_str!("../assets/figfonts/slant.flf")) + && let Some(ff) = font.convert(&app) + { app_ff = ff.to_string(); } } diff --git a/src/app/figfont.rs b/src/app/figfont.rs deleted file mode 100644 index 765ef265..00000000 --- a/src/app/figfont.rs +++ /dev/null @@ -1,20 +0,0 @@ -use crate::global; - -use std::sync::LazyLock; - -use figlet_rs::FIGlet; - -pub static FIGFONT: LazyLock = LazyLock::new(|| { - let slant = include_str!("slant.flf"); - let small = include_str!("small.flf"); - let speed = include_str!("speed.flf"); - let starwars = include_str!("starwars.flf"); - - FIGlet::from_content(match global::SETTINGS.app.startup_banner { - global::StartupBanner::Off | global::StartupBanner::Slant => slant, - global::StartupBanner::Small => small, - global::StartupBanner::Speed => speed, - global::StartupBanner::Starwars => starwars, - }) - .unwrap() -}); diff --git a/src/app/starwars.flf b/src/app/starwars.flf deleted file mode 100644 index 6ea55f02..00000000 --- a/src/app/starwars.flf +++ /dev/null @@ -1,719 +0,0 @@ -flf2a$ 7 6 22 15 4 -starwars.flf by Ryan Youck (youck@cs.uregina.ca) Dec 25/1994 -I am not responsible for use of this font -Based on Big.flf by Glenn Chappell - -$ $@ -$ $@ -$ $@ -$ $@ -$ $@ -$ $@ -$ $@@ - __ $@ -| |$@ -| |$@ -| |$@ -|__|$@ -(__)$@ - $@@ - _ _ @ -( | )@ - V V @ - $ @ - $ @ - $ @ - @@ - _ _ @ - _| || |_$@ -|_ __ _|@ - _| || |_ @ -|_ __ _|@ - |_||_| $@ - @@ - __,--,_.@ - / |@ - | (----`@ - \ \ $@ -.----) | $@ -|_ __/ $@ - '--' $@@ - _ ___$ @ - / \ / /$ @ -( o ) / / $ @ - \_/ / / _$ @ - / / / \ @ - / / ( o )@ - /__/ \_/ @@ - @ - ___ @ - ( _ ) $@ - / _ \/\@ -| (_> <@ - \___/\/@ - $@@ - __ @ -(_ )@ - |/ @ - $ @ - $ @ - $ @ - @@ - ___@ - / /@ -| |$@ -| |$@ -| |$@ -| |$@ - \__\@@ -___ @ -\ \ @ - | |@ - | |@ - | |@ - | |@ -/__/ @@ - _ @ - /\| |/\ @ - \ ` ' /$@ -|_ _|@ - / , . \$@ - \/|_|\/ @ - @@ - @ - _ @ - _| |_$@ -|_ _|@ - |_| $@ - $ @ - @@ - @ - @ - $ @ - $ @ - __ @ -(_ )@ - |/ @@ - @ - @ - ______ @ -|______|@ - $ @ - $ @ - @@ - @ - @ - @ - $ @ - __ @ -(__)@ - @@ - ___@ - / /@ - / / @ - / /$ @ - / /$ @ -/__/$ @ - @@ - ___ $@ - / _ \ $@ -| | | |$@ -| | | |$@ -| |_| |$@ - \___/ $@ - $@@ - __ $@ -/_ |$@ - | |$@ - | |$@ - | |$@ - |_|$@ - $@@ - ___ $@ -|__ \ $@ - $) |$@ - / / $@ - / /_ $@ -|____|$@ - $@@ - ____ $@ -|___ \ $@ - __) |$@ - |__ < $@ - ___) |$@ -|____/ $@ - $@@ - _ _ $@ -| || | $@ -| || |_ $@ -|__ _|$@ - | | $@ - |_| $@ - $@@ - _____ $@ -| ____|$@ -| |__ $@ -|___ \ $@ - ___) |$@ -|____/ $@ - $@@ - __ $@ - / / $@ - / /_ $@ -| '_ \ $@ -| (_) |$@ - \___/ $@ - $@@ - ______ $@ -|____ |$@ - $/ / $@ - / / $@ - / / $@ - /_/ $@ - $@@ - ___ $@ - / _ \ $@ -| (_) |$@ - > _ < $@ -| (_) |$@ - \___/ $@ - $@@ - ___ $@ - / _ \ $@ -| (_) |$@ - \__, |$@ - / / $@ - /_/ $@ - $@@ - @ - _ @ -(_)@ - $ @ - _ @ -(_)@ - @@ - @ - _ @ -(_)@ - $ @ - _ @ -( )@ -|/ @@ - ___@ - / /@ - / /$@ -< <$ @ - \ \$@ - \__\@ - @@ - @ - ______ @ -|______|@ - ______ @ -|______|@ - @ - @@ -___ @ -\ \$ @ - \ \ @ - > >@ - / / @ -/__/$ @ - @@ - ______ $@ -| \ $@ -`----) |$@ - / / $@ - |__| $@ - __ $@ - (__) $@@ - ____ @ - / __ \ @ - / / _` |@ -| | (_| |@ - \ \__,_|@ - \____/ @ - @@ - ___ $ @ - / \ $ @ - / ^ \$ @ - / /_\ \$ @ - / _____ \$ @ -/__/ \__\$@ - $@@ -.______ $@ -| _ \ $@ -| |_) |$@ -| _ < $@ -| |_) |$@ -|______/ $@ - $@@ - ______$@ - / |@ -| ,----'@ -| | $@ -| `----.@ - \______|@ - $@@ - _______ $@ -| \$@ -| .--. |@ -| | | |@ -| '--' |@ -|_______/$@ - $@@ - _______ @ -| ____|@ -| |__ $@ -| __| $@ -| |____ @ -|_______|@ - @@ - _______ @ -| ____|@ -| |__ $@ -| __| $@ -| | $ @ -|__| @ - @@ - _______ @ - / _____|@ -| | __ $@ -| | |_ |$@ -| |__| |$@ - \______|$@ - $@@ - __ __ $@ -| | | |$@ -| |__| |$@ -| __ |$@ -| | | |$@ -|__| |__|$@ - $@@ - __ $@ -| |$@ -| |$@ -| |$@ -| |$@ -|__|$@ - $@@ - __ $@ - | |$@ - | |$@ -.--. | |$@ -| `--' |$@ - \______/ $@ - $@@ - __ ___$@ -| |/ /$@ -| ' / $@ -| < $@ -| . \ $@ -|__|\__\$@ - $@@ - __ $@ -| | $@ -| | $@ -| | $@ -| `----.@ -|_______|@ - $@@ -.___ ___.$@ -| \/ |$@ -| \ / |$@ -| |\/| |$@ -| | | |$@ -|__| |__|$@ - $@@ -.__ __.$@ -| \ | |$@ -| \| |$@ -| . ` |$@ -| |\ |$@ -|__| \__|$@ - $@@ - ______ $@ - / __ \ $@ -| | | |$@ -| | | |$@ -| `--' |$@ - \______/ $@ - $@@ -.______ $@ -| _ \ $@ -| |_) |$@ -| ___/ $@ -| | $ @ -| _| $ @ - $ @@ - ______ $ @ - / __ \ $ @ -| | | | $ @ -| | | | $ @ -| `--' '--. @ - \_____\_____\@ - $ @@ -.______ $ @ -| _ \ $ @ -| |_) | $ @ -| / $ @ -| |\ \----.@ -| _| `._____|@ - $@@ - _______.@ - / |@ - | (----`@ - \ \ $@ -.----) | $@ -|_______/ $@ - $@@ -.___________.@ -| |@ -`---| |----`@ - | | $ @ - | | $ @ - |__| $ @ - $ @@ - __ __ $@ -| | | |$@ -| | | |$@ -| | | |$@ -| `--' |$@ - \______/ $@ - $@@ -____ ____$@ -\ \ / /$@ - \ \/ /$ @ - \ /$ @ - \ /$ @ - \__/$ @ - $ @@ -____ __ ____$@ -\ \ / \ / /$@ - \ \/ \/ /$ @ - \ /$ @ - \ /\ /$ @ - \__/ \__/$ @ - $ @@ -___ ___$@ -\ \ / /$@ - \ V / $@ - > < $@ - / . \ $@ -/__/ \__\$@ - $@@ -____ ____$@ -\ \ / /$@ - \ \/ /$ @ - \_ _/$ @ - | |$ @ - |__|$ @ - $ @@ - ________ $@ -| / $@ -`---/ / $@ - / / $@ - / /----.@ - /________|@ - $@@ - ____ @ -| |@ -| |-`@ -| | $@ -| | $@ -| |-.@ -|____|@@ -___ @ -\ \ $ @ - \ \$ @ - \ \$ @ - \ \$@ - \__\@ - @@ - ____ @ -| |@ -`-| |@ - | |@ - | |@ -.-| |@ -|____|@@ - ___ @ - / \ @ -/--^--\@ - $@ - $@ - $@ - $@@ - @ - @ - @ - $ @ - $ @ - ______ @ -|______|@@ - __ @ -( _)@ - \| @ - $ @ - $ @ - $ @ - @@ - ___ $ @ - / \ $ @ - / ^ \$ @ - / /_\ \$ @ - / _____ \$ @ -/__/ \__\$@ - $@@ -.______ $@ -| _ \ $@ -| |_) |$@ -| _ < $@ -| |_) |$@ -|______/ $@ - $@@ - ______$@ - / |@ -| ,----'@ -| | $@ -| `----.@ - \______|@ - $@@ - _______ $@ -| \$@ -| .--. |@ -| | | |@ -| '--' |@ -|_______/$@ - $@@ - _______ @ -| ____|@ -| |__ $@ -| __| $@ -| |____ @ -|_______|@ - @@ - _______ @ -| ____|@ -| |__ $@ -| __| $@ -| | $ @ -|__| @ - @@ - _______ @ - / _____|@ -| | __ $@ -| | |_ |$@ -| |__| |$@ - \______|$@ - $@@ - __ __ $@ -| | | |$@ -| |__| |$@ -| __ |$@ -| | | |$@ -|__| |__|$@ - $@@ - __ $@ -| |$@ -| |$@ -| |$@ -| |$@ -|__|$@ - $@@ - __ $@ - | |$@ - | |$@ -.--. | |$@ -| `--' |$@ - \______/ $@ - $@@ - __ ___$@ -| |/ /$@ -| ' / $@ -| < $@ -| . \ $@ -|__|\__\$@ - $@@ - __ $@ -| | $@ -| | $@ -| | $@ -| `----.@ -|_______|@ - $@@ -.___ ___.$@ -| \/ |$@ -| \ / |$@ -| |\/| |$@ -| | | |$@ -|__| |__|$@ - $@@ -.__ __.$@ -| \ | |$@ -| \| |$@ -| . ` |$@ -| |\ |$@ -|__| \__|$@ - $@@ - ______ $@ - / __ \ $@ -| | | |$@ -| | | |$@ -| `--' |$@ - \______/ $@ - $@@ -.______ $@ -| _ \ $@ -| |_) |$@ -| ___/ $@ -| | $ @ -| _| $ @ - $ @@ - ______ $ @ - / __ \ $ @ -| | | | $ @ -| | | | $ @ -| `--' '--. @ - \_____\_____\@ - $ @@ -.______ $ @ -| _ \ $ @ -| |_) | $ @ -| / $ @ -| |\ \----.@ -| _| `._____|@ - $@@ - _______.@ - / |@ - | (----`@ - \ \ $@ -.----) | $@ -|_______/ $@ - $@@ -.___________.@ -| |@ -`---| |----`@ - | | $ @ - | | $ @ - |__| $ @ - $ @@ - __ __ $@ -| | | |$@ -| | | |$@ -| | | |$@ -| `--' |$@ - \______/ $@ - $@@ -____ ____$@ -\ \ / /$@ - \ \/ /$ @ - \ /$ @ - \ /$ @ - \__/$ @ - $ @@ -____ __ ____$@ -\ \ / \ / /$@ - \ \/ \/ /$ @ - \ /$ @ - \ /\ /$ @ - \__/ \__/$ @ - $ @@ -___ ___$@ -\ \ / /$@ - \ V / $@ - > < $@ - / . \ $@ -/__/ \__\$@ - $@@ -____ ____$@ -\ \ / /$@ - \ \/ /$ @ - \_ _/$ @ - | |$ @ - |__|$ @ - $ @@ - ________ $@ -| / $@ -`---/ / $@ - / / $@ - / /----.@ - /________|@ - $@@ - ___@ - / /@ - | |$@ -/ /$ @ -\ \$ @ - | |$@ - \__\@@ - __ $@ -| |$@ -| |$@ -| |$@ -| |$@ -| |$@ -|__|$@@ -___ @ -\ \$ @ - | | @ - \ \@ - / /@ - | | @ -/__/$ @@ - __ _ @ - / \/ |@ -|_/\__/ @ - $ @ - $ @ - $ @ - @@ - _ _ @ - (_)_(_) @ - / \ @ - / _ \ @ - / ___ \ @ -/_/ \_\@ - @@ - _ _ @ -(_)_(_)@ - / _ \ @ -| | | |@ -| |_| |@ - \___/ @ - @@ - _ _ @ -(_) (_)@ -| | | |@ -| | | |@ -| |_| |@ - \___/ @ - @@ - _ _ @ -(_) (_)@ - __ _ @ - / _` |@ -| (_| |@ - \__,_|@ - @@ - _ _ @ -(_) (_)@ - ___ @ - / _ \ @ -| (_) |@ - \___/ @ - @@ - _ _ @ -(_) (_)@ - _ _ @ -| | | |@ -| |_| |@ - \__,_|@ - @@ - ___ @ - / _ \ @ -| | ) |@ -| |< < @ -| | ) |@ -| ||_/ @ -|_| @@ diff --git a/src/global.rs b/src/global.rs index f89a83d3..d4a97dd6 100644 --- a/src/global.rs +++ b/src/global.rs @@ -12,9 +12,6 @@ use std::sync::LazyLock; mod lang_negotiation; pub use lang_negotiation::LangNegotiation; -mod startup_banner; -pub use startup_banner::StartupBanner; - mod timezone_order; pub use timezone_order::TimezoneOrder; @@ -178,10 +175,9 @@ pub struct AppSettings { #[default = "/admin"] #[serde(deserialize_with = "admin_path")] pub admin_path: String, - /// Banner ASCII mostrado al inicio: *"Off"* (desactivado), *"Slant"*, *"Small"*, *"Speed"* o - /// *"Starwars"*. - #[default(StartupBanner::Slant)] - pub startup_banner: StartupBanner, + /// Muestra al iniciar un *banner* ASCII con el nombre de la aplicación (*true*) o no (*false*). + #[default = true] + pub startup_banner: bool, /// Modo de ejecución, dado por la variable de entorno `PAGETOP_RUN_MODE`, o *"default"* si no /// está definida o está vacía. Con la *feature* `testing` activa es siempre *"test"*. pub run_mode: String, diff --git a/src/global/startup_banner.rs b/src/global/startup_banner.rs deleted file mode 100644 index a30ef239..00000000 --- a/src/global/startup_banner.rs +++ /dev/null @@ -1,45 +0,0 @@ -use crate::AutoDefault; - -use serde::de::Error; -use serde::{Deserialize, Deserializer}; - -/// Opciones para el *banner* ASCII mostrado al arrancar la aplicación. -/// -/// Se obtiene de [`global::SETTINGS.app.startup_banner`] y controla si se muestra un *banner* en la -/// salida estándar al arrancar la aplicación. -/// -/// [`global::SETTINGS.app.startup_banner`]: crate::global::AppSettings::startup_banner -#[derive(AutoDefault, Clone, Copy, Debug, Eq, PartialEq)] -pub enum StartupBanner { - /// No muestra ningún banner de inicio. - Off, - /// Banner en estilo "Slant". Es el comportamiento por defecto. - #[default] - Slant, - /// Banner en estilo "Small". - Small, - /// Banner en estilo "Speed". - Speed, - /// Banner en estilo "Starwars". - Starwars, -} - -impl<'de> Deserialize<'de> for StartupBanner { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - let raw = String::deserialize(deserializer)?; - match raw.trim().to_ascii_lowercase().as_str() { - "off" => Ok(Self::Off), - "slant" => Ok(Self::Slant), - "small" => Ok(Self::Small), - "speed" => Ok(Self::Speed), - "starwars" => Ok(Self::Starwars), - _ => Err(D::Error::unknown_variant( - &raw, - &["Off", "Slant", "Small", "Speed", "Starwars"], - )), - } - } -} From a6d15ab211352de100fac37ebf352839af82393d Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sun, 8 Nov 2026 14:24:30 +0100 Subject: [PATCH 02/11] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Exige=20la=20petici?= =?UTF-8?q?=C3=B3n=20en=20las=20variantes=20de=20ErrorPage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sustituye `Option` por `HttpRequest` en todas las variantes. Ningún uso construía un ErrorPage sin petición y, sin ella, la página de error pierde el idioma negociado y el usuario actual. --- extensions/pagetop-admin/src/handlers.rs | 2 +- extensions/pagetop-cron/src/lib.rs | 4 +-- extensions/pagetop-mail/src/preview.rs | 2 +- .../pagetop-user/src/handlers/account.rs | 18 ++++++------ .../pagetop-user/src/handlers/admin/roles.rs | 20 ++++++------- .../pagetop-user/src/handlers/admin/users.rs | 28 +++++++++---------- extensions/pagetop-user/src/handlers/auth.rs | 10 +++---- src/admin/pages.rs | 2 +- src/auth.rs | 4 +-- src/response/page/error.rs | 23 +++++++-------- src/web/csrf.rs | 2 +- src/web/download.rs | 4 +-- src/web/upload.rs | 2 +- 13 files changed, 59 insertions(+), 62 deletions(-) diff --git a/extensions/pagetop-admin/src/handlers.rs b/extensions/pagetop-admin/src/handlers.rs index ec57cf97..10a2ae2b 100644 --- a/extensions/pagetop-admin/src/handlers.rs +++ b/extensions/pagetop-admin/src/handlers.rs @@ -13,7 +13,7 @@ use crate::settings::{self, SettingFieldType, SettingsSchema}; fn config_form_page( request: &HttpRequest, ) -> Result<(&'static AdminPage, &'static SettingsSchema), ErrorPage> { - let not_found = || ErrorPage::NotFound(Some(request.clone())); + let not_found = || ErrorPage::NotFound(request.clone()); let path = strip_admin_path(request.path()).ok_or_else(not_found)?; let page = AdminRegistry::global().page(path).ok_or_else(not_found)?; let schema = config_forms().get(path).ok_or_else(not_found)?; diff --git a/extensions/pagetop-cron/src/lib.rs b/extensions/pagetop-cron/src/lib.rs index bf33960a..66a76d89 100644 --- a/extensions/pagetop-cron/src/lib.rs +++ b/extensions/pagetop-cron/src/lib.rs @@ -411,7 +411,7 @@ async fn trigger_post(request: HttpRequest) -> Response { .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Bearer")) .map(|(_, token)| token.trim_start()); if !token.is_some_and(scheduler::token_matches) { - return ErrorPage::NotFound(Some(request)).into_response(); + return ErrorPage::NotFound(request).into_response(); } // Siempre `200 OK`, aunque falle algún trabajo: un reintento del programa externo podría // llegar a otra instancia y repetir también los que terminaron bien. Sólo se indica el tipo de @@ -433,5 +433,5 @@ async fn trigger_post(request: HttpRequest) -> Response { } async fn not_found(request: HttpRequest) -> ErrorPage { - ErrorPage::NotFound(Some(request)) + ErrorPage::NotFound(request) } diff --git a/extensions/pagetop-mail/src/preview.rs b/extensions/pagetop-mail/src/preview.rs index 71a9ae17..eba450bc 100644 --- a/extensions/pagetop-mail/src/preview.rs +++ b/extensions/pagetop-mail/src/preview.rs @@ -159,7 +159,7 @@ pub(crate) async fn preview_get( ) -> Result { let previews = MailPreviews::collect(); let Some(preview) = previews.previews.iter().find(|p| p.key == key) else { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); }; let cx = Context::new(request.clone()); let email = transport::prepare_preview((preview.build)(&cx)); diff --git a/extensions/pagetop-user/src/handlers/account.rs b/extensions/pagetop-user/src/handlers/account.rs index c91cb11e..0057447c 100644 --- a/extensions/pagetop-user/src/handlers/account.rs +++ b/extensions/pagetop-user/src/handlers/account.rs @@ -96,11 +96,11 @@ pub(crate) async fn profile_get(request: HttpRequest) -> Response { let user = match user_admin::find_user(id).await { Ok(user) => user, - Err(_) => return ErrorPage::NotFound(Some(request)).into_response(), + Err(_) => return ErrorPage::NotFound(request).into_response(), }; let roles = match user_admin::user_roles(id).await { Ok(roles) => roles, - Err(_) => return ErrorPage::InternalError(Some(request)).into_response(), + Err(_) => return ErrorPage::InternalError(request).into_response(), }; let can_edit = has_permission(&request, &UserPermission::EditOwnProfile); let can_change_password = has_permission(&request, &UserPermission::ChangeOwnPassword); @@ -213,12 +213,12 @@ pub(crate) async fn public_profile_get( return Ok(deny_access(request)); } let Ok(user) = user_admin::find_user(id).await else { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); }; if UserStatus::from_i16(user.status) != UserStatus::Active && !has_permission(&request, &UserPermission::AdminUsers) { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); } let title = match util::non_blank(user.display_name.as_deref().unwrap_or_default()) { @@ -278,7 +278,7 @@ pub(crate) async fn profile_edit_get(request: HttpRequest) -> Result Result ErrorPage::NotFound(Some(request)).into_response(), + Err(_) => ErrorPage::NotFound(request).into_response(), } } diff --git a/extensions/pagetop-user/src/handlers/admin/roles.rs b/extensions/pagetop-user/src/handlers/admin/roles.rs index c32070cd..0fb8c3d6 100644 --- a/extensions/pagetop-user/src/handlers/admin/roles.rs +++ b/extensions/pagetop-user/src/handlers/admin/roles.rs @@ -43,7 +43,7 @@ pub(crate) async fn list_get( let result = match role_admin::list_roles_page(¶ms).await { Ok(result) => result, - Err(_) => return Err(ErrorPage::InternalError(Some(request))), + Err(_) => return Err(ErrorPage::InternalError(request)), }; let mut table = RoleTable::new() @@ -156,10 +156,10 @@ pub(crate) async fn edit_get( ) -> Result { let role = match role_admin::find_role(id).await { Ok(role) => role, - Err(_) => return Err(ErrorPage::NotFound(Some(request))), + Err(_) => return Err(ErrorPage::NotFound(request)), }; if role.locked { - return Err(ErrorPage::AccessDenied(Some(request))); + return Err(ErrorPage::AccessDenied(request)); } let page = Page::admin(request); @@ -257,11 +257,11 @@ pub(crate) async fn view_get( ) -> Result { let role = match role_admin::find_role(id).await { Ok(role) => role, - Err(_) => return Err(ErrorPage::NotFound(Some(request))), + Err(_) => return Err(ErrorPage::NotFound(request)), }; let selected = match role_admin::role_permission_keys(id).await { Ok(keys) => keys, - Err(_) => return Err(ErrorPage::InternalError(Some(request))), + Err(_) => return Err(ErrorPage::InternalError(request)), }; let mut page = Page::admin(request); @@ -388,9 +388,9 @@ pub(crate) async fn delete_post( let mut cx = Context::admin(request); Ok(HtmxResponse::new(table.render(&mut cx).await).into_response()) } else { - let cx = Context::new(request); match result { Ok(()) => { + let cx = Context::new(request); let target = cx .route(ADMIN_ROLES_PATH.as_str()) .alter_param( @@ -402,7 +402,7 @@ pub(crate) async fn delete_post( .to_string(); Ok(Redirect::see_other(target).into_response()) } - Err(_) => Err(ErrorPage::BadRequest(cx.request().cloned())), + Err(_) => Err(ErrorPage::BadRequest(request)), } } } @@ -472,11 +472,11 @@ pub(crate) async fn permissions_get( require_permission(&request, &UserPermission::AdminPermissions)?; if role_admin::find_role(id).await.is_err() { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); } let selected = match role_admin::role_permission_keys(id).await { Ok(keys) => keys, - Err(_) => return Err(ErrorPage::InternalError(Some(request))), + Err(_) => return Err(ErrorPage::InternalError(request)), }; let page = Page::admin(request); @@ -517,7 +517,7 @@ pub(crate) async fn permissions_post( require_permission(&request, &UserPermission::AdminPermissions)?; let Ok(form) = serde_qs::from_bytes::(&raw.0) else { - return Err(ErrorPage::BadRequest(Some(request))); + return Err(ErrorPage::BadRequest(request)); }; match role_admin::set_role_permissions(id, &form.permission_keys).await { diff --git a/extensions/pagetop-user/src/handlers/admin/users.rs b/extensions/pagetop-user/src/handlers/admin/users.rs index b26b1386..bd0ae2c1 100644 --- a/extensions/pagetop-user/src/handlers/admin/users.rs +++ b/extensions/pagetop-user/src/handlers/admin/users.rs @@ -53,7 +53,7 @@ pub(crate) async fn list_get( let result = match user_admin::list_users(¶ms).await { Ok(result) => result, - Err(_) => return Err(ErrorPage::InternalError(Some(request))), + Err(_) => return Err(ErrorPage::InternalError(request)), }; let mut table = UserTable::new() @@ -135,10 +135,10 @@ fn parse_role_ids(role_ids: &[String]) -> Vec { // un administrador puede conceder. async fn require_manageable(request: &HttpRequest, id: i32) -> Result { let Ok(user) = user_admin::find_user(id).await else { - return Err(ErrorPage::NotFound(Some(request.clone()))); + return Err(ErrorPage::NotFound(request.clone())); }; if user.is_admin && !request.extension::().is_some_and(|a| a.is_admin()) { - return Err(ErrorPage::AccessDenied(Some(request.clone()))); + return Err(ErrorPage::AccessDenied(request.clone())); } Ok(user) } @@ -152,7 +152,7 @@ pub(crate) async fn new_get( ) -> Result { let roles = match available_roles(&[]).await { Ok(roles) => roles, - Err(_) => return Err(ErrorPage::InternalError(Some(request))), + Err(_) => return Err(ErrorPage::InternalError(request)), }; // El campo "administrador" sólo se ofrece si quien da de alta ya es administrador: no es un // permiso del catálogo (igual que conceder/revocar en la edición, ver `set_user_admin`). @@ -205,7 +205,7 @@ pub(crate) async fn new_post( raw: web::RawForm, ) -> Result { let Ok(form) = serde_qs::from_bytes::(&raw.0) else { - return Err(ErrorPage::BadRequest(Some(request))); + return Err(ErrorPage::BadRequest(request)); }; let allow_admin_field = request.extension::().is_some_and(|a| a.is_admin()); // Nunca fiarse sólo de que el campo esté presente en el formulario: sólo se concede si quien @@ -273,15 +273,15 @@ async fn render_user_edit( ) -> Response { let user = match user_admin::find_user(id).await { Ok(user) => user, - Err(_) => return ErrorPage::NotFound(Some(request)).into_response(), + Err(_) => return ErrorPage::NotFound(request).into_response(), }; let current = match user_admin::user_role_ids(id).await { Ok(ids) => ids, - Err(_) => return ErrorPage::InternalError(Some(request)).into_response(), + Err(_) => return ErrorPage::InternalError(request).into_response(), }; let roles = match available_roles(¤t).await { Ok(roles) => roles, - Err(_) => return ErrorPage::InternalError(Some(request)).into_response(), + Err(_) => return ErrorPage::InternalError(request).into_response(), }; let status = UserStatus::from_i16(user.status); let is_admin = user.is_admin; @@ -468,7 +468,7 @@ pub(crate) async fn edit_post( ) -> Result { let user = require_manageable(&request, id).await?; let Ok(form) = serde_qs::from_bytes::(&raw.0) else { - return Err(ErrorPage::BadRequest(Some(request))); + return Err(ErrorPage::BadRequest(request)); }; let role_ids = parse_role_ids(&form.role_ids); @@ -524,11 +524,11 @@ pub(crate) async fn view_get( ) -> Result { let user = match user_admin::find_user(id).await { Ok(user) => user, - Err(_) => return Err(ErrorPage::NotFound(Some(request))), + Err(_) => return Err(ErrorPage::NotFound(request)), }; let roles = match user_admin::user_roles(id).await { Ok(roles) => roles, - Err(_) => return Err(ErrorPage::InternalError(Some(request))), + Err(_) => return Err(ErrorPage::InternalError(request)), }; let mut page = Page::admin(request); @@ -625,7 +625,7 @@ pub(crate) async fn status_post( require_permission(&request, &UserPermission::BlockAccounts)?; require_manageable(&request, id).await?; let Some(account) = request.extension::().cloned() else { - return Err(ErrorPage::AccessDenied(Some(request))); + return Err(ErrorPage::AccessDenied(request)); }; let new_status = match form.status.as_str() { @@ -670,10 +670,10 @@ pub(crate) async fn admin_post( web::Form(form): web::Form, ) -> Result { let Some(account) = request.extension::().cloned() else { - return Err(ErrorPage::AccessDenied(Some(request))); + return Err(ErrorPage::AccessDenied(request)); }; if !account.is_admin() { - return Err(ErrorPage::AccessDenied(Some(request))); + return Err(ErrorPage::AccessDenied(request)); } let new_is_admin = form.is_admin == "true"; diff --git a/extensions/pagetop-user/src/handlers/auth.rs b/extensions/pagetop-user/src/handlers/auth.rs index d46cda0b..15be31ed 100644 --- a/extensions/pagetop-user/src/handlers/auth.rs +++ b/extensions/pagetop-user/src/handlers/auth.rs @@ -158,7 +158,7 @@ pub async fn logout_post(request: HttpRequest) -> Response { /// GET /user/register - Formulario de registro de cuenta. pub async fn register_get(request: HttpRequest) -> Result { if !SETTINGS.allow_registration { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); } Page::new(request) .with_title(Lc::t("title-register", &LOCALES_USER)) @@ -175,7 +175,7 @@ pub async fn register_post( web::Form(form): web::Form, ) -> Response { if !SETTINGS.allow_registration { - return ErrorPage::NotFound(Some(request)).into_response(); + return ErrorPage::NotFound(request).into_response(); } let cx = Context::new(request.clone()); let result = if throttle::allow(&request) { @@ -289,7 +289,7 @@ pub async fn password_reset_confirm_get( .await .unwrap_or(false) { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); } let page = Page::new(request) .with_title(Lc::t("title-new-password", &LOCALES_USER)) @@ -378,7 +378,7 @@ pub async fn verify_email_get( .await .unwrap_or(false) { - return Err(ErrorPage::NotFound(Some(request))); + return Err(ErrorPage::NotFound(request)); } Ok(no_referrer( confirm_page( @@ -430,7 +430,7 @@ pub async fn verify_email_post( MessageLevel::Info, Lc::t("msg-email-verified", &LOCALES_USER), ), - Err(_) => ErrorPage::NotFound(Some(request)).into_response(), + Err(_) => ErrorPage::NotFound(request).into_response(), } } diff --git a/src/admin/pages.rs b/src/admin/pages.rs index 2deee864..a7d198db 100644 --- a/src/admin/pages.rs +++ b/src/admin/pages.rs @@ -50,7 +50,7 @@ async fn dashboard(request: HttpRequest) -> Response { async fn section_page(request: HttpRequest) -> Response { let path = strip_admin_path(request.path()).unwrap_or_default(); let Some(section) = AdminRegistry::global().section_by_path(path) else { - return ErrorPage::NotFound(Some(request)).into_response(); + return ErrorPage::NotFound(request).into_response(); }; let page = Page::admin(request.clone()); diff --git a/src/auth.rs b/src/auth.rs index fbdcf842..06dc6866 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -319,7 +319,7 @@ pub fn require_permission(request: &HttpRequest, perm: PermissionRef) -> Result< Ok(()) } else { trace_denied(request); - Err(ErrorPage::AccessDenied(Some(request.clone()))) + Err(ErrorPage::AccessDenied(request.clone())) } } @@ -383,7 +383,7 @@ pub fn deny_access(request: HttpRequest) -> Response { { return response; } - ErrorPage::AccessDenied(Some(request)).into_response() + ErrorPage::AccessDenied(request).into_response() } // Los anónimos van en `debug` porque bots y sesiones caducadas los hacen frecuentes y poco diff --git a/src/response/page/error.rs b/src/response/page/error.rs index 7d2f5adf..9404c88b 100644 --- a/src/response/page/error.rs +++ b/src/response/page/error.rs @@ -23,9 +23,6 @@ use std::any::Any; /// plantilla y el contenido del mensaje con los métodos específicos del tema, como /// [`Theme::error_403()`], [`Theme::error_404()`] o [`Theme::error_fatal()`]. /// -/// Sin `request` (`None`), la página se renderiza igualmente, pero sin el idioma negociado ni el -/// usuario actual, que dependen de la petición original. -/// /// [`Theme::error_403()`]: crate::core::theme::Theme::error_403 /// [`Theme::error_404()`]: crate::core::theme::Theme::error_404 /// [`Theme::error_fatal()`]: crate::core::theme::Theme::error_fatal @@ -33,24 +30,24 @@ use std::any::Any; pub enum ErrorPage { /// Petición incorrecta (400). El servidor no puede procesar la petición tal y como está /// formulada (datos malformados, parámetros inválidos, etc.). - BadRequest(Option), + BadRequest(HttpRequest), /// Acceso denegado (403). El usuario actual no tiene permiso para acceder al recurso. /// /// Se renderiza con [`Theme::error_403()`](crate::core::theme::Theme::error_403). - AccessDenied(Option), + AccessDenied(HttpRequest), /// Recurso no encontrado (404). La ruta solicitada no existe o no coincide con ningún handler. /// /// Se renderiza con [`Theme::error_404()`](crate::core::theme::Theme::error_404). - NotFound(Option), + NotFound(HttpRequest), /// Error interno del servidor (500). Un fallo controlado (no un `panic!`) impide completar la /// petición. - InternalError(Option), + InternalError(HttpRequest), /// Servicio no disponible (503). El servidor no puede atender la petición temporalmente /// (mantenimiento, sobrecarga, etc.). - ServiceUnavailable(Option), + ServiceUnavailable(HttpRequest), /// Tiempo de espera agotado (504). Una dependencia externa (proxy, servicio remoto) no ha /// respondido a tiempo. - GatewayTimeout(Option), + GatewayTimeout(HttpRequest), } impl ErrorPage { @@ -72,12 +69,12 @@ impl ErrorPage { let status = self.status_code(); let mut page = match self { Self::AccessDenied(request) => { - let mut page = Page::default().with_request(request); + let mut page = Page::default().with_request(Some(request)); page.theme().error_403(&mut page); page } Self::NotFound(request) => { - let mut page = Page::default().with_request(request); + let mut page = Page::default().with_request(Some(request)); page.theme().error_404(&mut page); page } @@ -85,7 +82,7 @@ impl ErrorPage { | Self::InternalError(request) | Self::ServiceUnavailable(request) | Self::GatewayTimeout(request) => { - let mut page = Page::default().with_request(request); + let mut page = Page::default().with_request(Some(request)); page.theme().error_fatal( &mut page, status, @@ -126,7 +123,7 @@ impl IntoResponse for ErrorPage { // // Se registra como `.fallback()` del router principal desde [`Application`](crate::Application). pub(crate) async fn route_not_found(request: HttpRequest) -> Result { - Err(ErrorPage::NotFound(Some(request))) + Err(ErrorPage::NotFound(request)) } // Intercepta respuestas con un [`ErrorPage`] pendiente y las convierte en páginas HTML. diff --git a/src/web/csrf.rs b/src/web/csrf.rs index 833de1e8..af02fe4b 100644 --- a/src/web/csrf.rs +++ b/src/web/csrf.rs @@ -45,7 +45,7 @@ pub(crate) async fn reject_cross_origin(request: Request, next: Next) -> Respons ); let (mut parts, _) = request.into_parts(); let Ok(request) = HttpRequest::from_request_parts(&mut parts, &()).await; - ErrorPage::AccessDenied(Some(request)).into_response() + ErrorPage::AccessDenied(request).into_response() } // Con HTTP/2 el servidor llega en la URI (`:authority`) y no siempre en `Host`. diff --git a/src/web/download.rs b/src/web/download.rs index dc1e3ee2..5cc8e6ce 100644 --- a/src/web/download.rs +++ b/src/web/download.rs @@ -65,8 +65,8 @@ const FORWARDED_HEADERS: [http::HeaderName; 6] = [ /// .serve(&request) /// .await /// .map_err(|err| match err { -/// web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)), -/// _ => ErrorPage::InternalError(Some(request)), +/// web::UploadError::NotFound(_) => ErrorPage::NotFound(request), +/// _ => ErrorPage::InternalError(request), /// }) /// } /// ``` diff --git a/src/web/upload.rs b/src/web/upload.rs index 68c92250..bdb08036 100644 --- a/src/web/upload.rs +++ b/src/web/upload.rs @@ -362,7 +362,7 @@ impl Drop for SavedFiles { /// // Volver a mostrar el formulario con `err.message()`... /// # todo!() /// } -/// Err(_) => return Err(ErrorPage::InternalError(Some(request))), +/// Err(_) => return Err(ErrorPage::InternalError(request)), /// }; /// let Some(photo) = sent.file("photo") else { /// // Campo obligatorio sin archivo: volver a mostrar el formulario... From 698b917fb1b44cc4ed6c571876db9cebd3d6f578 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Mon, 9 Nov 2026 07:22:18 +0100 Subject: [PATCH 03/11] =?UTF-8?q?=E2=9E=96=20Sustituye=20parking=5Flot=20p?= =?UTF-8?q?or=20std::sync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PageTop ya no lo necesita como dependencia directa: `std::sync` cubre los bloqueos del contexto, los temas y las trazas. No se detecta pérdida de rendimiento en ningún caso. Usa `unwrap()` en los bloqueos, también en las extensiones, porque sus secciones exclusivas no pueden provocar panic. Sólo pagetop-cron ignora el envenenamiento, porque calcula fechas con el bloqueo tomado. --- Cargo.lock | 1 - Cargo.toml | 2 -- extensions/pagetop-cron/src/scheduler.rs | 5 +++-- extensions/pagetop-mail/src/outbox.rs | 20 ++++++-------------- extensions/pagetop-user/src/session.rs | 14 ++++---------- extensions/pagetop-user/src/throttle.rs | 12 ++++-------- src/core/component/context.rs | 3 +-- src/core/component/context/contextual.rs | 2 +- src/core/theme/all.rs | 9 ++++----- src/core/theme/regions.rs | 11 +++++------ src/trace.rs | 8 +++----- 11 files changed, 31 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 24ba63ca..67b1a195 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2174,7 +2174,6 @@ dependencies = [ "pagetop-macros", "pagetop-minimal", "pagetop-statics", - "parking_lot", "serde", "serde_json", "serde_qs", diff --git a/Cargo.toml b/Cargo.toml index b99f525d..b5b3d83a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,6 @@ itoa = "1.0" lettre = { version = "0.11", default-features = false } mime_guess = "2.0" minify-js = "0.6" -parking_lot = "0.12" pastey = "0.2" path-slash = "0.2" proc-macro2 = "1.0" @@ -131,7 +130,6 @@ fluent-templates.workspace = true getter-methods.workspace = true indexmap.workspace = true itoa.workspace = true -parking_lot.workspace = true pagetop-macros.workspace = true pagetop-minimal.workspace = true pagetop-statics.workspace = true diff --git a/extensions/pagetop-cron/src/scheduler.rs b/extensions/pagetop-cron/src/scheduler.rs index 772e408b..3eb27c0f 100644 --- a/extensions/pagetop-cron/src/scheduler.rs +++ b/extensions/pagetop-cron/src/scheduler.rs @@ -282,8 +282,9 @@ impl Entry { } } - // Un `panic!` sólo puede ocurrir fuera de la sección protegida (se ejecutan en otra tarea), - // así que el estado sigue siendo coherente aunque el `Mutex` quede envenenado. + // Los trabajos se ejecutan en otra tarea, fuera de la sección protegida. Dentro sólo podría + // fallar el cálculo de fechas de `take_due()`, que no deja el estado incoherente, así que un + // `Mutex` envenenado no debe detener el trabajo. fn state(&self) -> MutexGuard<'_, State> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } diff --git a/extensions/pagetop-mail/src/outbox.rs b/extensions/pagetop-mail/src/outbox.rs index e1ae3bd5..6f3e1326 100644 --- a/extensions/pagetop-mail/src/outbox.rs +++ b/extensions/pagetop-mail/src/outbox.rs @@ -36,7 +36,7 @@ use pagetop::prelude::*; use crate::Email; -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::Mutex; static OUTBOX: Mutex> = Mutex::new(Vec::new()); @@ -99,13 +99,13 @@ fn unescape(value: &str) -> String { /// Recoge todos los correos guardados, en el orden en que se enviaron. pub fn take() -> Vec { - std::mem::take(&mut *lock()) + std::mem::take(&mut *OUTBOX.lock().unwrap()) } /// Recoge los correos entregados a la dirección dada, en el orden en que se enviaron, y deja los /// demás. pub fn take_to(address: &str) -> Vec { - let mut outbox = lock(); + let mut outbox = OUTBOX.lock().unwrap(); let (taken, kept) = outbox .drain(..) .partition(|sent: &SentEmail| sent.is_delivered_to(address)); @@ -114,18 +114,13 @@ pub fn take_to(address: &str) -> Vec { } pub(crate) fn push(email: Email, envelope_to: Vec, raw: Vec) { - lock().push(SentEmail { + OUTBOX.lock().unwrap().push(SentEmail { email, envelope_to, raw: String::from_utf8_lossy(&raw).into_owned(), }); } -// Una prueba que falla con el bloqueo tomado no debe impedir que las demás sigan usándolo. -fn lock() -> MutexGuard<'static, Vec> { - OUTBOX.lock().unwrap_or_else(PoisonError::into_inner) -} - // Correos completos de la cola de envío pendientes de entregar con este transporte, por su // identificador en la cola. La cola sólo guarda el mensaje compuesto, y las pruebas necesitan el // correo completo para consultarlo con `SentEmail::email()`. @@ -134,15 +129,12 @@ static QUEUED: Mutex> = Mutex::new(Vec::new()); #[cfg(feature = "queue")] pub(crate) fn hold(id: i32, email: Email) { - QUEUED - .lock() - .unwrap_or_else(PoisonError::into_inner) - .push((id, email)); + QUEUED.lock().unwrap().push((id, email)); } #[cfg(feature = "queue")] pub(crate) fn release(id: i32) -> Option { - let mut queued = QUEUED.lock().unwrap_or_else(PoisonError::into_inner); + let mut queued = QUEUED.lock().unwrap(); let index = queued.iter().position(|(queued_id, _)| *queued_id == id)?; Some(queued.swap_remove(index).1) } diff --git a/extensions/pagetop-user/src/session.rs b/extensions/pagetop-user/src/session.rs index 12366581..00ddcf39 100644 --- a/extensions/pagetop-user/src/session.rs +++ b/extensions/pagetop-user/src/session.rs @@ -2,7 +2,7 @@ //! //! Incluye también los permisos del rol "anonymous", que se aplican a las peticiones sin sesión. -use std::sync::{Arc, PoisonError, RwLock}; +use std::sync::{Arc, RwLock}; use std::time::Instant; use pagetop::prelude::*; @@ -308,9 +308,7 @@ static ANONYMOUS_CACHE: RwLock = RwLock::new(AnonymousCache { /// a intentar en la siguiente petición. pub(crate) async fn anonymous_permissions() -> Arc { let generation = { - let cache = ANONYMOUS_CACHE - .read() - .unwrap_or_else(PoisonError::into_inner); + let cache = ANONYMOUS_CACHE.read().unwrap(); if let Some((loaded_at, permissions)) = &cache.loaded && loaded_at.elapsed() < ANONYMOUS_TTL { @@ -334,9 +332,7 @@ pub(crate) async fn anonymous_permissions() -> Arc { } }; - let mut cache = ANONYMOUS_CACHE - .write() - .unwrap_or_else(PoisonError::into_inner); + let mut cache = ANONYMOUS_CACHE.write().unwrap(); if cache.generation == generation { cache.loaded = Some((Instant::now(), Arc::clone(&permissions))); } @@ -346,9 +342,7 @@ pub(crate) async fn anonymous_permissions() -> Arc { /// Descarta los permisos de "anonymous" guardados en memoria, para que la siguiente petición sin /// sesión los vuelva a leer. Se llama al cambiar los permisos de ese rol. pub(crate) fn invalidate_anonymous_permissions() { - let mut cache = ANONYMOUS_CACHE - .write() - .unwrap_or_else(PoisonError::into_inner); + let mut cache = ANONYMOUS_CACHE.write().unwrap(); cache.generation = cache.generation.wrapping_add(1); cache.loaded = None; } diff --git a/extensions/pagetop-user/src/throttle.rs b/extensions/pagetop-user/src/throttle.rs index c14cb589..7d153de6 100644 --- a/extensions/pagetop-user/src/throttle.rs +++ b/extensions/pagetop-user/src/throttle.rs @@ -7,7 +7,7 @@ use crate::config::SETTINGS; use std::collections::{HashMap, VecDeque}; use std::net::{IpAddr, Ipv6Addr}; -use std::sync::{LazyLock, Mutex, PoisonError}; +use std::sync::{LazyLock, Mutex}; use std::time::{Duration as StdDuration, Instant}; // Momentos de las solicitudes de cada dirección dentro de la ventana, y última limpieza. @@ -41,7 +41,7 @@ pub(crate) fn allow(request: &HttpRequest) -> bool { return true; }; let allowed = allow_at( - &mut lock(&REQUESTS), + &mut REQUESTS.lock().unwrap(), network(ip), Instant::now(), SETTINGS.max_ip_requests, @@ -63,7 +63,7 @@ pub(crate) fn allow_login(request: &HttpRequest) -> bool { return true; }; let allowed = allow_at( - &mut lock(&FAILED_LOGINS), + &mut FAILED_LOGINS.lock().unwrap(), network(ip), Instant::now(), SETTINGS.max_ip_failed_logins, @@ -78,14 +78,10 @@ pub(crate) fn allow_login(request: &HttpRequest) -> bool { /// Retira un intento anotado por [`allow_login()`] que no ha resultado fallido. pub(crate) fn forget_login(request: &HttpRequest) { if let Some(ip) = request.client_ip() { - forget_at(&mut lock(&FAILED_LOGINS), network(ip)); + forget_at(&mut FAILED_LOGINS.lock().unwrap(), network(ip)); } } -fn lock(log: &Log) -> std::sync::MutexGuard<'_, Requests> { - log.lock().unwrap_or_else(PoisonError::into_inner) -} - fn window(secs: i64) -> StdDuration { StdDuration::from_secs(u64::try_from(secs).unwrap_or(0)) } diff --git a/src/core/component/context.rs b/src/core/component/context.rs index 654f2655..3a59368e 100644 --- a/src/core/component/context.rs +++ b/src/core/component/context.rs @@ -11,10 +11,9 @@ use crate::response::read_flash_messages; use crate::web::HttpRequest; use crate::{CowStr, util}; -use parking_lot::Mutex; - use std::any::{Any, TypeId}; use std::collections::HashMap; +use std::sync::Mutex; mod assets_op; pub use assets_op::AssetsOp; diff --git a/src/core/component/context/contextual.rs b/src/core/component/context/contextual.rs index b691a5e0..7587bb74 100644 --- a/src/core/component/context/contextual.rs +++ b/src/core/component/context/contextual.rs @@ -481,7 +481,7 @@ pub trait Contextual { segments }; let count = { - let mut map = self.context().id_counters.lock(); + let mut map = self.context().id_counters.lock().unwrap(); let n = map.entry(TypeId::of::()).or_insert(0); *n += 1; *n diff --git a/src/core/theme/all.rs b/src/core/theme/all.rs index 67542e61..8f9cfa65 100644 --- a/src/core/theme/all.rs +++ b/src/core/theme/all.rs @@ -1,9 +1,7 @@ use crate::core::theme::ThemeRef; use crate::{global, trace}; -use parking_lot::RwLock; - -use std::sync::LazyLock; +use std::sync::{LazyLock, RwLock}; // **< TEMAS >************************************************************************************** @@ -11,7 +9,7 @@ static THEMES: LazyLock>> = LazyLock::new(|| RwLock::new(Ve // Registra el tema si no lo estaba ya, para evitar duplicados. Devuelve `true` si lo ha añadido. pub(crate) fn register_theme(theme: ThemeRef) -> bool { - let mut themes = THEMES.write(); + let mut themes = THEMES.write().unwrap(); if themes.iter().any(|t| t.type_id() == theme.type_id()) { return false; } @@ -21,7 +19,7 @@ pub(crate) fn register_theme(theme: ThemeRef) -> bool { /// Devuelve los temas habilitados en la aplicación, en el orden en que se registraron. pub fn enabled_themes() -> Vec { - THEMES.read().clone() + THEMES.read().unwrap().clone() } /// Devuelve el tema identificado por su [`short_name()`](crate::core::AnyInfo::short_name). @@ -30,6 +28,7 @@ pub fn enabled_themes() -> Vec { pub fn theme_by_short_name(short_name: &str) -> Option { THEMES .read() + .unwrap() .iter() .find(|t| t.short_name().eq_ignore_ascii_case(short_name)) .copied() diff --git a/src/core/theme/regions.rs b/src/core/theme/regions.rs index db910f1e..718a7a11 100644 --- a/src/core/theme/regions.rs +++ b/src/core/theme/regions.rs @@ -2,10 +2,8 @@ use crate::core::component::{Child, ChildOp, Children, Component}; use crate::core::theme::{CoreRegions, RegionRef, ThemeRef}; use crate::{AutoDefault, UniqueId, builder_impl}; -use parking_lot::RwLock; - use std::collections::HashMap; -use std::sync::{Arc, LazyLock}; +use std::sync::{Arc, LazyLock, RwLock}; // Lista de prototipos de componentes por nombre de región. // @@ -90,7 +88,7 @@ impl ChildrenInRegions { let region_name = region.name(); // 1. Prototipos globales comunes. - if let Some(global_protos) = COMMON_REGIONS.read().get(region_name) { + if let Some(global_protos) = COMMON_REGIONS.read().unwrap().get(region_name) { result.add_many( global_protos .iter() @@ -102,7 +100,7 @@ impl ChildrenInRegions { result.add_many(page_children); } // 3. Prototipos del tema activo. - if let Some(theme_region) = THEME_REGIONS.read().get(&theme.type_id()) + if let Some(theme_region) = THEME_REGIONS.read().unwrap().get(&theme.type_id()) && let Some(theme_protos) = theme_region.get(region_name) { result.add_many( @@ -190,6 +188,7 @@ impl InRegion { InRegion::ForTheme(theme, region) => { THEME_REGIONS .write() + .unwrap() .entry(theme.type_id()) .or_default() .push((*region).name(), proto); @@ -200,6 +199,6 @@ impl InRegion { #[inline] fn add_to_common(region: RegionRef, proto: Arc) { - COMMON_REGIONS.write().push(region.name(), proto); + COMMON_REGIONS.write().unwrap().push(region.name(), proto); } } diff --git a/src/trace.rs b/src/trace.rs index 9b69e176..fe928788 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -22,8 +22,8 @@ pub use tracing::{debug_span, error_span, info_span, trace_span, warn_span}; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::EnvFilter; +use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Mutex, PoisonError}; // Avisos generados antes de iniciar las trazas. La configuración se lee antes, porque las trazas // dependen de la sección `[log]`, así que sus avisos se guardan aquí y se emiten al iniciarlas. @@ -34,9 +34,7 @@ static DEFERRED_WARNINGS: Mutex>> = Mutex::new(Some(Vec::new( // basta para la configuración global, que `init()` lee antes de recoger los avisos. Usarla después // es un error de programación: se emite como `error!` con el aviso incluido, para que no se pierda. pub(crate) fn defer_warning(message: String) { - let mut deferred = DEFERRED_WARNINGS - .lock() - .unwrap_or_else(PoisonError::into_inner); + let mut deferred = DEFERRED_WARNINGS.lock().unwrap(); match deferred.as_mut() { Some(warnings) => warnings.push(message), None => { @@ -70,7 +68,7 @@ pub(crate) fn init() -> Option { // Al leer `SETTINGS` en la línea anterior ya se han guardado los avisos de la configuración. let mut warnings = DEFERRED_WARNINGS .lock() - .unwrap_or_else(PoisonError::into_inner) + .unwrap() .take() // Deja `None`, desde ahora, `defer_warning()` trata cualquier aviso como mal uso. .unwrap_or_default(); if !enabled { From bdc94be92a55ccae1a8347d9450cb9e2ec685b08 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Mon, 9 Nov 2026 23:04:59 +0100 Subject: [PATCH 04/11] =?UTF-8?q?=F0=9F=92=84=20(user):=20Unifica=20botone?= =?UTF-8?q?ras=20y=20enlaces=20de=20vuelta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - "Guardar" y "Cancelar" en la misma fila en todos los formularios. - "Volver" sólo en fichas de sólo lectura. - Búsqueda de usuarios con `form::input::Field` y botones de alta en estilo principal. --- extensions/pagetop-user/src/component.rs | 23 +++++- .../component/admin/admin_password_form.rs | 11 +-- .../src/component/admin/role_form.rs | 10 +-- .../component/admin/role_permissions_form.rs | 10 ++- .../src/component/admin/role_table.rs | 5 +- .../src/component/admin/user_form.rs | 22 ++--- .../src/component/admin/user_table.rs | 5 +- .../src/component/change_email_form.rs | 10 +-- .../src/component/change_password_form.rs | 10 +-- .../pagetop-user/src/handlers/account.rs | 14 +--- extensions/pagetop-user/src/handlers/admin.rs | 13 +-- .../pagetop-user/src/handlers/admin/roles.rs | 12 --- .../pagetop-user/src/handlers/admin/users.rs | 80 +++++++++---------- .../pagetop-user/src/locale/en-US/common.ftl | 2 +- .../pagetop-user/src/locale/es-ES/common.ftl | 2 +- 15 files changed, 115 insertions(+), 114 deletions(-) diff --git a/extensions/pagetop-user/src/component.rs b/extensions/pagetop-user/src/component.rs index e4971ae1..bc7b2929 100644 --- a/extensions/pagetop-user/src/component.rs +++ b/extensions/pagetop-user/src/component.rs @@ -24,11 +24,11 @@ pub use user_name::UserName; use pagetop::prelude::*; -use crate::LOCALES_USER; use crate::account::UserStatus; use crate::component::admin::status_key; use crate::config::{user_language_applies, user_timezone_applies}; use crate::entity::user; +use crate::{LOCALES_USER, PROFILE_PATH}; // Texto libre de varias líneas como contenido seguro: cada salto de línea se convierte en `
`, // sin depender del CSS del tema. Se usa para mostrar el "Sobre mí" del usuario. @@ -87,6 +87,27 @@ pub(crate) fn error_banner(error: Option) -> Html { }) } +// Enlace para salir de un formulario sin guardar. +pub(crate) fn cancel_link(route: impl Into) -> Button { + Button::anchor(Lc::t("btn-cancel", &LOCALES_USER), route).with_style(button::Style::Link) +} + +// Botonera de un formulario: el botón de envío y, en la misma fila, el enlace para salir sin +// guardar. +pub(crate) fn form_actions(submit: Lc, cancel: impl Into) -> Flex { + Flex::new() + .with_wrap(flex::Behavior::Wrap) + .with_align(align::Items::Center) + .with_gap(align::Gap::Both(UnitValue::RelRem(0.5))) + .with_child(Button::submit(submit).with_style(button::Style::Solid(Intent::Primary))) + .with_child(cancel_link(cancel)) +} + +// Botonera de los formularios del perfil propio, que al cancelar vuelven al perfil. +pub(crate) fn profile_form_actions(submit: Lc, cx: &Context) -> Flex { + form_actions(submit, cx.route(PROFILE_PATH)) +} + // Bloque de sólo lectura con los datos de perfil de un usuario, para «Mi cuenta» y para la ficha de // administración. pub(crate) async fn user_details(user: &user::Model, cx: &mut Context) -> Block { diff --git a/extensions/pagetop-user/src/component/admin/admin_password_form.rs b/extensions/pagetop-user/src/component/admin/admin_password_form.rs index 5775d8b0..07f9d5ed 100644 --- a/extensions/pagetop-user/src/component/admin/admin_password_form.rs +++ b/extensions/pagetop-user/src/component/admin/admin_password_form.rs @@ -5,7 +5,7 @@ use pagetop::prelude::*; use crate::LOCALES_USER; use crate::user_path; -use crate::component::{PasswordConfirm, error_banner}; +use crate::component::{PasswordConfirm, error_banner, form_actions}; #[derive(AutoDefault, Clone, Debug, Getters)] pub(crate) struct AdminPasswordForm { @@ -34,10 +34,11 @@ impl Component for AdminPasswordForm { PasswordConfirm::new() .with_password_label(Lc::t("field-new-password", &LOCALES_USER)), ) - .with_child( - Button::submit(Lc::t("btn-save", &LOCALES_USER)) - .with_style(button::Style::Solid(Intent::Primary)), - ); + .with_child(form_actions( + Lc::t("btn-save", &LOCALES_USER), + self.waypoint() + .append_to(cx.route(user_path(self.user_id(), "edit"))), + )); Ok(form.render(cx).await) } diff --git a/extensions/pagetop-user/src/component/admin/role_form.rs b/extensions/pagetop-user/src/component/admin/role_form.rs index b195e496..1b63ecc0 100644 --- a/extensions/pagetop-user/src/component/admin/role_form.rs +++ b/extensions/pagetop-user/src/component/admin/role_form.rs @@ -6,7 +6,7 @@ use crate::ADMIN_ROLES_PATH; use crate::LOCALES_USER; use crate::role_path; -use crate::component::error_banner; +use crate::component::{error_banner, form_actions}; use crate::service::role_admin::{ROLE_LABEL_MAX_CHARS, ROLE_MACHINE_NAME_MAX_CHARS}; #[derive(AutoDefault, Clone, Copy, Debug, PartialEq)] @@ -86,10 +86,10 @@ impl Component for RoleForm { .with_inputmode(Some(form::input::Mode::Numeric)), ); - form = form.with_child( - Button::submit(Lc::t("btn-save", &LOCALES_USER)) - .with_style(button::Style::Solid(Intent::Primary)), - ); + form = form.with_child(form_actions( + Lc::t("btn-save", &LOCALES_USER), + self.waypoint().or(cx.route(ADMIN_ROLES_PATH.as_str())), + )); Ok(form.render(cx).await) } diff --git a/extensions/pagetop-user/src/component/admin/role_permissions_form.rs b/extensions/pagetop-user/src/component/admin/role_permissions_form.rs index 8efc0d34..070fdccb 100644 --- a/extensions/pagetop-user/src/component/admin/role_permissions_form.rs +++ b/extensions/pagetop-user/src/component/admin/role_permissions_form.rs @@ -4,7 +4,9 @@ use pagetop::prelude::*; +use crate::ADMIN_ROLES_PATH; use crate::LOCALES_USER; +use crate::component::form_actions; use crate::role_path; use crate::component::admin::PermissionGroups; @@ -52,10 +54,10 @@ impl Component for RolePermissionsForm { form = form.with_child(fieldset); } - form = form.with_child( - Button::submit(Lc::t("btn-save", &LOCALES_USER)) - .with_style(button::Style::Solid(Intent::Primary)), - ); + form = form.with_child(form_actions( + Lc::t("btn-save", &LOCALES_USER), + self.waypoint().or(cx.route(ADMIN_ROLES_PATH.as_str())), + )); Ok(form.render(cx).await) } diff --git a/extensions/pagetop-user/src/component/admin/role_table.rs b/extensions/pagetop-user/src/component/admin/role_table.rs index d03edcb1..f9f867ed 100644 --- a/extensions/pagetop-user/src/component/admin/role_table.rs +++ b/extensions/pagetop-user/src/component/admin/role_table.rs @@ -121,7 +121,10 @@ impl Component for RoleTable { Ok(html! { div (self.props().unpack(cx)) { - (Button::anchor(Lc::t("btn-create-role", &LOCALES_USER), new_href).render(cx).await) + (Button::anchor(Lc::t("btn-create-role", &LOCALES_USER), new_href) + .with_style(button::Style::Solid(Intent::Primary)) + .render(cx) + .await) @if let Some(message) = self.message() { div class="user-form-error" role="alert" { (message.clone().using(cx)) } } diff --git a/extensions/pagetop-user/src/component/admin/user_form.rs b/extensions/pagetop-user/src/component/admin/user_form.rs index bd7ee147..48414b56 100644 --- a/extensions/pagetop-user/src/component/admin/user_form.rs +++ b/extensions/pagetop-user/src/component/admin/user_form.rs @@ -7,7 +7,7 @@ use crate::config::{SETTINGS, user_language_applies, user_timezone_applies}; use crate::user_path; use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH}; -use crate::component::{PasswordConfirm, error_banner}; +use crate::component::{PasswordConfirm, error_banner, form_actions, profile_form_actions}; use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars}; use crate::service::user_admin::{ABOUT_MAX_CHARS, DISPLAY_NAME_MAX_CHARS}; @@ -159,14 +159,18 @@ impl Component for UserForm { ); } - // En modo `Edit`, "Guardar" se renderiza fuera del formulario, junto al resto de acciones - // de la pantalla (ver `USER_ADMIN_FORM_ID`); en los demás modos no hay ninguna botonera con - // la que agruparlo, así que se queda aquí, dentro del propio `
`. - if *self.mode() != UserFormMode::Edit { - form = form.with_child( - Button::submit(Lc::t("btn-save", &LOCALES_USER)) - .with_style(button::Style::Solid(Intent::Primary)), - ); + // En modo `Edit`, "Guardar" y "Cancelar" se renderizan fuera del formulario, junto al resto + // de acciones de la pantalla (ver `USER_ADMIN_FORM_ID`). + let save = Lc::t("btn-save", &LOCALES_USER); + match self.mode() { + UserFormMode::Edit => {} + UserFormMode::Profile => { + form = form.with_child(profile_form_actions(save, cx)); + } + UserFormMode::New => { + let cancel = self.waypoint().or(cx.route(ADMIN_USERS_PATH.as_str())); + form = form.with_child(form_actions(save, cancel)); + } } Ok(form.render(cx).await) diff --git a/extensions/pagetop-user/src/component/admin/user_table.rs b/extensions/pagetop-user/src/component/admin/user_table.rs index 4fa659ee..f161e1f7 100644 --- a/extensions/pagetop-user/src/component/admin/user_table.rs +++ b/extensions/pagetop-user/src/component/admin/user_table.rs @@ -87,7 +87,10 @@ impl Component for UserTable { Ok(html! { div (self.props().unpack(cx)) { - (Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href).render(cx).await) + (Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href) + .with_style(button::Style::Solid(Intent::Primary)) + .render(cx) + .await) (table.render(cx).await) (pager) } diff --git a/extensions/pagetop-user/src/component/change_email_form.rs b/extensions/pagetop-user/src/component/change_email_form.rs index 2512350e..6ebfda3f 100644 --- a/extensions/pagetop-user/src/component/change_email_form.rs +++ b/extensions/pagetop-user/src/component/change_email_form.rs @@ -4,7 +4,7 @@ use pagetop::prelude::*; use crate::{EMAIL_PATH, LOCALES_USER}; -use crate::component::error_banner; +use crate::component::{error_banner, profile_form_actions}; use crate::identity::EMAIL_MAX_CHARS; /// Pide la nueva dirección y la contraseña actual. Si ya hay un cambio pendiente de confirmar, lo @@ -56,10 +56,10 @@ impl Component for ChangeEmailForm { .with_autocomplete(Some(form::Autocomplete::current_password())) .with_required(true), ) - .with_child( - Button::submit(Lc::t("btn-change-email", &LOCALES_USER)) - .with_style(button::Style::Solid(Intent::Primary)), - ); + .with_child(profile_form_actions( + Lc::t("btn-change-email", &LOCALES_USER), + cx, + )); Ok(form.render(cx).await) } diff --git a/extensions/pagetop-user/src/component/change_password_form.rs b/extensions/pagetop-user/src/component/change_password_form.rs index b759b055..4b58b15b 100644 --- a/extensions/pagetop-user/src/component/change_password_form.rs +++ b/extensions/pagetop-user/src/component/change_password_form.rs @@ -4,7 +4,7 @@ use pagetop::prelude::*; use crate::{LOCALES_USER, PROFILE_PASSWORD_PATH}; -use crate::component::{PasswordConfirm, error_banner}; +use crate::component::{PasswordConfirm, error_banner, profile_form_actions}; /// Pide la contraseña actual además de la nueva y su confirmación, a diferencia del /// restablecimiento por un administrador. @@ -36,10 +36,10 @@ impl Component for ChangePasswordForm { PasswordConfirm::new() .with_password_label(Lc::t("field-new-password", &LOCALES_USER)), ) - .with_child( - Button::submit(Lc::t("btn-set-password", &LOCALES_USER)) - .with_style(button::Style::Solid(Intent::Primary)), - ); + .with_child(profile_form_actions( + Lc::t("btn-set-password", &LOCALES_USER), + cx, + )); Ok(form.render(cx).await) } diff --git a/extensions/pagetop-user/src/handlers/account.rs b/extensions/pagetop-user/src/handlers/account.rs index 0057447c..e4010f6a 100644 --- a/extensions/pagetop-user/src/handlers/account.rs +++ b/extensions/pagetop-user/src/handlers/account.rs @@ -547,21 +547,15 @@ pub(crate) async fn email_confirm_post( // **< render_profile_page >************************************************************************ -// Página del perfil propio con un formulario y un botón para volver al perfil sin guardar. +// Página del perfil propio con un formulario. async fn render_profile_page( request: HttpRequest, title: Lc, form: impl Component + 'static, ) -> Response { - let page = Page::new(request); - let cancel = Button::anchor(Lc::t("btn-cancel", &LOCALES_USER), page.route(PROFILE_PATH)); - page.with_title(title.clone()) - .with_child( - Block::new() - .with_title(title) - .with_child(form) - .with_child(cancel), - ) + Page::new(request) + .with_title(title.clone()) + .with_child(Block::new().with_title(title).with_child(form)) .render() .await .into_response() diff --git a/extensions/pagetop-user/src/handlers/admin.rs b/extensions/pagetop-user/src/handlers/admin.rs index 32ef5d21..9e4abb33 100644 --- a/extensions/pagetop-user/src/handlers/admin.rs +++ b/extensions/pagetop-user/src/handlers/admin.rs @@ -59,14 +59,7 @@ pub(crate) fn map_auth_error(err: &AuthError) -> Lc { } } -// Enlace de vuelta al listado, usado en las pantallas de alta/edición/asignación. -pub(crate) fn back_link(href: impl Into) -> Html { - let href = href.into(); - Html::with(move |cx| { - html! { - p class="user-admin-back-link" { - a href=(href.clone()) { (Lc::t("link-back-to-list", &LOCALES_USER).using(cx)) } - } - } - }) +// Enlace para salir de una ficha de sólo lectura. Los formularios tienen `form_actions()`. +pub(crate) fn back_link(route: impl Into) -> Button { + Button::anchor(Lc::t("link-back", &LOCALES_USER), route).with_style(button::Style::Link) } diff --git a/extensions/pagetop-user/src/handlers/admin/roles.rs b/extensions/pagetop-user/src/handlers/admin/roles.rs index 0fb8c3d6..855f01cb 100644 --- a/extensions/pagetop-user/src/handlers/admin/roles.rs +++ b/extensions/pagetop-user/src/handlers/admin/roles.rs @@ -76,7 +76,6 @@ pub(crate) async fn new_get( web::Query(waypoint): web::Query, ) -> Result { let page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let title = Lc::t("title-admin-role-new", &LOCALES_USER); Ok(page .with_title(title) @@ -85,7 +84,6 @@ pub(crate) async fn new_get( .with_mode(RoleFormMode::New) .with_waypoint(waypoint), ) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -125,7 +123,6 @@ pub(crate) async fn new_post( } Err(err) => { let page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let form_component = RoleForm::new() .with_mode(RoleFormMode::New) .with_machine_name(form.machine_name) @@ -138,7 +135,6 @@ pub(crate) async fn new_post( Ok(page .with_title(title) .with_child(form_component) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -163,7 +159,6 @@ pub(crate) async fn edit_get( } let page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let title = Lc::t("title-admin-role-edit", &LOCALES_USER); Ok(page @@ -178,7 +173,6 @@ pub(crate) async fn edit_get( .with_weight(role.weight) .with_waypoint(waypoint), ) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -224,7 +218,6 @@ pub(crate) async fn edit_post( .map(|role| role.machine_name) .unwrap_or_default(); let page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let form_component = RoleForm::new() .with_mode(RoleFormMode::Edit) .with_role_id(Some(id)) @@ -238,7 +231,6 @@ pub(crate) async fn edit_post( Ok(page .with_title(title) .with_child(form_component) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -481,7 +473,6 @@ pub(crate) async fn permissions_get( let page = Page::admin(request); let groups = build_permission_groups(&selected, page.context()); - let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let title = Lc::t("title-admin-role-permissions", &LOCALES_USER); Ok(page @@ -492,7 +483,6 @@ pub(crate) async fn permissions_get( .with_groups(groups) .with_waypoint(waypoint), ) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -530,7 +520,6 @@ pub(crate) async fn permissions_post( let page = Page::admin(request); let groups = build_permission_groups(&form.permission_keys, page.context()); - let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let form_component = RolePermissionsForm::new() .with_role_id(id) .with_groups(groups) @@ -540,7 +529,6 @@ pub(crate) async fn permissions_post( Ok(page .with_title(title) .with_child(form_component) - .with_child(back_link(back_href)) .render() .await .into_response()) diff --git a/extensions/pagetop-user/src/handlers/admin/users.rs b/extensions/pagetop-user/src/handlers/admin/users.rs index bd0ae2c1..02d97d92 100644 --- a/extensions/pagetop-user/src/handlers/admin/users.rs +++ b/extensions/pagetop-user/src/handlers/admin/users.rs @@ -11,7 +11,7 @@ use crate::account::{Account, UserStatus}; use crate::component::admin::{ AdminPasswordForm, USER_ADMIN_FORM_ID, UserForm, UserFormMode, UserTable, }; -use crate::component::user_details; +use crate::component::{cancel_link, user_details}; use crate::config::SETTINGS; use crate::entity::{role, user}; use crate::error::AuthError; @@ -70,9 +70,11 @@ pub(crate) async fn list_get( Ok(HtmxResponse::new(table.render(&mut cx).await).into_response()) } else { let title = Lc::t("title-admin-users", &LOCALES_USER); - Ok(Page::admin(request) + let page = Page::admin(request); + let search = search_bar(page.route(ADMIN_USERS_PATH.as_str()), query.q); + Ok(page .with_title(title) - .with_child(search_bar(query.q)) + .with_child(search) .with_child(table) .render() .await @@ -82,25 +84,24 @@ pub(crate) async fn list_get( // **< search_bar >********************************************************************************* -fn search_bar(current_query: Option) -> Html { - let value = current_query.unwrap_or_default(); - Html::with(move |cx| { - html! { - div class="user-admin-search" { - input - type="search" - id="user-admin-search-input" - name="q" - value=(value.as_str()) - placeholder=[Lc::t("field-search-users", &LOCALES_USER).lookup(cx)] - hx-get=(cx.route(ADMIN_USERS_PATH.as_str()).to_string()) - hx-trigger="keyup changed delay:400ms, search" - hx-target="#user-table-wrapper" - hx-swap=(hx::swap::OUTER_HTML_SCROLL_TOP) - hx-push-url="true"; - } - } - }) +// Los atributos HTMX van en el formulario porque `with_prop()` de un campo los pondría en su +// contenedor, que no enviaría el valor. `input` cubre también vaciar con la "x" del navegador. +fn search_bar(route: RoutePath, current_query: Option) -> Form { + Form::new() + .with_action(route.clone()) + .with_method(form::Method::Get) + .with_prop(PropsOp::set(hx::GET, route.to_string())) + .with_prop(PropsOp::set(hx::TRIGGER, "input delay:400ms, submit")) + .with_prop(PropsOp::set(hx::TARGET, "#user-table-wrapper")) + .with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP)) + .with_prop(PropsOp::set(hx::PUSH_URL, "true")) + .with_child( + form::input::Field::search() + .with_id("user-admin-search") + .with_name("q") + .with_value(current_query.unwrap_or_default()) + .with_placeholder(Lc::t("field-search-users", &LOCALES_USER)), + ) } // **< available_roles >**************************************************************************** @@ -158,7 +159,6 @@ pub(crate) async fn new_get( // permiso del catálogo (igual que conceder/revocar en la edición, ver `set_user_admin`). let allow_admin_field = request.extension::().is_some_and(|a| a.is_admin()); let page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str())); let title = Lc::t("title-admin-user-new", &LOCALES_USER); Ok(page .with_title(title) @@ -169,7 +169,6 @@ pub(crate) async fn new_get( .with_allow_admin_field(allow_admin_field) .with_waypoint(waypoint), ) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -236,7 +235,6 @@ pub(crate) async fn new_post( Err(err) => { let roles = available_roles(&role_ids).await.unwrap_or_default(); let page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str())); let form_component = UserForm::new() .with_mode(UserFormMode::New) .with_username(form.username) @@ -254,7 +252,6 @@ pub(crate) async fn new_post( Ok(page .with_title(title) .with_child(form_component) - .with_child(back_link(back_href)) .render() .await .into_response()) @@ -318,7 +315,6 @@ async fn render_edit_page( // Bloquear y activar exige además `user:block_accounts` (ver `status_post`). let can_change_status = has_permission(&request, &UserPermission::BlockAccounts); let mut page = Page::admin(request); - let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str())); let title = Lc::t("title-admin-user-edit", &LOCALES_USER); let actions = edit_actions( id, @@ -337,25 +333,22 @@ async fn render_edit_page( .with_waypoint(waypoint.clone()), ) .with_child(actions) - .with_child(back_link(back_href)) .render() .await .into_response() } -// Enlace a la pantalla de restablecer contraseña y botones de bloqueo/activación (sólo si -// `can_change_status`) y de concesión/revocación de acceso irrestricto (sólo si -// `can_toggle_admin`). El listado -// de origen (`waypoint`) se arrastra a todas ellas para que, al volver aquí, esta misma pantalla -// siga sabiendo devolver al listado en el estado en que se dejó. +// Botonera de la edición: "Guardar", "Cancelar", el enlace a la pantalla de restablecer contraseña +// y los botones de bloqueo/activación (sólo si `can_change_status`) y de concesión/revocación de +// acceso irrestricto (sólo si `can_toggle_admin`). El listado de origen (`waypoint`) se arrastra a +// todas ellas para que, al volver aquí, esta misma pantalla siga sabiendo devolver al listado en el +// estado en que se dejó. // -// "Guardar" (envía el `` de `UserForm` vía el atributo `form`, ver `USER_ADMIN_FORM_ID`) y -// "Restablecer contraseña" son botones sueltos; bloqueo/activación y concesión/revocación de admin -// (este último sólo si `can_toggle_admin`) van cada uno en su propio `Form`, con un campo `Hidden` -// para el nuevo valor, para conservar el envío nativo sin JavaScript, mejorado con -// `hx-post`/`hx-confirm`. Todos son hijos directos del mismo `Container` con Flex, que los alinea -// en fila con espaciado uniforme sin que ninguno tenga que ser forzosamente un `Button` suelto (ver -// PAGETOP.md, "Preferir componentes a `html!` en bruto"). +// "Guardar" (envía el `` de `UserForm` vía el atributo `form`, ver `USER_ADMIN_FORM_ID`), +// "Cancelar" y "Restablecer contraseña" son botones sueltos; bloqueo/activación y +// concesión/revocación de admin van cada uno en su propio `Form`, con un campo `Hidden` para el +// nuevo valor, para conservar el envío nativo sin JavaScript, mejorado con `hx-post`/`hx-confirm`. +// Todos son hijos directos del mismo `Flex`, que los alinea en fila con espaciado uniforme. fn edit_actions( user_id: i32, status: UserStatus, @@ -403,6 +396,9 @@ fn edit_actions( .with_style(button::Style::Solid(Intent::Primary)) .with_prop(PropsOp::set("form", USER_ADMIN_FORM_ID)), ) + .with_child(cancel_link( + waypoint.or(cx.route(ADMIN_USERS_PATH.as_str())), + )) .with_child( Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href) .with_style(button::Style::Solid(Intent::Neutral)), @@ -709,7 +705,6 @@ pub(crate) async fn password_get( ) -> Result { let user = require_manageable(&request, id).await?; let page = Page::admin(request); - let edit_href = waypoint.append_to(page.route(user_path(id, "edit"))); let title = Lc::t("title-admin-user-password", &LOCALES_USER); Ok(page .with_title(title) @@ -719,7 +714,6 @@ pub(crate) async fn password_get( .with_user_id(id) .with_waypoint(waypoint), ) - .with_child(back_link(edit_href)) .render() .await .into_response()) @@ -755,7 +749,6 @@ pub(crate) async fn password_post( } Err(err) => { let page = Page::admin(request); - let edit_href = waypoint.append_to(page.route(user_path(id, "edit"))); let title = Lc::t("title-admin-user-password", &LOCALES_USER); Ok(page .with_title(title) @@ -766,7 +759,6 @@ pub(crate) async fn password_post( .with_error(map_auth_error(&err)) .with_waypoint(waypoint), ) - .with_child(back_link(edit_href)) .render() .await .into_response()) diff --git a/extensions/pagetop-user/src/locale/en-US/common.ftl b/extensions/pagetop-user/src/locale/en-US/common.ftl index 290079fa..8119c062 100644 --- a/extensions/pagetop-user/src/locale/en-US/common.ftl +++ b/extensions/pagetop-user/src/locale/en-US/common.ftl @@ -247,7 +247,7 @@ btn-block = Block btn-activate = Activate btn-grant-admin = Grant administrator btn-revoke-admin = Revoke administrator -link-back-to-list = Back to list +link-back = Back # **< Admin: confirmations and badges >** diff --git a/extensions/pagetop-user/src/locale/es-ES/common.ftl b/extensions/pagetop-user/src/locale/es-ES/common.ftl index 4b19242b..9c2b5a61 100644 --- a/extensions/pagetop-user/src/locale/es-ES/common.ftl +++ b/extensions/pagetop-user/src/locale/es-ES/common.ftl @@ -248,7 +248,7 @@ btn-block = Bloquear btn-activate = Activar btn-grant-admin = Conceder administrador btn-revoke-admin = Revocar administrador -link-back-to-list = Volver al listado +link-back = Volver # **< Administración: confirmaciones y distintivos >** From 7e7720bd493e00aafcf29910ee3fc9ccd6fe18c6 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Tue, 10 Nov 2026 22:02:25 +0100 Subject: [PATCH 05/11] =?UTF-8?q?=F0=9F=92=84=20(bootsier):=20Centra=20ver?= =?UTF-8?q?ticalmente=20celdas=20de=20tablas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/pagetop-bootsier/assets/_bootsier-variables.scss | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/extensions/pagetop-bootsier/assets/_bootsier-variables.scss b/extensions/pagetop-bootsier/assets/_bootsier-variables.scss index c67cbfee..61eb6a25 100644 --- a/extensions/pagetop-bootsier/assets/_bootsier-variables.scss +++ b/extensions/pagetop-bootsier/assets/_bootsier-variables.scss @@ -9,3 +9,8 @@ $navbar-brand-font-size: 1.75rem; $font-family-sans-serif: "Source Sans 3", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + +// Table cells centered vertically, as in the Basic theme: with Bootstrap's default (top), a cell +// holding a button is taller and the text of the other cells sticks to the top of the row. Header +// cells keep Bootstrap's bottom alignment. +$table-cell-vertical-align: middle; From 0f71eba7ab9978170e740a74afb9ad5962b62b48 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Tue, 10 Nov 2026 22:02:50 +0100 Subject: [PATCH 06/11] =?UTF-8?q?=F0=9F=93=9D=20Acorta=20la=20descripci?= =?UTF-8?q?=C3=B3n=20de=20AdminFrame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/component/admin_frame.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/base/component/admin_frame.rs b/src/base/component/admin_frame.rs index e77c66f1..cd9db2a5 100644 --- a/src/base/component/admin_frame.rs +++ b/src/base/component/admin_frame.rs @@ -1,7 +1,6 @@ use crate::prelude::*; -/// Marco de una página del panel de administración, alrededor de la región -/// [`CoreRegions::Content`]. +/// Marco de las páginas de administración, alrededor de [`CoreRegions::Content`]. /// /// Pinta, para la ruta de la petición actual, las migas de pan del panel, el título de la página /// ([`Contextual::title()`]) con sus botones de acción ([`AdminAction`]), las pestañas de la From d8493291e430332f12c06402ea99f440866cd831 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Tue, 10 Nov 2026 22:49:40 +0100 Subject: [PATCH 07/11] =?UTF-8?q?=E2=9C=A8=20(base)=20A=C3=B1ade=20ListVie?= =?UTF-8?q?w=20y=20ListFilter=20para=20listados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ListView: botones, mensajes, tabla y paginador en orden fijo; anuncia el número de resultados a los lectores de pantalla. - ListFilter: filtros en fila con "Filtrar" y "Limpiar", envío automático opcional y marcas de cambios sin aplicar. - pagetop-htmx: hx_pager::boost() y hx_filter::boost(); cancelan las peticiones solapadas y atenúan el listado mientras carga, con estilos sólo en las páginas con listado. - Usuarios y roles migrados al nuevo patrón. --- assets/js/list-filter.js | 114 +++++++++ assets/js/list-view.js | 52 ++++ assets/scss/basic.scss | 2 + assets/scss/basic/_list-filter.scss | 59 +++++ assets/scss/basic/_list-view.scss | 8 + assets/scss/basic/_user.scss | 4 - build.rs | 6 + .../assets/_bootsier-custom.scss | 62 +++++ extensions/pagetop-htmx/README.md | 4 +- extensions/pagetop-htmx/src/hx_filter.rs | 51 ++++ extensions/pagetop-htmx/src/hx_pager.rs | 62 +++-- extensions/pagetop-htmx/src/hx_table.rs | 14 +- extensions/pagetop-htmx/src/lib.rs | 32 ++- extensions/pagetop-htmx/tests/extension.rs | 30 ++- extensions/pagetop-htmx/tests/hx_list.rs | 100 ++++++++ extensions/pagetop-htmx/tests/hx_table.rs | 2 +- .../pagetop-user/src/component/admin.rs | 2 +- .../src/component/admin/role_table.rs | 86 +++---- .../src/component/admin/user_table.rs | 46 +--- .../pagetop-user/src/handlers/admin/roles.rs | 5 +- .../pagetop-user/src/handlers/admin/users.rs | 39 ++- src/base/component.rs | 6 + src/base/component/list_filter.rs | 236 ++++++++++++++++++ src/base/component/list_view.rs | 150 +++++++++++ src/locale/en-US/base.ftl | 12 + src/locale/es-ES/base.ftl | 12 + tests/component_list_filter.rs | 126 ++++++++++ tests/component_list_view.rs | 86 +++++++ 28 files changed, 1264 insertions(+), 144 deletions(-) create mode 100644 assets/js/list-filter.js create mode 100644 assets/js/list-view.js create mode 100644 assets/scss/basic/_list-filter.scss create mode 100644 assets/scss/basic/_list-view.scss create mode 100644 extensions/pagetop-htmx/src/hx_filter.rs create mode 100644 extensions/pagetop-htmx/tests/hx_list.rs create mode 100644 src/base/component/list_filter.rs create mode 100644 src/base/component/list_view.rs create mode 100644 tests/component_list_filter.rs create mode 100644 tests/component_list_view.rs diff --git a/assets/js/list-filter.js b/assets/js/list-filter.js new file mode 100644 index 00000000..cb6a0154 --- /dev/null +++ b/assets/js/list-filter.js @@ -0,0 +1,114 @@ +// Señala en los filtros de listado (`ListFilter`) que se aplican con botón los campos cuyo valor ya +// no coincide con el del filtro aplicado, para que el usuario sepa que el listado todavía no +// corresponde a lo que muestra el formulario. Sólo pone y quita clases (`list-filter-changed` en el +// contenedor de cada campo, `list-filter-pending` en el formulario) y el texto del aviso para +// lectores de pantalla; el aspecto lo da cada tema. Sin dependencias. +// +// Actúa sólo en los formularios con el aviso `.list-filter-status`, que `ListFilter` no pinta +// cuando los filtros se envían solos. + +(function () { + "use strict"; + + var FIELDS = + 'input:not([type="hidden"]):not([type="submit"])' + + ':not([type="button"]):not([type="reset"]), select, textarea'; + + // Opción que estaba elegida al aplicar el filtro. Un desplegable simple sin ninguna opción + // marcada en el HTML muestra la primera. + function wasSelected(select, option, index) { + if (option.defaultSelected) { + return true; + } + if (select.multiple) { + return false; + } + for (var i = 0; i < select.options.length; i++) { + if (select.options[i].defaultSelected) { + return false; + } + } + return index === 0; + } + + // Indica si el campo tiene un valor distinto del que tenía al aplicar el filtro. + function isChanged(field) { + if (field.type === "checkbox" || field.type === "radio") { + return field.checked !== field.defaultChecked; + } + if (field.tagName === "SELECT") { + for (var i = 0; i < field.options.length; i++) { + if (field.options[i].selected !== wasSelected(field, field.options[i], i)) { + return true; + } + } + return false; + } + return field.value !== field.defaultValue; + } + + // Toma los valores actuales como los del filtro aplicado. Hace falta cuando sólo se actualiza + // el listado y el formulario no se vuelve a pintar. + function commit(field) { + if (field.type === "checkbox" || field.type === "radio") { + field.defaultChecked = field.checked; + } else if (field.tagName === "SELECT") { + for (var i = 0; i < field.options.length; i++) { + field.options[i].defaultSelected = field.options[i].selected; + } + } else { + field.defaultValue = field.value; + } + } + + function refresh(form) { + var changed = []; + form.querySelectorAll(FIELDS).forEach(function (field) { + var container = field.closest(".form-field") || field; + if (changed.indexOf(container) === -1 && isChanged(field)) { + changed.push(container); + } + }); + form.querySelectorAll(".list-filter-changed").forEach(function (container) { + if (changed.indexOf(container) === -1) { + container.classList.remove("list-filter-changed"); + } + }); + changed.forEach(function (container) { + container.classList.add("list-filter-changed"); + }); + + var pending = changed.length > 0; + form.classList.toggle("list-filter-pending", pending); + // Sólo se cambia el texto al empezar o terminar los cambios pendientes, para que el lector + // de pantalla lo anuncie una vez y no con cada pulsación. + var status = form.querySelector(".list-filter-status"); + var text = pending ? status.getAttribute("data-pending") || "" : ""; + if (status.textContent !== text) { + status.textContent = text; + } + } + + function filterOf(element) { + var form = element instanceof Element ? element.closest("form.list-filter") : null; + return form && form.querySelector(".list-filter-status") ? form : null; + } + + function onChange(event) { + var form = filterOf(event.target); + if (form) { + refresh(form); + } + } + + document.addEventListener("input", onChange); + document.addEventListener("change", onChange); + + document.addEventListener("submit", function (event) { + var form = filterOf(event.target); + if (form) { + form.querySelectorAll(FIELDS).forEach(commit); + refresh(form); + } + }); +})(); diff --git a/assets/js/list-view.js b/assets/js/list-view.js new file mode 100644 index 00000000..b57647cd --- /dev/null +++ b/assets/js/list-view.js @@ -0,0 +1,52 @@ +// Anuncia a los lectores de pantalla el resumen de un listado (`ListView`, atributo +// `data-summary`, p. ej. "23 resultados") cuando se actualiza sin recargar la página, al filtrar, +// ordenar o cambiar de página. Un lector de pantalla no suele anunciar una zona `aria-live` que se +// inserta de golpe, así que el aviso usa una única zona creada al cargar la página, y el listado +// nuevo sólo le pasa su texto. Al cargar la página no anuncia nada. Sin dependencias: vale para +// HTMX o para cualquier otra forma de actualizar sólo una parte de la página. + +(function () { + "use strict"; + + var SELECTOR = ".list-view[data-summary]"; + var REGION_ID = "list-view-status"; + + // La zona se busca por su identificador cada vez: si se restaura una página del historial + // sustituyendo el contenido del `` (como hace HTMX al volver atrás), la zona creada al + // cargar desaparece y queda la copia restaurada. + function region() { + var element = document.getElementById(REGION_ID); + if (!element) { + element = document.createElement("div"); + element.id = REGION_ID; + element.className = "visually-hidden"; + element.setAttribute("role", "status"); + document.body.appendChild(element); + } + return element; + } + region(); + + function announce(text) { + var element = region(); + // Se vacía primero para que se anuncie también un texto igual al anterior. + element.textContent = ""; + setTimeout(function () { + element.textContent = text; + }, 50); + } + + new MutationObserver(function (mutations) { + mutations.forEach(function (mutation) { + mutation.addedNodes.forEach(function (node) { + if (!(node instanceof Element)) { + return; + } + var list = node.matches(SELECTOR) ? node : node.querySelector(SELECTOR); + if (list) { + announce(list.getAttribute("data-summary")); + } + }); + }); + }).observe(document.body, { childList: true, subtree: true }); +})(); diff --git a/assets/scss/basic.scss b/assets/scss/basic.scss index 7b7c7d6c..70110aa6 100644 --- a/assets/scss/basic.scss +++ b/assets/scss/basic.scss @@ -25,6 +25,8 @@ @use "basic/dropdown"; @use "basic/form"; @use "basic/image"; +@use "basic/list-filter"; +@use "basic/list-view"; @use "basic/messages"; @use "basic/nav"; @use "basic/navbar"; diff --git a/assets/scss/basic/_list-filter.scss b/assets/scss/basic/_list-filter.scss new file mode 100644 index 00000000..90ad095f --- /dev/null +++ b/assets/scss/basic/_list-filter.scss @@ -0,0 +1,59 @@ +// List filters (ListFilter): fields and button on one row, wrapping when there is no room. +.list-filter { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 0.5rem 1rem; + margin-bottom: 1rem; +} + +.list-filter > .form-field { + margin-bottom: 0; +} + +// Marks of changed filters not applied yet (filters with a button), set by `list-filter.js`. Only +// colors and opacity change, never sizes: the dot always takes its room, hidden, so nothing moves +// when it shows up. A vivid orange, set apart from the primary color of the button, darkened just +// enough to keep a 3:1 contrast against the background. Every changed field gets the dot by its +// label, once per field (on the title of a group); text fields and dropdowns also show a gray +// background. +.list-filter { + --list-filter-mark: color-mix(in srgb, #fd7e14 85%, black); +} + +.list-filter .form-field > .form-label::after, +.list-filter .form-field.form-check > .form-check-label::after { + content: "\25CF" / ""; + margin-left: 0.25em; + color: var(--list-filter-mark); + opacity: 0; +} + +.list-filter .list-filter-changed > .form-label::after, +.list-filter .list-filter-changed.form-check > .form-check-label::after { + opacity: 1; +} + +.list-filter .list-filter-changed .form-control, +.list-filter .list-filter-changed .form-select { + background-color: color-mix(in srgb, var(--val-color--bg--muted) 60%, #fff); +} + +// Native checkboxes only take a color when checked; a switch is drawn by the theme. +.list-filter .list-filter-changed .form-check-input { + accent-color: var(--list-filter-mark); +} + +.list-filter .list-filter-changed.form-switch .form-check-input:checked { + background-color: var(--list-filter-mark); +} + +.list-filter-pending > button[type="submit"] { + background-color: var(--val-color--primary); + border-color: var(--val-color--primary); +} + +.list-filter-pending > button[type="submit"]:hover { + background-color: color-mix(in srgb, var(--val-color--primary) 85%, black); + border-color: color-mix(in srgb, var(--val-color--primary) 85%, black); +} diff --git a/assets/scss/basic/_list-view.scss b/assets/scss/basic/_list-view.scss new file mode 100644 index 00000000..62857711 --- /dev/null +++ b/assets/scss/basic/_list-view.scss @@ -0,0 +1,8 @@ +// List view (ListView): action buttons above the table, then messages, table and pager. +.list-view { + margin: 1.5rem 0; +} + +.list-view-actions { + margin-bottom: 1rem; +} diff --git a/assets/scss/basic/_user.scss b/assets/scss/basic/_user.scss index 498c8262..59f142d5 100644 --- a/assets/scss/basic/_user.scss +++ b/assets/scss/basic/_user.scss @@ -30,10 +30,6 @@ margin-top: 1.5rem; } -.user-admin-table-wrapper { - margin: 1.5rem 0; -} - .user-form-error { padding: 0.625rem 0.875rem; margin-bottom: 1rem; diff --git a/build.rs b/build.rs index 0dcf973d..29bb6c5c 100644 --- a/build.rs +++ b/build.rs @@ -23,6 +23,12 @@ fn main() -> std::io::Result<()> { "static/js/basic.dialog.min.js", )?; + // JS: minifica el aviso del resumen de `ListView` a los lectores de pantalla. + minify_js("assets/js/list-view.js", "static/js/list-view.min.js")?; + + // JS: minifica las marcas de cambios sin aplicar de `ListFilter`, independientes del tema. + minify_js("assets/js/list-filter.js", "static/js/list-filter.min.js")?; + // JS: minifica la integración de `Dropdown` con `accessible-menu` del tema Basic. minify_js( "assets/js/basic.dropdown.init.js", diff --git a/extensions/pagetop-bootsier/assets/_bootsier-custom.scss b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss index 7429effe..6454a103 100644 --- a/extensions/pagetop-bootsier/assets/_bootsier-custom.scss +++ b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss @@ -133,6 +133,68 @@ fieldset > legend { opacity: 1; } +// List filters (ListFilter): fields and button on one row, wrapping when there is no room. +.list-filter { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: ($spacer * .5) $spacer; + margin-bottom: $spacer; + + > .form-field { + margin-bottom: 0; + } +} + +// Marks of changed filters not applied yet (filters with a button), set by `list-filter.js`. Only +// colors and opacity change, never sizes: the dot always takes its room, hidden, so nothing moves +// when it shows up. A vivid orange, set apart from the primary color of the button, darkened just +// enough to keep a 3:1 contrast against the background. Every changed field gets the dot by its +// label, once per field (on the title of a group); text fields and dropdowns also show a gray +// background. Floating labels are left out: Bootstrap draws their background with `::after`. +.list-filter { + --list-filter-mark: #{mix(#000, $orange, 15%)}; +} + +.list-filter .form-field:not(.form-floating) > .form-label::after, +.list-filter .form-field.form-check > .form-check-label::after { + content: "\25CF" / ""; + margin-left: .25em; + color: var(--list-filter-mark); + opacity: 0; +} + +.list-filter .list-filter-changed { + &:not(.form-floating) > .form-label::after, + &.form-check > .form-check-label::after { + opacity: 1; + } + + .form-control, + .form-select, + .form-check-input { + background-color: var(--bs-secondary-bg); + } + + .form-check-input:checked { + background-color: var(--list-filter-mark); + border-color: var(--list-filter-mark); + } +} + +.list-filter-pending > .btn-secondary[type="submit"] { + @extend .btn-primary; +} + +// List view (ListView): action buttons above the table. +.list-view { + margin-block: $spacer * 1.5; +} + +.list-view-actions { + margin-bottom: $spacer; +} + // Pager component. // `.pagination`, `.page-item`, `.page-link`, `.active` and `.disabled` already come styled by // Bootstrap, since Pager reuses that same markup (the ellipsis is a disabled `.page-link` span, diff --git a/extensions/pagetop-htmx/README.md b/extensions/pagetop-htmx/README.md index 6fbc8144..97110fc0 100644 --- a/extensions/pagetop-htmx/README.md +++ b/extensions/pagetop-htmx/README.md @@ -47,7 +47,9 @@ impl Extension for MyApp { ``` A partir de ese momento, todas las páginas de la aplicación incluirán automáticamente el script de -HTMX 2. Puedes usar los atributos `hx-*` directamente en tus componentes o el código HTML generado: +HTMX 2, y las que tengan algún listado (`ListView`), unos pocos estilos que lo atenúan mientras +se actualiza. Puedes usar los atributos `hx-*` directamente en tus componentes o el código HTML +generado: ```rust use pagetop::prelude::*; diff --git a/extensions/pagetop-htmx/src/hx_filter.rs b/extensions/pagetop-htmx/src/hx_filter.rs new file mode 100644 index 00000000..47695317 --- /dev/null +++ b/extensions/pagetop-htmx/src/hx_filter.rs @@ -0,0 +1,51 @@ +//! Soporte HTMX al componente [`ListFilter`]. +//! +//! [`ListFilter`] es un formulario GET que funciona sin JavaScript: al aplicarlo, el navegador pide +//! de nuevo la página con los filtros aplicados. [`boost()`] hace que sólo se actualice el listado, +//! tanto al pulsar su botón como, con [`ListFilter::with_auto_submit()`], al cambiar un campo. + +use pagetop::prelude::*; + +use crate::hx; + +/// Hace que, al aplicar `filter`, se actualice sólo el elemento `target` (un selector CSS, p. ej. +/// `"#user-list"`), sin recargar la página. +/// +/// Añade al formulario `hx::BOOST` (envía sus campos a su propia ruta), `hx::TARGET`, `hx::SWAP` +/// (reemplaza el elemento entero y sube al principio) y `hx::PUSH_URL`, para que la dirección del +/// navegador refleje los filtros aplicados. No cambia cuándo se aplican: al pulsar el botón o, con +/// [`ListFilter::with_auto_submit()`], al cambiar un campo. Sin JavaScript, el filtro recarga la +/// página como cualquier formulario. +/// +/// Para que las peticiones no se pisen, una nueva petición contra `target` (desde los filtros, el +/// paginador o una cabecera) cancela la que estuviera en curso (`hx::SYNC`). Y mientras llega la +/// respuesta, `target` recibe la clase `htmx-request` (`hx::INDICATOR`), con la que la extensión +/// atenúa el listado ([`ListView`]). +/// +/// La ruta del filtro debe responder a las peticiones HTMX con el elemento `target` ya filtrado, +/// normalmente el [`ListView`] del listado. +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// use pagetop_htmx::prelude::*; +/// +/// let filter = hx_filter::boost( +/// ListFilter::new() +/// .with_filter_action("/admin/users") +/// .with_field(form::input::Field::search().with_name("q")), +/// "#user-list", +/// ); +/// ``` +pub fn boost(filter: ListFilter, target: impl Into) -> ListFilter { + let target: CowStr = target.into(); + filter + .with_prop(PropsOp::set(hx::BOOST, "true")) + .with_prop(PropsOp::set( + hx::SYNC, + util::join!(target.as_ref(), ":replace"), + )) + .with_prop(PropsOp::set(hx::INDICATOR, target.clone())) + .with_prop(PropsOp::set(hx::TARGET, target)) + .with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP)) + .with_prop(PropsOp::set(hx::PUSH_URL, "true")) +} diff --git a/extensions/pagetop-htmx/src/hx_pager.rs b/extensions/pagetop-htmx/src/hx_pager.rs index 7a126d17..ed5154d8 100644 --- a/extensions/pagetop-htmx/src/hx_pager.rs +++ b/extensions/pagetop-htmx/src/hx_pager.rs @@ -8,25 +8,53 @@ //! Para una navegación sin recarga basta con añadir `hx::BOOST` (más `hx::TARGET` y `hx::SWAP`) al //! propio `