From 38fd24453e8ccb84c8ee9dee8e8eb4b458420b89 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Sat, 13 Jun 2026 18:41:15 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20(htmx):=20A=C3=B1ade=20integraci?= =?UTF-8?q?=C3=B3n=20con=20HTMX=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Constantes `hx-*`, `HtmxRequestExt` y `HtmxResponse` cubren el ciclo completo: escribir atributos, leer la petición y construir la respuesta. La extensión Htmx inyecta el script automáticamente. Añade `IntoResponse` y `Response` al prelude de PageTop. --- Cargo.toml | 2 + extensions/pagetop-htmx/Cargo.toml | 21 + extensions/pagetop-htmx/LICENSE-APACHE | 201 +++++++ extensions/pagetop-htmx/LICENSE-MIT | 21 + extensions/pagetop-htmx/README.md | 88 +++ extensions/pagetop-htmx/build.rs | 7 + extensions/pagetop-htmx/src/hx.rs | 549 ++++++++++++++++++ extensions/pagetop-htmx/src/lib.rs | 129 ++++ .../src/locale/en-US/extension.ftl | 2 + .../src/locale/es-ES/extension.ftl | 2 + extensions/pagetop-htmx/src/request.rs | 132 +++++ extensions/pagetop-htmx/src/response.rs | 228 ++++++++ extensions/pagetop-htmx/static/js/htmx.min.js | 1 + src/prelude.rs | 2 +- tools/changelog.sh | 5 + 15 files changed, 1389 insertions(+), 1 deletion(-) create mode 100644 extensions/pagetop-htmx/Cargo.toml create mode 100644 extensions/pagetop-htmx/LICENSE-APACHE create mode 100644 extensions/pagetop-htmx/LICENSE-MIT create mode 100644 extensions/pagetop-htmx/README.md create mode 100644 extensions/pagetop-htmx/build.rs create mode 100644 extensions/pagetop-htmx/src/hx.rs create mode 100644 extensions/pagetop-htmx/src/lib.rs create mode 100644 extensions/pagetop-htmx/src/locale/en-US/extension.ftl create mode 100644 extensions/pagetop-htmx/src/locale/es-ES/extension.ftl create mode 100644 extensions/pagetop-htmx/src/request.rs create mode 100644 extensions/pagetop-htmx/src/response.rs create mode 100644 extensions/pagetop-htmx/static/js/htmx.min.js diff --git a/Cargo.toml b/Cargo.toml index 269f752f..fb4dc225 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ # Extensions "extensions/pagetop-aliner", "extensions/pagetop-bootsier", + "extensions/pagetop-htmx", "extensions/pagetop-seaorm", ] @@ -62,6 +63,7 @@ pagetop-statics = { version = "0.1", path = "helpers/pagetop-statics" } # Extensions pagetop-aliner = { version = "0.1", path = "extensions/pagetop-aliner" } pagetop-bootsier = { version = "0.1", path = "extensions/pagetop-bootsier" } +pagetop-htmx = { version = "0.1", path = "extensions/pagetop-htmx" } pagetop-seaorm = { version = "0.0", path = "extensions/pagetop-seaorm" } # PageTop pagetop = { version = "0.5", path = "." } diff --git a/extensions/pagetop-htmx/Cargo.toml b/extensions/pagetop-htmx/Cargo.toml new file mode 100644 index 00000000..5a1c254f --- /dev/null +++ b/extensions/pagetop-htmx/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "pagetop-htmx" +version = "0.1.0" + +description = """ + Extensión de PageTop que integra HTMX para enriquecer las páginas con interacciones dinámicas. +""" +categories = ["web-programming"] +keywords = ["pagetop", "htmx", "ajax", "ssr"] + +repository.workspace = true +homepage.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +pagetop.workspace = true + +[build-dependencies] +pagetop-build.workspace = true diff --git a/extensions/pagetop-htmx/LICENSE-APACHE b/extensions/pagetop-htmx/LICENSE-APACHE new file mode 100644 index 00000000..56cfd2db --- /dev/null +++ b/extensions/pagetop-htmx/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Manuel Cillero + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/extensions/pagetop-htmx/LICENSE-MIT b/extensions/pagetop-htmx/LICENSE-MIT new file mode 100644 index 00000000..4227455e --- /dev/null +++ b/extensions/pagetop-htmx/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Manuel Cillero + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/extensions/pagetop-htmx/README.md b/extensions/pagetop-htmx/README.md new file mode 100644 index 00000000..1bf1c623 --- /dev/null +++ b/extensions/pagetop-htmx/README.md @@ -0,0 +1,88 @@ +
+ +

PageTop HTMX

+ +

Extensión para PageTop que integra HTMX para enriquecer las páginas con interacciones dinámicas.

