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