diff --git a/Cargo.lock b/Cargo.lock index 67b1a195..24ba63ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2174,6 +2174,7 @@ dependencies = [ "pagetop-macros", "pagetop-minimal", "pagetop-statics", + "parking_lot", "serde", "serde_json", "serde_qs", diff --git a/Cargo.toml b/Cargo.toml index b5b3d83a..b99f525d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ 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" @@ -130,6 +131,7 @@ 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/assets/js/list-filter.js b/assets/js/list-filter.js deleted file mode 100644 index cb6a0154..00000000 --- a/assets/js/list-filter.js +++ /dev/null @@ -1,114 +0,0 @@ -// 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 deleted file mode 100644 index b57647cd..00000000 --- a/assets/js/list-view.js +++ /dev/null @@ -1,52 +0,0 @@ -// 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 70110aa6..7b7c7d6c 100644 --- a/assets/scss/basic.scss +++ b/assets/scss/basic.scss @@ -25,8 +25,6 @@ @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/_form.scss b/assets/scss/basic/_form.scss index 6fdc3d7e..7d8550cf 100644 --- a/assets/scss/basic/_form.scss +++ b/assets/scss/basic/_form.scss @@ -9,9 +9,7 @@ } .form-text { - font-size: 0.875rem; - font-style: italic; - line-height: 1.3; + font-size: 0.9375rem; color: var(--val-color--text--muted); } @@ -35,37 +33,23 @@ fieldset > legend { } .form-check { - display: grid; - grid-template-columns: auto 1fr; + display: flex; align-items: center; - gap: 0.25rem 0.5rem; + gap: 0.5rem; min-height: 1.5rem; margin-bottom: 0.25rem; } -// A single checkbox has no label above it to give it room, as the other fields do. -.form-field.form-check:not(.form-check-inline) { - margin-top: 1em; -} .form-check-inline { - display: inline-grid; + display: inline-flex; margin-right: 1rem; } .form-check-reverse { - grid-template-columns: 1fr auto; + flex-direction: row-reverse; + justify-content: flex-start; text-align: right; } -.form-check-reverse > .form-check-input { - grid-column: 2; - grid-row: 1; -} -// Help text goes below the label, aligned with it. -.form-check > .form-text { - grid-column: 2; -} -.form-check-reverse > .form-text { - grid-column: 1; -} .form-check-input { + flex-shrink: 0; cursor: pointer; } .form-check-label { diff --git a/assets/scss/basic/_list-filter.scss b/assets/scss/basic/_list-filter.scss deleted file mode 100644 index 90ad095f..00000000 --- a/assets/scss/basic/_list-filter.scss +++ /dev/null @@ -1,59 +0,0 @@ -// 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 deleted file mode 100644 index 62857711..00000000 --- a/assets/scss/basic/_list-view.scss +++ /dev/null @@ -1,8 +0,0 @@ -// 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 59f142d5..498c8262 100644 --- a/assets/scss/basic/_user.scss +++ b/assets/scss/basic/_user.scss @@ -30,6 +30,10 @@ 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 29bb6c5c..0dcf973d 100644 --- a/build.rs +++ b/build.rs @@ -23,12 +23,6 @@ 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/config/reference.toml b/config/reference.toml index 83c2b9ff..189ebf6b 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 = true # Muestra al arrancar un banner ASCII con el nombre de la - # aplicación (true) o no (false). +startup_banner = "Slant" # Banner ASCII al arrancar: "Off", "Slant", "Small", "Speed" + # o "Starwars". [dev] pagetop_static_dir = "" # Directorio static/ de PageTop para servir sus archivos diff --git a/extensions/pagetop-admin/src/handlers.rs b/extensions/pagetop-admin/src/handlers.rs index 10a2ae2b..ec57cf97 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(request.clone()); + let not_found = || ErrorPage::NotFound(Some(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-bootsier/assets/_bootsier-custom.scss b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss index ed317b38..7429effe 100644 --- a/extensions/pagetop-bootsier/assets/_bootsier-custom.scss +++ b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss @@ -133,68 +133,6 @@ 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, @@ -358,41 +296,3 @@ fieldset > legend { border-bottom-color: var(--bs-primary); font-weight: 600; } - -// Login page (pagetop-user `LoginForm`): the form inside a centered card, as in Bootstrap's sign-in -// example. The submit button takes the full width of the card. -.user-login-page { - display: flex; - align-items: center; - justify-content: center; - min-height: 70vh; - padding: $spacer * 2 $spacer; - background-color: var(--bs-tertiary-bg); -} - -.user-login-card { - width: 100%; - max-width: 24rem; - padding: $spacer * 2; - background-color: var(--bs-body-bg); - border: var(--bs-border-width) solid var(--bs-border-color-translucent); - border-radius: var(--bs-border-radius-lg); - box-shadow: var(--bs-box-shadow); -} - -.user-login-card .btn[type="submit"] { - width: 100%; - margin-top: $spacer * .5; -} - -.user-register-link, -.user-reset-link { - margin: $spacer 0 0; - text-align: center; -} - -// Form errors of pagetop-user, with the palette of Bootstrap's own alerts. -.user-form-error { - @extend .alert; - @extend .alert-danger; -} diff --git a/extensions/pagetop-bootsier/assets/_bootsier-variables.scss b/extensions/pagetop-bootsier/assets/_bootsier-variables.scss index 61eb6a25..c67cbfee 100644 --- a/extensions/pagetop-bootsier/assets/_bootsier-variables.scss +++ b/extensions/pagetop-bootsier/assets/_bootsier-variables.scss @@ -9,8 +9,3 @@ $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; diff --git a/extensions/pagetop-cron/src/lib.rs b/extensions/pagetop-cron/src/lib.rs index 66a76d89..bf33960a 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(request).into_response(); + return ErrorPage::NotFound(Some(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(request) + ErrorPage::NotFound(Some(request)) } diff --git a/extensions/pagetop-cron/src/scheduler.rs b/extensions/pagetop-cron/src/scheduler.rs index 3eb27c0f..772e408b 100644 --- a/extensions/pagetop-cron/src/scheduler.rs +++ b/extensions/pagetop-cron/src/scheduler.rs @@ -282,9 +282,8 @@ impl Entry { } } - // 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. + // 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. fn state(&self) -> MutexGuard<'_, State> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } diff --git a/extensions/pagetop-htmx/README.md b/extensions/pagetop-htmx/README.md index 97110fc0..6fbc8144 100644 --- a/extensions/pagetop-htmx/README.md +++ b/extensions/pagetop-htmx/README.md @@ -47,9 +47,7 @@ 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, 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: +HTMX 2. 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 deleted file mode 100644 index 47695317..00000000 --- a/extensions/pagetop-htmx/src/hx_filter.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! 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