✨ (base) Añade ListView y ListFilter para listados

- 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.
This commit is contained in:
Manuel Cillero 2026-11-10 22:49:40 +01:00
parent 0f71eba7ab
commit d8493291e4
28 changed files with 1264 additions and 144 deletions

114
assets/js/list-filter.js Normal file
View file

@ -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);
}
});
})();

52
assets/js/list-view.js Normal file
View file

@ -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 `<body>` (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 });
})();

View file

@ -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";

View file

@ -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);
}

View file

@ -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;
}

View file

@ -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;

View file

@ -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",

View file

@ -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,

View file

@ -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::*;

View file

@ -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<CowStr>) -> 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"))
}

View file

@ -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 `<nav>`. HTMX convierte automáticamente en peticiones AJAX los enlaces de todas las
//! páginas, reutilizando el `href` que cada uno ya tiene resuelto, sin que [`Pager`] tenga que
//! generar ningún atributo `hx-*` por sí misma.
//!
//! ```rust,no_run
//! use pagetop::prelude::*;
//! use pagetop_htmx::prelude::*;
//!
//! let pager = Pager::new()
//! .with_base_path("/admin/users")
//! .with_extra_query("sort", "username")
//! .with_current_page(2)
//! .with_items_per_page(20)
//! .with_total_items(97)
//! .with_prop(PropsOp::set(hx::BOOST, "true"))
//! .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"));
//! ```
//! generar ningún atributo `hx-*` por sí misma. [`boost()`] los añade todos de una vez.
//!
//! [`Pager`]: pagetop::base::component::Pager
//! [`Props`]: pagetop::html::Props
//! [`PropsOp::set()`]: pagetop::html::PropsOp::set
//! [`with_prop()`]: pagetop::base::component::Pager::with_prop
use pagetop::prelude::*;
use crate::hx;
/// Hace que los enlaces de `pager` reemplacen sólo el elemento `target` (un selector CSS, p. ej.
/// `"#user-list"`), sin recargar la página.
///
/// Añade al `<nav>` del paginador `hx::BOOST`, `hx::TARGET`, `hx::SWAP` (reemplaza el elemento
/// entero y sube al principio) y `hx::PUSH_URL`, para que la dirección del navegador refleje la
/// página mostrada. Sin JavaScript, los enlaces siguen funcionando como peticiones normales.
///
/// 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`]).
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_htmx::prelude::*;
///
/// let pager = hx_pager::boost(
/// Pager::new()
/// .with_base_path("/admin/users")
/// .with_extra_query("sort", "username")
/// .with_current_page(2)
/// .with_items_per_page(20)
/// .with_total_items(97),
/// "#user-list",
/// );
/// ```
pub fn boost(pager: Pager, target: impl Into<CowStr>) -> Pager {
let target: CowStr = target.into();
pager
.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"))
}

View file

