✨ (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:
parent
0f71eba7ab
commit
d8493291e4
28 changed files with 1264 additions and 144 deletions
|
|
@ -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::*;
|
||||
|
|
|
|||
51
extensions/pagetop-htmx/src/hx_filter.rs
Normal file
51
extensions/pagetop-htmx/src/hx_filter.rs
Normal 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"))
|
||||
}
|
||||
|
|
@ -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"))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"))
|
||||
|
|
|
|||
|
|
@ -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")],
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}");
|
||||
}
|
||||
|
|
|
|||
100
extensions/pagetop-htmx/tests/hx_list.rs
Normal file
100
extensions/pagetop-htmx/tests/hx_list.rs
Normal 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}");
|
||||
}
|
||||
}
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue