diff --git a/README.md b/README.md index edcb775..256a668 100644 --- a/README.md +++ b/README.md @@ -4,28 +4,32 @@ [![Build](https://github.com/rameel/ramstack.htmxtoolkit/actions/workflows/test.yml/badge.svg)](https://github.com/rameel/ramstack.htmxtoolkit/actions/workflows/test.yml) [![License: MIT](https://img.shields.io/github/license/rameel/ramstack.htmxtoolkit)](LICENSE) -HtmxToolkit connects [HTMX](https://htmx.org/) with ASP.NET Core. It adds strongly typed request and response headers, MVC action filters, Razor Tag Helpers, application-wide HTMX configuration, and antiforgery support. +HtmxToolkit integrates [HTMX](https://htmx.org/) with ASP.NET Core. It provides strongly typed APIs for request and response headers, +MVC action filters, Razor Tag Helpers, application-wide HTMX configuration, and antiforgery support. -The package targets .NET 6 and can be used by applications running on .NET 6 or later. It supports HTMX 1.9.x, HTMX 2.x, and HTMX 4.x. HTMX 2.x is selected by default. +The package targets .NET 6 and can be used by applications running on .NET 6 or later. +It supports HTMX 1.9.x, HTMX 2.x, and HTMX 4.x. HTMX 2.x is selected by default. ## Features -- Detect HTMX and boosted requests without comparing header strings. +- Detect HTMX requests, including boosted requests, without comparing header strings. - Read and write all standard HTMX headers through strongly typed APIs. - Route HTMX requests to dedicated MVC actions with `[HtmxRequest]`. - Configure response behavior fluently or with `[HtmxResponse]`. - Generate HTMX URLs, headers, values, and request options with Razor Tag Helpers. - Render version-specific HTMX configuration from ASP.NET Core options. -- Add antiforgery tokens to unsafe HTMX requests with a small companion script. +- Add antiforgery tokens to non-GET HTMX requests with a small companion script. ## Designed for Low Overhead -HtmxToolkit is designed to make HTMX integration inexpensive on the application's request path: +HtmxToolkit is designed to minimize HTMX integration overhead in the application's request-processing path: -- `HtmxRequestHeaders` and `HtmxResponseHeaders` are readonly, single-reference structs. In normal use they add no wrapper allocation while preserving a strongly typed API. -- Version-specific HTMX configuration is serialized only when it changes; the resulting JSON is cached and reused across requests. -- Known JSON shapes use source-generated `System.Text.Json` metadata, avoiding reflection-based metadata discovery at runtime. Event details passed to `TriggerEvent` are the deliberate exception because their types are defined by the application. -- Work is skipped for non-HTMX requests, and state-passing overloads allow static callbacks when callers need to avoid closure allocations. +- `HtmxRequestHeaders` and `HtmxResponseHeaders` are `readonly` structs, each containing a single reference. + In normal use, they incur no wrapper allocations while preserving a strongly typed API. +- Version-specific HTMX configuration is serialized only when the configuration changes; the resulting JSON is cached and reused across requests. +- Known JSON shapes use source-generated `System.Text.Json` metadata, avoiding reflection-based metadata discovery at runtime. + Event details passed to `TriggerEvent` are the deliberate exception because their types are defined by the application. +- Work is skipped for non-HTMX requests, and overloads that accept state allow callers to use static callbacks and avoid closure allocations. ## Installation @@ -50,14 +54,14 @@ builder.Services.AddHtmxToolkit(); Make the Tag Helpers and toolkit types available to Razor views in `_ViewImports.cshtml`: -```razor +```html @using Ramstack.HtmxToolkit @addTagHelper *, Ramstack.HtmxToolkit ``` Render the configuration metadata in the document ``: -```razor +```html @@ -71,16 +75,16 @@ app.MapHtmxToolkitScript(); Load HTMX first, then the toolkit script in the layout: -```razor +```html ``` -The default script URL contains a content hash, so it can be cached indefinitely and is invalidated automatically when the script changes. +The default script URL contains a content hash, so the script can be cached indefinitely. When the script changes, its URL changes automatically. You can now generate an HTMX URL from ASP.NET Core route information: -```razor +```html ``` -Use `hx-all-route-data` for an `IDictionary` of route values. The helper also supports `hx-route`, `hx-host`, `hx-protocol`, and `hx-fragment`. +Use `hx-all-route-data` for an `IDictionary` of route values. +The helper also supports `hx-route`, `hx-host`, `hx-protocol`, and `hx-fragment`. -### Headers And Values +### Headers and Values Create `hx-headers` without manually escaping JSON: -```razor +```html + + + + + +``` + +The `/profile/morph` endpoint should return the replacement root, such as `
Updated profile
`. + +The toolkit script does not bundle HTMX or Idiomorph and must be loaded after HTMX. Idiomorph remains an optional dependency +and may be loaded before or after the toolkit script because the adapter resolves it when each morph swap runs. Do not enable +the extension with HTMX 4.x, which handles these swap styles natively. + +If Idiomorph is unavailable, the adapter logs a warning and falls back from `innerMorph` to `innerHTML` and from `outerMorph` +to `outerHTML`. With HTMX 1.9.x and 2.x, `outerSync` falls back to synchronizing the target's attributes and then replacing +its children using `innerHTML`. + +`HtmxSwap.TextContent` is also handled by the `ramstack-morph` extension and does not require Idiomorph. It is supported natively +by HTMX 2.x and 4.x; only HTMX 1.9.x needs the extension. ## Sample -The [`samples/Ramstack.HtmxToolkit.Demo`](samples/Ramstack.HtmxToolkit.Demo) project demonstrates request detection, response headers, Tag Helpers, polling, boosted navigation, and antiforgery integration. +The [`samples/Ramstack.HtmxToolkit.Demo`](samples/Ramstack.HtmxToolkit.Demo) project demonstrates request detection, +response headers, Tag Helpers, polling, boosted navigation, and antiforgery integration. Run it with: diff --git a/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.js b/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.js index 05f6cdf..9225690 100644 --- a/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.js +++ b/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.js @@ -1,4 +1,61 @@ document._r_htmx ||= ((document, htmx) => { + const warn = message => console.warn(`ramstack.htmxtoolkit: ${message}`); + + if (htmx.defineExtension) { + htmx.defineExtension("ramstack-morph", { + isInlineSwap(swap_style) { + return swap_style === "outerMorph" || swap_style === "outerSync"; + }, + handleSwap(swap_style, target, fragment) { + if (swap_style === "textContent") { + target.textContent = fragment.textContent; + return [target]; + } + + let morph_style = + swap_style === "innerMorph" ? "innerHTML" : + swap_style === "outerMorph" ? "outerHTML" : null; + + if (morph_style) { + let idiomorph = globalThis.Idiomorph; + if (idiomorph?.morph) { + return idiomorph.morph(target, fragment.children, { morphStyle: morph_style }); + } + + warn(`Idiomorph is unavailable; falling back from ${swap_style} to ${morph_style}`); + + let nodes = [...fragment.childNodes]; + morph_style === "innerHTML" + ? target.replaceChildren(...nodes) + : target.replaceWith(...nodes); + + return nodes; + } + + if (swap_style === "outerSync") { + warn("outerSync requires HTMX 4.x; falling back to attribute sync and innerHTML"); + + let source = fragment.firstElementChild; + if (source) { + for (let attr of [...target.attributes]) { + source.hasAttribute(attr.name) || target.removeAttribute(attr.name); + } + + for (let attr of source.attributes) { + target.setAttribute(attr.name, attr.value); + } + + let nodes = source.childNodes; + target.replaceChildren(...nodes); + + return nodes; + } + + } + } + }); + } + const listen = (type, listener) => { document.addEventListener(type, listener); }; diff --git a/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.min.js b/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.min.js index 62a98c8..a37d755 100644 --- a/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.min.js +++ b/src/Ramstack.HtmxToolkit/Assets/htmx-toolkit.min.js @@ -1 +1 @@ -document._r_htmx||=((e,t)=>{const r=(t,r)=>{e.addEventListener(t,r)},a=e=>{let t=e.querySelector("meta[name='htmx-config']")?.dataset||{};return{headerName:t.antiforgeryHeaderName,formFieldName:t.antiforgeryFormFieldName,requestToken:t.antiforgeryRequestToken}};let o=a(e);const s=(e,t,r)=>{if(!/^get$/i.test(e)){const{headerName:e,formFieldName:a,requestToken:s}=o;s&&(r.has?.(a)||r[a]||(e?t[e]=s:r.set?r.set(a,s):r[a]=s))}},d=e=>{let t=(new DOMParser).parseFromString(e||"","text/html"),r=a(t);r&&(o=r)};return r("htmx:afterOnLoad",e=>{let t=e.detail;t.boosted&&d(t.xhr.responseText)}),r("htmx:after:request",e=>{let t=e.detail.ctx;t.boosted&&d(t.text)}),r("htmx:configRequest",e=>{let t=e.detail;s(t.verb,t.headers,t.parameters)}),r("htmx:config:request",e=>{let t=e.detail.ctx.request;s(t.method,t.headers,t.body)}),r("rs:events",e=>{for(let r of e.detail.value||e.detail)t.trigger(e.target,r.key,r.value)}),!0})(document,htmx); \ No newline at end of file +document._r_htmx||=((e,t)=>{const r=e=>console.warn(`ramstack.htmxtoolkit: ${e}`);t.defineExtension&&t.defineExtension("ramstack-morph",{isInlineSwap:e=>"outerMorph"===e||"outerSync"===e,handleSwap(e,t,n){if("textContent"===e)return t.textContent=n.textContent,[t];let o="innerMorph"===e?"innerHTML":"outerMorph"===e?"outerHTML":null;if(o){let a=globalThis.Idiomorph;if(a?.morph)return a.morph(t,n.children,{morphStyle:o});r(`Idiomorph is unavailable; falling back from ${e} to ${o}`);let i=[...n.childNodes];return"innerHTML"===o?t.replaceChildren(...i):t.replaceWith(...i),i}if("outerSync"===e){r("outerSync requires HTMX 4.x; falling back to attribute sync and innerHTML");let e=n.firstElementChild;if(e){for(let r of[...t.attributes])e.hasAttribute(r.name)||t.removeAttribute(r.name);for(let r of e.attributes)t.setAttribute(r.name,r.value);let r=e.childNodes;return t.replaceChildren(...r),r}}}});const n=(t,r)=>{e.addEventListener(t,r)},o=e=>{let t=e.querySelector("meta[name='htmx-config']")?.dataset||{};return{headerName:t.antiforgeryHeaderName,formFieldName:t.antiforgeryFormFieldName,requestToken:t.antiforgeryRequestToken}};let a=o(e);const i=(e,t,r)=>{if(!/^get$/i.test(e)){const{headerName:e,formFieldName:n,requestToken:o}=a;o&&(r.has?.(n)||r[n]||(e?t[e]=o:r.set?r.set(n,o):r[n]=o))}},l=e=>{let t=(new DOMParser).parseFromString(e||"","text/html"),r=o(t);r&&(a=r)};return n("htmx:afterOnLoad",e=>{let t=e.detail;t.boosted&&l(t.xhr.responseText)}),n("htmx:after:request",e=>{let t=e.detail.ctx;t.boosted&&l(t.text)}),n("htmx:configRequest",e=>{let t=e.detail;i(t.verb,t.headers,t.parameters)}),n("htmx:config:request",e=>{let t=e.detail.ctx.request;i(t.method,t.headers,t.body)}),n("rs:events",e=>{for(let r of e.detail.value||e.detail)t.trigger(e.target,r.key,r.value)}),!0})(document,htmx); \ No newline at end of file diff --git a/src/Ramstack.HtmxToolkit/HtmxSwap.cs b/src/Ramstack.HtmxToolkit/HtmxSwap.cs index ec6c78b..9d79d6a 100644 --- a/src/Ramstack.HtmxToolkit/HtmxSwap.cs +++ b/src/Ramstack.HtmxToolkit/HtmxSwap.cs @@ -18,21 +18,59 @@ public enum HtmxSwap /// /// Morphs the inner HTML of the target element. /// + /// + /// + /// Supported natively by HTMX 4.x. + /// + /// + /// With HTMX 1.9.x or 2.x, activate the ramstack-morph extension + /// and optionally load Idiomorph. Without Idiomorph, the extension + /// falls back to innerHTML. + /// + /// InnerMorph, /// /// Morphs the target element itself. /// + /// + /// + /// Supported natively by HTMX 4.x. + /// + /// + /// With HTMX 1.9.x or 2.x, activate the ramstack-morph extension + /// and optionally load Idiomorph. Without Idiomorph, the extension + /// falls back to outerHTML. + /// + /// OuterMorph, /// /// Synchronizes the target element with the response. /// + /// + /// + /// Supported natively by HTMX 4.x. + /// + /// + /// With HTMX 1.9.x or 2.x, activate the ramstack-morph extension + /// to fall back to attribute synchronization and innerHTML. + /// + /// OuterSync, /// /// Replaces the text content of the target element. /// + /// + /// + /// Supported natively by HTMX 2.x and 4.x. + /// + /// + /// With HTMX 1.9.x, activate the ramstack-morph extension. + /// Idiomorph is not required for this style. + /// + /// TextContent, ///