+ +[![Doc API](https://img.shields.io/docsrs/pagetop-htmx?label=Doc%20API&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-htmx) +[![Crates.io](https://img.shields.io/crates/v/pagetop-htmx.svg?style=for-the-badge&logo=ipfs)](https://crates.io/crates/pagetop-htmx) +[![Descargas](https://img.shields.io/crates/d/pagetop-htmx.svg?label=Descargas&style=for-the-badge&logo=transmission)](https://crates.io/crates/pagetop-htmx) +[![Licencia](https://img.shields.io/badge/license-MIT%2FApache-blue.svg?label=Licencia&style=for-the-badge)](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-htmx#licencia) + +
+ +## Sobre PageTop + +[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web +clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y +configurables, basadas en HTML, CSS y JavaScript. + +## Guía rápida + +**Añade la dependencia** a tu `Cargo.toml`: + +```toml +[dependencies] +pagetop-htmx = { ... } +``` + +**Declara la extensión** en tu aplicación (o extensión que la requiera). Recuerda que el orden en +`dependencies()` determina la prioridad relativa frente a las otras extensiones: + +```rust +use pagetop::prelude::*; + +struct MyApp; + +impl Extension for MyApp { + fn dependencies(&self) -> Vec { + vec![ + // ... + &pagetop_htmx::Htmx + // ... + ] + } +} +``` + +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: + +```rust +use pagetop::prelude::*; + +async fn homepage(request: HttpRequest) -> Result { + Page::new(request) + .with_child(Html::with(|_| html! { + button hx-get="/api/hello" hx-target="#result" { + "Say hello" + } + div #result {} + })) + .render() +} +``` + +## Créditos + +Este *crate* integra la biblioteca [HTMX 2.0.10](https://htmx.org), distribuida bajo licencia +[BSD 2-Clause](https://github.com/bigskysoftware/htmx/blob/master/LICENSE). + +## Advertencia + +**PageTop** es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su +ecosistema. Su API está sujeta a cambios frecuentes. No se recomienda su uso en producción, al menos +hasta que se libere la versión **1.0.0**. + +## Licencia + +El código está disponible bajo una doble licencia: + + * **Licencia MIT** + ([LICENSE-MIT](LICENSE-MIT) o también https://opensource.org/licenses/MIT) + + * **Licencia Apache, Versión 2.0** + ([LICENSE-APACHE](LICENSE-APACHE) o también https://www.apache.org/licenses/LICENSE-2.0) + +Puedes elegir la licencia que prefieras. Este enfoque de doble licencia es el estándar de facto en +el ecosistema Rust. diff --git a/extensions/pagetop-htmx/build.rs b/extensions/pagetop-htmx/build.rs new file mode 100644 index 00000000..dfadf712 --- /dev/null +++ b/extensions/pagetop-htmx/build.rs @@ -0,0 +1,7 @@ +use pagetop_build::StaticFilesBundle; + +fn main() -> std::io::Result<()> { + StaticFilesBundle::from_dir("./static", None) + .with_name("htmx") + .build() +} diff --git a/extensions/pagetop-htmx/src/hx.rs b/extensions/pagetop-htmx/src/hx.rs new file mode 100644 index 00000000..f1f1f666 --- /dev/null +++ b/extensions/pagetop-htmx/src/hx.rs @@ -0,0 +1,549 @@ +//! Constantes para los atributos y valores de HTMX 2. +//! +//! Usar estas constantes en lugar de literales evita errores tipográficos en tiempo de compilación. +//! Una mala declaración como `"hx-gte"` no genera ningún error en tiempo de ejecución, falla +//! silenciosamente. Con constantes, el compilador lo detecta de inmediato. +//! +//! # Atributos estáticos en `html!` +//! +//! Para valores conocidos en tiempo de compilación, los atributos `hx-*` pueden escribirse +//! directamente en la macro `html!` sin necesidad de [`Props`](pagetop::html::Props): +//! +//! ```rust,no_run +//! use pagetop::prelude::*; +//! +//! let markup = html! { +//! button hx-get="/api/items" hx-target="#list" hx-swap="outerHTML" { "Load" } +//! }; +//! ``` +//! +//! # Atributos dinámicos con [`Props`](pagetop::html::Props) +//! +//! Cuando los valores se construyen en tiempo de ejecución o se inyectan desde una extensión, +//! puedes usar [`Props`](pagetop::html::Props) combinado con las constantes de este módulo: +//! +//! ```rust,no_run +//! use pagetop::prelude::*; +//! use pagetop_htmx::hx; +//! +//! let endpoint = "/api/items"; // Calculado en tiempo de ejecución. +//! +//! let props = Props::new(hx::GET, endpoint) +//! .with_prop(PropsOp::set(hx::TARGET, "#list")) +//! .with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML)); +//! +//! let markup = html! { +//! button (props) { "Load" } +//! }; +//! ``` +//! +//! # Integración en componentes +//! +//! El patrón recomendado es añadir un campo `props: Props` al componente y exponerlo con +//! `with_prop()`. Cualquier extensión puede entonces inyectar atributos HTMX sin que el componente +//! ni el tema necesiten conocer HTMX: +//! +//! ```rust,no_run +//! use pagetop::prelude::*; +//! use pagetop_htmx::hx; +//! +//! #[derive(AutoDefault, Getters)] +//! pub struct MyButton { +//! props: Props, +//! } +//! +//! impl MyButton { +//! pub fn new() -> Self { Self::default() } +//! +//! #[builder_fn] +//! pub fn with_prop(mut self, op: PropsOp) -> Self { +//! self.props.alter_prop(op); +//! self +//! } +//! } +//! +//! MyButton::new() +//! .with_prop(PropsOp::set(hx::POST, "/api/save")) +//! .with_prop(PropsOp::set(hx::TARGET, "#message")) +//! .with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML)); +//! ``` +//! +//! # Eventos en línea +//! +//! Para el atributo `hx-on:*` (cuyo nombre incluye el evento y no puede ser una constante) usa las +//! funciones [`on()`] y [`on_htmx()`]: +//! +//! ```rust,no_run +//! use pagetop::prelude::*; +//! use pagetop_htmx::hx; +//! +//! // Evento nativo del DOM: hx-on:click="..." +//! // Evento propio de HTMX: hx-on::after-swap="..." +//! let props = Props::new(hx::on("click"), "this.classList.toggle('active')") +//! .with_prop(PropsOp::set(hx::on_htmx("after-swap"), "console.log('done')")); +//! ``` + +// **< HTTP Methods >******************************************************************************* + +/// Realiza una petición GET al servidor y aplica la respuesta al objetivo. +/// +/// Es el atributo HTMX más común: carga contenido desde el servidor sin recargar la página. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// let props = Props::new(hx::GET, "/api/search") +/// .with_prop(PropsOp::set(hx::TARGET, "#results")); +/// ``` +pub const GET: &str = "hx-get"; + +/// Realiza una petición POST al servidor. +/// +/// Se usa habitualmente para enviar datos de formulario o acciones que modifican el estado del +/// servidor. Para subida de ficheros, combinar con [`ENCODING`] = `"multipart/form-data"`. +pub const POST: &str = "hx-post"; + +/// Realiza una petición PUT al servidor. +pub const PUT: &str = "hx-put"; + +/// Realiza una petición PATCH al servidor. +pub const PATCH: &str = "hx-patch"; + +/// Realiza una petición DELETE al servidor. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// // Al eliminar un elemento, reemplazarlo con respuesta vacía borra el nodo del DOM. +/// let props = Props::new(hx::DELETE, "/api/item/42") +/// .with_prop(PropsOp::set(hx::TARGET, "closest li")) +/// .with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML)); +/// ``` +pub const DELETE: &str = "hx-delete"; + +// **< Target and Swap >**************************************************************************** + +/// Selector CSS del elemento que recibirá la respuesta. Por defecto, el elemento mismo. +/// +/// Además de selectores CSS estándar, HTMX acepta `"this"` (el elemento), `"closest X"` (ancestro +/// más próximo), `"find X"` (descendiente) y `"next X"` / `"previous X"`. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// let props = Props::new(hx::GET, "/api/detalles") +/// .with_prop(PropsOp::set(hx::TARGET, "closest article")); +/// ``` +pub const TARGET: &str = "hx-target"; + +/// Cómo se inserta la respuesta en el DOM. Por defecto, `innerHTML`. +/// +/// Los valores estándar están disponibles en el sub-módulo [`swap`]. Además del modo base, se +/// pueden añadir modificadores separados por espacio: retrasos (`swap:200ms`), tiempo de +/// asentamiento (`settle:300ms`), scroll (`scroll:top`) y foco (`focus-scroll:true`). +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// // Reemplaza el elemento completo con una transición de 300 ms. +/// let props = Props::new(hx::SWAP, "outerHTML swap:300ms"); +/// // O usando la constante tipada más los modificadores: +/// let props = Props::new(hx::SWAP, format!("{} swap:300ms", hx::swap::OUTER_HTML)); +/// ``` +pub const SWAP: &str = "hx-swap"; + +/// Sustituye fuera de banda el elemento del DOM cuyo `id` coincida con el indicado. +/// +/// La respuesta del servidor puede incluir elementos marcados con `hx-swap-oob="true"`: HTMX los +/// extrae y actualiza el DOM en la posición correcta, independientemente del objetivo principal. +pub const SWAP_OOB: &str = "hx-swap-oob"; + +/// Selector CSS del fragmento de la respuesta que se insertará en el objetivo. +/// +/// Permite devolver una página completa desde el servidor y que HTMX extraiga sólo la parte +/// relevante, facilitando la reutilización de rutas existentes. +pub const SELECT: &str = "hx-select"; + +/// Selector CSS de fragmentos de la respuesta que se sustituyen fuera de banda. +pub const SELECT_OOB: &str = "hx-select-oob"; + +// **< Trigger >************************************************************************************ + +/// Evento que activa la petición. Por defecto, `click` en botones y links, `change` en inputs. +/// +/// Los valores simples están disponibles en el sub-módulo [`trigger`]. Las expresiones de disparo +/// compuestas se escriben como literales de cadena: +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// // Buscar mientras se escribe, con 400 ms de espera y sólo si el valor cambia: +/// let props = Props::new(hx::GET, "/api/search") +/// .with_prop(PropsOp::set(hx::TRIGGER, "keyup changed delay:400ms")) +/// .with_prop(PropsOp::set(hx::TARGET, "#results")); +/// +/// // Disparar una vez al cargar la página: +/// let lazy = Props::new(hx::GET, "/api/stats") +/// .with_prop(PropsOp::set(hx::TRIGGER, "load once")); +/// +/// // Polling cada 5 segundos: +/// let poll = Props::new(hx::GET, "/api/estado") +/// .with_prop(PropsOp::set(hx::TRIGGER, "every 5s")); +/// ``` +pub const TRIGGER: &str = "hx-trigger"; + +/// Convierte en AJAX todos los enlaces y formularios del elemento y sus descendientes. +/// +/// El valor debe ser `"true"` o `"false"`. Cuando vale `"true"`, las respuestas se aplican al +/// `` por defecto; se puede combinar con [`TARGET`] para redirigirlas. +pub const BOOST: &str = "hx-boost"; + +/// Empuja la URL de la respuesta al historial del navegador. +/// +/// Acepta `"true"` (usa la URL de la petición), `"false"` (desactiva) o una URL concreta. Permite +/// navegación con el botón atrás manteniendo el comportamiento SPA. +pub const PUSH_URL: &str = "hx-push-url"; + +/// Reemplaza la URL actual en el historial sin añadir una nueva entrada. +/// +/// Acepta `"true"`, `"false"` o una URL concreta. Útil cuando la petición refina la vista sin que +/// deba ser un paso independiente en el historial. +pub const REPLACE_URL: &str = "hx-replace-url"; + +/// Sincroniza las peticiones del elemento con las de otros elementos. +/// +/// Formato: `"selector:estrategia"`. Estrategias disponibles: `drop` (descarta la nueva si hay una +/// en curso), `abort` (cancela la nueva), `replace` (cancela la anterior), `queue first|last|all` +/// (encola). Ejemplo: `"#form:abort"`. +pub const SYNC: &str = "hx-sync"; + +// **< Request Data >******************************************************************************* + +/// Selector CSS de elementos adicionales cuyos valores se incluyen en la petición. +/// +/// Acepta selectores CSS estándar más las extensiones de HTMX: `"this"`, `"closest X"`, `"find X"`. +/// Útil para incluir campos de un formulario padre en una petición de detalle. +pub const INCLUDE: &str = "hx-include"; + +/// Controla qué parámetros del formulario se envían en la petición. +/// +/// - `"*"` - todos (valor por defecto). +/// - `"none"` - ninguno. +/// - Lista de nombres: `"name surname"` - sólo esos. +/// - Exclusión: `"not surname"` - todos excepto los indicados. +pub const PARAMS: &str = "hx-params"; + +/// Valores extra en JSON que se añaden a los parámetros de la petición. +/// +/// Formato: objeto JSON. Los valores sobreescriben parámetros del formulario con el mismo nombre. +/// Admite JavaScript con el prefijo `js:`: `"js:{date: new Date().toISOString()}"`. +pub const VALS: &str = "hx-vals"; + +/// Cabeceras extra en JSON que se añaden a la petición. +/// +/// Formato: objeto JSON. Permiten enviar contexto (token de sesión, versión de API, etc.) sin +/// exponerlo en los parámetros visibles del formulario. +pub const HEADERS: &str = "hx-headers"; + +/// Codificación de la petición. Por defecto, `"application/x-www-form-urlencoded"`. +/// +/// Usar `"multipart/form-data"` para peticiones que incluyan campos de tipo `file`. +pub const ENCODING: &str = "hx-encoding"; + +// **< Element Behavior >*************************************************************************** + +/// Selector CSS del indicador de carga que se muestra mientras dura la petición. +/// +/// El elemento indicado recibe la clase `htmx-request` durante la petición. Por defecto, si no se +/// especifica, la recibe el propio elemento que realiza la petición. +pub const INDICATOR: &str = "hx-indicator"; + +/// Selector CSS de elementos que se deshabilitan mientras dura la petición. +/// +/// Añade el atributo `disabled` durante la petición y lo elimina al terminar. Evita envíos +/// duplicados al hacer clic varias veces. +pub const DISABLED_ELT: &str = "hx-disabled-elt"; + +/// Muestra un diálogo de confirmación (`window.confirm`) antes de enviar la petición. +/// +/// Si el usuario cancela, la petición no se realiza. El valor es el texto del mensaje. +pub const CONFIRM: &str = "hx-confirm"; + +/// Muestra un `prompt` de texto y envía el resultado como cabecera `HX-Prompt`. +/// +/// Si el usuario cancela el prompt, la petición no se realiza. +pub const PROMPT: &str = "hx-prompt"; + +/// Activa la validación HTML5 del formulario antes de enviar la petición. +/// +/// Si algún campo no supera la validación nativa del navegador, la petición se cancela. +pub const VALIDATE: &str = "hx-validate"; + +/// Preserva el elemento entre respuestas HTMX. +/// +/// El elemento debe tener un `id` único. HTMX no lo destruye ni lo recrea al aplicar la respuesta, +/// manteniendo su estado interno (p. ej. posición de reproducción de un vídeo). +pub const PRESERVE: &str = "hx-preserve"; + +// **< Config and Extensions >********************************************************************** + +/// Activa una o varias extensiones HTMX en el elemento y sus descendientes. +/// +/// Las extensiones se identifican por nombre y se separan con comas. Extensiones comunes: +/// - `"ws"` - soporte WebSocket. +/// - `"sse"` - soporte Server-Sent Events. +/// - `"json-enc"` - codifica la petición como JSON en lugar de form-urlencoded. +/// - `"loading-states"` - gestión avanzada de estados de carga. +pub const EXT: &str = "hx-ext"; + +/// Atributos HTMX que los elementos descendientes NO heredarán de este elemento. +/// +/// Acepta una lista de atributos separados por comas o `"*"` para bloquear toda herencia. +pub const DISINHERIT: &str = "hx-disinherit"; + +/// Atributos HTMX que los elementos descendientes SÍ heredarán (anula [`DISINHERIT`]). +pub const INHERIT: &str = "hx-inherit"; + +/// Opciones de configuración de la petición en JSON. +/// +/// Claves disponibles: `timeout` (ms), `credentials` (`"include"`, `"omit"`...), `noHeaders` +/// (bool), `getWithBody` (bool). +pub const REQUEST: &str = "hx-request"; + +/// Controla si este elemento participa en el historial del navegador. +/// +/// Con el valor `"false"`, las peticiones de este elemento no se guardan en el historial aunque +/// [`PUSH_URL`] esté activo en un elemento padre. +pub const HISTORY: &str = "hx-history"; + +/// Designa el elemento como contenedor del historial del navegador. +/// +/// HTMX guarda y restaura el contenido de este elemento al navegar hacia atrás/adelante. Sólo debe +/// haber un elemento con este atributo en la página. +pub const HISTORY_ELT: &str = "hx-history-elt"; + +/// Desactiva el procesamiento HTMX en el elemento y todos sus descendientes. +/// +/// Útil para aislar zonas del DOM gestionadas por otra librería o para desactivar HTMX en secciones +/// de contenido generado dinámicamente donde no debe intervenir. +pub const DISABLE: &str = "hx-disable"; + +// **< Inline Events (hx-on) >********************************************************************** + +/// Genera `hx-on:{event}` para escuchar eventos nativos del DOM en línea. +/// +/// Es la alternativa de HTMX a los manejadores `on*` de HTML (`onclick`, `onmouseenter`, ...). La +/// diferencia clave está en cómo los trata el navegador bajo una política CSP (*Content Security +/// Policy*): los atributos `on*` son JavaScript en línea y quedan bloqueados si la CSP no incluye +/// `'unsafe-inline'`; en cambio, `hx-on:*` es un atributo de datos que HTMX lee e interpreta desde +/// su propio código ya autorizado, por lo que la CSP no lo bloquea. +/// +/// La CSP puede definirla el servidor en la cabecera HTTP `Content-Security-Policy`, o la +/// aplicación en una etiqueta `` en el `` del +/// documento. En la práctica, pocas aplicaciones configuran una CSP estricta, pero es una buena +/// práctica de seguridad que conviene tener en cuenta. +/// +/// El valor es código JavaScript que se ejecuta cuando el evento se dispara; `event` contiene el +/// objeto del evento. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// let props = Props::new(hx::on("click"), "this.classList.toggle('active')") +/// .with_prop(PropsOp::set(hx::on("mouseenter"), "this.style.opacity='0.8'")); +/// ``` +pub fn on(event: &str) -> String { + format!("hx-on:{event}") +} + +/// Genera `hx-on::{event}` para escuchar eventos propios de HTMX en línea. +/// +/// Los eventos de HTMX usan un doble carácter dos-puntos (`hx-on::evento`). El ciclo de vida +/// completo incluye `before-request`, `after-request`, `before-swap`, `after-swap`, +/// `before-settle`, `after-settle`, `after-on-load`, `history-restore`, entre otros. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// let props = Props::new(hx::on_htmx("before-request"), "console.log('enviando...')") +/// .with_prop(PropsOp::set(hx::on_htmx("after-swap"), "initTooltips()")); +/// ``` +pub fn on_htmx(event: &str) -> String { + format!("hx-on::{event}") +} + +// **< HTMX Request Headers >*********************************************************************** + +/// Nombres de las cabeceras que HTMX envía con cada petición AJAX. +/// +/// Están en minúsculas porque así las normaliza el módulo `http`. Se pueden usar con +/// [`HttpRequest::headers()`](pagetop::web::HttpRequest::headers) para leer sus valores +/// directamente, aunque lo habitual es usar el trait [`HtmxRequestExt`](crate::HtmxRequestExt). +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// use pagetop_htmx::hx; +/// +/// async fn handler(request: HttpRequest) { +/// if let Some(target) = request.headers().get(hx::request::TARGET) { +/// // El elemento objetivo tenía este id. +/// } +/// } +/// ``` +pub mod request { + /// Siempre `"true"` en peticiones HTMX. Permite distinguirlas de navegaciones directas. + pub const REQUEST: &str = "hx-request"; + /// `"true"` si la petición viene de un enlace o formulario con `hx-boost`. + pub const BOOSTED: &str = "hx-boosted"; + /// URL de la página activa en el navegador cuando se realizó la petición. + pub const CURRENT_URL: &str = "hx-current-url"; + /// `"true"` si la petición es una restauración del historial del navegador. + pub const HISTORY_RESTORE_REQUEST: &str = "hx-history-restore-request"; + /// Texto introducido por el usuario en un diálogo `hx-prompt`. + pub const PROMPT: &str = "hx-prompt"; + /// Valor del atributo `id` del elemento objetivo de la petición. + pub const TARGET: &str = "hx-target"; + /// Valor del atributo `id` del elemento que disparó la petición. + pub const TRIGGER: &str = "hx-trigger"; + /// Valor del atributo `name` del elemento que disparó la petición. + pub const TRIGGER_NAME: &str = "hx-trigger-name"; +} + +// **< HTMX Response Headers >********************************************************************** + +/// Cabeceras de respuesta HTTP para HTMX. +/// +/// Se pueden usar con [`HeaderMap`](pagetop::web::http::HeaderMap) para construir respuestas +/// manualmente, aunque lo habitual es usar el constructor [`HtmxResponse`](crate::HtmxResponse). +/// +/// ```rust,no_run +/// use pagetop_htmx::hx; +/// use pagetop::web::http::{HeaderMap, HeaderName, HeaderValue}; +/// +/// let mut headers = HeaderMap::new(); +/// headers.insert( +/// hx::response::TRIGGER.parse::().unwrap(), +/// HeaderValue::from_static("itemAdded"), +/// ); +/// ``` +pub mod response { + /// Redirige mediante AJAX a la URL o configuración JSON indicada. Ver + /// [`HtmxResponse::location()`](crate::HtmxResponse::location). + pub const LOCATION: &str = "HX-Location"; + /// Empuja la URL indicada al historial del navegador. Ver + /// [`HtmxResponse::push_url()`](crate::HtmxResponse::push_url). + pub const PUSH_URL: &str = "HX-Push-Url"; + /// Provoca una redirección completa del navegador. Ver + /// [`HtmxResponse::redirect()`](crate::HtmxResponse::redirect). + pub const REDIRECT: &str = "HX-Redirect"; + /// Provoca una recarga completa de la página. Ver + /// [`HtmxResponse::refresh()`](crate::HtmxResponse::refresh). + pub const REFRESH: &str = "HX-Refresh"; + /// Reemplaza la URL actual en el historial. Ver + /// [`HtmxResponse::replace_url()`](crate::HtmxResponse::replace_url). + pub const REPLACE_URL: &str = "HX-Replace-Url"; + /// Anula el `hx-swap` del elemento. Ver + /// [`HtmxResponse::reswap()`](crate::HtmxResponse::reswap). + pub const RESWAP: &str = "HX-Reswap"; + /// Anula el `hx-target` del elemento. Ver + /// [`HtmxResponse::retarget()`](crate::HtmxResponse::retarget). + pub const RETARGET: &str = "HX-Retarget"; + /// Anula el `hx-select` del elemento. Ver + /// [`HtmxResponse::reselect()`](crate::HtmxResponse::reselect). + pub const RESELECT: &str = "HX-Reselect"; + /// Dispara eventos JavaScript al completar la respuesta. Ver + /// [`HtmxResponse::trigger()`](crate::HtmxResponse::trigger). + pub const TRIGGER: &str = "HX-Trigger"; + /// Dispara eventos tras la fase *settle*. Ver + /// [`HtmxResponse::trigger_after_settle()`](crate::HtmxResponse::trigger_after_settle). + pub const TRIGGER_AFTER_SETTLE: &str = "HX-Trigger-After-Settle"; + /// Dispara eventos tras el *swap*. Ver + /// [`HtmxResponse::trigger_after_swap()`](crate::HtmxResponse::trigger_after_swap). + pub const TRIGGER_AFTER_SWAP: &str = "HX-Trigger-After-Swap"; +} + +// **< hx-swap Values >***************************************************************************** + +/// Valores estándar del atributo [`SWAP`] (`hx-swap`). +/// +/// Se pueden combinar con modificadores separados por espacio: +/// - `swap:Xms` - tiempo de espera antes de realizar el intercambio. +/// - `settle:Xms` - tiempo de espera antes de quitar las clases de transición. +/// - `scroll:top` / `scroll:bottom` - desplaza el objetivo tras el intercambio. +/// - `show:top` / `show:bottom` - hace visible el objetivo tras el intercambio. +/// - `focus-scroll:true` - sigue al elemento enfocado. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// // Reemplaza el elemento con una transición de 200 ms y desplaza al inicio: +/// let props = Props::new(hx::SWAP, format!("{} swap:200ms scroll:top", hx::swap::OUTER_HTML)); +/// ``` +pub mod swap { + /// Reemplaza el contenido interior del objetivo (valor por defecto de HTMX). + pub const INNER_HTML: &str = "innerHTML"; + /// Reemplaza el elemento objetivo completo. + pub const OUTER_HTML: &str = "outerHTML"; + /// Inserta la respuesta antes de la etiqueta de apertura del objetivo. + pub const BEFORE_BEGIN: &str = "beforebegin"; + /// Inserta la respuesta al inicio del contenido del objetivo. + pub const AFTER_BEGIN: &str = "afterbegin"; + /// Inserta la respuesta al final del contenido del objetivo. + pub const BEFORE_END: &str = "beforeend"; + /// Inserta la respuesta después de la etiqueta de cierre del objetivo. + pub const AFTER_END: &str = "afterend"; + /// Elimina el elemento objetivo independientemente de la respuesta. + pub const DELETE: &str = "delete"; + /// No realiza ningún intercambio; útil cuando sólo importan las cabeceras de respuesta. + pub const NONE: &str = "none"; +} + +// **< hx-trigger Values >************************************************************************** + +/// Eventos comunes del atributo [`TRIGGER`] (`hx-trigger`). +/// +/// Estos valores cubren los disparadores más simples. Las expresiones de disparo compuestas deben +/// escribirse como literales de cadena. Modificadores disponibles: +/// - `once` - se dispara sólo la primera vez. +/// - `changed` - sólo si el valor del elemento ha cambiado. +/// - `delay:Xms` - espera antes de disparar (se cancela si el evento vuelve a ocurrir). +/// - `throttle:Xms` - limita la frecuencia máxima de disparo. +/// - `from:selector` - escucha el evento en otro elemento. +/// - `target:selector` - sólo si el evento viene del selector indicado. +/// - `consume` - evita que el evento se propague a otros elementos HTMX. +/// - `queue:first|last|all|none` - política de cola cuando llegan eventos consecutivos. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # use pagetop_htmx::hx; +/// // Búsqueda progresiva: petición 400 ms después de que el usuario deje de escribir. +/// let search = Props::new(hx::TRIGGER, "keyup changed delay:400ms"); +/// +/// // Carga diferida al entrar en el viewport, una sola vez. +/// let lazy = Props::new(hx::TRIGGER, "intersect once"); +/// +/// // Polling: actualiza cada 10 segundos mientras el elemento esté en el DOM. +/// let poll = Props::new(hx::TRIGGER, "every 10s"); +/// +/// // Múltiples eventos: clic o pulsación de Enter en el campo. +/// let multi = Props::new(hx::TRIGGER, "click, keyup[key=='Enter']"); +/// +/// // Escucha un evento personalizado emitido desde otro elemento. +/// let custom = Props::new(hx::TRIGGER, "itemAdded from:body"); +/// ``` +pub mod trigger { + /// Se dispara al hacer clic (valor por defecto en la mayoría de elementos interactivos). + pub const CLICK: &str = "click"; + /// Se dispara cuando el valor del elemento cambia (valor por defecto en `input`/`select`). + pub const CHANGE: &str = "change"; + /// Se dispara al enviar un formulario. + pub const SUBMIT: &str = "submit"; + /// Se dispara al soltar una tecla. + pub const KEYUP: &str = "keyup"; + /// Se dispara cuando la página termina de cargarse. + pub const LOAD: &str = "load"; + /// Se dispara cuando el elemento entra en el área visible del *viewport* al hacer scroll. + pub const REVEALED: &str = "revealed"; + /// Se dispara cuando el elemento intersecta con el *viewport* (Intersection Observer API). + pub const INTERSECT: &str = "intersect"; +} diff --git a/extensions/pagetop-htmx/src/lib.rs b/extensions/pagetop-htmx/src/lib.rs new file mode 100644 index 00000000..e65f310c --- /dev/null +++ b/extensions/pagetop-htmx/src/lib.rs @@ -0,0 +1,129 @@ +/*! +
+ +

PageTop HTMX

+ +

Extensión para PageTop que integra HTMX para enriquecer las páginas con interacciones dinámicas.

+ +[![Doc API](https://img.shields.io/docsrs/pagetop-htmx?label=Doc%20API&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-htmx) +[![Crates.io](https://img.shields.io/crates/v/pagetop-htmx.svg?style=for-the-badge&logo=ipfs)](https://crates.io/crates/pagetop-htmx) +[![Descargas](https://img.shields.io/crates/d/pagetop-htmx.svg?label=Descargas&style=for-the-badge&logo=transmission)](https://crates.io/crates/pagetop-htmx) +[![Licencia](https://img.shields.io/badge/license-MIT%2FApache-blue.svg?label=Licencia&style=for-the-badge)](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-htmx#licencia) + +
+ +## Sobre PageTop + +[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web +clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y +configurables, basadas en HTML, CSS y JavaScript. + +## Guía rápida + +**Añade la dependencia** a tu `Cargo.toml`: + +```toml +[dependencies] +pagetop-htmx = { ... } +``` + +**Declara la extensión** en tu aplicación (o extensión que la requiera). Recuerda que el orden en +`dependencies()` determina la prioridad relativa frente a las otras extensiones: + +```rust +use pagetop::prelude::*; + +struct MyApp; + +impl Extension for MyApp { + fn dependencies(&self) -> Vec { + vec![ + // ... + &pagetop_htmx::Htmx + // ... + ] + } +} +``` + +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: + +```rust +use pagetop::prelude::*; + +async fn homepage(request: HttpRequest) -> Result { + Page::new(request) + .with_child(Html::with(|_| html! { + button hx-get="/api/hello" hx-target="#result" { + "Say hello" + } + div #result {} + })) + .render() +} +``` +*/ + +use pagetop::prelude::*; + +pub mod hx; + +mod request; +pub use request::HtmxRequestExt; + +mod response; +pub use response::HtmxResponse; + +include_locales!(LOCALES_HTMX); + +/// Integra HTMX 2 en cualquier aplicación PageTop. +/// +/// 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. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// +/// struct MyApp; +/// +/// impl Extension for MyApp { +/// fn dependencies(&self) -> Vec { +/// vec![ +/// // ... +/// &pagetop_htmx::Htmx +/// // ... +/// ] +/// } +/// } +/// ``` +pub struct Htmx; + +impl Extension for Htmx { + fn name(&self) -> L10n { + L10n::t("extension_name", &LOCALES_HTMX) + } + + fn description(&self) -> L10n { + L10n::t("extension_description", &LOCALES_HTMX) + } + + fn actions(&self) -> Vec { + actions![action::page::BeforeRenderBody::new(add_htmx_script)] + } + + fn configure_router(&self, router: Router) -> Router { + serve_static_files!(router, [htmx] => "/htmx"); + router + } +} + +fn add_htmx_script(page: &mut Page) { + page.alter_assets(AssetsOp::AddJavaScript( + JavaScript::defer("/htmx/js/htmx.min.js").with_version("2.0.10"), + )); +} diff --git a/extensions/pagetop-htmx/src/locale/en-US/extension.ftl b/extensions/pagetop-htmx/src/locale/en-US/extension.ftl new file mode 100644 index 00000000..c6580f02 --- /dev/null +++ b/extensions/pagetop-htmx/src/locale/en-US/extension.ftl @@ -0,0 +1,2 @@ +extension_name = HTMX +extension_description = Integrates HTMX to enrich pages with dynamic interactions. diff --git a/extensions/pagetop-htmx/src/locale/es-ES/extension.ftl b/extensions/pagetop-htmx/src/locale/es-ES/extension.ftl new file mode 100644 index 00000000..1a32e44a --- /dev/null +++ b/extensions/pagetop-htmx/src/locale/es-ES/extension.ftl @@ -0,0 +1,2 @@ +extension_name = HTMX +extension_description = Integra HTMX para enriquecer las páginas con interacciones dinámicas. \ No newline at end of file diff --git a/extensions/pagetop-htmx/src/request.rs b/extensions/pagetop-htmx/src/request.rs new file mode 100644 index 00000000..32b68f86 --- /dev/null +++ b/extensions/pagetop-htmx/src/request.rs @@ -0,0 +1,132 @@ +//! Implementación de [`HtmxRequestExt`] para [`pagetop::web::HttpRequest`]. + +use pagetop::prelude::*; + +// **< HtmxRequestExt >***************************************************************************** + +/// Extiende [`HttpRequest`](pagetop::web::HttpRequest) con métodos para detectar y leer peticiones +/// HTMX. +/// +/// HTMX añade cabeceras especiales a cada petición AJAX. Este trait permite acceder a ellas de +/// forma expresiva, sin manipular [`pagetop::web::http::HeaderMap`] directamente. +/// +/// El patrón más común es devolver una respuesta distinta según si la petición viene de HTMX +/// (fragmento parcial) o de una navegación directa (página completa). Cuando las dos ramas retornan +/// tipos distintos, se usa [`pagetop::web::Response`] como tipo común: +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// use pagetop_htmx::{HtmxRequestExt, HtmxResponse}; +/// +/// async fn list_items(request: HttpRequest) -> Response { +/// if request.is_htmx() { +/// // Fragmento parcial con cabeceras HTMX opcionales. +/// HtmxResponse::new(html! { ul { li { "Item 1" } li { "Item 2" } } }) +/// .into_response() +/// } else { +/// // Página completa para navegación directa. +/// Page::new(request) +/// .with_child(Html::with(|_| html! { +/// ul { li { "Item 1" } li { "Item 2" } } +/// })) +/// .render() +/// .into_response() +/// } +/// } +/// ``` +/// +/// Los nombres de cabecera como constantes están en [`crate::hx::request`]. +pub trait HtmxRequestExt { + /// Devuelve `true` si la petición proviene de HTMX (`HX-Request: true`). + /// + /// Es la comprobación principal para distinguir una petición HTMX de una navegación directa del + /// navegador. + fn is_htmx(&self) -> bool; + + /// Devuelve `true` si la petición proviene de un enlace o formulario con `hx-boost`. + /// + /// Las peticiones boosted son HTMX pero conservan la semántica de navegación completa: el + /// objetivo por defecto es ``. Puede ser útil para no devolver un fragmento parcial en + /// este caso. + fn is_boosted(&self) -> bool; + + /// Devuelve `true` si la petición es una restauración del historial del navegador. + /// + /// Ocurre cuando el usuario navega hacia atrás o adelante y HTMX necesita restaurar el estado + /// de la página. En este caso conviene devolver la página completa. + fn is_history_restore(&self) -> bool; + + /// URL de la página activa en el navegador en el momento de la petición (`HX-Current-URL`). + /// + /// Útil para redirigir o actualizar la URL del historial en función de dónde estaba el usuario. + fn hx_current_url(&self) -> Option<&str>; + + /// Valor del atributo `id` del elemento objetivo de la petición (`HX-Target`). + /// + /// Si el elemento objetivo no tiene `id`, esta cabecera no se envía. + fn hx_target(&self) -> Option<&str>; + + /// Valor del atributo `id` del elemento que disparó la petición (`HX-Trigger`). + /// + /// Si el elemento disparador no tiene `id`, esta cabecera no se envía. Ver también + /// [`hx_trigger_name()`](Self::hx_trigger_name). + fn hx_trigger_id(&self) -> Option<&str>; + + /// Valor del atributo `name` del elemento que disparó la petición (`HX-Trigger-Name`). + /// + /// Especialmente útil en formularios, donde el elemento disparador puede tener `name` pero no + /// `id`. + fn hx_trigger_name(&self) -> Option<&str>; + + /// Texto introducido por el usuario en un diálogo `hx-prompt` (`HX-Prompt`). + /// + /// Sólo presente si el elemento tiene el atributo `hx-prompt` y el usuario no canceló el + /// diálogo. + fn hx_prompt(&self) -> Option<&str>; +} + +impl HtmxRequestExt for HttpRequest { + fn is_htmx(&self) -> bool { + header_equals(self.headers(), "hx-request", "true") + } + + fn is_boosted(&self) -> bool { + header_equals(self.headers(), "hx-boosted", "true") + } + + fn is_history_restore(&self) -> bool { + header_equals(self.headers(), "hx-history-restore-request", "true") + } + + fn hx_current_url(&self) -> Option<&str> { + header_str(self.headers(), "hx-current-url") + } + + fn hx_target(&self) -> Option<&str> { + header_str(self.headers(), "hx-target") + } + + fn hx_trigger_id(&self) -> Option<&str> { + header_str(self.headers(), "hx-trigger") + } + + fn hx_trigger_name(&self) -> Option<&str> { + header_str(self.headers(), "hx-trigger-name") + } + + fn hx_prompt(&self) -> Option<&str> { + header_str(self.headers(), "hx-prompt") + } +} + +fn header_equals(headers: &web::http::HeaderMap, name: &str, expected: &str) -> bool { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(|v| v == expected) + .unwrap_or(false) +} + +fn header_str<'a>(headers: &'a web::http::HeaderMap, name: &str) -> Option<&'a str> { + headers.get(name).and_then(|v| v.to_str().ok()) +} diff --git a/extensions/pagetop-htmx/src/response.rs b/extensions/pagetop-htmx/src/response.rs new file mode 100644 index 00000000..66550cf2 --- /dev/null +++ b/extensions/pagetop-htmx/src/response.rs @@ -0,0 +1,228 @@ +//! Implementación de [`HtmxResponse`] e [`IntoResponse`](pagetop::web::IntoResponse) para HTMX. + +use pagetop::prelude::*; + +// **< HtmxResponse >******************************************************************************* + +/// Generador de respuestas HTML parciales con cabeceras HTMX. +/// +/// En una aplicación HTMX, los *handlers* del servidor devuelven con frecuencia fragmentos HTML +/// parciales acompañados de cabeceras especiales que instruyen al cliente sobre qué hacer con la +/// respuesta: actualizar la URL del historial, disparar eventos JavaScript, redirigir, etc. +/// +/// Implementa [`IntoResponse`](pagetop::web::IntoResponse), por lo que puede devolverse +/// directamente desde cualquier *handler*. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// use pagetop_htmx::{HtmxResponse, hx}; +/// +/// async fn add_item(request: HttpRequest) -> impl IntoResponse { +/// let new_item = html! { li #item-42 { "New item" } }; +/// +/// HtmxResponse::new(new_item) +/// .retarget("#list") +/// .reswap(hx::swap::BEFORE_END) +/// .push_url("/items") +/// .trigger("itemAdded") +/// } +/// ``` +/// +/// # Respuestas de sólo cabeceras +/// +/// Cuando la respuesta no lleva cuerpo HTML (por ejemplo, una redirección o un refresco), usa +/// [`HtmxResponse::empty()`](Self::empty): +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// use pagetop_htmx::HtmxResponse; +/// +/// async fn delete_item() -> impl IntoResponse { +/// HtmxResponse::empty().redirect("/items") +/// } +/// ``` +/// +/// # Construcción +/// +/// - [`HtmxResponse::new(markup)`](Self::new), con el fragmento HTML. +/// - [`HtmxResponse::empty()`](Self::empty), sin cuerpo, sólo cabeceras. +/// +/// # Cabeceras disponibles +/// +/// Los nombres de cabecera como constantes están en [`crate::hx::response`]. +/// +/// # Múltiples eventos en `trigger` +/// +/// Para disparar varios eventos en una sola llamada, pasa una cadena con comas o un objeto JSON: +/// +/// ```rust,no_run +/// use pagetop::prelude::*; +/// use pagetop_htmx::HtmxResponse; +/// +/// // Dos eventos sin datos: +/// HtmxResponse::empty().trigger("itemAdded, listUpdated"); +/// +/// // Evento con datos en JSON: +/// HtmxResponse::empty().trigger(r#"{"itemAdded": {"id": 42}}"#); +/// ``` +pub struct HtmxResponse { + markup: Markup, + headers: web::http::HeaderMap, +} + +impl HtmxResponse { + /// Crea una respuesta con el fragmento HTML indicado. + pub fn new(markup: Markup) -> Self { + Self { + markup, + headers: web::http::HeaderMap::new(), + } + } + + /// Crea una respuesta sin cuerpo HTML, útil para respuestas de sólo cabeceras. + pub fn empty() -> Self { + Self::new(html! {}) + } + + // **< HtmxResponse BUILDER >******************************************************************* + + /// Hace que HTMX realice una navegación AJAX a la URL indicada sin recargar la página. + /// + /// A diferencia de [`redirect()`](Self::redirect), la navegación usa HTMX y actualiza sólo el + /// objetivo definido por el destino. Acepta una URL o un objeto JSON con claves `path`, + /// `target`, `swap`, `select` y `values` para personalizar la navegación: + /// + /// ```rust,no_run + /// use pagetop::prelude::*; + /// use pagetop_htmx::HtmxResponse; + /// + /// // Navegación simple: + /// HtmxResponse::empty().location("/items"); + /// + /// // Navegación con destino personalizado: + /// HtmxResponse::empty() + /// .location(r##"{"path": "/items", "target": "#content"}"##); + /// ``` + pub fn location(self, url: impl Into) -> Self { + self.set_header(b"hx-location", url) + } + + /// Empuja la URL indicada al historial del navegador. + /// + /// El usuario podrá navegar hacia atrás hasta esa URL. Usar `"false"` para desactivar el empuje + /// aunque esté habilitado por el atributo `hx-push-url` del elemento. + pub fn push_url(self, url: impl Into) -> Self { + self.set_header(b"hx-push-url", url) + } + + /// Reemplaza la URL actual en el historial sin añadir una nueva entrada. + /// + /// Usar `"false"` para desactivar el reemplazo. + pub fn replace_url(self, url: impl Into) -> Self { + self.set_header(b"hx-replace-url", url) + } + + /// Provoca una redirección completa del navegador a la URL indicada. + /// + /// A diferencia de [`location()`](Self::location), esta redirección recarga la página por + /// completo, como un `window.location.href = url` en JavaScript. + pub fn redirect(self, url: impl Into) -> Self { + self.set_header(b"hx-redirect", url) + } + + /// Provoca una recarga completa de la página actual. + /// + /// Equivale a `window.location.reload()` en JavaScript. + pub fn refresh(self) -> Self { + self.set_header(b"hx-refresh", "true") + } + + /// Anula el `hx-target` del elemento y redirige la respuesta al selector CSS indicado. + /// + /// Útil cuando el servidor necesita actualizar un elemento distinto al que realizó la petición, + /// sin modificar el HTML del cliente. + pub fn retarget(self, selector: impl Into) -> Self { + self.set_header(b"hx-retarget", selector) + } + + /// Anula el `hx-swap` del elemento e impone la estrategia de sustitución indicada. + /// + /// Acepta los mismos valores que el atributo `hx-swap`, incluidos modificadores (`swap:200ms`, + /// `scroll:top`, ...). Los valores tipados están en [`crate::hx::swap`]. + pub fn reswap(self, strategy: impl Into) -> Self { + self.set_header(b"hx-reswap", strategy) + } + + /// Anula el `hx-select` del elemento y selecciona el fragmento CSS indicado de la respuesta + /// para insertarlo en el objetivo. + pub fn reselect(self, selector: impl Into) -> Self { + self.set_header(b"hx-reselect", selector) + } + + /// Dispara uno o varios eventos JavaScript en el cliente al completar la respuesta. + /// + /// Los eventos se disparan inmediatamente tras procesar la respuesta. Para disparar eventos con + /// datos o después de otras fases del ciclo HTMX, ver + /// [`trigger_after_settle()`](Self::trigger_after_settle) y + /// [`trigger_after_swap()`](Self::trigger_after_swap). + /// + /// ```rust,no_run + /// use pagetop::prelude::*; + /// use pagetop_htmx::HtmxResponse; + /// + /// // Evento simple: + /// HtmxResponse::empty().trigger("itemAdded"); + /// + /// // Múltiples eventos sin datos: + /// HtmxResponse::empty().trigger("itemAdded, listUpdated"); + /// + /// // Evento con datos en JSON: + /// HtmxResponse::empty().trigger(r#"{"itemAdded": {"id": 42, "name": "Example"}}"#); + /// ``` + pub fn trigger(self, event: impl Into) -> Self { + self.set_header(b"hx-trigger", event) + } + + /// Dispara eventos JavaScript después de que HTMX haya aplicado la respuesta al DOM y haya + /// completado la fase de *settle* (animaciones CSS). + /// + /// Acepta los mismos formatos que [`trigger()`](Self::trigger). + pub fn trigger_after_settle(self, event: impl Into) -> Self { + self.set_header(b"hx-trigger-after-settle", event) + } + + /// Dispara eventos JavaScript después de que HTMX haya aplicado la respuesta al DOM, pero antes + /// de la fase de *settle*. + /// + /// Acepta los mismos formatos que [`trigger()`](Self::trigger). + pub fn trigger_after_swap(self, event: impl Into) -> Self { + self.set_header(b"hx-trigger-after-swap", event) + } + + // Inserta o reemplaza una cabecera. Los nombres deben ser bytes ASCII en minúsculas. + fn set_header(mut self, name: &[u8], value: impl Into) -> Self { + let value = value.into(); + if let (Ok(n), Ok(v)) = ( + web::http::HeaderName::from_bytes(name), + web::http::HeaderValue::from_str(&value), + ) { + self.headers.insert(n, v); + } else { + trace::warn!(value = %value, "HtmxResponse: invalid header value, header discarded"); + } + self + } +} + +impl web::IntoResponse for HtmxResponse { + fn into_response(self) -> Response { + let mut headers = self.headers; + headers.insert( + web::http::header::CONTENT_TYPE, + web::http::HeaderValue::from_static("text/html; charset=utf-8"), + ); + (headers, self.markup.into_string()).into_response() + } +} diff --git a/extensions/pagetop-htmx/static/js/htmx.min.js b/extensions/pagetop-htmx/static/js/htmx.min.js new file mode 100644 index 00000000..3b7ac1ac --- /dev/null +++ b/extensions/pagetop-htmx/static/js/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.10"};Q.onLoad=j;Q.process=Ft;Q.on=ye;Q.off=xe;Q.trigger=ae;Q.ajax=Nn;Q.find=f;Q.findAll=y;Q.closest=g;Q.remove=z;Q.addClass=w;Q.removeClass=b;Q.toggleClass=G;Q.takeClass=W;Q.swap=_e;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=$;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:U,findThisElement:we,filterValues:yn,swap:_e,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:A,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Se,makeFragment:P,mergeObjects:le,makeSettleInfo:Sn,oobSwap:He,querySelectorExt:ce,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function q(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function A(e,t){while(e&&!t(e)){e=c(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;A(t,function(e){return!!(r=o(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function N(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function I(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function D(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=N(t);let r;if(n==="html"){r=new DocumentFragment;const i=I(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=I(t);L(r,i.body);r.title=i.title}else{const i=I('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){D(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function M(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function F(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function X(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function U(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function V(e){try{const t=new URL(e,window.location.href);e=t.pathname+t.search}catch(e){}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function $(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function y(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return y(te(),e)}}function x(){return window}function z(e,t){e=S(e);if(t){x().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function J(e){return e instanceof HTMLElement?e:null}function K(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function w(e,t,n){e=ue(S(e));if(!e){return}if(n){x().setTimeout(function(){w(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function b(e,t,n){let r=ue(S(e));if(!r){return}if(n){x().setTimeout(function(){b(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function G(e,t){e=S(e);e.classList.toggle(t)}function W(e,t){e=S(e);ie(e.parentElement.children,function(e){b(e,t)});w(ue(e),t)}function g(e,t){e=ue(S(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Z(e,t){return e.substring(e.length-t.length)===t}function Y(e){const t=e.trim();if(l(t,"<")&&Z(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=S(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=Y(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),Y(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),Y(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,Y(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=ge(t,Y(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=q(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const u=p(q(t,!!n));i.push(...F(u.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=p(q(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ce(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function S(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function me(e,t,n,r){if(k(t)){return{target:te().body,event:K(e),listener:t,options:n}}else{return{target:S(e),event:K(t),listener:n,options:r}}}function ye(t,n,r,o){Gn(function(){const e=me(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function xe(t,n,r){Gn(function(){const e=me(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const be=te().createElement("output");function ve(t,n){const e=ne(t,n);if(e){if(e==="this"){return[we(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ue(A(t,function(e){return e!==t&&s(ue(e),n)}));if(i){r.push(...ve(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[be]}else{return r}}}}function we(e,t){return ue(A(e,function(e){return a(ue(e),t)!=null}))}function Se(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return we(e,"hx-target")}else{return ce(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ee(e){return Q.config.attributesToSettle.includes(e)}function Ce(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ee(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ee(e.name)){t.setAttribute(e.name,e.value)}})}function Oe(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!Oe(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){Re(t);je(s,e,e,t,i);Te()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o,target:n})}return e}function Te(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function Re(e){ie(y(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function qe(i,e,s){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const e=p(i);const r=e&&e.querySelector(CSS.escape(t.tagName)+"#"+CSS.escape(n));if(r&&r!==e){const o=t.cloneNode();Ce(t,r);s.tasks.push(function(){Ce(t,o)})}}})}function Ae(e){return function(){b(e,Q.config.addedClass);Ft(ue(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=J(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function u(e,t,n,r){qe(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;w(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function _e(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=S(h);const r=g.contextElement?q(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=P(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){x().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){x().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function ze(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(M(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,C)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,Ze);const l=o.length;const u=O(o,/[,\[\s]/);if(u!==""){if(u==="every"){const c={trigger:"every"};O(o,Ze);c.pollInterval=d(O(o,/[,\[\s]/));O(o,Ze);var i=nt(e,o,"event");if(i){c.eventFilter=i}r.push(c)}else{const f={trigger:u};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,Ze);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,C))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,C);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,C))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,C)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,C)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,Ze)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,Ze)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ut(e,t,n){const r=oe(e);r.timeout=x().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ut(e,t,n)}},n.pollInterval)}function ct(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ct(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ue(e);if(ft(n)){E(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,u,e,c,f){const a=oe(l);let t;if(c.from){t=m(l,c.from)}else{t=[l]}if(c.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(c)){a.lastValue.set(c,new WeakMap)}a.lastValue.get(c).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(c.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(c,l,e)){return}const t=oe(e);t.triggerSpec=c;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(c.consume){e.stopPropagation()}if(c.target&&e.target){if(!h(ue(e.target),c.target)){return}}if(c.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(c.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(c);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(c.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");u(l,e);a.throttle=x().setTimeout(function(){a.throttle=null},c.throttle)}}else if(c.delay>0){a.delayed=x().setTimeout(function(){ae(l,"htmx:trigger");u(l,e)},c.delay)}else{ae(l,"htmx:trigger");u(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:c.trigger,listener:s,on:i});i.addEventListener(c.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&B(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){x().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(ft(n)){E(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ce(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ut(ue(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=It(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=It(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ue(e),"button, input[type='submit']")}function Nt(e){return e.form||g(e,"form")}function It(e){const t=At(e.target);if(!t){return}const n=Nt(t);if(!n){return}return oe(n)}function Lt(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){De(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!U()){return null}t=V(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);_e(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){_e(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=ve(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;w(e,Q.config.requestClass)});return t}function nn(e){let t=ve(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;if(!e.hasAttribute("disabled")){e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")}});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){b(e,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0&&e.hasAttribute("data-disabled-by-htmx")){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function cn(e){if(e instanceof HTMLSelectElement&&e.multiple){return F(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return F(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,cn(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){un(e.name,cn(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Nt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const c=s.lastButtonClicked||e;const f=ee(c,"name");ln(f,c.value,o)}const u=ve(e,"hx-include");ie(u,function(e){fn(n,r,i,ue(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=X(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=c;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ce(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){x().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ce(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const u in n){if(n.hasOwnProperty(u)){if(i[u]==null){i[u]=n[u]}}}}return Cn(ue(c(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Nn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:S(r)||be,returnPromise:true})}else{let e=S(r.target);if(r.target&&!e||r.source&&!e&&!S(r.source)){e=be}return he(t,n,S(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function In(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Ln(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const u=i.targetOverride||ue(Se(r));if(u==null||u==be){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let c=oe(r);const f=c.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const N=ee(f,"formmethod");if(N!=null){if(de.includes(N.toLowerCase())){t=N}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:u,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const I=d.split(":");const L=I[0].trim();if(L==="this"){h=we(r,"hx-sync")}else{h=ue(ce(r,L))}d=(I[1]||"drop").trim();c=oe(h);if(d==="drop"&&c.xhr&&c.abortable!==true){re(s);return e}else if(d==="abort"){if(c.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(c.xhr){if(c.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(c.queuedRequests==null){c.queuedRequests=[]}if(p==="first"&&c.queuedRequests.length===0){c.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){c.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){c.queuedRequests=[];c.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;c.xhr=g;c.abortable=B;const m=function(){c.xhr=null;c.abortable=false;if(c.queuedRequests!=null&&c.queuedRequests.length>0){const e=c.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:u})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,u,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(u,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:u,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!Ln(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:u,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=In(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;let l=t.etc.push||ne(e,"hx-push-url");let u=t.etc.replace||ne(e,"hx-replace-url");if(l==="false")l=null;if(u==="false")u=null;const c=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(u){f="replace";a=u}else if(c){f="push";a=s||i}if(a){if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};x().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/src/prelude.rs b/src/prelude.rs index 5e6f7ec1..fbd84da3 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -36,7 +36,7 @@ pub use crate::locale::*; pub use crate::datetime::*; pub use crate::web; -pub use crate::web::{HttpRequest, Router}; +pub use crate::web::{HttpRequest, IntoResponse, Response, Router}; pub use crate::core::{AnyCast, AnyInfo, TypeInfo}; diff --git a/tools/changelog.sh b/tools/changelog.sh index fc2a8a0c..81c85747 100755 --- a/tools/changelog.sh +++ b/tools/changelog.sh @@ -65,6 +65,7 @@ case "$CRATE" in # Extensions --exclude-path "extensions/pagetop-aliner/**/*" --exclude-path "extensions/pagetop-bootsier/**/*" + --exclude-path "extensions/pagetop-htmx/**/*" --exclude-path "extensions/pagetop-seaorm/**/*" ) ;; @@ -76,6 +77,10 @@ case "$CRATE" in CHANGELOG_FILE="extensions/pagetop-bootsier/CHANGELOG.md" PATH_FLAGS=(--include-path "extensions/pagetop-bootsier/**/*") ;; + pagetop-htmx) + CHANGELOG_FILE="extensions/pagetop-htmx/CHANGELOG.md" + PATH_FLAGS=(--include-path "extensions/pagetop-htmx/**/*") + ;; pagetop-seaorm) CHANGELOG_FILE="extensions/pagetop-seaorm/CHANGELOG.md" PATH_FLAGS=(--include-path "extensions/pagetop-seaorm/**/*")