2 Commits

Author SHA1 Message Date
de75672bb3 v4, alpha 6 (#17)
Reviewed-on: #17
2026-01-07 11:37:26 +00:00
121eb95d87 v2.0.8 (#16)
- Embed htmx library to `Giraffe.Htmx.Common`, add links to load package-provided script
- Update CDN links for v2.0.8
- Add .NET 10 support

Reviewed-on: #16
2025-12-28 16:53:44 +00:00
13 changed files with 1226 additions and 582 deletions

View File

@@ -14,6 +14,8 @@ htmx uses attributes and HTTP headers to attain its interactivity; the libraries
|---|---| |---|---|
|[![Nuget](https://img.shields.io/nuget/v/Giraffe.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.Htmx/)|[![Nuget](https://img.shields.io/nuget/v/Giraffe.ViewEngine.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx/)| |[![Nuget](https://img.shields.io/nuget/v/Giraffe.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.Htmx/)|[![Nuget](https://img.shields.io/nuget/v/Giraffe.ViewEngine.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx/)|
Both of these packages will also install `Giraffe.Htmx.Common`, which has some common definitions and provides a local-to-your-project version of the htmx JavaScript _(as of v2.0.8)_.
## Server Side (`Giraffe.Htmx`) ## Server Side (`Giraffe.Htmx`)
In addition to the regular HTTP request payloads, htmx sets [one or more headers](https://htmx.org/docs/#request_headers) along with the request. Once `Giraffe.Htmx` is opened, these are available as properties on `HttpContext.Request.Headers`. These consist of the header name, translated to a .NET name (ex. `HX-Current-URL` becomes `HxCurrentUrl`), and a strongly-typed property based on the expected value of that header. Additionally, they are all exposed as `Option`s, as they may or may not be present for any given request. In addition to the regular HTTP request payloads, htmx sets [one or more headers](https://htmx.org/docs/#request_headers) along with the request. Once `Giraffe.Htmx` is opened, these are available as properties on `HttpContext.Request.Headers`. These consist of the header name, translated to a .NET name (ex. `HX-Current-URL` becomes `HxCurrentUrl`), and a strongly-typed property based on the expected value of that header. Additionally, they are all exposed as `Option`s, as they may or may not be present for any given request.
@@ -42,6 +44,8 @@ let theHandler : HttpHandler =
Of note is that the `HX-Trigger` headers can take either one or more events. For a single event with no parameters, use `withHxTrigger`; for a single event with parameters, or multiple events, use `withHxTriggerMany`. Both these have `AfterSettle` and `AfterSwap` versions as well. Of note is that the `HX-Trigger` headers can take either one or more events. For a single event with no parameters, use `withHxTrigger`; for a single event with parameters, or multiple events, use `withHxTriggerMany`. Both these have `AfterSettle` and `AfterSwap` versions as well.
`HtmxScript.local` provides an `HtmlString` with a script tag to load the package-provided htmx library. This can be used in code, Razor templates, etc. (If you're using Giraffe.ViewEngine, see below.)
## View Engine (`Giraffe.ViewEngine.Htmx`) ## View Engine (`Giraffe.ViewEngine.Htmx`)
As htmx uses [attributes](https://htmx.org/docs/#attributes) to extend HTML, the primary part of this library defines attributes that can be used within Giraffe views. Simply open `Giraffe.ViewEngine.Htmx`, and these attributes, along with support modules, will be visible. As htmx uses [attributes](https://htmx.org/docs/#attributes) to extend HTML, the primary part of this library defines attributes that can be used within Giraffe views. Simply open `Giraffe.ViewEngine.Htmx`, and these attributes, along with support modules, will be visible.
@@ -66,7 +70,7 @@ let shiftClick =
] ]
``` ```
If you want to load htmx from unpkg, `Htmx.Script.minified` or `Htmx.Script.unminified` can be used to load the script in your HTML trees. If you want to use the package-provided htmx library, `Htmx.Script.local` will create the `script` tag for you. To load htmx from jsDelivr, `Htmx.Script.cdnMinified` or `Htmx.Script.cdnUnminified` can be used to load the script in your HTML trees. In this case, if you are using a Content Security Policy (CSP) header, `cdn.jsdelivr.net` will need to be added to the `script-src` list.
## Feedback / Help ## Feedback / Help

View File

@@ -2,6 +2,12 @@
[<AutoOpen>] [<AutoOpen>]
module Giraffe.Htmx.Common module Giraffe.Htmx.Common
/// <summary>The version of htmx embedded in the package</summary>
let HtmxVersion = "4.0.0-alpha6"
/// <summary>The path for the provided htmx script</summary>
let internal htmxLocalScript = $"/_content/Giraffe.Htmx.Common/htmx.min.js?ver={HtmxVersion}"
/// <summary>Serialize a list of key/value pairs to JSON (very rudimentary)</summary> /// <summary>Serialize a list of key/value pairs to JSON (very rudimentary)</summary>
/// <param name="pairs">The key/value pairs to be serialized to JSON</param> /// <param name="pairs">The key/value pairs to be serialized to JSON</param>
/// <returns>A string with the key/value pairs serialized to JSON</returns> /// <returns>A string with the key/value pairs serialized to JSON</returns>
@@ -19,8 +25,8 @@ let internal toLowerBool (boolValue: bool) =
/// <summary>Valid values for the <c>hx-swap</c> attribute / <c>HX-Reswap</c> header</summary> /// <summary>Valid values for the <c>hx-swap</c> attribute / <c>HX-Reswap</c> header</summary>
/// <remarks>May be combined with <c>swap</c> / <c>settle</c> / <c>scroll</c> / <c>show</c> config)</remarks> /// <remarks>May be combined with <c>swap</c> / <c>scroll</c> / <c>show</c> config)</remarks>
/// <seealso href="https://htmx.org/attributes/hx-swap/">Documentation</seealso> /// <seealso href="https://four.htmx.org/attributes/hx-swap/">Documentation</seealso>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module HxSwap = module HxSwap =
@@ -32,22 +38,60 @@ module HxSwap =
[<Literal>] [<Literal>]
let OuterHtml = "outerHTML" let OuterHtml = "outerHTML"
/// <summary>Morph the inner HTML of the target to the new content</summary>
[<Literal>]
let InnerMorph = "innerMorph"
/// <summary>Morph the outer HTML of the target to the new content</summary>
[<Literal>]
let OuterMorph = "innerMorph"
/// <summary>Replace the text content of the target without parsing the response as HTML</summary>
[<Literal>]
let TextContent = "textContent"
/// <summary>Insert the response before the target element</summary> /// <summary>Insert the response before the target element</summary>
[<Literal>] [<Literal>]
let BeforeBegin = "beforebegin" let Before = "before"
/// <summary>Insert the response before the target element (pre-v4 name)</summary>
[<Literal>]
let BeforeBegin = Before
/// <summary>Insert the response before the first child of the target element</summary> /// <summary>Insert the response before the first child of the target element</summary>
[<Literal>] [<Literal>]
let AfterBegin = "afterbegin" let Prepend = "prepend"
/// <summary>Insert the response before the first child of the target element (pre-v4 name)</summary>
[<Literal>]
let AfterBegin = Prepend
/// <summary>Insert the response after the last child of the target element</summary> /// <summary>Insert the response after the last child of the target element</summary>
[<Literal>] [<Literal>]
let BeforeEnd = "beforeend" let Append = "append"
/// <summary>Insert the response after the last child of the target element (pre-v4 name)</summary>
[<Literal>]
let BeforeEnd = Append
/// <summary>Insert the response after the target element</summary> /// <summary>Insert the response after the target element</summary>
[<Literal>] [<Literal>]
let AfterEnd = "afterend" let After = "after"
/// <summary>Does not append content from response (out of band items will still be processed).</summary> /// <summary>Insert the response after the target element (pre-v4 name)</summary>
[<Literal>]
let AfterEnd = After
/// <summary>Delete the target element regardless of response</summary>
[<Literal>]
let Delete = "delete"
/// <summary>Does not append content from response (out of band items will still be processed)</summary>
[<Literal>] [<Literal>]
let None = "none" let None = "none"
/// <summary>Update existing elements by <c>id</c> and add new ones</summary>
/// <remarks>This requires the <c>upsert</c> extension</remarks>
/// <seealso href="https://four.htmx.org/extensions/upsert">Extension</seealso>
[<Literal>]
let Upsert = "upsert"

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup> <PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>

View File

@@ -1,5 +1,7 @@
## Giraffe.Htmx.Common ## Giraffe.Htmx.Common
This package contains common code shared between [`Giraffe.Htmx`](https://www.nuget.org/packages/Giraffe.Htmx) and [`Giraffe.ViewEngine.Htmx`](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx), and will be automatically installed when you install either one. This package contains common code shared between [`Giraffe.Htmx`](https://www.nuget.org/packages/Giraffe.Htmx) and [`Giraffe.ViewEngine.Htmx`](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx), and will be automatically installed when you install either one. It also contains htmx as a static web asset, allowing it to be loaded from your local (or published) project.
**htmx version: 2.0.6** **htmx version: 4.0.0-alpha6**
_**NOTE:** Pay special attention to breaking changes highlighted in the packages listed above._

1
src/Common/wwwroot/htmx.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,15 +1,17 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?> <?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks> <TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
<VersionPrefix>2.0.6</VersionPrefix> <VersionPrefix>4.0.0</VersionPrefix>
<VersionSuffix>alpha6a</VersionSuffix>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>- All packages now have full XML documentation <PackageReleaseNotes>First htmx 4 alpha release of these libraries
- Adds HxSync module and attribute helper to view engine - [Server] Marked removed headers as obsolete; added new HX-Source header
- Updates script tags to pull htmx 2.0.6 (no header or attribute changes) - [View Engine] Marked removed attributes as obsolete
- Drops .NET 6 support - [View Engine] Added new attributes, modifiers, and support for new hx-partial tag
- Updated script tags to pull htmx 4.0.0-alpha6
NOTE: The CDN for htmx changed from unpkg.com to cdn.jsdelivr.net; sites with Content-Security-Policy headers will want to update their allowed domains accordingly See package READMEs; this is not an update-and-forget-it release
</PackageReleaseNotes> </PackageReleaseNotes>
<Authors>danieljsummers</Authors> <Authors>danieljsummers</Authors>
<Company>Bit Badger Solutions</Company> <Company>Bit Badger Solutions</Company>

View File

@@ -24,6 +24,7 @@ type IHeaderDictionary with
with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse
/// <summary>The user response to an <c>hx-prompt</c></summary> /// <summary>The user response to an <c>hx-prompt</c></summary>
[<Obsolete "hx-prompt is removed in v4">]
member this.HxPrompt member this.HxPrompt
with get () = hdr this "HX-Prompt" with get () = hdr this "HX-Prompt"
@@ -31,15 +32,29 @@ type IHeaderDictionary with
member this.HxRequest member this.HxRequest
with get () = hdr this "HX-Request" |> Option.map bool.Parse with get () = hdr this "HX-Request" |> Option.map bool.Parse
/// <summary>The tag name (fst) and <c>id</c> attribute (snd) of the element triggering this request</summary>
member this.HxSource
with get () =
match hdr this "HX-Source" with
| Some src ->
let parts = src.Split "#"
if parts.Length = 1 then
Some (parts[0], None)
else
Some (parts[0], if parts[1] <> "" then Some parts[1] else None)
| None -> None
/// <summary>The <c>id</c> attribute of the target element if it exists</summary> /// <summary>The <c>id</c> attribute of the target element if it exists</summary>
member this.HxTarget member this.HxTarget
with get () = hdr this "HX-Target" with get () = hdr this "HX-Target"
/// <summary>The <c>id</c> attribute of the triggered element if it exists</summary> /// <summary>The <c>id</c> attribute of the triggered element if it exists</summary>
[<Obsolete "HX-Trigger is removed in v4; use the second item of HX-Source">]
member this.HxTrigger member this.HxTrigger
with get () = hdr this "HX-Trigger" with get () = hdr this "HX-Trigger"
/// <summary>The <c>name</c> attribute of the triggered element if it exists</summary> /// <summary>The <c>name</c> attribute of the triggered element if it exists</summary>
[<Obsolete "HX-Trigger-Name is removed in v4; may be available via extension, but will be removed from this library">]
member this.HxTriggerName member this.HxTriggerName
with get () = hdr this "HX-Trigger-Name" with get () = hdr this "HX-Trigger-Name"
@@ -170,3 +185,15 @@ module Handlers =
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso> /// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTriggerManyAfterSwap evts : HttpHandler = let withHxTriggerManyAfterSwap evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger-After-Swap" toJson evts |> setHttpHeader "HX-Trigger-After-Swap"
/// <summary>Load the package-provided version of the htmx script</summary>
[<RequireQualifiedAccess>]
module HtmxScript =
open Giraffe.Htmx.Common
open Microsoft.AspNetCore.Html
/// <summary><c>script</c> tag to load the package-provided version of the htmx script</summary>
let local = HtmlString $"""<script src="{htmxLocalScript}"></script>"""

View File

@@ -2,9 +2,11 @@
This package enables server-side support for [htmx](https://htmx.org) within [Giraffe](https://giraffe.wiki) and ASP.NET's `HttpContext`. This package enables server-side support for [htmx](https://htmx.org) within [Giraffe](https://giraffe.wiki) and ASP.NET's `HttpContext`.
**htmx version: 2.0.6** **htmx version: 4.0.0-alpha6**
_Upgrading from v1.x: the [migration guide](https://htmx.org/migration-guide-htmx-1/) does not currently specify any request or response header changes. This means that there are no required code changes in moving from v1.* to v2.*._ _Upgrading from v2.x: the [migration guide](https://four.htmx.org/migration-guide-htmx-4/) lists changes for v4. For this package, the `HX-Trigger` and `HX-Trigger-Name` headers are marked obsolete. They are replaced by `HX-Source`, which provides the triggering tag name and `id` attribute. The `HX-Prompt` header has also been marked as obsolete, as the `hx-prompt` attribute which generated its content has been removed._
_Obsolete elements will be removed in the first production v4 release._
### Setup ### Setup
@@ -18,9 +20,9 @@ To obtain a request header, using the `IHeaderDictionary` extension properties:
```fsharp ```fsharp
let myHandler : HttpHander = let myHandler : HttpHander =
fun next ctx -> fun next ctx ->
match ctx.HxPrompt with match ctx.Target with
| Some prompt -> ... // do something with the text the user provided | Some elt -> ... // do something with id of the target element
| None -> ... // no text provided | None -> ... // no target element provided
``` ```
To set a response header: To set a response header:
@@ -34,6 +36,8 @@ let myHandler : HttpHander =
The `HxSwap` module has constants to use for the `HX-Reswap` header. These may be extended with settle, show, and other qualifiers; see the htmx documentation for the `hx-swap` attribute for more information. The `HxSwap` module has constants to use for the `HX-Reswap` header. These may be extended with settle, show, and other qualifiers; see the htmx documentation for the `hx-swap` attribute for more information.
To load the package-provided htmx library without using Giraffe.ViewEngine, use `HtmxScript.local`.
### Learn ### Learn
The naming conventions of this library were selected to mirror those provided by htmx. The header properties become `Hx*` on the `ctx.Request.Headers` object, and the response handlers are `withHx*` based on the header being set. The only part that does not line up is `withHxTrigger*` and `withHxTriggerMany`; the former set work with a single string (to trigger a single event with no arguments), while the latter set supports both arguments and multiple events. The naming conventions of this library were selected to mirror those provided by htmx. The header properties become `Hx*` on the `ctx.Request.Headers` object, and the response handlers are `withHx*` based on the header being set. The only part that does not line up is `withHxTrigger*` and `withHxTriggerMany`; the former set work with a single string (to trigger a single event with no arguments), while the latter set supports both arguments and multiple events.

View File

@@ -3,6 +3,12 @@ module Common
open Expecto open Expecto
open Giraffe.Htmx open Giraffe.Htmx
/// Test to ensure the version was updated
let version =
test "HtmxVersion is correct" {
Expect.equal HtmxVersion "4.0.0-alpha6" "htmx version incorrect"
}
/// Tests for the HxSwap module /// Tests for the HxSwap module
let swap = let swap =
testList "HxSwap" [ testList "HxSwap" [
@@ -12,22 +18,49 @@ let swap =
test "OuterHtml is correct" { test "OuterHtml is correct" {
Expect.equal HxSwap.OuterHtml "outerHTML" "Outer HTML swap value incorrect" Expect.equal HxSwap.OuterHtml "outerHTML" "Outer HTML swap value incorrect"
} }
test "BeforeBegin is correct" { test "InnerMorph is correct" {
Expect.equal HxSwap.BeforeBegin "beforebegin" "Before Begin swap value incorrect" Expect.equal HxSwap.InnerMorph "innerMorph" "Inner Morph swap value incorrect"
} }
test "BeforeEnd is correct" { test "OuterMorph is correct" {
Expect.equal HxSwap.BeforeEnd "beforeend" "Before End swap value incorrect" Expect.equal HxSwap.OuterMorph "innerMorph" "Outer Morph swap value incorrect"
}
test "TextContent is correct" {
Expect.equal HxSwap.TextContent "textContent" "Text Content swap value incorrect"
}
test "Before is correct" {
Expect.equal HxSwap.Before "before" "Before swap value incorrect"
}
test "BeforeBegin is correct" {
Expect.equal HxSwap.BeforeBegin HxSwap.Before "Before Begin swap value incorrect"
}
test "Prepend is correct" {
Expect.equal HxSwap.Prepend "prepend" "Prepend swap value incorrect"
} }
test "AfterBegin is correct" { test "AfterBegin is correct" {
Expect.equal HxSwap.AfterBegin "afterbegin" "After Begin swap value incorrect" Expect.equal HxSwap.AfterBegin HxSwap.Prepend "Prepend swap value incorrect"
}
test "Append is correct" {
Expect.equal HxSwap.Append "append" "Append swap value incorrect"
}
test "BeforeEnd is correct" {
Expect.equal HxSwap.BeforeEnd HxSwap.Append "Before End swap value incorrect"
}
test "After is correct" {
Expect.equal HxSwap.After "after" "After swap value incorrect"
} }
test "AfterEnd is correct" { test "AfterEnd is correct" {
Expect.equal HxSwap.AfterEnd "afterend" "After End swap value incorrect" Expect.equal HxSwap.AfterEnd HxSwap.After "After End swap value incorrect"
}
test "Delete is correct" {
Expect.equal HxSwap.Delete "delete" "Delete swap value incorrect"
} }
test "None is correct" { test "None is correct" {
Expect.equal HxSwap.None "none" "None swap value incorrect" Expect.equal HxSwap.None "none" "None swap value incorrect"
} }
test "Upsert is correct" {
Expect.equal HxSwap.Upsert "upsert" "Upsert swap value incorrect"
}
] ]
/// All tests for this module /// All tests for this module
let allTests = testList "Htmx.Common" [ swap ] let allTests = testList "Htmx.Common" [ version; swap ]

View File

@@ -73,21 +73,6 @@ let dictExtensions =
ctx.Request.Headers.HxHistoryRestoreRequest.Value "The header should have been false" ctx.Request.Headers.HxHistoryRestoreRequest.Value "The header should have been false"
} }
] ]
testList "HxPrompt" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxPrompt "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Prompt", "of course")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxPrompt "There should be a header present"
Expect.equal ctx.Request.Headers.HxPrompt.Value "of course" "The header value was incorrect"
}
]
testList "HxRequest" [ testList "HxRequest" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext>()
@@ -111,6 +96,44 @@ let dictExtensions =
Expect.isFalse ctx.Request.Headers.HxRequest.Value "The header should have been false" Expect.isFalse ctx.Request.Headers.HxRequest.Value "The header should have been false"
} }
] ]
testList "HxSource" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxSource "There should not have been a header returned"
}
test "succeeds when the header is present and both parts exist" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Source", "button#theId")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxSource
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "button" "The source tag was incorrect"
Expect.isSome (snd hdr.Value) "There should be a source ID present"
Expect.equal (snd hdr.Value).Value "theId" "The source ID was incorrect"
}
test "succeeds when the header is present and ID is blank" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Source", "a#")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxSource
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "a" "The source tag was incorrect"
Expect.isNone (snd hdr.Value) "There should not be a source ID present"
}
test "succeeds when the header is present and ID is missing" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Source", "form")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxSource
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "form" "The source tag was incorrect"
Expect.isNone (snd hdr.Value) "There should not be a source ID present"
}
]
testList "HxTarget" [ testList "HxTarget" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext>()
@@ -126,36 +149,6 @@ let dictExtensions =
Expect.equal ctx.Request.Headers.HxTarget.Value "#leItem" "The header value was incorrect" Expect.equal ctx.Request.Headers.HxTarget.Value "#leItem" "The header value was incorrect"
} }
] ]
testList "HxTrigger" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxTrigger "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Trigger", "#trig")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTrigger "There should be a header present"
Expect.equal ctx.Request.Headers.HxTrigger.Value "#trig" "The header value was incorrect"
}
]
testList "HxTriggerName" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxTriggerName "There should not have been a header returned"
}
test "HxTriggerName succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Trigger-Name", "click")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTriggerName "There should be a header present"
Expect.equal ctx.Request.Headers.HxTriggerName.Value "click" "The header value was incorrect"
}
]
] ]
/// Tests for the HttpRequest extension properties /// Tests for the HttpRequest extension properties
@@ -354,5 +347,66 @@ let handlers =
} }
] ]
/// Tests for the HtmxScript module
let script =
testList "HtmxScript" [
test "local generates correct link" {
Expect.equal
(string HtmxScript.local)
$"""<script src="/_content/Giraffe.Htmx.Common/htmx.min.js?ver={HtmxVersion}"></script>"""
"htmx script link is incorrect"
}
]
#nowarn 44 // Obsolete items still have tests
let dictExtensionsObs =
testList "IHeaderDictionaryExtensions (Obsolete)" [
testList "HxPrompt" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxPrompt "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Prompt", "of course")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxPrompt "There should be a header present"
Expect.equal ctx.Request.Headers.HxPrompt.Value "of course" "The header value was incorrect"
}
]
testList "HxTrigger" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxTrigger "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Trigger", "#trig")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTrigger "There should be a header present"
Expect.equal ctx.Request.Headers.HxTrigger.Value "#trig" "The header value was incorrect"
}
]
testList "HxTriggerName" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxTriggerName "There should not have been a header returned"
}
test "HxTriggerName succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Trigger-Name", "click")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTriggerName "There should be a header present"
Expect.equal ctx.Request.Headers.HxTriggerName.Value "click" "The header value was incorrect"
}
]
]
/// All tests for this module /// All tests for this module
let allTests = testList "Htmx" [ dictExtensions; reqExtensions; handlers ] let allTests = testList "Htmx" [ dictExtensions; reqExtensions; handlers; script; dictExtensionsObs ]

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,42 @@
/// <summary>Types and functions supporting htmx attributes in Giraffe View Engine</summary> /// <summary>Types and functions supporting htmx attributes in Giraffe View Engine</summary>
module Giraffe.ViewEngine.Htmx module Giraffe.ViewEngine.Htmx
/// <summary>Helpers to define <c>hx-config</c> attribute values</summary>
/// <seealso href="https://four.htmx.org/attributes/hx-config/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxConfig =
open Giraffe.Htmx.Common
/// <summary>Configure the request with various options</summary>
/// <param name="opts">The options to configure</param>
/// <returns>A string with the configured options</returns>
let Configure (opts: string list) =
opts
|> String.concat ", "
|> sprintf "{ %s }"
/// <summary>Set a timeout (in milliseconds)</summary>
/// <param name="ms">The milliseconds for the request timeout</param>
/// <returns>A string with the configured request timeout</returns>
let Timeout (ms: int) =
$"\"timeout\": {ms}"
/// <summary>Include or exclude credentials from the request</summary>
/// <param name="send"><c>true</c> if credentials should be sent, <c>false</c> if not</param>
/// <returns>A string with the configured credential options</returns>
let Credentials send =
(toLowerBool >> sprintf "\"credentials\": %s") send
/// <summary>Exclude or include headers from the request</summary>
/// <param name="exclude">
/// <c>true</c> if no headers should be sent; <c>false</c> if headers should be sent
/// </param>
/// <returns>A string with the configured header options</returns>
let NoHeaders exclude =
(toLowerBool >> sprintf "\"noHeaders\": %s") exclude
/// <summary>Valid values for the <c>hx-encoding</c> attribute</summary> /// <summary>Valid values for the <c>hx-encoding</c> attribute</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module HxEncoding = module HxEncoding =
@@ -14,45 +50,98 @@ module HxEncoding =
let MultipartForm = "multipart/form-data" let MultipartForm = "multipart/form-data"
#nowarn 44 // Obsolete elements still have entries in the conversion map; will be removed for v4 final
/// <summary>The events recognized by htmx</summary> /// <summary>The events recognized by htmx</summary>
/// <seealso href="https://four.htmx.org/events/">Documentation</seealso>
[<Struct>] [<Struct>]
type HxEvent = type HxEvent =
/// <summary>Send this event to an element to abort a request</summary> /// <summary>Send this event to an element to abort a request</summary>
| Abort | Abort
/// <summary>Triggered after htmx disables an element or removes it from the DOM</summary>
| AfterCleanup
/// <summary>Triggered after content is saved to the history cache</summary>
| AfterHistoryUpdate
/// <summary>Triggered after a request has initialized</summary>
| AfterInit
/// <summary>Triggered after an AJAX request has completed processing a successful response</summary> /// <summary>Triggered after an AJAX request has completed processing a successful response</summary>
| AfterOnLoad | [<System.Obsolete "Removed in v4; use AfterInit">] AfterOnLoad
/// <summary>Triggered after htmx has initialized a node</summary> /// <summary>Triggered after htmx has initialized a node</summary>
| AfterProcessNode | [<System.Obsolete "Removed in v4; use AfterInit">] AfterProcessNode
/// <summary>Triggered after an AJAX request has completed</summary> /// <summary>Triggered after new content is saved to the history cache</summary>
| AfterPushIntoHistory
/// <summary>Triggered after updated content is saved to the history cache</summary>
| AfterReplaceIntoHistory
/// <summary>Triggered after an HTTP request has completed successfully</summary>
| AfterRequest | AfterRequest
/// <summary>Triggered after the DOM has settled</summary> /// <summary>Triggered after the DOM has settled</summary>
| AfterSettle | [<System.Obsolete "Removed in v4; use AfterSwap">] AfterSettle
/// <summary>Triggered after a Server Sent Events (SSE) message is read</summary>
| AfterSseMessage
/// <summary>Triggered after a Server Sent Events (SSE) stream is closed</summary>
| AfterSseStream
/// <summary>Triggered after new content has been swapped in</summary> /// <summary>Triggered after new content has been swapped in</summary>
| AfterSwap | AfterSwap
/// <summary>Triggered before htmx disables an element or removes it from the DOM</summary> /// <summary>Triggered after a CSS view transition completes</summary>
| BeforeCleanupElement | AfterViewTransition
/// <summary>Triggered before any response processing occurs</summary> /// <summary>Triggered before htmx disables an element or removes it from the DOM</summary>
| BeforeOnLoad | BeforeCleanup
/// <summary>Triggered before htmx disables an element or removes it from the DOM</summary>
| [<System.Obsolete "Removed in v4; use BeforeCleanup">] BeforeCleanupElement
/// <summary>Triggered before content is saved to the history cache</summary>
| [<System.Obsolete "Removed in v4; use BeforeHistoryUpdate">] BeforeHistorySave
/// <summary>Triggered before content is saved to the history cache</summary>
| BeforeHistoryUpdate
/// <summary>Triggered before htmx initializes a node</summary> /// <summary>Triggered before htmx initializes a node</summary>
| BeforeProcessNode | BeforeInit
/// <summary>Triggered before an AJAX request is made</summary> /// <summary>Triggered before any response processing occurs</summary>
| [<System.Obsolete "Removed in v4; use BeforeInit">] BeforeOnLoad
/// <summary>Triggered before htmx initializes a node</summary>
| [<System.Obsolete "Removed in v4; use BeforeInit">] BeforeProcessNode
/// <summary>Triggered before an HTTP request is made</summary>
| BeforeRequest | BeforeRequest
/// <summary>Triggered before a history restore request is made</summary>
| BeforeRestoreHistory
/// <summary>Triggered just before an ajax request is sent</summary>
| [<System.Obsolete "Removed in v4; use BeforeRequest">] BeforeSend
/// <summary>Triggered before a Server Sent Events (SSE) message is read</summary>
| BeforeSseMessage
/// <summary>Triggered before a Server Sent Events (SSE) connection is reconnected</summary>
| BeforeSseReconnect
/// <summary>Triggered before a Server Sent Events (SSE) stream is opened</summary>
| BeforeSseStream
/// <summary>Triggered before a swap is done, allows you to configure the swap</summary> /// <summary>Triggered before a swap is done, allows you to configure the swap</summary>
| BeforeSwap | BeforeSwap
/// <summary>Triggered just before an ajax request is sent</summary> /// <summary>Triggered before a CSS view transition starts</summary>
| BeforeSend | BeforeViewTransition
/// <summary>Triggered before the request, allows you to customize parameters, headers</summary> /// <summary>Triggered before the request, allows you to customize parameters, headers</summary>
| ConfigRequest | ConfigRequest
@@ -62,129 +151,150 @@ type HxEvent =
/// </summary> /// </summary>
| Confirm | Confirm
/// <summary>Triggered when an error occurs</summary>
| Error
/// <summary>Triggered after an HTTP request is made, whether it was successful or not</summary>
| FinallyRequest
/// <summary>Triggered on an error during cache writing</summary> /// <summary>Triggered on an error during cache writing</summary>
| HistoryCacheError | [<System.Obsolete "Removed in v4; history no longer uses localStorage">] HistoryCacheError
/// <summary>Triggered on a cache miss in the history subsystem</summary> /// <summary>Triggered on a cache miss in the history subsystem</summary>
| HistoryCacheMiss | [<System.Obsolete "Removed in v4; use BeforeRestoreHistory">] HistoryCacheMiss
/// <summary>Triggered on a unsuccessful remote retrieval</summary> /// <summary>Triggered on a unsuccessful remote retrieval</summary>
| HistoryCacheMissError | [<System.Obsolete "Removed in v4; history no longer uses localStorage">] HistoryCacheMissError
/// <summary>Triggered on a successful remote retrieval</summary> /// <summary>Triggered on a successful remote retrieval</summary>
| HistoryCacheMissLoad | [<System.Obsolete "Removed in v4; use BeforeRestoreHistory">] HistoryCacheMissLoad
/// <summary>Triggered when htmx handles a history restoration action</summary> /// <summary>Triggered when htmx handles a history restoration action</summary>
| HistoryRestore | [<System.Obsolete "Removed in v4; use BeforeRestoreHistory">] HistoryRestore
/// <summary>Triggered before content is saved to the history cache</summary>
| BeforeHistorySave
/// <summary>Triggered when new content is added to the DOM</summary> /// <summary>Triggered when new content is added to the DOM</summary>
| Load | [<System.Obsolete "Removed in v4; use AfterInit">] Load
/// <summary> /// <summary>
/// Triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined /// Triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined
/// </summary> /// </summary>
| NoSseSourceError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] NoSseSourceError
/// <summary>Triggered when an exception occurs during the onLoad handling in htmx</summary> /// <summary>Triggered when an exception occurs during the onLoad handling in htmx</summary>
| OnLoadError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] OnLoadError
/// <summary>Triggered after an out of band element as been swapped in</summary> /// <summary>Triggered after an out of band element as been swapped in</summary>
| OobAfterSwap | [<System.Obsolete "Removed in v4; use AfterSwap (no separate OOB event)">] OobAfterSwap
/// <summary>Triggered before an out of band element swap is done, allows you to configure the swap</summary> /// <summary>Triggered before an out of band element swap is done, allows you to configure the swap</summary>
| OobBeforeSwap | [<System.Obsolete "Removed in v4; use BeforeSwap (no separate OOB event)">] OobBeforeSwap
/// <summary>Triggered when an out of band element does not have a matching ID in the current DOM</summary> /// <summary>Triggered when an out of band element does not have a matching ID in the current DOM</summary>
| OobErrorNoTarget | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] OobErrorNoTarget
/// <summary>Triggered after a prompt is shown</summary> /// <summary>Triggered after a prompt is shown</summary>
| Prompt | [<System.Obsolete "Removed in v4; use Confirm with custom JavaScript">] Prompt
/// <summary>Triggered after an url is pushed into history</summary> /// <summary>Triggered after an url is pushed into history</summary>
| PushedIntoHistory | [<System.Obsolete "Removed in v4; use AfterPushIntoHistory (or AfterHistoryUpdate to catch new and updated content)">] PushedIntoHistory
/// <summary>Triggered when an HTTP response error (non-200 or 300 response code) occurs</summary> /// <summary>Triggered when an HTTP response error (non-200 or 300 response code) occurs</summary>
| ResponseError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] ResponseError
/// <summary>Triggered when a network error prevents an HTTP request from happening</summary> /// <summary>Triggered when a network error prevents an HTTP request from happening</summary>
| SendError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] SendError
/// <summary>Triggered when an error occurs with a SSE source</summary> /// <summary>Triggered when an error occurs with a SSE source</summary>
| SseError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] SseError
/// <summary>Triggered when a SSE source is opened</summary> /// <summary>Triggered when an SSE source is opened</summary>
| SseOpen | [<System.Obsolete "Removed in v4; use fetch event listener">] SseOpen
/// <summary>Triggered when an error occurs during the swap phase</summary> /// <summary>Triggered when an error occurs during the swap phase</summary>
| SwapError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] SwapError
/// <summary>Triggered when an invalid target is specified</summary> /// <summary>Triggered when an invalid target is specified</summary>
| TargetError | [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] TargetError
/// <summary>Triggered when a request timeout occurs</summary> /// <summary>Triggered when a request timeout occurs</summary>
| Timeout | [<System.Obsolete "Removed in v4; use Error (timeout is exposed as an error)">] Timeout
/// <summary>Triggered before an element is validated</summary> /// <summary>Triggered before an element is validated</summary>
| ValidationValidate | [<System.Obsolete "Removed in v4; use native validation API">] ValidationValidate
/// <summary>Triggered when an element fails validation</summary> /// <summary>Triggered when an element fails validation</summary>
| ValidationFailed | [<System.Obsolete "Removed in v4; use native validation API">] ValidationFailed
/// <summary>Triggered when a request is halted due to validation errors</summary> /// <summary>Triggered when a request is halted due to validation errors</summary>
| ValidationHalted | [<System.Obsolete "Removed in v4; use native validation API">] ValidationHalted
/// <summary>Triggered when an ajax request aborts</summary> /// <summary>Triggered when an ajax request aborts</summary>
| XhrAbort | [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrAbort
/// <summary>Triggered when an ajax request ends</summary> /// <summary>Triggered when an ajax request ends</summary>
| XhrLoadEnd | [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrLoadEnd
/// <summary>Triggered when an ajax request starts</summary> /// <summary>Triggered when an ajax request starts</summary>
| XhrLoadStart | [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrLoadStart
/// <summary>Triggered periodically during an ajax request that supports progress events</summary> /// <summary>Triggered periodically during an ajax request that supports progress events</summary>
| XhrProgress | [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrProgress
/// The htmx event name (fst) and kebab-case name (snd, for use with hx-on) /// The htmx event name (fst) and kebab-case name (snd, for use with hx-on)
static member private Values = Map [ static member private Values = Map [
Abort, ("abort", "abort") Abort, ("abort", "abort")
AfterOnLoad, ("afterOnLoad", "after-on-load") AfterCleanup, ("afterCleanup", "after:cleanup")
AfterProcessNode, ("afterProcessNode", "after-process-node") AfterHistoryUpdate, ("afterHistoryUpdate", "after:history:update")
AfterRequest, ("afterRequest", "after-request") AfterInit, ("afterInit", "after:init")
AfterSettle, ("afterSettle", "after-settle") AfterOnLoad, ("afterOnLoad", "after:init")
AfterSwap, ("afterSwap", "after-swap") AfterProcessNode, ("afterProcessNode", "after:init")
BeforeCleanupElement, ("beforeCleanupElement", "before-cleanup-element") AfterPushIntoHistory, ("afterPushIntoHistory", "after:push:into:history")
BeforeOnLoad, ("beforeOnLoad", "before-on-load") AfterReplaceIntoHistory, ("afterReplaceIntoHistory", "after:replace:into:history")
BeforeProcessNode, ("beforeProcessNode", "before-process-node") AfterRequest, ("afterRequest", "after:request")
BeforeRequest, ("beforeRequest", "before-request") AfterSettle, ("afterSettle", "after:swap")
BeforeSwap, ("beforeSwap", "before-swap") AfterSseMessage, ("afterSseMessage", "after:sse:message")
BeforeSend, ("beforeSend", "before-send") AfterSseStream, ("afterSseStream", "after:sse:stream")
ConfigRequest, ("configRequest", "config-request") AfterSwap, ("afterSwap", "after:swap")
AfterViewTransition, ("afterViewTransition", "after:viewTransition")
BeforeCleanup, ("beforeCleanup", "before:cleanup")
BeforeCleanupElement, ("beforeCleanupElement", "before:cleanup")
BeforeHistorySave, ("beforeHistorySave", "before:history:update")
BeforeHistoryUpdate, ("beforeHistoryUpdate", "before:history:update")
BeforeInit, ("beforeInit", "before:init")
BeforeOnLoad, ("beforeOnLoad", "before:init")
BeforeProcessNode, ("beforeProcessNode", "before:init")
BeforeRestoreHistory, ("beforeRestoreHistory", "before:restore:history")
BeforeRequest, ("beforeRequest", "before:request")
BeforeSend, ("beforeSend", "before:request")
BeforeSseMessage, ("beforeSseMessage", "before:sse:message")
BeforeSseReconnect, ("beforeSseReconnect", "before:sse:reconnect")
BeforeSseStream, ("beforeSseStream", "before:sse:stream")
BeforeSwap, ("beforeSwap", "before:swap")
BeforeViewTransition, ("beforeTransition", "before:viewTransition")
ConfigRequest, ("configRequest", "config:request")
Confirm, ("confirm", "confirm") Confirm, ("confirm", "confirm")
Error, ("error", "error")
FinallyRequest, ("finallyRequest", "finally:request")
HistoryCacheError, ("historyCacheError", "history-cache-error") HistoryCacheError, ("historyCacheError", "history-cache-error")
HistoryCacheMiss, ("historyCacheMiss", "history-cache-miss") HistoryCacheMiss, ("historyCacheMiss", "before:history:restore")
HistoryCacheMissError, ("historyCacheMissError", "history-cache-miss-error") HistoryCacheMissError, ("historyCacheMissError", "history-cache-miss-error")
HistoryCacheMissLoad, ("historyCacheMissLoad", "history-cache-miss-load") HistoryCacheMissLoad, ("historyCacheMissLoad", "before:history:restore")
HistoryRestore, ("historyRestore", "history-restore") HistoryRestore, ("historyRestore", "before:history:restore")
BeforeHistorySave, ("beforeHistorySave", "before-history-save") Load, ("load", "after:init")
Load, ("load", "load") NoSseSourceError, ("noSSESourceError", "error")
NoSseSourceError, ("noSSESourceError", "no-sse-source-error") OnLoadError, ("onLoadError", "error")
OnLoadError, ("onLoadError", "on-load-error") OobAfterSwap, ("oobAfterSwap", "after:swap")
OobAfterSwap, ("oobAfterSwap", "oob-after-swap") OobBeforeSwap, ("oobBeforeSwap", "before:swap")
OobBeforeSwap, ("oobBeforeSwap", "oob-before-swap") OobErrorNoTarget, ("oobErrorNoTarget", "error")
OobErrorNoTarget, ("oobErrorNoTarget", "oob-error-no-target")
Prompt, ("prompt", "prompt") Prompt, ("prompt", "prompt")
PushedIntoHistory, ("pushedIntoHistory", "pushed-into-history") PushedIntoHistory, ("pushedIntoHistory", "after:push:into:history")
ResponseError, ("responseError", "response-error") ResponseError, ("responseError", "error")
SendError, ("sendError", "send-error") SendError, ("sendError", "error")
SseError, ("sseError", "sse-error") SseError, ("sseError", "error")
SseOpen, ("sseOpen", "sse-open") SseOpen, ("sseOpen", "sse-open")
SwapError, ("swapError", "swap-error") SwapError, ("swapError", "error")
TargetError, ("targetError", "target-error") TargetError, ("targetError", "error")
Timeout, ("timeout", "timeout") Timeout, ("timeout", "error")
ValidationValidate, ("validation:validate", "validation:validate") ValidationValidate, ("validation:validate", "validation:validate")
ValidationFailed, ("validation:failed", "validation:failed") ValidationFailed, ("validation:failed", "validation:failed")
ValidationHalted, ("validation:halted", "validation:halted") ValidationHalted, ("validation:halted", "validation:halted")
@@ -199,6 +309,7 @@ type HxEvent =
/// <summary>The <c>hx-on</c> variant of the htmx event name</summary> /// <summary>The <c>hx-on</c> variant of the htmx event name</summary>
member this.ToHxOnString() = snd HxEvent.Values[this] member this.ToHxOnString() = snd HxEvent.Values[this]
#warn 44 // restore obsolete warning
/// <summary>Helper to create the <c>hx-headers</c> attribute</summary> /// <summary>Helper to create the <c>hx-headers</c> attribute</summary>
@@ -212,6 +323,7 @@ module HxHeaders =
/// <summary>Values / helpers for the <c>hx-params</c> attribute</summary> /// <summary>Values / helpers for the <c>hx-params</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
[<System.Obsolete "Removed in v4; filter parameters via JavaScript in configRequest event">]
module HxParams = module HxParams =
/// <summary>Include all parameters</summary> /// <summary>Include all parameters</summary>
@@ -238,6 +350,7 @@ module HxParams =
/// <summary>Helpers to define <c>hx-request</c> attribute values</summary> /// <summary>Helpers to define <c>hx-request</c> attribute values</summary>
/// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
[<System.Obsolete "Removed in v4; change to HxConfig">]
module HxRequest = module HxRequest =
open Giraffe.Htmx.Common open Giraffe.Htmx.Common
@@ -487,17 +600,30 @@ module HxVals =
let From = Giraffe.Htmx.Common.toJson let From = Giraffe.Htmx.Common.toJson
open System.Net.Http
open Giraffe.Htmx open Giraffe.Htmx
/// <summary>Attributes and flags for htmx</summary> /// <summary>Attributes and flags for htmx</summary>
[<AutoOpen>] [<AutoOpen>]
module HtmxAttrs = module HtmxAttrs =
/// <summary>The URL which will receive the request (use with <c>_hxMethod</c>)</summary>
/// <param name="url">The URL for the attribute</param>
/// <seealso href="https://four.htmx.org/attributes/hx-action/">Documentation</seealso>
let _hxAction url = attr "hx-action" url
/// <summary>Progressively enhances anchors and forms to use AJAX requests</summary> /// <summary>Progressively enhances anchors and forms to use AJAX requests</summary>
/// <remarks>Use <c>_hxNoBoost</c> to set to false</remarks> /// <remarks>Use <c>_hxNoBoost</c> to set to false</remarks>
/// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso>
let _hxBoost = attr "hx-boost" "true" let _hxBoost = attr "hx-boost" "true"
/// <summary>Configure request behavior</summary>
/// <param name="config">The configuration parameters to use for the request</param>
/// <returns>A configured <c>hx-config</c> attribute</returns>
/// <seealso cref="https://four.htmx.org/attributes/hx-config/">Documentation</seealso>
let _hxConfig config =
attr "hx-config" (toJson config)
/// <summary>Shows a <c>confirm()</c> dialog before issuing a request</summary> /// <summary>Shows a <c>confirm()</c> dialog before issuing a request</summary>
/// <param name="prompt">The prompt to present to the user when seeking their confirmation</param> /// <param name="prompt">The prompt to present to the user when seeking their confirmation</param>
/// <returns>A configured <c>hx-confirm</c> attribute</returns> /// <returns>A configured <c>hx-confirm</c> attribute</returns>
@@ -512,14 +638,23 @@ module HtmxAttrs =
let _hxDelete url = let _hxDelete url =
attr "hx-delete" url attr "hx-delete" url
/// <summary>Disables htmx processing for the given node and any children nodes</summary> /// <summary>Specifies elements that should be disabled when an htmx request is in flight</summary>
/// <seealso href="https://htmx.org/attributes/hx-disable/">Documentation</seealso> /// <param name="elt">The element to disable when an htmx request is in flight</param>
let _hxDisable = flag "hx-disable" /// <returns>A configured <c>hx-disable</c> attribute</returns>
/// <remarks>This behavior changed in v4
/// <ul><li>For the v2 behavior of <c>hx-disable</c> (which will manifest as compile errors), change instances to
/// <c>_hxIgnore</c></li>
/// <li>For v4 behavior, changing <c>_hxDisabledElt</c> to <c>_hxDisable</c> should be sufficient</li></ul>
/// </remarks>
/// <seealso href="https://four.htmx.org/attributes/hx-disable/">Documentation</seealso>
let _hxDisable elt =
attr "hx-disable" elt
/// <summary>Specifies elements that should be disabled when an htmx request is in flight</summary> /// <summary>Specifies elements that should be disabled when an htmx request is in flight</summary>
/// <param name="elt">The element to disable when an htmx request is in flight</param> /// <param name="elt">The element to disable when an htmx request is in flight</param>
/// <returns>A configured <c>hx-disabled-elt</c> attribute</returns> /// <returns>A configured <c>hx-disabled-elt</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-disabled-elt/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-disabled-elt/">Documentation</seealso>
[<System.Obsolete "hx-disabled-elt has become hx-disable in v4">]
let _hxDisabledElt elt = let _hxDisabledElt elt =
attr "hx-disabled-elt" elt attr "hx-disabled-elt" elt
@@ -527,6 +662,7 @@ module HtmxAttrs =
/// <param name="hxAttrs">The htmx attributes to disinherit (should start with "hx-")</param> /// <param name="hxAttrs">The htmx attributes to disinherit (should start with "hx-")</param>
/// <returns>A configured <c>hx-disinherit</c> attribute</returns> /// <returns>A configured <c>hx-disinherit</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-disinherit/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-disinherit/">Documentation</seealso>
[<System.Obsolete "hx-disinherit removed in v4; use explicit inheritance">]
let _hxDisinherit hxAttrs = let _hxDisinherit hxAttrs =
attr "hx-disinherit" hxAttrs attr "hx-disinherit" hxAttrs
@@ -542,6 +678,7 @@ module HtmxAttrs =
/// <param name="exts">A list of extensions to apply to this element</param> /// <param name="exts">A list of extensions to apply to this element</param>
/// <returns>A configured <c>hx-ext</c> attribute</returns> /// <returns>A configured <c>hx-ext</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-ext/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-ext/">Documentation</seealso>
[<System.Obsolete "hx-ext removed in v4; extensions register via JavaScript">]
let _hxExt exts = let _hxExt exts =
attr "hx-ext" exts attr "hx-ext" exts
@@ -565,14 +702,21 @@ module HtmxAttrs =
/// <param name="shouldStore">Whether the page should be stored in the history cache</param> /// <param name="shouldStore">Whether the page should be stored in the history cache</param>
/// <returns>A configured <c>hx-history</c> attribute</returns> /// <returns>A configured <c>hx-history</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-history/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-history/">Documentation</seealso>
[<System.Obsolete "hx-history removed in v4; history does not use localStorage">]
let _hxHistory shouldStore = let _hxHistory shouldStore =
attr "hx-history" (toLowerBool shouldStore) attr "hx-history" (toLowerBool shouldStore)
/// <summary>The element to snapshot and restore during history navigation</summary> /// <summary>The element to snapshot and restore during history navigation</summary>
/// <seealso href="https://htmx.org/attributes/hx-history-elt/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-history-elt/">Documentation</seealso>
[<System.Obsolete "hx-history-elt removed in v4; history based on target element">]
let _hxHistoryElt = let _hxHistoryElt =
flag "hx-history-elt" flag "hx-history-elt"
/// <summary>Disables htmx processing for the given node and any children nodes</summary>
/// <seealso href="https://four.htmx.org/attributes/hx-ignore/">Documentation</seealso>
let _hxIgnore =
flag "hx-ignore"
/// <summary>Includes additional data in AJAX requests</summary> /// <summary>Includes additional data in AJAX requests</summary>
/// <param name="spec">The specification of what should be included in the request</param> /// <param name="spec">The specification of what should be included in the request</param>
/// <returns>A configured <c>hx-include</c> attribute</returns> /// <returns>A configured <c>hx-include</c> attribute</returns>
@@ -587,6 +731,12 @@ module HtmxAttrs =
let _hxIndicator selector = let _hxIndicator selector =
attr "hx-indicator" selector attr "hx-indicator" selector
/// <summary>The HTTP method to use for the request(use with <c>_hxAction</c>)</summary>
/// <param name="method">The method to use</param>
/// <seealso href="https://four.htmx.org/attributes/hx-method/">Documentation</seealso>
let _hxMethod (method: HttpMethod) =
attr "hx-method" (method.Method.ToLowerInvariant())
/// <summary>Overrides a previous <c>hx-boost</c> (hx-boost="false")</summary> /// <summary>Overrides a previous <c>hx-boost</c> (hx-boost="false")</summary>
/// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso>
let _hxNoBoost = let _hxNoBoost =
@@ -614,6 +764,7 @@ module HtmxAttrs =
/// <returns>A configured <c>hx-params</c> attribute</returns> /// <returns>A configured <c>hx-params</c> attribute</returns>
/// <seealso cref="HxParams" /> /// <seealso cref="HxParams" />
/// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso>
[<System.Obsolete "hx-params removed in v4; use htmx:config:request to filter parameter">]
let _hxParams toInclude = let _hxParams toInclude =
attr "hx-params" toInclude attr "hx-params" toInclude
@@ -641,6 +792,7 @@ module HtmxAttrs =
/// <returns>A configured <c>hx-prompt</c> attribute</returns> /// <returns>A configured <c>hx-prompt</c> attribute</returns>
/// <remarks>The value provided will be in the <c>HX-Prompt</c> request header</remarks> /// <remarks>The value provided will be in the <c>HX-Prompt</c> request header</remarks>
/// <seealso href="https://htmx.org/attributes/hx-prompt/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-prompt/">Documentation</seealso>
[<System.Obsolete "hx-prompt removed in v4; use hx-confirm with async JavaScript function">]
let _hxPrompt text = let _hxPrompt text =
attr "hx-prompt" text attr "hx-prompt" text
@@ -682,6 +834,7 @@ module HtmxAttrs =
/// <returns>A configured <c>hx-request</c> attribute</returns> /// <returns>A configured <c>hx-request</c> attribute</returns>
/// <seealso cref="HxRequest.Configure" /> /// <seealso cref="HxRequest.Configure" />
/// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso> /// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso>
[<System.Obsolete "hx-request removed in v4; use hx-config instead">]
let _hxRequest spec = let _hxRequest spec =
attr "hx-request" spec attr "hx-request" spec
@@ -785,21 +938,65 @@ module HtmxAttrs =
attr "sse-swap" messages attr "sse-swap" messages
/// <summary>Modifiers for htmx attributes</summary>
[<AutoOpen>]
module HxModifiers =
/// <summary>Append this value to any inherited value of the attribute</summary>
/// <param name="attrib">The attribute to which <c>:append</c> should be applied</param>
/// <returns>The given attribute with <c>:append</c> applied</returns>
let hxAppend attrib =
match attrib with
| KeyValue (name, value) -> attr $"{name}:append" value
| Boolean name -> flag $"{name}:append"
/// <summary>Explicitly propagate inheritance for the value for this attribute</summary>
/// <param name="attrib">The attribute whose value should be inherited</param>
/// <returns>The given attribute with <c>:inherited</c> applied</returns>
let hxInherited attrib =
match attrib with
| KeyValue (name, value) -> attr $"{name}:inherited" value
| Boolean name -> flag $"{name}:inherited"
/// <summary>htmx-specific HTML tags</summary>
[<AutoOpen>]
module HxTags =
/// <summary>An <c>hx-partial</c> tag</summary>
let hxPartial = tag "hx-partial"
/// <summary>Script tags to pull htmx into a web page</summary> /// <summary>Script tags to pull htmx into a web page</summary>
module Script = module Script =
/// <summary>Script tag to load the minified version from unpkg.com</summary> open System
let minified =
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@2.0.6/dist/htmx.min.js" /// <summary>Script tag to load the package-provided version of htmx</summary>
_integrity "sha384-Akqfrbj/HpNVo8k11SXBb6TlBWmXXlYQrCSqEWmyKJe+hDm3Z/B2WVG4smwBkRVm" let local = script [ _src htmxLocalScript ] []
/// <summary>Script tag to load the minified version from jsdelivr.net</summary>
/// <remarks>Ensure <c>cdn.jsdelivr.net</c> is in your CSP <c>script-src</c> list (if applicable)</remarks>
let cdnMinified =
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@4.0.0-alpha6/dist/htmx.min.js"
_integrity "sha384-/5n21KGM472oBhvzUrvju8FRDq/4WNMS3TGw5RWFkZR/kq+sCevqNXFcakqRtaHu"
_crossorigin "anonymous" ] [] _crossorigin "anonymous" ] []
/// <summary>Script tag to load the unminified version from unpkg.com</summary> /// <summary>Script tag to load the unminified version from jsdelivr.net</summary>
let unminified = /// <remarks>Ensure <c>cdn.jsdelivr.net</c> is in your CSP <c>script-src</c> list (if applicable)</remarks>
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@2.0.6/dist/htmx.js" let cdnUnminified =
_integrity "sha384-ksKjJrwjL5VxqAkAZAVOPXvMkwAykMaNYegdixAESVr+KqLkKE8XBDoZuwyWVUDv" script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@4.0.0-alpha6/dist/htmx.js"
_integrity "sha384-I3uRy2RjSNcS8Oi2SNWZD9IrafyrrrBb4QaHNA9pWVWfJuKtL0p8qAwHSrEyXoKh"
_crossorigin "anonymous" ] [] _crossorigin "anonymous" ] []
/// <summary>Script tag to load the minified version from jsdelivr.net</summary>
[<Obsolete "Use cdnMinified instead; this will be removed in v4">]
let minified = cdnMinified
/// <summary>Script tag to load the unminified version from jsdelivr.net</summary>
[<Obsolete "Use cdnUnminified instead; this will be removed in v4">]
let unminified = cdnUnminified
/// <summary>Functions to extract and render an HTML fragment from a document</summary> /// <summary>Functions to extract and render an HTML fragment from a document</summary>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]

View File

@@ -2,9 +2,13 @@
This package enables [htmx](https://htmx.org) support within the [Giraffe](https://giraffe.wiki) view engine. This package enables [htmx](https://htmx.org) support within the [Giraffe](https://giraffe.wiki) view engine.
**htmx version: 2.0.6** **htmx version: 4.0.0-alpha6**
_Upgrading from v1.x: see [the migration guide](https://htmx.org/migration-guide-htmx-1/) for changes_ _Upgrading from v2.x: see [the migration guide](https://four.htmx.org/migration-guide-htmx-4/) for changes, which are plentiful. htmx switches from `XMLHTTPRequest` to `fetch`, and many changes are related to the new event cycle._
_Inheritance is now explicit; to have an attribute's value inherited to its children, wrap the attribute in `hxInherited` (ex. `hxInherited (_hxTarget "#main")`). Values can be appended to inherited values as well using the `hxAppend` modifier._
_Several constructs have been marked obsolete in this release, and will be removed from the first production release of v4. With the exception of `_hxDisable`, though (which now functions as the deprecated `_hxDisabledElt` did), this should not introduce compile errors. Rather, this package will raise warnings for deprecated constructs, along with suggestions of what to use instead._
### Setup ### Setup
@@ -21,15 +25,16 @@ let autoload =
``` ```
Support modules include: Support modules include:
- `HxConfig` _(new in v4)_
- `HxEncoding` - `HxEncoding`
- `HxHeaders` - `HxHeaders`
- `HxParams` - ~~`HxParams`~~ _(removed in v4)_
- `HxRequest` - ~~`HxRequest`~~ _(renamed to `HxConfig`)_
- `HxSwap` (requires `open Giraffe.Htmx`) - `HxSwap` (requires `open Giraffe.Htmx`)
- `HxTrigger` - `HxTrigger`
- `HxVals` - `HxVals`
There are two `XmlNode`s that will load the htmx script from jsdelivr; `Htmx.Script.minified` loads the minified version, and `Htmx.Script.unminified` loads the unminified version (useful for debugging). `Htmx.Script.local` creates an `XmlNode` to load the package-provided htmx library. There are also two `XmlNode`s that will load the htmx script from jsdelivr; `Htmx.Script.cdnMinified` loads the minified version, and `Htmx.Script.cdnUnminified` loads the unminified version (useful for debugging). When using the CDN nodes and a Content Security Policy (CSP) header, `cdn.jsdelivr.net` needs to be listed as an allowable `script-src`.
This also supports [fragment rendering](https://bitbadger.solutions/blog/2022/fragment-rendering-in-giraffe-view-engine.html), providing the flexibility to render an entire template, or only a portion of it (based on the element's `id` attribute). This also supports [fragment rendering](https://bitbadger.solutions/blog/2022/fragment-rendering-in-giraffe-view-engine.html), providing the flexibility to render an entire template, or only a portion of it (based on the element's `id` attribute).