From d8493291e430332f12c06402ea99f440866cd831 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Tue, 10 Nov 2026 22:49:40 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20(base)=20A=C3=B1ade=20ListView=20y?= =?UTF-8?q?=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 `