@ -23,9 +23,14 @@ use crate::hx;
///
/// [`Table`] y `SortLink` no requieren HTMX. Cada extensión que quiera aplicar una navegación sin
/// recarga debe añadir sus propios atributos `hx-*` usando [`SortLink::with_prop()`]. Como esos
/// cuatro atributos son siempre los mismos para cualquier cabecera ordenable (`hx-get` igual al
/// `href`, `hx-swap="outerHTML scroll:top"` y `hx-push-url="true"`, y sólo `hx-target` cambia según
/// la tabla), [`sort_link()`] evita reescribirlos en cada columna de cada listado.
/// atributos son siempre los mismos para cualquier cabecera ordenable (`hx-get` igual al `href`,
/// `hx-swap="outerHTML scroll:top"` y `hx-push-url="true"`, y sólo `hx-target` cambia según la
/// tabla), [`sort_link()`] evita reescribirlos en cada columna de cada listado.
///
/// 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`]).
///
/// El enlace resultante funciona igual con o sin HTMX: `href` es siempre la URL real del nuevo
/// estado de orden, así que navega correctamente aunque HTMX no esté disponible en el cliente.
@ -80,9 +85,12 @@ pub fn sort_link(
// `RoutePath` en `SortLink::new()` (vía `href.as_str()`) y como `CowStr` en `PropsOp::set()`.
let href = href.into().to_string();
let target = target.as_ref().to_owned();
let sync = util::join!(target.as_str(), ":replace");
table::SortLink::new(href.as_ref())
.with_dir(dir)
.with_prop(PropsOp::set(hx::GET, href))
.with_prop(PropsOp::set(hx::SYNC, sync))
.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"))

View file

@ -48,7 +48,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::*;
@ -92,6 +94,7 @@ use pagetop::prelude::*;
include_locales!(LOCALES_HTMX);
pub mod hx;
pub mod hx_filter;
pub mod hx_pager;
pub mod hx_table;
pub mod request;
@ -100,6 +103,7 @@ pub mod response;
/// Prelude de `pagetop-htmx`.
pub mod prelude {
pub use crate::hx;
pub use crate::hx_filter;
pub use crate::hx_pager;
pub use crate::hx_table;
pub use crate::request::HtmxRequestExt;
@ -110,8 +114,9 @@ pub mod prelude {
///
/// Poner esta extensión en [`dependencies()`](pagetop::core::extension::Extension::dependencies)
/// hace que todas las páginas de la aplicación incluyan automáticamente el script de HTMX mediante
/// un atributo [`defer`](pagetop::html::JavaScript::defer). No es necesaria ninguna configuración
/// adicional.
/// un atributo [`defer`](pagetop::html::JavaScript::defer), y las que tienen algún listado
/// ([`ListView`]), los estilos con los que se atenúa mientras se actualiza. No es necesaria ninguna
/// configuración adicional.
///
/// # Ejemplo
///
@ -144,7 +149,10 @@ impl Extension for Htmx {
}
fn actions(&self) -> Vec<ActionBox> {
actions![action::page::BeforeRenderBody::new(add_htmx_script)]
actions![
action::page::BeforeRenderBody::new(add_htmx_script),
action::component::BeforeRender::<ListView>::new(add_list_loading_styles),
]
}
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
@ -156,3 +164,19 @@ impl Extension for Htmx {
fn add_htmx_script(page: &mut Page) {
page.alter_assets(JavaScript::defer("/htmx/js/htmx.min.js").with_version("2.0.10"));
}
// Mientras los helpers de listado (filtros, paginador, cabeceras ordenables) esperan una respuesta,
// HTMX pone la clase `htmx-request` en el listado: se atenúa para que se vea que está cargando. El
// retardo evita el parpadeo cuando la respuesta es rápida. Sólo en las páginas con algún listado.
fn add_list_loading_styles(_list: &mut ListView, cx: &mut Context) {
cx.alter_assets(AssetsOp::add_responsive_styles(
None,
"list-view",
[("transition", "opacity 0.2s ease-in-out 0.15s")],
));
cx.alter_assets(AssetsOp::add_responsive_styles(
None,
"list-view htmx-request",
[("opacity", "0.5")],
));
}

View file

@ -10,7 +10,9 @@ impl Extension for TestApp {
}
fn configure_router(&self, routes: Routes) -> Routes {
routes.public_route("/page", web::get(render_page))
routes
.public_route("/page", web::get(render_page))
.public_route("/list", web::get(render_list))
}
}
@ -21,6 +23,13 @@ async fn render_page(request: HttpRequest) -> Result<Markup, ErrorPage> {
.await
}
async fn render_list(request: HttpRequest) -> Result<Markup, ErrorPage> {
Page::new(request)
.with_child(ListView::new().with_table(Table::new().with_column(Lc::n("Name"))))
.render()
.await
}
// All tests in this file share the same root extension (`TestApp`), since `EXTENSIONS` is a global
// `OnceLock` initialized only once per test binary (see `core/extension/all.rs`).
@ -60,3 +69,22 @@ async fn rendered_pages_automatically_include_the_pinned_htmx_script_tag() {
assert!(body.contains("defer"));
assert!(body.contains("<p>hello</p>"));
}
// **< List loading styles >************************************************************************
#[pagetop::test]
async fn pages_with_a_list_embed_the_list_loading_styles_and_others_do_not() {
let app = web::test::init_router(Application::prepare(&TestApp).await.test());
let req = web::test::TestRequest::get().uri("/list").to_request();
let body = web::test::read_body_text(web::test::send_request(&app, req).await).await;
// HTMX sets `htmx-request` on the element named by `hx-indicator`: the list.
assert!(
body.contains(".list-view.htmx-request{opacity:0.5}"),
"{body}"
);
let req = web::test::TestRequest::get().uri("/page").to_request();
let body = web::test::read_body_text(web::test::send_request(&app, req).await).await;
assert!(!body.contains("htmx-request"), "{body}");
}

View file

@ -0,0 +1,100 @@
use pagetop::prelude::*;
use pagetop_htmx::prelude::*;
// Forces an effective language different from the default negotiated one (en-US, with no `?lang` in
// the request), so that `Context::route()` decides to propagate `?lang=...` in local routes.
fn cx_with_lang(lang: &str) -> Context {
Context::default().with_langid(&Locale::resolve(lang))
}
// **< hx_pager::boost() >**************************************************************************
#[pagetop::test]
async fn boost_targets_the_list_from_the_pager_nav() {
let mut pager = hx_pager::boost(
Pager::new()
.with_base_path("/items")
.with_current_page(1)
.with_items_per_page(10)
.with_total_items(50),
"#item-list",
);
let html = pager.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"hx-boost="true""#), "{html}");
assert!(html.contains(r##"hx-target="#item-list""##), "{html}");
assert!(html.contains(r#"hx-swap="outerHTML scroll:top""#), "{html}");
assert!(html.contains(r#"hx-push-url="true""#), "{html}");
}
// **< hx_filter::boost() >*************************************************************************
#[pagetop::test]
async fn boost_sends_the_filter_form_to_the_list() {
let mut filter = hx_filter::boost(
ListFilter::new()
.with_filter_action("/items")
.with_field(form::input::Field::search().with_name("q")),
"#item-list",
);
let html = filter.render(&mut Context::default()).await.into_string();
// `hx-boost` on the form sends its fields to its own `action`, so no `hx-get` is needed.
assert!(html.contains(r#"hx-boost="true""#), "{html}");
assert!(!html.contains("hx-get"), "{html}");
// When it applies is up to the filter (button or auto submit), not to HTMX.
assert!(!html.contains("hx-trigger"), "{html}");
assert!(html.contains(r##"hx-target="#item-list""##), "{html}");
assert!(html.contains(r#"hx-push-url="true""#), "{html}");
}
#[pagetop::test]
async fn boosted_filter_keeps_the_language_in_a_hidden_field() {
// A boosted GET form drops the query of its `action`, the same as the browser does.
let mut filter = hx_filter::boost(
ListFilter::new()
.with_filter_action("/items")
.with_field(form::input::Field::search().with_name("q")),
"#item-list",
);
let html = filter
.render(&mut cx_with_lang("es-ES"))
.await
.into_string();
assert!(html.contains(r#"name="lang""#), "{html}");
assert!(html.contains(r#"value="es-ES""#), "{html}");
}
// **< Overlapping requests and loading indicator >*************************************************
#[pagetop::test]
async fn list_helpers_cancel_overlapping_requests_and_mark_the_list_while_loading() {
let mut pager = hx_pager::boost(
Pager::new()
.with_base_path("/items")
.with_current_page(1)
.with_items_per_page(10)
.with_total_items(50),
"#item-list",
);
let mut filter = hx_filter::boost(ListFilter::new().with_filter_action("/items"), "#item-list");
let mut table = Table::new().with_column(
table::Column::new(Lc::n("Name")).with_sort(hx_table::sort_link(
"/items",
"#item-list",
None,
)),
);
let mut cx = Context::default();
for html in [
pager.render(&mut cx).await.into_string(),
filter.render(&mut cx).await.into_string(),
table.render(&mut cx).await.into_string(),
] {
// Every request against the list cancels the one in progress, wherever it comes from.
assert!(html.contains(r##"hx-sync="#item-list:replace""##), "{html}");
assert!(html.contains(r##"hx-indicator="#item-list""##), "{html}");
}
}

View file

@ -15,7 +15,7 @@ async fn render_column(column: table::Column) -> String {
// **< sort_link() - htmx attributes >**************************************************************
#[pagetop::test]
async fn sort_link_sets_the_four_fixed_htmx_attributes() {
async fn sort_link_sets_the_fixed_htmx_attributes() {
let column = table::Column::new(Lc::n("User")).with_sort(hx_table::sort_link(
"/admin/users",
"#user-table",

View file

@ -12,7 +12,7 @@ mod user_table;
pub(crate) use admin_password_form::AdminPasswordForm;
pub(crate) use role_form::{RoleForm, RoleFormMode};
pub(crate) use role_permissions_form::RolePermissionsForm;
pub(crate) use role_table::RoleTable;
pub(crate) use role_table::{RoleTable, delete_dialog};
pub(crate) use user_form::{UserForm, UserFormMode};
pub(crate) use user_table::{UserTable, status_key};

View file

@ -1,8 +1,8 @@
//! Tabla de roles: cabeceras ordenables y filas con acciones.
//! Listado de roles: cabeceras ordenables y filas con acciones, en un `ListView`.
use pagetop::prelude::*;
use pagetop_htmx::hx;
use pagetop_htmx::hx_table::sort_link;
use pagetop_htmx::{hx, hx_pager};
use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
@ -12,7 +12,6 @@ use crate::service::role_admin::{RoleListItem, RoleSortField};
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct RoleTable {
props: Props,
items: Vec<RoleListItem>,
sort: RoleSortField,
dir: SortDir,
@ -29,15 +28,6 @@ impl Component for RoleTable {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::set_id("role-table-wrapper"));
self.alter_prop(PropsOp::prepend_classes("user-admin-table-wrapper"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let pager = Pager::new()
.with_base_path(ADMIN_ROLES_PATH.as_str())
@ -45,13 +35,7 @@ impl Component for RoleTable {
.with_extra_query("dir", *self.dir())
.with_current_page(self.page())
.with_items_per_page(self.per_page())
.with_total_items(self.total())
.with_prop(PropsOp::set(hx::BOOST, "true"))
.with_prop(PropsOp::set(hx::TARGET, "#role-table-wrapper"))
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
.render(cx)
.await;
.with_total_items(self.total());
let mut table = Table::new()
.with_prop(PropsOp::add_classes("user-admin-table"))
@ -62,21 +46,6 @@ impl Component for RoleTable {
.with_column(Lc::t("col-actions", &LOCALES_USER))
.with_empty(Lc::t("empty-roles-list", &LOCALES_USER));
let confirm_dialog = Dialog::new()
.with_id("confirm-delete-role")
.with_child(Html::with(|cx| {
html! { p { (Lc::t("confirm-delete-role", &LOCALES_USER).using(cx)) } }
}))
.with_footer(
Button::plain(Lc::t("btn-cancel", &LOCALES_USER))
.with_prop(PropsOp::set("data-dialog-dismiss", "modal")),
)
.with_footer(Html::with(
|_cx| html! { span id="role-delete-confirm-action" {} },
))
.render(cx)
.await;
let waypoint = Waypoint::from(self.list_href(cx));
for role in self.items() {
@ -119,32 +88,43 @@ impl Component for RoleTable {
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_ROLES_PATH.as_str(), "/new")));
Ok(html! {
div (self.props().unpack(cx)) {
(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)) }
}
(table.render(cx).await)
(pager)
(confirm_dialog)
}
})
if let Some(message) = self.message() {
cx.push_message(MessageLevel::Error, message.clone());
}
let mut list = ListView::new()
.with_id("role-table-wrapper")
.with_action(
Button::anchor(Lc::t("btn-create-role", &LOCALES_USER), new_href)
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_table(table)
.with_pager(hx_pager::boost(pager, "#role-table-wrapper"));
Ok(list.render(cx).await)
}
}
// Diálogo de confirmación de borrado, compartido por todas las filas: el botón de borrar de cada
// una lo abre y carga en él su botón de confirmación (ver `delete_confirm_get` en los *handlers* de
// roles). Va en la página, fuera del listado, para que HTMX no lo reemplace al actualizarlo.
pub(crate) fn delete_dialog() -> Dialog {
Dialog::new()
.with_id("confirm-delete-role")
.with_child(Html::with(|cx| {
html! { p { (Lc::t("confirm-delete-role", &LOCALES_USER).using(cx)) } }
}))
.with_footer(
Button::plain(Lc::t("btn-cancel", &LOCALES_USER))
.with_prop(PropsOp::set("data-dialog-dismiss", "modal")),
)
.with_footer(Html::with(
|_cx| html! { span id="role-delete-confirm-action" {} },
))
}
#[builder_impl]
impl RoleTable {
// **< RoleTable BUILDER >**********************************************************************
pub(crate) fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
pub(crate) fn with_items(mut self, items: Vec<RoleListItem>) -> Self {
self.items = items;
self

View file

@ -1,7 +1,7 @@
//! Tabla de usuarios: cabeceras ordenables, filas y paginación embebida.
//! Listado de usuarios: cabeceras ordenables, filas y paginación, en un `ListView`.
use pagetop::prelude::*;
use pagetop_htmx::hx;
use pagetop_htmx::hx_pager;
use pagetop_htmx::hx_table::sort_link;
use crate::ADMIN_USERS_PATH;
@ -12,7 +12,6 @@ use crate::user_path;
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct UserTable {
props: Props,
items: Vec<UserListItem>,
sort: UserSortField,
dir: SortDir,
@ -28,15 +27,6 @@ impl Component for UserTable {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::set_id("user-table-wrapper"));
self.alter_prop(PropsOp::prepend_classes("user-admin-table-wrapper"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let pager = Pager::new()
.with_base_path(ADMIN_USERS_PATH.as_str())
@ -45,13 +35,7 @@ impl Component for UserTable {
.with_extra_query("dir", *self.dir())
.with_current_page(self.page())
.with_items_per_page(self.per_page())
.with_total_items(self.total())
.with_prop(PropsOp::set(hx::BOOST, "true"))
.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"))
.render(cx)
.await;
.with_total_items(self.total());
let mut table = Table::new()
.with_prop(PropsOp::add_classes("user-admin-table"))
@ -85,16 +69,15 @@ impl Component for UserTable {
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new")));
Ok(html! {
div (self.props().unpack(cx)) {
(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)
}
})
let mut list = ListView::new()
.with_id("user-table-wrapper")
.with_action(
Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href)
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_table(table)
.with_pager(hx_pager::boost(pager, "#user-table-wrapper"));
Ok(list.render(cx).await)
}
}
@ -102,11 +85,6 @@ impl Component for UserTable {
impl UserTable {
// **< UserTable BUILDER >**********************************************************************
pub(crate) fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
pub(crate) fn with_items(mut self, items: Vec<UserListItem>) -> Self {
self.items = items;
self

View file

@ -8,7 +8,7 @@ use pagetop_htmx::prelude::*;
use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
use crate::component::admin::{
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable,
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable, delete_dialog,
};
use crate::config::SETTINGS;
use crate::entity::role;
@ -62,6 +62,7 @@ pub(crate) async fn list_get(
Ok(Page::admin(request)
.with_title(title)
.with_child(table)
.with_child(delete_dialog())
.render()
.await
.into_response())
@ -403,7 +404,7 @@ pub(crate) async fn delete_post(
/// GET /admin/user/roles/{id}/delete/confirm - Botón de confirmación de borrado para esta fila,
/// insertado vía htmx en el diálogo de confirmación compartido por toda la tabla (ver
/// `RoleTable`), con la URL de borrado de este rol ya incrustada.
/// `delete_dialog()`), con la URL de borrado de este rol ya incrustada.
///
/// Propaga `sort`/`dir`/`page` (recibidos como query string desde la propia fila) hacia la URL de
/// borrado, para que `delete_post` pueda volver a mostrar la misma página tras el borrado, en vez

View file

@ -70,11 +70,9 @@ 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);
let page = Page::admin(request);
let search = search_bar(page.route(ADMIN_USERS_PATH.as_str()), query.q);
Ok(page
Ok(Page::admin(request)
.with_title(title)
.with_child(search)
.with_child(search_filter(query.q))
.with_child(table)
.render()
.await
@ -82,26 +80,21 @@ pub(crate) async fn list_get(
}
}
// **< search_bar >*********************************************************************************
// **< search_filter >******************************************************************************
// 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<String>) -> 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)),
)
fn search_filter(current_query: Option<String>) -> ListFilter {
hx_filter::boost(
ListFilter::new()
.with_filter_action(ADMIN_USERS_PATH.as_str())
.with_field(
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)),
),
"#user-table-wrapper",
)
}
// **< available_roles >****************************************************************************

View file

@ -57,6 +57,12 @@ pub mod intro;
#[doc(inline)]
pub use intro::Intro;
mod list_filter;
pub use list_filter::ListFilter;
mod list_view;
pub use list_view::ListView;
mod messages;
pub use messages::Messages;

View file

@ -0,0 +1,236 @@
use crate::prelude::*;
use crate::base::component::form;
/// Componente para crear los **filtros de un listado** (ver [`ListView`]).
///
/// Es un formulario GET con los campos en fila y el botón para aplicarlos que se coloca en la
/// página por encima del listado ([`ListView`]), no dentro: si se reemplazara con él, un campo de
/// texto perdería el foco en cada pulsación.
///
/// Envía los campos a la ruta de [`with_filter_action()`], que vuelve a pintar el listado ya
/// filtrado:
///
/// ```html
/// <form class="list-filter" action="...">
/// ... <!-- campos -->
/// <button type="submit">...</button> <!-- "Filtrar", si no se indica otro texto -->
/// <a href="..." target="_top">...</a> <!-- "Limpiar": el listado sin filtros -->
/// </form>
/// ```
///
/// Por defecto, los filtros **no** se envían solos: se aplican al pulsar el botón (o Enter en un
/// campo de texto), de modo que se pueden ajustar varios campos y pedir el listado una sola vez.
/// Con [`with_auto_submit(true)`](Self::with_auto_submit) se aplican en cuanto cambia cualquier
/// campo, sin botón.
///
/// Junto al botón aparece por defecto el enlace "Limpiar", que vuelve a la ruta del filtro sin
/// ningún parámetro: el listado tal como se ve al entrar, también sin orden ni página. Recarga la
/// página entera, para que los campos del filtro se vacíen también. Se quita con
/// [`with_reset(false)`](Self::with_reset).
///
/// Con el botón, y si hay JavaScript, cada campo cuyo valor ya no coincide con el del filtro
/// aplicado se marca (clase `list-filter-changed` en su contenedor, `list-filter-pending` en el
/// formulario) hasta que se pulsa el botón, y un aviso oculto lo anuncia a los lectores de
/// pantalla. Así se sabe que el listado aún no corresponde a lo que muestra el filtro. El aspecto
/// de las marcas lo da cada tema.
///
/// Al enviar un formulario GET, el navegador descarta los parámetros que ya traiga la ruta de
/// destino, así que el idioma (`lang`) de la ruta se conserva en un campo oculto.
///
/// Como [`ListView`], no sabe nada de HTMX. Para aplicar los filtros sin recargar la página, se le
/// añaden los atributos necesarios con [`with_prop()`].
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
///
/// let filter = ListFilter::new()
/// .with_filter_action("/items")
/// .with_field(
/// form::input::Field::search()
/// .with_name("q")
/// .with_placeholder(Lc::n("Search...")),
/// );
/// ```
///
/// [`with_filter_action()`]: Self::with_filter_action
/// [`with_prop()`]: Self::with_prop
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct ListFilter {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
/// Devuelve la ruta del formulario del filtro (su atributo `action`).
filter_action: Route,
/// Devuelve los campos de los filtros.
fields: Children,
/// Devuelve el texto del botón, o [`Lc::none()`] para el predeterminado ("Filtrar").
submit: Lc,
/// Devuelve si los filtros se aplican en cuanto cambia un campo, sin botón (por defecto, no).
#[getters(copy)]
auto_submit: bool,
/// Devuelve si se muestra el enlace "Limpiar" (por defecto, sí).
#[default(true)]
#[getters(copy)]
reset: bool,
}
#[async_trait]
impl Component for ListFilter {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes("list-filter"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let action = self.filter_action().try_resolve(cx);
let lang = action
.as_ref()
.and_then(|route| route.param("lang"))
.map(|lang| form::Hidden::field("lang", lang));
let label = if self.submit().is_none() {
Lc::l("list_filter_submit")
} else {
self.submit().clone()
};
let submit = Button::submit(label)
.with_style(button::Style::Solid(Intent::Neutral))
.render(cx)
.await;
// `target="_top"` navega igual que un enlace normal, pero las librerías que interceptan los
// enlaces para cargar sólo una parte de la página (como HTMX con `hx-boost`) dejan pasar
// los que tienen un `target` propio. Así se recarga la página entera y se vacían los
// campos, que no se volverían a pintar si sólo se actualizara el listado.
let reset = match (&action, self.reset()) {
(Some(route), true) => Some(
Button::anchor(Lc::l("list_filter_reset"), route.clone())
.with_style(button::Style::Link)
.with_prop(PropsOp::set("target", "_top"))
.render(cx)
.await,
),
_ => None,
};
let auto_submit = self.auto_submit();
// Con el botón, un script del componente marca los campos cambiados y no aplicados todavía,
// y el aviso oculto los anuncia a los lectores de pantalla (`role="status"`).
let pending = (!auto_submit).then(|| Lc::l("list_filter_pending").lookup(cx));
if pending.is_some() {
cx.alter_assets(
JavaScript::defer("/pagetop/js/list-filter.min.js").with_version(PAGETOP_VERSION),
);
}
Ok(html! {
form
(self.props().unpack(cx))
action=[action]
onchange=[auto_submit.then_some("this.requestSubmit()")]
{
@if let Some(mut lang) = lang { (lang.render(cx).await) }
(self.fields().render(cx).await)
@if auto_submit { noscript { (submit) } } @else { (submit) }
@if let Some(reset) = reset { (reset) }
@if let Some(pending) = pending {
span
class="list-filter-status visually-hidden"
role="status"
data-pending=[pending]
{}
}
}
})
}
}
#[builder_impl]
impl ListFilter {
// **< ListFilter BUILDER >*********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id);
self
}
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
/// Establece la ruta del formulario del filtro: el atributo `action` del `<form>` que genera el
/// componente, es decir, la ruta a la que se envían los filtros.
///
/// Normalmente es la del propio listado. Su *handler* recibe los campos en la consulta
/// (`?q=...`) y vuelve a pintar el listado con ellos aplicados: la página entera en una
/// petición normal o, con filtrado en vivo, sólo el listado. No tiene que ver con las acciones
/// de PageTop ([`core::action`](crate::core::action)).
///
/// Acepta un literal, un `String` o una [`Route`]; como en cualquier enlace, se le añade el
/// idioma (`lang`) cuando corresponde, y el componente lo conserva en un campo oculto para que
/// el formulario no lo pierda al enviarse.
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// // GET /items?q=... vuelve a pintar el listado con la búsqueda aplicada.
/// let filter = ListFilter::new()
/// .with_filter_action("/items")
/// .with_field(form::input::Field::search().with_name("q"));
/// ```
pub fn with_filter_action(mut self, action: impl Into<Route>) -> Self {
self.filter_action = action.into();
self
}
/// Añade un campo de filtro (texto, desplegable, casilla...).
pub fn with_field(mut self, op: impl Into<ChildOp>) -> Self {
self.fields.alter_child(op);
self
}
/// Aplica los filtros en cuanto cambia cualquier campo, sin pulsar el botón.
///
/// **Por defecto está desactivado** (`false`): los filtros se aplican sólo con el botón.
/// Con JavaScript activo, el filtro se muestra **sin botón**: un desplegable o una casilla se
/// aplican al cambiar, y un campo de texto al pulsar Enter o al salir de él (no con cada
/// tecla). Sin JavaScript, el botón sigue apareciendo y los filtros se aplican al pulsarlo.
///
/// Cada cambio pide de nuevo el listado. Conviene en filtros de uno o dos campos; con muchos,
/// el botón evita consultas intermedias que el usuario no quería.
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// let filter = ListFilter::new()
/// .with_filter_action("/items")
/// .with_field(form::Checkbox::check().with_name("active").with_label(Lc::n("Active")))
/// .with_auto_submit(true);
/// ```
pub fn with_auto_submit(mut self, auto_submit: bool) -> Self {
self.auto_submit = auto_submit;
self
}
/// Muestra u oculta el enlace "Limpiar", que vuelve al listado sin filtros.
///
/// **Por defecto se muestra** (`true`), al contrario que
/// [`with_auto_submit()`](Self::with_auto_submit); con `false` se quita, por ejemplo en un
/// filtro de un único campo de texto, que ya se limpia vaciándolo.
pub fn with_reset(mut self, reset: bool) -> Self {
self.reset = reset;
self
}
/// Cambia el texto del botón; con [`Lc::none()`] vuelve al predeterminado ("Filtrar").
pub fn with_submit(mut self, label: Lc) -> Self {
self.submit = label;
self
}
}

View file

@ -0,0 +1,150 @@
use crate::prelude::*;
/// Componente para presentar un **listado**: botones de acción, mensajes, tabla y paginador.
///
/// Reúne las piezas de cualquier pantalla de listado y las pinta siempre en el mismo orden, sea
/// cual sea el orden en que se añadan:
///
/// ```html
/// <div class="list-view" id="..." data-summary="...">
/// <div class="list-view-actions">...</div> <!-- botones, si los hay -->
/// ... <!-- mensajes del contexto, si los hay -->
/// <table class="table">...</table>
/// <nav class="pager">...</nav> <!-- si hay más de una página -->
/// </div>
/// ```
///
/// Los mensajes son los que haya en el contexto al renderizar el listado (ver [`Messages`]), así
/// que un error o un aviso empujado antes, por ejemplo al rechazar un borrado, aparece junto a la
/// tabla también cuando se actualiza sólo el listado.
///
/// El listado lleva además un resumen del número de resultados (atributo `data-summary`, p. ej.
/// "23 resultados"): el total del paginador o, sin él, las filas de la tabla. Si JavaScript está
/// activo, cuando el listado se actualiza sin recargar la página, al filtrar, ordenar o cambiar de
/// página, el resumen se anuncia a los lectores de pantalla.
///
/// No sabe nada de HTMX. Para actualizar el listado sin recargar la página, se le da un
/// identificador con [`with_id()`](Self::with_id) y se apuntan a él los enlaces de la tabla y del
/// paginador. Los filtros y la búsqueda van **fuera** del listado, en la propia página: si se
/// reemplazaran con él, el campo de búsqueda perdería el foco en cada pulsación.
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
///
/// let list = ListView::new()
/// .with_id("item-list")
/// .with_action(
/// Button::anchor(Lc::n("New item"), "/items/new")
/// .with_style(button::Style::Solid(Intent::Primary)),
/// )
/// .with_table(
/// Table::new()
/// .with_column(Lc::n("Name"))
/// .with_empty(Lc::n("There are no items.")),
/// )
/// .with_pager(
/// Pager::new()
/// .with_base_path("/items")
/// .with_current_page(1)
/// .with_items_per_page(20)
/// .with_total_items(97),
/// );
/// ```
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct ListView {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
/// Devuelve los botones de acción del listado.
actions: Children,
/// Devuelve la tabla del listado.
table: Embed<Table>,
/// Devuelve el paginador del listado.
pager: Embed<Pager>,
}
#[async_trait]
impl Component for ListView {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes("list-view"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
// Un script del componente anuncia el resumen cuando el listado se actualiza sin recargar
// la página (al cargarla no anuncia nada).
cx.alter_assets(
JavaScript::defer("/pagetop/js/list-view.min.js").with_version(PAGETOP_VERSION),
);
let count = match self.pager().get() {
Some(pager) => pager.total_items(),
None => self
.table()
.get()
.map_or(0, |table| table.rows().len() as u64),
};
let summary = Lc::l("list_view_summary")
.with_number("count", u32::try_from(count).unwrap_or(u32::MAX))
.lookup(cx);
let mut actions = Flex::new()
.with_prop(PropsOp::add_classes("list-view-actions"))
.with_wrap(flex::Behavior::Wrap)
.with_align(align::Items::Center)
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)));
for action in self.actions().iter() {
actions.alter_child(action.clone());
}
Ok(html! {
div (self.props().unpack(cx)) data-summary=[summary] {
(actions.render(cx).await)
(Messages::new().render(cx).await)
(self.table().render(cx).await)
(self.pager().render(cx).await)
}
})
}
}
#[builder_impl]
impl ListView {
// **< ListView BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id);
self
}
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
/// Añade un botón de acción, o cualquier otro componente, sobre la tabla; habitualmente el de
/// crear un elemento nuevo.
pub fn with_action(mut self, op: impl Into<ChildOp>) -> Self {
self.actions.alter_child(op);
self
}
/// Establece la tabla del listado.
pub fn with_table(mut self, table: Table) -> Self {
self.table.alter_component(table);
self
}
/// Establece el paginador del listado.
pub fn with_pager(mut self, pager: Pager) -> Self {
self.pager.alter_component(pager);
self
}
}

View file

@ -48,6 +48,18 @@ intro_text2 = PageTop brings back the essence of the classic web, renders on the
intro_code = Code
intro_have_fun = Coding is creating
# ListFilter component.
list_filter_submit = Filter
list_filter_reset = Clear
list_filter_pending = There are filters not applied yet
# ListView component.
list_view_summary = { $count ->
[0] No results
[one] 1 result
*[other] { $count } results
}
# Navbar component.
navbar_toggle = Toggle navigation

View file

@ -48,6 +48,18 @@ intro_text2 = PageTop reivindica la esencia de la web clásica, renderiza en el
intro_code = Código
intro_have_fun = Programar es crear
# ListFilter component.
list_filter_submit = Filtrar
list_filter_reset = Limpiar
list_filter_pending = Hay filtros sin aplicar
# ListView component.
list_view_summary = { $count ->
[0] Ningún resultado
[one] 1 resultado
*[other] { $count } resultados
}
# Navbar component.
navbar_toggle = Alternar navegación

View file

@ -0,0 +1,126 @@
use pagetop::prelude::*;
// **< ListFilter >*********************************************************************************
#[pagetop::test]
async fn renders_a_get_form_with_its_fields_and_the_button() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_field(form::input::Field::search().with_name("q"));
let html = filter.render(&mut Context::default()).await.into_string();
assert!(html.starts_with("<form"), "{html}");
assert!(html.contains(r#"class="list-filter""#), "{html}");
assert!(html.contains(r#"action="/items""#), "{html}");
assert!(
!html.contains("method="),
"a GET form needs no method: {html}"
);
assert!(html.contains(r#"name="q""#), "{html}");
assert!(html.contains(r#"type="submit""#), "{html}");
}
#[pagetop::test]
async fn keeps_the_language_of_the_action_in_a_hidden_field() {
// A GET form drops the query of its action, so the language must travel as a field.
let mut filter =
ListFilter::new().with_filter_action(RoutePath::new("/items").with_param("lang", "es-ES"));
let html = filter.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"type="hidden""#), "{html}");
assert!(html.contains(r#"name="lang""#), "{html}");
assert!(html.contains(r#"value="es-ES""#), "{html}");
}
#[pagetop::test]
async fn the_button_label_can_be_changed() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_submit(Lc::n("Search"));
let html = filter.render(&mut Context::default()).await.into_string();
assert!(html.contains("Search"), "{html}");
}
#[pagetop::test]
async fn by_default_it_applies_with_the_button() {
let mut filter = ListFilter::new().with_filter_action("/items");
let html = filter.render(&mut Context::default()).await.into_string();
assert!(!html.contains("onchange"), "{html}");
assert!(!html.contains("<noscript>"), "{html}");
}
#[pagetop::test]
async fn auto_submit_applies_on_change_and_keeps_the_button_only_without_javascript() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_auto_submit(true);
let html = filter.render(&mut Context::default()).await.into_string();
assert!(
html.contains(r#"onchange="this.requestSubmit()""#),
"{html}"
);
assert!(
html.contains(r#"<noscript><button type="submit""#),
"{html}"
);
}
#[pagetop::test]
async fn the_reset_link_goes_back_to_the_list_with_no_filters() {
let mut filter = ListFilter::new().with_filter_action("/items");
let html = filter.render(&mut Context::default()).await.into_string();
let link = html
.find("<a")
.map(|start| &html[start..])
.expect("reset link");
assert!(link.contains(r#"href="/items""#), "{html}");
// Not intercepted by libraries that load only part of the page, so the fields are emptied too.
assert!(link.contains(r#"target="_top""#), "{html}");
}
#[pagetop::test]
async fn the_reset_link_can_be_removed() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_reset(false);
let html = filter.render(&mut Context::default()).await.into_string();
assert!(!html.contains("<a"), "{html}");
}
#[pagetop::test]
async fn with_the_button_it_marks_pending_changes() {
let mut cx = Context::default();
let mut filter = ListFilter::new().with_filter_action("/items");
let html = filter.render(&mut cx).await.into_string();
let assets = cx.render_assets().into_string();
// The script marks changed fields; the hidden status announces them to screen readers.
assert!(
assets.contains("/pagetop/js/list-filter.min.js"),
"{assets}"
);
assert!(
html.contains(r#"class="list-filter-status visually-hidden""#),
"{html}"
);
assert!(html.contains(r#"role="status""#), "{html}");
assert!(html.contains("data-pending="), "{html}");
}
#[pagetop::test]
async fn auto_submit_has_nothing_pending_to_mark() {
let mut cx = Context::default();
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_auto_submit(true);
let html = filter.render(&mut cx).await.into_string();
let assets = cx.render_assets().into_string();
assert!(!assets.contains("list-filter.min.js"), "{assets}");
assert!(!html.contains("list-filter-status"), "{html}");
}

View file

@ -0,0 +1,86 @@
use pagetop::prelude::*;
// **< ListView >***********************************************************************************
fn pager() -> Pager {
Pager::new()
.with_base_path("/items")
.with_current_page(1)
.with_items_per_page(10)
.with_total_items(50)
}
fn table() -> Table {
Table::new()
.with_column(Lc::n("Name"))
.with_empty(Lc::n("No items"))
}
#[pagetop::test]
async fn renders_its_id_and_class() {
let mut list = ListView::new().with_id("item-list").with_table(table());
let html = list.render(&mut Context::default()).await.into_string();
assert!(html.starts_with("<div"), "{html}");
assert!(html.contains(r#"id="item-list""#), "{html}");
assert!(html.contains(r#"class="list-view""#), "{html}");
}
#[pagetop::test]
async fn renders_the_parts_in_a_fixed_order() {
// Added in reverse order on purpose: the output order must not depend on it.
let mut list = ListView::new()
.with_pager(pager())
.with_table(table())
.with_action(Button::anchor(Lc::n("New item"), "/items/new"));
let mut cx = Context::default();
cx.push_message(MessageLevel::Error, Lc::n("Something failed"));
let html = list.render(&mut cx).await.into_string();
let actions = html.find("list-view-actions").expect("actions");
let message = html.find("Something failed").expect("message");
let table = html.find("<table").expect("table");
let pager = html.find("<nav").expect("pager");
assert!(actions < message && message < table && table < pager);
}
#[pagetop::test]
async fn without_actions_there_is_no_actions_row() {
let mut list = ListView::new().with_table(table());
let html = list.render(&mut Context::default()).await.into_string();
assert!(!html.contains("list-view-actions"));
assert!(html.contains("No items"));
}
#[pagetop::test]
async fn it_carries_a_summary_of_the_results_and_its_script() {
let mut cx = Context::default();
let mut list = ListView::new().with_table(table()).with_pager(pager());
let html = list.render(&mut cx).await.into_string();
let assets = cx.render_assets().into_string();
// The total of the pager, not only the rows on this page.
assert!(html.contains(r#"data-summary="50 results""#), "{html}");
assert!(assets.contains("/pagetop/js/list-view.min.js"), "{assets}");
}
#[pagetop::test]
async fn without_a_pager_the_summary_counts_the_rows() {
let mut list = ListView::new().with_table(
table()
.with_row(table::Row::new().with_cell(Lc::n("A")))
.with_row(table::Row::new().with_cell(Lc::n("B"))),
);
let html = list.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"data-summary="2 results""#), "{html}");
let mut one =
ListView::new().with_table(table().with_row(table::Row::new().with_cell(Lc::n("A"))));
let html = one.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"data-summary="1 result""#), "{html}");
let mut none = ListView::new().with_table(table());
let html = none.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"data-summary="No results""#), "{html}");
}