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/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/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/_form.scss b/assets/scss/basic/_form.scss index 7d8550cf..6fdc3d7e 100644 --- a/assets/scss/basic/_form.scss +++ b/assets/scss/basic/_form.scss @@ -9,7 +9,9 @@ } .form-text { - font-size: 0.9375rem; + font-size: 0.875rem; + font-style: italic; + line-height: 1.3; color: var(--val-color--text--muted); } @@ -33,23 +35,37 @@ fieldset > legend { } .form-check { - display: flex; + display: grid; + grid-template-columns: auto 1fr; align-items: center; - gap: 0.5rem; + gap: 0.25rem 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-flex; + display: inline-grid; margin-right: 1rem; } .form-check-reverse { - flex-direction: row-reverse; - justify-content: flex-start; + grid-template-columns: 1fr auto; 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 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/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/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-bootsier/assets/_bootsier-custom.scss b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss index 7429effe..ed317b38 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, @@ -296,3 +358,41 @@ 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 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; 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-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-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