✨ (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
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")],
|
||||
));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue