54 Commits

Author SHA1 Message Date
6b7458070b v2.0.6 (#15)
- Adds XML documentation (#13)
- Adds `HxSync` module and attribute helper
- Updates script version to 2.0.6
- Drops .NET 6 support (#14 )

Reviewed-on: #15
2025-07-03 00:15:24 +00:00
10c31d77b5 Update version in READMEs 2024-12-13 17:02:28 -05:00
f4cd184a15 Update script and version to 2.0.4; add .NET 9 support 2024-12-13 16:57:27 -05:00
5626031593 Update script tags and package version to 2.0.3 2024-10-18 09:36:28 -04:00
f0de18845f Update script tags and package version to 2.0.2 2024-08-12 21:36:47 -04:00
961307fd99 Update htmx script to 2.0.1 2024-07-29 18:06:19 -04:00
a2960a79c6 Add pack script; drop beta tag 2024-06-18 19:38:28 -04:00
541384a92f htmx v2
- Drop `hx-sse` and `hx-ws` attributes
- Drop explicit .NET 7 support
- Update deps to latest versions
2024-06-18 19:16:10 -04:00
8cb5d6bfa7 Merge pull request 'htmx v2-beta4' (#12) from v2-beta4 into main
Reviewed-on: #12
2024-05-23 23:30:58 +00:00
1a11e3511a Update htmx to v2.0.0-beta4 2024-05-23 19:26:00 -04:00
32e962416d Migrate PR 10 from GitHub
https://github.com/bit-badger/Giraffe.Htmx/pull/10
2024-05-23 19:19:07 -04:00
29839fa795 Update script tags for v2.0.0 beta3
- Update paths in package metadata
2024-04-17 22:25:06 -04:00
7f9b3a6234 Merge branch 'htmx-version-2' 2024-04-17 22:06:23 -04:00
a8d2b819dc Merge branch 'htmx-version-2' of https://git.bitbadger.solutions/bit-badger/Giraffe.Htmx into htmx-version-2 2024-04-17 22:04:21 -04:00
1ea05b79ed Update for htmx v1.9.11 2024-03-18 20:14:51 -04:00
4f6bb8367a Update for v2 beta 1 2024-03-18 20:03:18 -04:00
b3665a4b72 Update CI to Node 20-based versions 2024-02-12 18:29:27 -05:00
bdb7255a1c Update for v2 alpha 2 2024-02-12 17:45:16 -05:00
9276db7ffe Sync changes from main 2024-01-30 23:04:19 -05:00
94b68f76c9 Add workflow dispatch to CI 2024-01-30 23:02:45 -05:00
90de16529c Move packaging to .NET 8 2024-01-30 22:58:45 -05:00
452f15b2d4 Add alpha tag 2024-01-30 22:55:36 -05:00
59246ae7f5 Add v2 branch to CI 2024-01-30 22:48:08 -05:00
16355e8f58 Add v2.0.0-alpha1 support 2024-01-30 22:46:34 -05:00
71286b9064 Move FSharp.Core version to .fsproj files
- Change event DU to struct
2024-01-02 19:26:09 -05:00
85ac22877c v1.9.10 (#9) 2024-01-02 19:02:24 -05:00
dea2323499 Update NuGet READMEs 2023-11-22 16:13:57 -05:00
fcaaa693bc Bump htmx version; add .NET 8 support 2023-11-22 16:09:52 -05:00
8fd6af8c26 Add support for hx-disabled-elt
- Update script tag to 1.9.6
2023-09-27 20:31:56 -04:00
69a4034661 Update to htmx 1.9.5 2023-08-25 12:36:30 -04:00
5aa9408e60 Update to htmx 1.9.4 2023-07-26 12:54:48 -04:00
98f53a5e53 Add HX-Reselect; update for 1.9.3 2023-07-15 17:54:01 -04:00
7798314fb8 Update script tags for v1.9.2 2023-05-06 13:14:58 -04:00
50c66435e8 Add _hxOn and _hxSwapWithTransition
- Update scripts and version to 1.9.0
2023-04-14 16:56:08 -04:00
5b3a1be87e Update script for 1.8.6
- Sync version in package READMEs
2023-03-03 12:26:40 -05:00
168f434030 Remove PostgreSQL verbiage
oops
2023-02-27 20:56:49 -05:00
e3db0bced0 Xunit -> Expecto (#7) 2023-02-27 20:55:16 -05:00
fb5c4f1bcb Change to main branch 2023-02-27 20:51:51 -05:00
c3229d51d1 Remove manual start 2023-02-27 20:42:42 -05:00
951edef8ad Allow manual starting 2023-02-27 20:41:25 -05:00
3908451d6e Add CI action 2023-02-27 20:38:33 -05:00
277d93dd99 Add hx-history attribute
Add .NET 7 support
2023-01-17 20:41:54 -05:00
061f6e5a4e Add link to frag render post 2022-11-24 11:34:07 -05:00
bb2df73175 Add _hxValidate, fragment rendering
Also bump version to 1.8.4
2022-11-24 10:50:08 -05:00
e0c567098d Add files to package common project 2022-07-14 11:32:42 -04:00
4be5bad8ef Update package READMEs 2022-07-14 09:24:49 -04:00
a169000ce2 Update for version 1.8.0 (#6)
- Bump library version
- Bump htmx script version
- Add hx-replace-url / HX-Replace-Url
- Add hx-select-oob
- Change hx-push-url to accept a string
- Add HX-Push-Url, obsolete HX-Push
- Implement HX-Reswap header
- Rework project structure to add common project
2022-07-14 09:13:52 -04:00
c587a28770 Update for htmx 1.7.0 (#4)
Fixes #3
2022-02-23 21:54:51 -05:00
b5292bffc4 HTMX -> htmx 2022-01-07 16:02:01 -05:00
86defea3c1 Add scripts to README
Also prep for release
2022-01-06 21:31:36 -05:00
9a9f159cab Add script functions
Also bump version to match htmx
2022-01-04 12:54:36 -05:00
9fcba06e75 Add HX-Retarget header (#2) 2021-11-26 12:49:48 -05:00
5906f3b295 Add NuGet READMEs 2021-11-11 18:40:22 -05:00
dc06b06b1f Finish view engine helpers 2021-11-11 13:33:50 -05:00
27 changed files with 2810 additions and 842 deletions

57
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,57 @@
name: CI
on:
push:
branches: [ "main", "htmx-version-2" ]
pull_request:
branches: [ "main" ]
workflow_dispatch:
jobs:
build-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
dotnet-version: [ "6.0", "7.0", "8.0" ]
steps:
- uses: actions/checkout@v4
- name: Setup .NET ${{ matrix.dotnet-version }}.x
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ matrix.dotnet-version }}.x
- name: Restore dependencies
run: dotnet restore src/Giraffe.Htmx.sln
- name: Build
run: dotnet build src/Giraffe.Htmx.sln --no-restore
- name: Test (.NET ${{ matrix.dotnet-version }})
run: dotnet run --project src/Tests/Tests.fsproj -f net${{ matrix.dotnet-version }}
publish:
runs-on: ubuntu-latest
needs: build-and-test
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: "8.0"
- name: Package Common library
run: dotnet pack src/Common/Giraffe.Htmx.Common.fsproj -c Release
- name: Move Common package
run: cp src/Common/bin/Release/Giraffe.Htmx.Common.*.nupkg .
- name: Package Server library
run: dotnet pack src/Htmx/Giraffe.Htmx.fsproj -c Release
- name: Move Server package
run: cp src/Htmx/bin/Release/Giraffe.Htmx.*.nupkg .
- name: Package View Engine library
run: dotnet pack src/ViewEngine.Htmx/Giraffe.ViewEngine.Htmx.fsproj -c Release
- name: Move View Engine package
run: cp src/ViewEngine.Htmx/bin/Release/Giraffe.ViewEngine.Htmx.*.nupkg .
- name: Save Packages
uses: actions/upload-artifact@v4
with:
name: packages
path: |
*.nupkg

4
.gitignore vendored
View File

@@ -5,3 +5,7 @@
.ionide
.idea
*.user
.vscode
src/*.nupkg
src/tests*.txt

View File

@@ -25,9 +25,10 @@ A server may want to respond to a request that originated from htmx differently
// "view" can be whatever your view engine needs for the body of the page
let result view : HttpHandler =
fun next ctx ->
match ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh with
| true -> partial view
| false -> full view
if ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh then
partial view
else
full view
```
htmx also utilizes [response headers](https://htmx.org/docs/#response_headers) to affect client-side behavior. For each of these, this library provides `HttpHandler`s that can be chained along with the response. As an example, if the server returns a redirect response (301, 302, 303, 307), the `XMLHttpRequest` handler on the client will follow the redirection before htmx can do anything with it. To redirect to a new page, you would return an OK (200) response with an `HX-Redirect` header set in the response.
@@ -49,7 +50,9 @@ As an example, creating a `div` that loads data once the HTML is rendered:
```fsharp
let autoload =
div [ _hxGet "/lazy-load-data"; _hxTrigger "load" ] [ str "Loading..." ]
div [ _hxGet "/lazy-load-data"; _hxTrigger HxTrigger.Load ] [
str "Loading..."
]
```
_(As `hx-boost="true"` is the usual desire for boosting, `_hxBoost` implies true. To disable it for an element, use `_hxNoBoost` instead.)_
@@ -63,12 +66,14 @@ Some attributes have known values, such as `hx-trigger` and `hx-swap`; for these
]
```
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.
## Feedback / Help
The author hangs out in the #htmx-general channel of the [htmx Discord server](https://htmx.org/discord) and the #web channel of the [F# Software Foundation's Slack server](https://fsharp.org/guides/slack/).
The author hangs out in the #dotnet-htmx channel (and most others) of the [htmx Discord server](https://htmx.org/discord) and the #web channel of the [F# Software Foundation's Slack server](https://fsharp.org/guides/slack/).
## Thanks
|[<img src="https://giraffe.wiki/giraffe.png" alt="Giraffe logo" width="200">](https://giraffe.wiki)|[<img src="https://bitbadger.solutions/htmx-black-transparent.svg" alt="htmx logo" width="200">](https://htmx.org)|[<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main)" width="200">](https://jb.gg/OpenSource)|
| :---: | :---: | :---: |
|[<img src="https://giraffe.wiki/giraffe.png" alt="Giraffe logo" width="200">](https://giraffe.wiki)| [<img src="https://bitbadger.solutions/upload/bit-badger/2024/01/htmx-black-transparent.svg" alt="htmx logo" width="200">](https://htmx.org) |[<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main)" width="200">](https://jb.gg/OpenSource)|
| :---: |:------------------------------------------------------------------------------------------------------------------------------------:| :---: |
|for making ASP.NET Core functional| for making HTML cool again |for licensing their tools to this project|

53
src/Common/Common.fs Normal file
View File

@@ -0,0 +1,53 @@
/// <summary>Common definitions shared between attribute values and response headers</summary>
[<AutoOpen>]
module Giraffe.Htmx.Common
/// <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>
/// <returns>A string with the key/value pairs serialized to JSON</returns>
let internal toJson (pairs: (string * string) list) =
pairs
|> List.map (fun pair -> sprintf "\"%s\": \"%s\"" (fst pair) ((snd pair).Replace ("\"", "\\\"")))
|> String.concat ", "
|> sprintf "{ %s }"
/// <summary>Convert a boolean to lowercase "true" or "false"</summary>
/// <param name="boolValue">The boolean value to convert</param>
/// <returns>"true" for <c>true</c>, "false" for <c>false</c></returns>
let internal toLowerBool (boolValue: bool) =
(string boolValue).ToLowerInvariant()
/// <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>
/// <seealso href="https://htmx.org/attributes/hx-swap/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxSwap =
/// <summary>The default, replace the inner HTML of the target element</summary>
[<Literal>]
let InnerHtml = "innerHTML"
/// <summary>Replace the entire target element with the response</summary>
[<Literal>]
let OuterHtml = "outerHTML"
/// <summary>Insert the response before the target element</summary>
[<Literal>]
let BeforeBegin = "beforebegin"
/// <summary>Insert the response before the first child of the target element</summary>
[<Literal>]
let AfterBegin = "afterbegin"
/// <summary>Insert the response after the last child of the target element</summary>
[<Literal>]
let BeforeEnd = "beforeend"
/// <summary>Insert the response after the target element</summary>
[<Literal>]
let AfterEnd = "afterend"
/// <summary>Does not append content from response (out of band items will still be processed).</summary>
[<Literal>]
let None = "none"

View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>Common definitions for Giraffe.Htmx</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Compile Include="Common.fs" />
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="..\icon.png" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Giraffe.Htmx" />
<InternalsVisibleTo Include="Giraffe.ViewEngine.Htmx" />
</ItemGroup>
</Project>

5
src/Common/README.md Normal file
View File

@@ -0,0 +1,5 @@
## 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.
**htmx version: 2.0.6**

View File

@@ -1,13 +1,21 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VersionPrefix>0.9.1</VersionPrefix>
<PackageReleaseNotes>Initial NuGet release</PackageReleaseNotes>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<VersionPrefix>2.0.6</VersionPrefix>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>- All packages now have full XML documentation
- Adds HxSync module and attribute helper to view engine
- Updates script tags to pull htmx 2.0.6 (no header or attribute changes)
- Drops .NET 6 support
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
</PackageReleaseNotes>
<Authors>danieljsummers</Authors>
<Company>Bit Badger Solutions</Company>
<PackageProjectUrl>https://github.com/bit-badger/Giraffe.Htmx</PackageProjectUrl>
<PackageProjectUrl>https://git.bitbadger.solutions/bit-badger/Giraffe.Htmx</PackageProjectUrl>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<RepositoryUrl>https://github.com/bit-badger/Giraffe.Htmx</RepositoryUrl>
<RepositoryUrl>https://git.bitbadger.solutions/bit-badger/Giraffe.Htmx</RepositoryUrl>
<RepositoryType>Git</RepositoryType>
<Copyright>MIT License</Copyright>
<PackageLicenseExpression>MIT</PackageLicenseExpression>

40
src/Giraffe.Htmx.sln Normal file
View File

@@ -0,0 +1,40 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Giraffe.Htmx", "Htmx\Giraffe.Htmx.fsproj", "{8AB3085C-5236-485A-8565-A09106E72E1E}"
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Giraffe.ViewEngine.Htmx", "ViewEngine.Htmx\Giraffe.ViewEngine.Htmx.fsproj", "{F718B3C1-EE01-4F04-ABCE-BF2AE700FDA9}"
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Giraffe.Htmx.Common", "Common\Giraffe.Htmx.Common.fsproj", "{75D66845-F93A-4463-AD29-A8B16E4D4BA9}"
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Tests", "Tests\Tests.fsproj", "{39823773-4311-4E79-9CA0-F9DDC40CAF6A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8AB3085C-5236-485A-8565-A09106E72E1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8AB3085C-5236-485A-8565-A09106E72E1E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8AB3085C-5236-485A-8565-A09106E72E1E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8AB3085C-5236-485A-8565-A09106E72E1E}.Release|Any CPU.Build.0 = Release|Any CPU
{F718B3C1-EE01-4F04-ABCE-BF2AE700FDA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F718B3C1-EE01-4F04-ABCE-BF2AE700FDA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F718B3C1-EE01-4F04-ABCE-BF2AE700FDA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F718B3C1-EE01-4F04-ABCE-BF2AE700FDA9}.Release|Any CPU.Build.0 = Release|Any CPU
{75D66845-F93A-4463-AD29-A8B16E4D4BA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{75D66845-F93A-4463-AD29-A8B16E4D4BA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{75D66845-F93A-4463-AD29-A8B16E4D4BA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{75D66845-F93A-4463-AD29-A8B16E4D4BA9}.Release|Any CPU.Build.0 = Release|Any CPU
{39823773-4311-4E79-9CA0-F9DDC40CAF6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{39823773-4311-4E79-9CA0-F9DDC40CAF6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{39823773-4311-4E79-9CA0-F9DDC40CAF6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{39823773-4311-4E79-9CA0-F9DDC40CAF6A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -1,34 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
<GenerateProgramFile>false</GenerateProgramFile>
</PropertyGroup>
<ItemGroup>
<Compile Include="Tests.fs" />
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Giraffe" Version="5.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NSubstitute" Version="4.2.2" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Htmx\Giraffe.Htmx.fsproj" />
</ItemGroup>
</Project>

View File

@@ -1 +0,0 @@
module Program = let [<EntryPoint>] main _ = 0

View File

@@ -1,318 +0,0 @@
module Giraffe.Htmx.Tests
open System
open Giraffe.Htmx
open Microsoft.AspNetCore.Http
open NSubstitute
open Xunit
/// Tests for the IHeaderDictionary extension properties
module IHeaderDictionaryExtensions =
[<Fact>]
let ``HxBoosted succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxBoosted |> Assert.True
[<Fact>]
let ``HxBoosted succeeds when the header is present and true`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Boosted", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxBoosted |> Assert.True
Option.get ctx.Request.Headers.HxBoosted |> Assert.True
[<Fact>]
let ``HxBoosted succeeds when the header is present and false`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Boosted", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxBoosted |> Assert.True
Option.get ctx.Request.Headers.HxBoosted |> Assert.False
[<Fact>]
let ``HxCurrentUrl succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxCurrentUrl |> Assert.True
[<Fact>]
let ``HxCurrentUrl succeeds when the header is present`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Current-URL", "http://localhost/test.htm")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxCurrentUrl |> Assert.True
Assert.Equal (Uri "http://localhost/test.htm", Option.get ctx.Request.Headers.HxCurrentUrl)
[<Fact>]
let ``HxHistoryRestoreRequest succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxHistoryRestoreRequest |> Assert.True
[<Fact>]
let ``HxHistoryRestoreRequest succeeds when the header is present and true`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-History-Restore-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxHistoryRestoreRequest |> Assert.True
Option.get ctx.Request.Headers.HxHistoryRestoreRequest |> Assert.True
[<Fact>]
let ``HxHistoryRestoreRequest succeeds when the header is present and false`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-History-Restore-Request", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxHistoryRestoreRequest |> Assert.True
Option.get ctx.Request.Headers.HxHistoryRestoreRequest |> Assert.False
[<Fact>]
let ``HxPrompt succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxPrompt |> Assert.True
[<Fact>]
let ``HxPrompt 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
Option.isSome ctx.Request.Headers.HxPrompt |> Assert.True
Assert.Equal("of course", Option.get ctx.Request.Headers.HxPrompt)
[<Fact>]
let ``HxRequest succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxRequest |> Assert.True
[<Fact>]
let ``HxRequest succeeds when the header is present and true`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxRequest |> Assert.True
Option.get ctx.Request.Headers.HxRequest |> Assert.True
[<Fact>]
let ``HxRequest succeeds when the header is present and false`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Request", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxRequest |> Assert.True
Option.get ctx.Request.Headers.HxRequest |> Assert.False
[<Fact>]
let ``HxTarget succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxTarget |> Assert.True
[<Fact>]
let ``HxTarget succeeds when the header is present`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Target", "#leItem")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Option.isSome ctx.Request.Headers.HxTarget |> Assert.True
Assert.Equal("#leItem", Option.get ctx.Request.Headers.HxTarget)
[<Fact>]
let ``HxTrigger succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxTrigger |> Assert.True
[<Fact>]
let ``HxTrigger 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
Option.isSome ctx.Request.Headers.HxTrigger |> Assert.True
Assert.Equal("#trig", Option.get ctx.Request.Headers.HxTrigger)
[<Fact>]
let ``HxTriggerName succeeds when the header is not present`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Option.isNone ctx.Request.Headers.HxTriggerName |> Assert.True
[<Fact>]
let ``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
Option.isSome ctx.Request.Headers.HxTriggerName |> Assert.True
Assert.Equal("click", Option.get ctx.Request.Headers.HxTriggerName)
/// Tests for the HttpRequest extension properties
module HttpRequestExtensions =
[<Fact>]
let ``IsHtmx succeeds when request is not from htmx`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Assert.False ctx.Request.IsHtmx
[<Fact>]
let ``IsHtmx succeeds when request is from htmx`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Assert.True ctx.Request.IsHtmx
[<Fact>]
let ``IsHtmxRefresh succeeds when request is not from htmx`` () =
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Assert.False ctx.Request.IsHtmxRefresh
[<Fact>]
let ``IsHtmxRefresh succeeds when request is from htmx, but not a refresh`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Assert.False ctx.Request.IsHtmxRefresh
[<Fact>]
let ``IsHtmxRefresh succeeds when request is from htmx and is a refresh`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Request", "true")
dic.Add ("HX-History-Restore-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Assert.True ctx.Request.IsHtmxRefresh
/// Tests for the HttpHandler functions provided in the Handlers module
module HandlerTests =
open System.Threading.Tasks
/// Dummy "next" parameter to get the pipeline to execute/terminate
let next (ctx : HttpContext) = Task.FromResult (Some ctx)
[<Fact>]
let ``withHxPush succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxPush "/a-new-url" next ctx
Assert.True (dic.ContainsKey "HX-Push")
Assert.Equal ("/a-new-url", dic.["HX-Push"].[0])
}
[<Fact>]
let ``withHxRedirect succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxRedirect "/somewhere-else" next ctx
Assert.True (dic.ContainsKey "HX-Redirect")
Assert.Equal ("/somewhere-else", dic.["HX-Redirect"].[0])
}
[<Fact>]
let ``withHxRefresh succeeds when set to true`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxRefresh true next ctx
Assert.True (dic.ContainsKey "HX-Refresh")
Assert.Equal ("true", dic.["HX-Refresh"].[0])
}
[<Fact>]
let ``withHxRefresh succeeds when set to false`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxRefresh false next ctx
Assert.True (dic.ContainsKey "HX-Refresh")
Assert.Equal ("false", dic.["HX-Refresh"].[0])
}
[<Fact>]
let ``withHxTrigger succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxTrigger "doSomething" next ctx
Assert.True (dic.ContainsKey "HX-Trigger")
Assert.Equal ("doSomething", dic.["HX-Trigger"].[0])
}
[<Fact>]
let ``withHxTriggerMany succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxTriggerMany [ "blah", "foo"; "bleh", "bar" ] next ctx
Assert.True (dic.ContainsKey "HX-Trigger")
Assert.Equal ("""{ "blah": "foo", "bleh": "bar" }""", dic.["HX-Trigger"].[0])
}
[<Fact>]
let ``withHxTriggerAfterSettle succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxTriggerAfterSettle "byTheWay" next ctx
Assert.True (dic.ContainsKey "HX-Trigger-After-Settle")
Assert.Equal ("byTheWay", dic.["HX-Trigger-After-Settle"].[0])
}
[<Fact>]
let ``withHxTriggerManyAfterSettle succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxTriggerManyAfterSettle [ "oof", "ouch"; "hmm", "uh" ] next ctx
Assert.True (dic.ContainsKey "HX-Trigger-After-Settle")
Assert.Equal ("""{ "oof": "ouch", "hmm": "uh" }""", dic.["HX-Trigger-After-Settle"].[0])
}
[<Fact>]
let ``withHxTriggerAfterSwap succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxTriggerAfterSwap "justASec" next ctx
Assert.True (dic.ContainsKey "HX-Trigger-After-Swap")
Assert.Equal ("justASec", dic.["HX-Trigger-After-Swap"].[0])
}
[<Fact>]
let ``withHxTriggerManyAfterSwap succeeds`` () =
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
task {
let! _ = withHxTriggerManyAfterSwap [ "this", "1"; "that", "2" ] next ctx
Assert.True (dic.ContainsKey "HX-Trigger-After-Swap")
Assert.Equal ("""{ "this": "1", "that": "2" }""", dic.["HX-Trigger-After-Swap"].[0])
}

View File

@@ -1,17 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>htmx header extensions and helpers for Giraffe</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Compile Include="Htmx.fs" />
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="..\icon.png" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Giraffe" Version="5.0.0" />
<PackageReference Include="Giraffe" Version="6.4.0" />
<PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Giraffe.Htmx.Common.fsproj" />
</ItemGroup>
</Project>

View File

@@ -1,4 +1,4 @@
module Giraffe.Htmx
module Giraffe.Htmx
open Microsoft.AspNetCore.Http
open Microsoft.Extensions.Primitives
@@ -6,94 +6,167 @@ open System
/// Determine if the given header is present
let private hdr (headers : IHeaderDictionary) hdr =
match headers.[hdr] with it when it = StringValues.Empty -> None | it -> Some it.[0]
match headers[hdr] with it when it = StringValues.Empty -> None | it -> Some it[0]
/// Extensions to the header dictionary
type IHeaderDictionary with
/// Indicates that the request is via an element using `hx-boost`
member this.HxBoosted with get () = hdr this "HX-Boosted" |> Option.map bool.Parse
/// <summary>Indicates that the request is via an element using <c>hx-boost</c></summary>
member this.HxBoosted
with get () = hdr this "HX-Boosted" |> Option.map bool.Parse
/// The current URL of the browser _(note that this does not update until after settle)_
member this.HxCurrentUrl with get () = hdr this "HX-Current-URL" |> Option.map Uri
/// <summary>The current URL of the browser <em>(note that this does not update until after settle)</em></summary>
member this.HxCurrentUrl
with get () = hdr this "HX-Current-URL" |> Option.map Uri
/// `true` if the request is for history restoration after a miss in the local history cache
member this.HxHistoryRestoreRequest with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse
/// <summary><c>true</c> if the request is for history restoration after a miss in the local history cache</summary>
member this.HxHistoryRestoreRequest
with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse
/// The user response to an `hx-prompt`
member this.HxPrompt with get () = hdr this "HX-Prompt"
/// <summary>The user response to an <c>hx-prompt</c></summary>
member this.HxPrompt
with get () = hdr this "HX-Prompt"
/// `true` if the request came from HTMX
member this.HxRequest with get () = hdr this "HX-Request" |> Option.map bool.Parse
/// <summary><c>true</c> if the request came from htmx</summary>
member this.HxRequest
with get () = hdr this "HX-Request" |> Option.map bool.Parse
/// The `id` of the target element if it exists
member this.HxTarget with get () = hdr this "HX-Target"
/// <summary>The <c>id</c> attribute of the target element if it exists</summary>
member this.HxTarget
with get () = hdr this "HX-Target"
/// The `id` of the triggered element if it exists
member this.HxTrigger with get () = hdr this "HX-Trigger"
/// <summary>The <c>id</c> attribute of the triggered element if it exists</summary>
member this.HxTrigger
with get () = hdr this "HX-Trigger"
/// The `name` of the triggered element if it exists
member this.HxTriggerName with get () = hdr this "HX-Trigger-Name"
/// <summary>The <c>name</c> attribute of the triggered element if it exists</summary>
member this.HxTriggerName
with get () = hdr this "HX-Trigger-Name"
/// Extensions for the request object
type HttpRequest with
/// Whether this request was initiated from HTMX
member this.IsHtmx with get () = this.Headers.HxRequest |> Option.defaultValue false
/// <summary>Whether this request was initiated from htmx</summary>
member this.IsHtmx
with get () = this.Headers.HxRequest |> Option.defaultValue false
/// Whether this request is an HTMX history-miss refresh request
member this.IsHtmxRefresh with get () =
this.IsHtmx && (this.Headers.HxHistoryRestoreRequest |> Option.defaultValue false)
/// <summary>Whether this request is an htmx history-miss refresh request</summary>
member this.IsHtmxRefresh
with get () = this.IsHtmx && (this.Headers.HxHistoryRestoreRequest |> Option.defaultValue false)
/// HTTP handlers for setting output headers
/// <summary>HTTP handlers for setting output headers</summary>
[<AutoOpen>]
module Handlers =
/// Convert a boolean to lowercase `true` or `false`
let private toLowerBool (trueOrFalse : bool) =
(string trueOrFalse).ToLowerInvariant ()
open Giraffe.Htmx.Common
/// Serialize a list of key/value pairs to JSON (very rudimentary)
let private toJson (evts : (string * string) list) =
evts
|> List.map (fun evt -> sprintf "\"%s\": \"%s\"" (fst evt) ((snd evt).Replace ("\"", "\\\"")))
|> String.concat ", "
|> sprintf "{ %s }"
/// <summary>Instruct htmx to perform a client-side redirect for content</summary>
/// <param name="path">The path where the content should be found</param>
/// <returns>An HTTP handler with the <c>HX-Location</c> header set</returns>
/// <seealso href="https://htmx.org/headers/hx-location/">Documentation</seealso>
let withHxLocation (path: string) : HttpHandler =
setHttpHeader "HX-Location" path
// Pushes a new url into the history stack
let withHxPush : string -> HttpHandler =
setHttpHeader "HX-Push"
/// <summary>Pushes a new url into the history stack</summary>
/// <param name="url">The URL to be pushed</param>
/// <returns>An HTTP handler with the <c>HX-Push-Url</c> header set</returns>
/// <remarks>Use <see cref="withHxNoPushUrl" /> to explicitly not push a new URL</remarks>
/// <seealso href="https://htmx.org/headers/hx-push-url/">Documentation</seealso>
let withHxPushUrl (url: string) : HttpHandler =
setHttpHeader "HX-Push-Url" url
/// Can be used to do a client-side redirect to a new location
let withHxRedirect : string -> HttpHandler =
setHttpHeader "HX-Redirect"
/// <summary>Explicitly do not push a new URL into the history stack</summary>
/// <returns>An HTTP handler with the <c>HX-Push-Url</c> header set to <c>false</c></returns>
/// <seealso href="https://htmx.org/headers/hx-push-url/">Documentation</seealso>
let withHxNoPushUrl : HttpHandler =
toLowerBool false |> withHxPushUrl
/// If set to `true` the client side will do a a full refresh of the page
let withHxRefresh : bool -> HttpHandler =
toLowerBool >> setHttpHeader "HX-Refresh"
/// <summary>Can be used to do a client-side redirect to a new location</summary>
/// <param name="url">The URL to which the client should be redirected</param>
/// <returns>An HTTP handler with the <c>HX-Redirect</c> header set</returns>
/// <seealso href="https://htmx.org/headers/hx-redirect/">Documentation</seealso>
let withHxRedirect (url: string) : HttpHandler =
setHttpHeader "HX-Redirect" url
/// Allows you to trigger a single client side event
let withHxTrigger : string -> HttpHandler =
setHttpHeader "HX-Trigger"
/// <summary>If set to <c>true</c> the client side will do a full refresh of the page</summary>
/// <param name="shouldRefresh">Whether the client should refresh their page</param>
/// <returns>An HTTP handler with the <c>HX-Refresh</c> header set</returns>
let withHxRefresh shouldRefresh : HttpHandler =
(toLowerBool >> setHttpHeader "HX-Refresh") shouldRefresh
/// Allows you to trigger multiple client side events
/// <summary>Replaces the current URL in the history stack</summary>
/// <param name="url">The URL to place in the history stack in place of the current one</param>
/// <returns>An HTTP handler with the <c>HX-Replace-URL</c> header set</returns>
/// <remarks>Use <see cref="withHxNoRelaceUrl" /> to explicitly not replace the current URL</remarks>
/// <seealso href="https://htmx.org/headers/hx-replace-url/">Documentation</seealso>
let withHxReplaceUrl url : HttpHandler =
setHttpHeader "HX-Replace-Url" url
/// <summary>Explicitly do not replace the current URL in the history stack</summary>
/// <returns>An HTTP handler with the <c>HX-Replace-URL</c> header set to <c>false</c></returns>
/// <seealso href="https://htmx.org/headers/hx-replace-url/">Documentation</seealso>
let withHxNoReplaceUrl : HttpHandler =
toLowerBool false |> withHxReplaceUrl
/// <summary>Override which portion of the response will be swapped into the target document</summary>
/// <param name="target">The selector for the new response target</param>
/// <returns>An HTTP handler with the <c>HX-Reselect</c> header set</returns>
let withHxReselect (target: string) : HttpHandler =
setHttpHeader "HX-Reselect" target
/// <summary>Override the <c>hx-swap</c> attribute from the initiating element</summary>
/// <param name="swap">The swap value to override</param>
/// <returns>An HTTP handler with the <c>HX-Reswap</c> header set</returns>
/// <remarks>Use <see cref="T:Giraffe.Htmx.Common.HxSwap">HxSwap</see> constants for best results</remarks>
let withHxReswap (swap: string) : HttpHandler =
setHttpHeader "HX-Reswap" swap
/// <summary>Allows you to override the <c>hx-target</c> attribute</summary>
/// <param name="target">The new target for the response</param>
/// <returns>An HTTP handler with the <c>HX-Retarget</c> header set</returns>
let withHxRetarget (target: string) : HttpHandler =
setHttpHeader "HX-Retarget" target
/// <summary>Allows you to trigger a single client side event</summary>
/// <param name="evt">The call to the event that should be triggered</param>
/// <returns>An HTTP handler with the <c>HX-Trigger</c> header set</returns>
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTrigger (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger" evt
/// <summary>Allows you to trigger multiple client side events</summary>
/// <param name="evts">The calls to events that should be triggered</param>
/// <returns>An HTTP handler with the <c>HX-Trigger</c> header set for all given events</returns>
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTriggerMany evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger"
/// Allows you to trigger a single client side event after changes have settled
let withHxTriggerAfterSettle : string -> HttpHandler =
setHttpHeader "HX-Trigger-After-Settle"
/// <summary>Allows you to trigger a single client side event after changes have settled</summary>
/// <param name="evt">The call to the event that should be triggered</param>
/// <returns>An HTTP handler with the <c>HX-Trigger-After-Settle</c> header set</returns>
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTriggerAfterSettle (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger-After-Settle" evt
/// Allows you to trigger multiple client side events after changes have settled
/// <summary>Allows you to trigger multiple client side events after changes have settled</summary>
/// <param name="evts">The calls to events that should be triggered</param>
/// <returns>An HTTP handler with the <c>HX-Trigger-After-Settle</c> header set for all given events</returns>
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTriggerManyAfterSettle evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger-After-Settle"
/// Allows you to trigger a single client side event after DOM swapping occurs
let withHxTriggerAfterSwap : string -> HttpHandler =
setHttpHeader "HX-Trigger-After-Swap"
/// <summary>Allows you to trigger a single client side event after DOM swapping occurs</summary>
/// <param name="evt">The call to the event that should be triggered</param>
/// <returns>An HTTP handler with the <c>HX-Trigger-After-Swap</c> header set</returns>
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTriggerAfterSwap (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger-After-Swap" evt
/// Allows you to trigger multiple client side events after DOM swapping occurs
/// <summary>Allows you to trigger multiple client side events after DOM swapping occurs</summary>
/// <param name="evts">The calls to events that should be triggered</param>
/// <returns>An HTTP handler with the <c>HX-Trigger-After-Swap</c> header set for all given events</returns>
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
let withHxTriggerManyAfterSwap evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger-After-Swap"

39
src/Htmx/README.md Normal file
View File

@@ -0,0 +1,39 @@
## Giraffe.Htmx
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**
_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.*._
### Setup
1. Install the package.
2. Prior to using the request header extension properties or the header-setting `HttpHandler`s, `open Giraffe.Htmx`.
### Use
To obtain a request header, using the `IHeaderDictionary` extension properties:
```fsharp
let myHandler : HttpHander =
fun next ctx ->
match ctx.HxPrompt with
| Some prompt -> ... // do something with the text the user provided
| None -> ... // no text provided
```
To set a response header:
```fsharp
let myHandler : HttpHander =
fun next ctx ->
// some meaningful work
withHxPushUrl "/some/new/url" >=> [other handlers]
```
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.
### 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.

33
src/Tests/Common.fs Normal file
View File

@@ -0,0 +1,33 @@
module Common
open Expecto
open Giraffe.Htmx
/// Tests for the HxSwap module
let swap =
testList "HxSwap" [
test "InnerHtml is correct" {
Expect.equal HxSwap.InnerHtml "innerHTML" "Inner HTML swap value incorrect"
}
test "OuterHtml is correct" {
Expect.equal HxSwap.OuterHtml "outerHTML" "Outer HTML swap value incorrect"
}
test "BeforeBegin is correct" {
Expect.equal HxSwap.BeforeBegin "beforebegin" "Before Begin swap value incorrect"
}
test "BeforeEnd is correct" {
Expect.equal HxSwap.BeforeEnd "beforeend" "Before End swap value incorrect"
}
test "AfterBegin is correct" {
Expect.equal HxSwap.AfterBegin "afterbegin" "After Begin swap value incorrect"
}
test "AfterEnd is correct" {
Expect.equal HxSwap.AfterEnd "afterend" "After End swap value incorrect"
}
test "None is correct" {
Expect.equal HxSwap.None "none" "None swap value incorrect"
}
]
/// All tests for this module
let allTests = testList "Htmx.Common" [ swap ]

358
src/Tests/Htmx.fs Normal file
View File

@@ -0,0 +1,358 @@
module Htmx
open System
open Expecto
open Giraffe.Htmx
open Microsoft.AspNetCore.Http
open NSubstitute
/// Tests for the IHeaderDictionary extension properties
let dictExtensions =
testList "IHeaderDictionaryExtensions" [
testList "HxBoosted" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxBoosted "There should not have been a header returned"
}
test "succeeds when the header is present and true" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Boosted", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxBoosted "There should be a header present"
Expect.isTrue ctx.Request.Headers.HxBoosted.Value "The header value should have been true"
}
test "succeeds when the header is present and false" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Boosted", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxBoosted "There should be a header present"
Expect.isFalse ctx.Request.Headers.HxBoosted.Value "The header value should have been false"
}
]
testList "HxCurrentUrl" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxCurrentUrl "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-Current-URL", "http://localhost/test.htm")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxCurrentUrl "There should be a header present"
Expect.equal
ctx.Request.Headers.HxCurrentUrl.Value (Uri "http://localhost/test.htm")
"The header value was not correct"
}
]
testList "HxHistoryRestoreRequest" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxHistoryRestoreRequest "There should not have been a header returned"
}
test "succeeds when the header is present and true" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-History-Restore-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxHistoryRestoreRequest "There should be a header present"
Expect.isTrue ctx.Request.Headers.HxHistoryRestoreRequest.Value "The header value should have been true"
}
test "succeeds when the header is present and false" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-History-Restore-Request", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxHistoryRestoreRequest "There should be a header present"
Expect.isFalse
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" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxRequest "There should not have been a header returned"
}
test "succeeds when the header is present and true" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxRequest "There should be a header present"
Expect.isTrue ctx.Request.Headers.HxRequest.Value "The header should have been true"
}
test "succeeds when the header is present and false" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxRequest "There should be a header present"
Expect.isFalse ctx.Request.Headers.HxRequest.Value "The header should have been false"
}
]
testList "HxTarget" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxTarget "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-Target", "#leItem")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTarget "There should be a header present"
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
let reqExtensions =
testList "HttpRequestExtensions" [
testList "IsHtmx" [
test "succeeds when request is not from htmx" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isFalse ctx.Request.IsHtmx "The request should not be an htmx request"
}
test "succeeds when request is from htmx" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isTrue ctx.Request.IsHtmx "The request should have been an htmx request"
}
]
testList "IsHtmxRefresh" [
test "succeeds when request is not from htmx" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isFalse ctx.Request.IsHtmxRefresh "The request should not have been an htmx refresh"
}
test "succeeds when request is from htmx, but not a refresh" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isFalse ctx.Request.IsHtmxRefresh "The request should not have been an htmx refresh"
}
test "IsHtmxRefresh succeeds when request is from htmx and is a refresh" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request", "true")
dic.Add("HX-History-Restore-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isTrue ctx.Request.IsHtmxRefresh "The request should have been an htmx refresh"
}
]
]
open System.Threading.Tasks
/// Dummy "next" parameter to get the pipeline to execute/terminate
let next (ctx: HttpContext) = Task.FromResult(Some ctx)
/// Tests for the HttpHandler functions provided in the Handlers module
let handlers =
testList "HandlerTests" [
testTask "withHxLocation succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxLocation "/pagina-otro.html" next ctx
Expect.isTrue (dic.ContainsKey "HX-Location") "The HX-Location header should be present"
Expect.equal dic["HX-Location"].[0] "/pagina-otro.html" "The HX-Location value was incorrect"
}
testTask "withHxPushUrl succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxPushUrl "/a-new-url" next ctx
Expect.isTrue (dic.ContainsKey "HX-Push-Url") "The HX-Push-Url header should be present"
Expect.equal dic["HX-Push-Url"].[0] "/a-new-url" "The HX-Push-Url value was incorrect"
}
testTask "withHxNoPushUrl succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxNoPushUrl next ctx
Expect.isTrue (dic.ContainsKey "HX-Push-Url") "The HX-Push-Url header should be present"
Expect.equal dic["HX-Push-Url"].[0] "false" "The HX-Push-Url value was incorrect"
}
testTask "withHxRedirect succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRedirect "/somewhere-else" next ctx
Expect.isTrue (dic.ContainsKey "HX-Redirect") "The HX-Redirect header should be present"
Expect.equal dic["HX-Redirect"].[0] "/somewhere-else" "The HX-Redirect value was incorrect"
}
testList "withHxRefresh" [
testTask "succeeds when set to true" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRefresh true next ctx
Expect.isTrue (dic.ContainsKey "HX-Refresh") "The HX-Refresh header should be present"
Expect.equal dic["HX-Refresh"].[0] "true" "The HX-Refresh value was incorrect"
}
testTask "succeeds when set to false" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRefresh false next ctx
Expect.isTrue (dic.ContainsKey "HX-Refresh") "The HX-Refresh header should be present"
Expect.equal dic["HX-Refresh"].[0] "false" "The HX-Refresh value was incorrect"
}
]
testTask "withHxReplaceUrl succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxReplaceUrl "/a-substitute-url" next ctx
Expect.isTrue (dic.ContainsKey "HX-Replace-Url") "The HX-Replace-Url header should be present"
Expect.equal dic["HX-Replace-Url"].[0] "/a-substitute-url" "The HX-Replace-Url value was incorrect"
}
testTask "withHxNoReplaceUrl succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxNoReplaceUrl next ctx
Expect.isTrue (dic.ContainsKey "HX-Replace-Url") "The HX-Replace-Url header should be present"
Expect.equal dic["HX-Replace-Url"].[0] "false" "The HX-Replace-Url value was incorrect"
}
testTask "withHxReselect succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxReselect "#test" next ctx
Expect.isTrue (dic.ContainsKey "HX-Reselect") "The HX-Reselect header should be present"
Expect.equal dic["HX-Reselect"].[0] "#test" "The HX-Reselect value was incorrect"
}
testTask "withHxReswap succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxReswap HxSwap.BeforeEnd next ctx
Expect.isTrue (dic.ContainsKey "HX-Reswap") "The HX-Reswap header should be present"
Expect.equal dic["HX-Reswap"].[0] HxSwap.BeforeEnd "The HX-Reswap value was incorrect"
}
testTask "withHxRetarget succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRetarget "#somewhereElse" next ctx
Expect.isTrue (dic.ContainsKey "HX-Retarget") "The HX-Retarget header should be present"
Expect.equal dic["HX-Retarget"].[0] "#somewhereElse" "The HX-Retarget value was incorrect"
}
testTask "withHxTrigger succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTrigger "doSomething" next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present"
Expect.equal dic["HX-Trigger"].[0] "doSomething" "The HX-Trigger value was incorrect"
}
testTask "withHxTriggerMany succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerMany [ "blah", "foo"; "bleh", "bar" ] next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present"
Expect.equal
dic["HX-Trigger"].[0] """{ "blah": "foo", "bleh": "bar" }""" "The HX-Trigger value was incorrect"
}
testTask "withHxTriggerAfterSettle succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerAfterSettle "byTheWay" next ctx
Expect.isTrue
(dic.ContainsKey "HX-Trigger-After-Settle") "The HX-Trigger-After-Settle header should be present"
Expect.equal dic["HX-Trigger-After-Settle"].[0] "byTheWay" "The HX-Trigger-After-Settle value was incorrect"
}
testTask "withHxTriggerManyAfterSettle succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerManyAfterSettle [ "oof", "ouch"; "hmm", "uh" ] next ctx
Expect.isTrue
(dic.ContainsKey "HX-Trigger-After-Settle") "The HX-Trigger-After-Settle header should be present"
Expect.equal
dic["HX-Trigger-After-Settle"].[0] """{ "oof": "ouch", "hmm": "uh" }"""
"The HX-Trigger-After-Settle value was incorrect"
}
testTask "withHxTriggerAfterSwap succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerAfterSwap "justASec" next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger-After-Swap") "The HX-Trigger-After-Swap header should be present"
Expect.equal dic["HX-Trigger-After-Swap"].[0] "justASec" "The HX-Trigger-After-Swap value was incorrect"
}
testTask "withHxTriggerManyAfterSwap succeeds" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerManyAfterSwap [ "this", "1"; "that", "2" ] next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger-After-Swap") "The HX-Trigger-After-Swap header should be present"
Expect.equal
dic["HX-Trigger-After-Swap"].[0] """{ "this": "1", "that": "2" }"""
"The HX-Trigger-After-Swap value was incorrect"
}
]
/// All tests for this module
let allTests = testList "Htmx" [ dictExtensions; reqExtensions; handlers ]

6
src/Tests/Program.fs Normal file
View File

@@ -0,0 +1,6 @@
open Expecto
let allTests = testList "Giraffe" [ Common.allTests; Htmx.allTests; ViewEngine.allTests ]
[<EntryPoint>]
let main args = runTestsWithCLIArgs [] args allTests

26
src/Tests/Tests.fsproj Normal file
View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Include="Common.fs" />
<Compile Include="Htmx.fs" />
<Compile Include="ViewEngine.fs" />
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Giraffe.Htmx.Common.fsproj" />
<ProjectReference Include="..\Htmx\Giraffe.Htmx.fsproj" />
<ProjectReference Include="..\ViewEngine.Htmx\Giraffe.ViewEngine.Htmx.fsproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Expecto" Version="10.2.1" />
<PackageReference Include="NSubstitute" Version="5.1.0" />
<PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup>
</Project>

1025
src/Tests/ViewEngine.fs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,33 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
<GenerateProgramFile>false</GenerateProgramFile>
</PropertyGroup>
<ItemGroup>
<Compile Include="Tests.fs" />
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Giraffe.ViewEngine" Version="1.4.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ViewEngine.Htmx\Giraffe.ViewEngine.Htmx.fsproj" />
</ItemGroup>
</Project>

View File

@@ -1 +0,0 @@
module Program = let [<EntryPoint>] main _ = 0

View File

@@ -1,245 +0,0 @@
module Giraffe.ViewEngine.Htmx.Tests
open Giraffe.ViewEngine
open Xunit
/// Tests for the HxEncoding module
module Encoding =
[<Fact>]
let ``Form is correct`` () =
Assert.Equal ("application/x-www-form-urlencoded", HxEncoding.Form)
[<Fact>]
let ``MultipartForm is correct`` () =
Assert.Equal ("multipart/form-data", HxEncoding.MultipartForm)
/// Tests for the HxParams module
module Params =
[<Fact>]
let ``All is correct`` () =
Assert.Equal ("*", HxParams.All)
[<Fact>]
let ``None is correct`` () =
Assert.Equal ("none", HxParams.None)
[<Fact>]
let ``With succeeds with empty list`` () =
Assert.Equal ("", HxParams.With [])
[<Fact>]
let ``With succeeds with one list item`` () =
Assert.Equal ("boo", HxParams.With [ "boo" ])
[<Fact>]
let ``With succeeds with multiple list items`` () =
Assert.Equal ("foo,bar,baz", HxParams.With [ "foo"; "bar"; "baz" ])
[<Fact>]
let ``Except succeeds with empty list`` () =
Assert.Equal ("not ", HxParams.Except [])
[<Fact>]
let ``Except succeeds with one list item`` () =
Assert.Equal ("not that", HxParams.Except [ "that" ])
[<Fact>]
let ``Except succeeds with multiple list items`` () =
Assert.Equal ("not blue,green", HxParams.Except [ "blue"; "green" ])
/// Tests for the HxSwap module
module Swap =
[<Fact>]
let ``InnerHtml is correct`` () =
Assert.Equal ("innerHTML", HxSwap.InnerHtml)
[<Fact>]
let ``OuterHtml is correct`` () =
Assert.Equal ("outerHTML", HxSwap.OuterHtml)
[<Fact>]
let ``BeforeBegin is correct`` () =
Assert.Equal ("beforebegin", HxSwap.BeforeBegin)
[<Fact>]
let ``BeforeEnd is correct`` () =
Assert.Equal ("beforeend", HxSwap.BeforeEnd)
[<Fact>]
let ``AfterBegin is correct`` () =
Assert.Equal ("afterbegin", HxSwap.AfterBegin)
[<Fact>]
let ``AfterEnd is correct`` () =
Assert.Equal ("afterend", HxSwap.AfterEnd)
[<Fact>]
let ``None is correct`` () =
Assert.Equal ("none", HxSwap.None)
/// Tests for the HxTrigger module
module Trigger =
[<Fact>]
let ``Click is correct`` () =
Assert.Equal ("click", HxTrigger.Click)
[<Fact>]
let ``Load is correct`` () =
Assert.Equal ("load", HxTrigger.Load)
[<Fact>]
let ``Filter.Alt succeeds`` () =
Assert.Equal ("click[altKey]", HxTrigger.Filter.Alt HxTrigger.Click)
[<Fact>]
let ``Filter.Ctrl succeeds`` () =
Assert.Equal ("click[ctrlKey]", HxTrigger.Filter.Ctrl HxTrigger.Click)
[<Fact>]
let ``Filter.Shift succeeds`` () =
Assert.Equal ("click[shiftKey]", HxTrigger.Filter.Shift HxTrigger.Click)
[<Fact>]
let ``Filter.CtrlAlt succeeds`` () =
Assert.Equal ("click[ctrlKey&&altKey]", HxTrigger.Filter.CtrlAlt HxTrigger.Click)
[<Fact>]
let ``Filter.CtrlShift succeeds`` () =
Assert.Equal ("click[ctrlKey&&shiftKey]", HxTrigger.Filter.CtrlShift HxTrigger.Click)
[<Fact>]
let ``Filter.CtrlAltShift succeeds`` () =
Assert.Equal ("click[ctrlKey&&altKey&&shiftKey]", HxTrigger.Filter.CtrlAltShift HxTrigger.Click)
[<Fact>]
let ``Filter.AltShift succeeds`` () =
Assert.Equal ("click[altKey&&shiftKey]", HxTrigger.Filter.AltShift HxTrigger.Click)
/// Tests for the HtmxAttrs module
module Attributes =
/// Pipe-able assertion for a rendered node
let shouldRender expected node = Assert.Equal (expected, RenderView.AsString.htmlNode node)
[<Fact>]
let ``_hxBoost succeeds`` () =
div [ _hxBoost ] [] |> shouldRender """<div hx-boost="true"></div>"""
[<Fact>]
let ``_hxConfirm succeeds`` () =
button [ _hxConfirm "REALLY?!?" ] [] |> shouldRender """<button hx-confirm="REALLY?!?"></button>"""
[<Fact>]
let ``_hxDelete succeeds`` () =
span [ _hxDelete "/this-endpoint" ] [] |> shouldRender """<span hx-delete="/this-endpoint"></span>"""
[<Fact>]
let ``_hxDisable succeeds`` () =
p [ _hxDisable ] [] |> shouldRender """<p hx-disable></p>"""
[<Fact>]
let ``_hxEncoding succeeds`` () =
form [ _hxEncoding "utf-7" ] [] |> shouldRender """<form hx-encoding="utf-7"></form>"""
[<Fact>]
let ``_hxExt succeeds`` () =
section [ _hxExt "extendme" ] [] |> shouldRender """<section hx-ext="extendme"></section>"""
[<Fact>]
let ``_hxGet succeeds`` () =
article [ _hxGet "/the-text" ] [] |> shouldRender """<article hx-get="/the-text"></article>"""
[<Fact>]
let ``_hxHeaders succeeds`` () =
figure [ _hxHeaders """{ "X-Special-Header": "some-header" }""" ] []
|> shouldRender """<figure hx-headers="{ &quot;X-Special-Header&quot;: &quot;some-header&quot; }"></figure>"""
[<Fact>]
let ``_hxHistoryElt succeeds`` () =
table [ _hxHistoryElt ] [] |> shouldRender """<table hx-history-elt></table>"""
[<Fact>]
let ``_hxInclude succeeds`` () =
a [ _hxInclude ".extra-stuff" ] [] |> shouldRender """<a hx-include=".extra-stuff"></a>"""
[<Fact>]
let ``_hxIndicator succeeds`` () =
aside [ _hxIndicator "#spinner" ] [] |> shouldRender """<aside hx-indicator="#spinner"></aside>"""
[<Fact>]
let ``_hxNoBoost succeeds`` () =
td [ _hxNoBoost ] [] |> shouldRender """<td hx-boost="false"></td>"""
[<Fact>]
let ``_hxParams succeeds`` () =
br [ _hxParams "[p1,p2]" ] |> shouldRender """<br hx-params="[p1,p2]">"""
[<Fact>]
let ``_hxPatch succeeds`` () =
div [ _hxPatch "/arrrgh" ] [] |> shouldRender """<div hx-patch="/arrrgh"></div>"""
[<Fact>]
let ``_hxPost succeeds`` () =
hr [ _hxPost "/hear-ye-hear-ye" ] |> shouldRender """<hr hx-post="/hear-ye-hear-ye">"""
[<Fact>]
let ``_hxPreserve succeeds`` () =
img [ _hxPreserve ] |> shouldRender """<img hx-preserve="true">"""
[<Fact>]
let ``_hxPrompt succeeds`` () =
strong [ _hxPrompt "Who goes there?" ] [] |> shouldRender """<strong hx-prompt="Who goes there?"></strong>"""
[<Fact>]
let ``_hxPushUrl succeeds`` () =
dl [ _hxPushUrl ] [] |> shouldRender """<dl hx-push-url></dl>"""
[<Fact>]
let ``_hxPut succeeds`` () =
s [ _hxPut "/take-this" ] [] |> shouldRender """<s hx-put="/take-this"></s>"""
[<Fact>]
let ``_hxRequest succeeds`` () =
u [ _hxRequest "noHeaders" ] [] |> shouldRender """<u hx-request="noHeaders"></u>"""
[<Fact>]
let ``_hxSelect succeeds`` () =
nav [ _hxSelect "#navbar" ] [] |> shouldRender """<nav hx-select="#navbar"></nav>"""
[<Fact>]
let ``_hxSse succeeds`` () =
footer [ _hxSse "connect:/my-events" ] [] |> shouldRender """<footer hx-sse="connect:/my-events"></footer>"""
[<Fact>]
let ``_hxSwap succeeds`` () =
del [ _hxSwap "innerHTML" ] [] |> shouldRender """<del hx-swap="innerHTML"></del>"""
[<Fact>]
let ``_hxSwapOob succeeds`` () =
li [ _hxSwapOob "true" ] [] |> shouldRender """<li hx-swap-oob="true"></li>"""
[<Fact>]
let ``_hxTarget succeeds`` () =
header [ _hxTarget "#somewhereElse" ] [] |> shouldRender """<header hx-target="#somewhereElse"></header>"""
[<Fact>]
let ``_hxTrigger succeeds`` () =
figcaption [ _hxTrigger "load" ] [] |> shouldRender """<figcaption hx-trigger="load"></figcaption>"""
[<Fact>]
let ``_hxVals succeeds`` () =
dt [ _hxVals """{ "extra": "values" }""" ] []
|> shouldRender """<dt hx-vals="{ &quot;extra&quot;: &quot;values&quot; }"></dt>"""
[<Fact>]
let ``_hxWs succeeds`` () =
ul [ _hxWs "connect:/web-socket" ] [] |> shouldRender """<ul hx-ws="connect:/web-socket"></ul>"""

View File

@@ -1,17 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>Extensions to Giraffe View Engine to support htmx attributes and their values</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Compile Include="Htmx.fs" />
<None Include="README.md" Pack="true" PackagePath="\" />
<None Include="..\icon.png" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Giraffe.ViewEngine" Version="1.4.0" />
<PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Giraffe.Htmx.Common.fsproj" />
</ItemGroup>
</Project>

View File

@@ -1,139 +1,897 @@
module Giraffe.ViewEngine.Htmx
/// <summary>Types and functions supporting htmx attributes in Giraffe View Engine</summary>
module Giraffe.ViewEngine.Htmx
/// Valid values for the `hx-encoding` attribute
/// <summary>Valid values for the <c>hx-encoding</c> attribute</summary>
[<RequireQualifiedAccess>]
module HxEncoding =
/// A standard HTTP form
/// <summary>A standard HTTP form</summary>
[<Literal>]
let Form = "application/x-www-form-urlencoded"
/// A multipart form (used for file uploads)
/// <summary>A multipart form (used for file uploads)</summary>
[<Literal>]
let MultipartForm = "multipart/form-data"
// TODO: hx-header helper
/// Values / helpers for the `hx-params` attribute
/// <summary>The events recognized by htmx</summary>
[<Struct>]
type HxEvent =
/// <summary>Send this event to an element to abort a request</summary>
| Abort
/// <summary>Triggered after an AJAX request has completed processing a successful response</summary>
| AfterOnLoad
/// <summary>Triggered after htmx has initialized a node</summary>
| AfterProcessNode
/// <summary>Triggered after an AJAX request has completed</summary>
| AfterRequest
/// <summary>Triggered after the DOM has settled</summary>
| AfterSettle
/// <summary>Triggered after new content has been swapped in</summary>
| AfterSwap
/// <summary>Triggered before htmx disables an element or removes it from the DOM</summary>
| BeforeCleanupElement
/// <summary>Triggered before any response processing occurs</summary>
| BeforeOnLoad
/// <summary>Triggered before htmx initializes a node</summary>
| BeforeProcessNode
/// <summary>Triggered before an AJAX request is made</summary>
| BeforeRequest
/// <summary>Triggered before a swap is done, allows you to configure the swap</summary>
| BeforeSwap
/// <summary>Triggered just before an ajax request is sent</summary>
| BeforeSend
/// <summary>Triggered before the request, allows you to customize parameters, headers</summary>
| ConfigRequest
/// <summary>
/// Triggered after a trigger occurs on an element, allows you to cancel (or delay) issuing the AJAX request
/// </summary>
| Confirm
/// <summary>Triggered on an error during cache writing</summary>
| HistoryCacheError
/// <summary>Triggered on a cache miss in the history subsystem</summary>
| HistoryCacheMiss
/// <summary>Triggered on a unsuccessful remote retrieval</summary>
| HistoryCacheMissError
/// <summary>Triggered on a successful remote retrieval</summary>
| HistoryCacheMissLoad
/// <summary>Triggered when htmx handles a history restoration action</summary>
| HistoryRestore
/// <summary>Triggered before content is saved to the history cache</summary>
| BeforeHistorySave
/// <summary>Triggered when new content is added to the DOM</summary>
| Load
/// <summary>
/// Triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined
/// </summary>
| NoSseSourceError
/// <summary>Triggered when an exception occurs during the onLoad handling in htmx</summary>
| OnLoadError
/// <summary>Triggered after an out of band element as been swapped in</summary>
| OobAfterSwap
/// <summary>Triggered before an out of band element swap is done, allows you to configure the swap</summary>
| OobBeforeSwap
/// <summary>Triggered when an out of band element does not have a matching ID in the current DOM</summary>
| OobErrorNoTarget
/// <summary>Triggered after a prompt is shown</summary>
| Prompt
/// <summary>Triggered after an url is pushed into history</summary>
| PushedIntoHistory
/// <summary>Triggered when an HTTP response error (non-200 or 300 response code) occurs</summary>
| ResponseError
/// <summary>Triggered when a network error prevents an HTTP request from happening</summary>
| SendError
/// <summary>Triggered when an error occurs with a SSE source</summary>
| SseError
/// <summary>Triggered when a SSE source is opened</summary>
| SseOpen
/// <summary>Triggered when an error occurs during the swap phase</summary>
| SwapError
/// <summary>Triggered when an invalid target is specified</summary>
| TargetError
/// <summary>Triggered when a request timeout occurs</summary>
| Timeout
/// <summary>Triggered before an element is validated</summary>
| ValidationValidate
/// <summary>Triggered when an element fails validation</summary>
| ValidationFailed
/// <summary>Triggered when a request is halted due to validation errors</summary>
| ValidationHalted
/// <summary>Triggered when an ajax request aborts</summary>
| XhrAbort
/// <summary>Triggered when an ajax request ends</summary>
| XhrLoadEnd
/// <summary>Triggered when an ajax request starts</summary>
| XhrLoadStart
/// <summary>Triggered periodically during an ajax request that supports progress events</summary>
| XhrProgress
/// The htmx event name (fst) and kebab-case name (snd, for use with hx-on)
static member private Values = Map [
Abort, ("abort", "abort")
AfterOnLoad, ("afterOnLoad", "after-on-load")
AfterProcessNode, ("afterProcessNode", "after-process-node")
AfterRequest, ("afterRequest", "after-request")
AfterSettle, ("afterSettle", "after-settle")
AfterSwap, ("afterSwap", "after-swap")
BeforeCleanupElement, ("beforeCleanupElement", "before-cleanup-element")
BeforeOnLoad, ("beforeOnLoad", "before-on-load")
BeforeProcessNode, ("beforeProcessNode", "before-process-node")
BeforeRequest, ("beforeRequest", "before-request")
BeforeSwap, ("beforeSwap", "before-swap")
BeforeSend, ("beforeSend", "before-send")
ConfigRequest, ("configRequest", "config-request")
Confirm, ("confirm", "confirm")
HistoryCacheError, ("historyCacheError", "history-cache-error")
HistoryCacheMiss, ("historyCacheMiss", "history-cache-miss")
HistoryCacheMissError, ("historyCacheMissError", "history-cache-miss-error")
HistoryCacheMissLoad, ("historyCacheMissLoad", "history-cache-miss-load")
HistoryRestore, ("historyRestore", "history-restore")
BeforeHistorySave, ("beforeHistorySave", "before-history-save")
Load, ("load", "load")
NoSseSourceError, ("noSSESourceError", "no-sse-source-error")
OnLoadError, ("onLoadError", "on-load-error")
OobAfterSwap, ("oobAfterSwap", "oob-after-swap")
OobBeforeSwap, ("oobBeforeSwap", "oob-before-swap")
OobErrorNoTarget, ("oobErrorNoTarget", "oob-error-no-target")
Prompt, ("prompt", "prompt")
PushedIntoHistory, ("pushedIntoHistory", "pushed-into-history")
ResponseError, ("responseError", "response-error")
SendError, ("sendError", "send-error")
SseError, ("sseError", "sse-error")
SseOpen, ("sseOpen", "sse-open")
SwapError, ("swapError", "swap-error")
TargetError, ("targetError", "target-error")
Timeout, ("timeout", "timeout")
ValidationValidate, ("validation:validate", "validation:validate")
ValidationFailed, ("validation:failed", "validation:failed")
ValidationHalted, ("validation:halted", "validation:halted")
XhrAbort, ("xhr:abort", "xhr:abort")
XhrLoadEnd, ("xhr:loadend", "xhr:loadend")
XhrLoadStart, ("xhr:loadstart", "xhr:loadstart")
XhrProgress, ("xhr:progress", "xhr:progress")
]
/// <summary>The htmx event name</summary>
override this.ToString() = fst HxEvent.Values[this]
/// <summary>The <c>hx-on</c> variant of the htmx event name</summary>
member this.ToHxOnString() = snd HxEvent.Values[this]
/// <summary>Helper to create the <c>hx-headers</c> attribute</summary>
[<RequireQualifiedAccess>]
module HxHeaders =
/// <summary>Create headers from a list of key/value pairs</summary>
let From = Giraffe.Htmx.Common.toJson
/// <summary>Values / helpers for the <c>hx-params</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxParams =
/// Include all parameters
/// <summary>Include all parameters</summary>
[<Literal>]
let All = "*"
/// Include no parameters
/// <summary>Include no parameters</summary>
[<Literal>]
let None = "none"
/// Include the specified parameters
let With fields = match fields with [] -> "" | _ -> fields |> List.reduce (fun acc it -> $"{acc},{it}")
/// Exclude the specified parameters
let Except fields = With fields |> sprintf "not %s"
// TODO: hx-request helper
/// <summary>Include the specified parameters</summary>
/// <param name="fields">One or more fields to include in the request</param>
/// <returns>The list of fields for the <c>hx-params</c> attribute value</returns>
let With fields =
match fields with [] -> "" | _ -> fields |> List.reduce (fun acc it -> $"{acc},{it}")
/// Valid values for the `hx-swap` attribute (may be combined with swap/settle/scroll/show config)
/// <summary>Exclude the specified parameters</summary>
/// <param name="fields">One or more fields to exclude from the request</param>
/// <returns>The list of fields for the <c>hx-params</c> attribute value prefixed with "not"</returns>
let Except fields =
With fields |> sprintf "not %s"
/// <summary>Helpers to define <c>hx-request</c> attribute values</summary>
/// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxSwap =
/// The default, replace the inner html of the target element
let InnerHtml = "innerHTML"
/// Replace the entire target element with the response
let OuterHtml = "outerHTML"
/// Insert the response before the target element
let BeforeBegin = "beforebegin"
/// Insert the response before the first child of the target element
let AfterBegin = "afterbegin"
/// Insert the response after the last child of the target element
let BeforeEnd = "beforeend"
/// Insert the response after the target element
let AfterEnd = "afterend"
/// Does not append content from response (out of band items will still be processed).
let None = "none"
module HxRequest =
/// Helpers for the `hx-trigger` attribute
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>Helpers for the <c>hx-sync</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-sync/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxSync =
/// <summary>Drop (ignore) this request if a request is already in flight</summary>
/// <remarks>This is the default for <c>hx-sync</c></remarks>
[<Literal>]
let Drop = "drop"
/// <summary>
/// Drop (ignore) this request if a request is already in flight, and if another request occurs while this one is in
/// flight, abort this request
/// </summary>
[<Literal>]
let Abort = "abort"
/// <summary>Abort any current in-flight request and replace it with this one</summary>
[<Literal>]
let Replace = "replace"
/// <summary>Place this request in an element-associated queue</summary>
[<Literal>]
let Queue = "queue"
/// <summary>Queue only the first request received while another request is in flight</summary>
[<Literal>]
let QueueFirst = "queue first"
/// <summary>Queue only the last request received while another request is in flight</summary>
[<Literal>]
let QueueLast = "queue last"
/// <summary>Queue all requests received while another request is in flight</summary>
[<Literal>]
let QueueAll = "queue all"
/// <summary>Helpers for the <c>hx-trigger</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-trigger/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxTrigger =
/// Append a filter to a trigger
let private appendFilter filter (trigger : string) =
match trigger.Contains "[" with
| true ->
let parts = trigger.Split ('[', ']')
$"{parts.[0]}[{parts.[1]}&&{filter}]"
$"{parts[0]}[{parts[1]}&&{filter}]"
| false -> $"{trigger}[{filter}]"
/// Trigger the event on a click
/// <summary>Trigger the event on a click</summary>
[<Literal>]
let Click = "click"
/// Trigger the event on page load
/// <summary>Trigger the event on page load</summary>
[<Literal>]
let Load = "load"
/// Helpers for defining filters
/// <summary>Trigger the event when the item is visible</summary>
[<Literal>]
let Revealed = "revealed"
/// <summary>Trigger this event every [timing declaration]</summary>
/// <param name="duration">The duration on which this trigger should fire (e.g., "1s", "500ms")</param>
/// <returns>A trigger timing specification</returns>
let Every duration =
$"every %s{duration}"
/// <summary>Helpers for defining filters</summary>
module Filter =
/// Only trigger the event if the `ALT` key is pressed
/// <summary>Only trigger the event if the <c>ALT</c> key is pressed</summary>
let Alt = appendFilter "altKey"
/// Only trigger the event if the `CTRL` key is pressed
/// <summary>Only trigger the event if the <c>CTRL</c> key is pressed</summary>
let Ctrl = appendFilter "ctrlKey"
/// Only trigger the event if the `SHIFT` key is pressed
/// <summary>Only trigger the event if the <c>SHIFT</c> key is pressed</summary>
let Shift = appendFilter "shiftKey"
/// Only trigger the event if `CTRL+ALT` are pressed
/// <summary>Only trigger the event if <c>CTRL</c> and <c>ALT</c> are pressed</summary>
let CtrlAlt = Ctrl >> Alt
/// Only trigger the event if `CTRL+SHIFT` are pressed
/// <summary>Only trigger the event if <c>CTRL</c> and <c>SHIFT</c> are pressed</summary>
let CtrlShift = Ctrl >> Shift
/// Only trigger the event if `CTRL+ALT+SHIFT` are pressed
/// <summary>Only trigger the event if <c>CTRL</c>, <c>ALT</c>, and <c>SHIFT</c> are pressed</summary>
let CtrlAltShift = CtrlAlt >> Shift
/// Only trigger the event if `ALT+SHIFT` are pressed
/// <summary>Only trigger the event if <c>ALT</c> and <c>SHIFT</c> are pressed</summary>
let AltShift = Alt >> Shift
// TODO: more stuff for the hx-trigger helper
/// Append a modifier to the current trigger
let private appendModifier modifier current =
if current = "" then modifier else $"{current} {modifier}"
// TODO: hx-vals helper
/// <summary>Only trigger once</summary>
/// <param name="action">The action which should only be fired once</param>
/// <returns>A trigger spec to fire the given action once</returns>
let Once action =
appendModifier "once" action
/// <summary>Trigger when changed</summary>
/// <param name="elt">The element from which the <c>onchange</c> event will be emitted</param>
/// <returns>A trigger spec to fire when the given element changes</returns>
let Changed elt =
appendModifier "changed" elt
/// <summary>Delay execution; resets every time the event is seen</summary>
/// <param name="duration">The duration for the delay (e.g., "1s", "500ms")</param>
/// <param name="action">The action which should be fired after the given delay</param>
/// <returns>A trigger spec to fire the given action after the specified delay</returns>
let Delay duration action =
appendModifier $"delay:%s{duration}" action
/// <summary>Throttle execution; ignore other events, fire when duration passes</summary>
/// <param name="duration">The duration for the throttling (e.g., "1s", "500ms")</param>
/// <param name="action">The action which should be fired after the given duration</param>
/// <returns>A trigger spec to fire the given action after the specified duration</returns>
let Throttle duration action =
appendModifier $"throttle:%s{duration}" action
/// <summary>Trigger this event from a CSS selector</summary>
/// <param name="selector">A CSS selector to identify elements which may fire this trigger</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the given element(s)</returns>
let From selector action =
appendModifier $"from:%s{selector}" action
/// <summary>Trigger this event from the <c>document</c> object</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the <c>document</c> element</returns>
let FromDocument action =
From "document" action
/// <summary>Trigger this event from the <c>window</c> object</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the <c>window</c> object</returns>
let FromWindow action =
From "window" action
/// <summary>Trigger this event from the closest parent CSS selector</summary>
/// <param name="selector">The CSS selector from which the action should be fired</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the closest element</returns>
let FromClosest selector action =
From $"closest %s{selector}" action
/// <summary>Trigger this event from the closest child CSS selector</summary>
/// <param name="selector">The child CSS selector from which the action should be fired</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the closest child element</returns>
let FromFind selector action =
From $"find %s{selector}" action
/// <summary>Target the given CSS selector with the results of this event</summary>
/// <param name="selector">The CSS selector to which the result of the action will be applied</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to target the given selector</returns>
let Target selector action =
appendModifier $"target:%s{selector}" action
/// <summary>Prevent any further events from occurring after this one fires</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire the given action and prevent further events</returns>
let Consume action =
appendModifier "consume" action
/// <summary>
/// Configure queueing when events fire when others are in flight; if unspecified, the default is <c>last</c>
/// </summary>
/// <param name="how">
/// How the request should be queued (consider <see cref="QueueFirst" />, <see cref="QueueLast" />,
/// <see cref="QueueAll" />, and <see cref="QueueNone" />)
/// </param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let Queue how action =
let qSpec = if how = "" then "" else $":{how}"
appendModifier $"queue{qSpec}" action
/// <summary>Queue the first event, discard all others (i.e., a FIFO queue of 1)</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueFirst action =
Queue "first" action
/// <summary>Queue the last event; discards current when another is received (i.e., a LIFO queue of 1)</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueLast action =
Queue "last" action
/// <summary>Queue all events; discard none</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueAll action =
Queue "all" action
/// <summary>Queue no events; discard all</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueNone action =
Queue "none" action
/// Attributes and flags for HTMX
/// <summary>Helper to create the <c>hx-vals</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-vals/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxVals =
/// <summary>Create values from a list of key/value pairs</summary>
let From = Giraffe.Htmx.Common.toJson
open Giraffe.Htmx
/// <summary>Attributes and flags for htmx</summary>
[<AutoOpen>]
module HtmxAttrs =
/// Progressively enhances anchors and forms to use AJAX requests (use `_hxNoBoost` to set to false)
/// <summary>Progressively enhances anchors and forms to use AJAX requests</summary>
/// <remarks>Use <c>_hxNoBoost</c> to set to false</remarks>
/// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso>
let _hxBoost = attr "hx-boost" "true"
/// Shows a confirm() dialog before issuing a request
let _hxConfirm = attr "hx-confirm"
/// Issues a DELETE to the specified URL
let _hxDelete = attr "hx-delete"
/// Disables htmx processing for the given node and any children nodes
/// <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>
/// <returns>A configured <c>hx-confirm</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-confirm/">Documentation</seealso>
let _hxConfirm prompt =
attr "hx-confirm" prompt
/// <summary>Issues a <c>DELETE</c> to the specified URL</summary>
/// <param name="url">The URL to which the <c>DELETE</c> request should be sent</param>
/// <returns>A configured <c>hx-delete</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-delete/">Documentation</seealso>
let _hxDelete url =
attr "hx-delete" url
/// <summary>Disables htmx processing for the given node and any children nodes</summary>
/// <seealso href="https://htmx.org/attributes/hx-disable/">Documentation</seealso>
let _hxDisable = flag "hx-disable"
/// Changes the request encoding type
let _hxEncoding = attr "hx-encoding"
/// Extensions to use for this element
let _hxExt = attr "hx-ext"
/// Issues a GET to the specified URL
let _hxGet = attr "hx-get"
/// Adds to the headers that will be submitted with the request
let _hxHeaders = attr "hx-headers"
/// The element to snapshot and restore during history navigation
let _hxHistoryElt = flag "hx-history-elt"
/// Includes additional data in AJAX requests
let _hxInclude = attr "hx-include"
/// The element to put the htmx-request class on during the AJAX request
let _hxIndicator = attr "hx-indicator"
/// Overrides a previous `hx-boost`
let _hxNoBoost = attr "hx-boost" "false"
/// Filters the parameters that will be submitted with a request
let _hxParams = attr "hx-params"
/// Issues a PATCH to the specified URL
let _hxPatch = attr "hx-patch"
/// Issues a POST to the specified URL
let _hxPost = attr "hx-post"
/// Preserves an element between requests
let _hxPreserve = attr "hx-preserve" "true"
/// Shows a prompt before submitting a request
let _hxPrompt = attr "hx-prompt"
/// Pushes the URL into the location bar, creating a new history entry
let _hxPushUrl = flag "hx-push-url"
/// Issues a PUT to the specified URL
let _hxPut = attr "hx-put"
/// Configures various aspects of the request
let _hxRequest = attr "hx-request"
/// Selects a subset of the server response to process
let _hxSelect = attr "hx-select"
/// Establishes and listens to Server Sent Event (SSE) sources for events
let _hxSse = attr "hx-sse"
/// Controls how the response content is swapped into the DOM (e.g. 'outerHTML' or 'beforeEnd')
let _hxSwap = attr "hx-swap"
/// <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>
/// <returns>A configured <c>hx-disabled-elt</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-disabled-elt/">Documentation</seealso>
let _hxDisabledElt elt =
attr "hx-disabled-elt" elt
/// <summary>Disinherit all ("*") or specific htmx attributes</summary>
/// <param name="hxAttrs">The htmx attributes to disinherit (should start with "hx-")</param>
/// <returns>A configured <c>hx-disinherit</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-disinherit/">Documentation</seealso>
let _hxDisinherit hxAttrs =
attr "hx-disinherit" hxAttrs
/// <summary>Changes the request encoding type</summary>
/// <param name="enc">The encoding type (use <c>HxEncoding</c> constants)</param>
/// <returns>A configured <c>hx-encoding</c> attribute</returns>
/// <seealso cref="HxEncoding" />
/// <seealso href="https://htmx.org/attributes/hx-encoding/">Documentation</seealso>
let _hxEncoding enc =
attr "hx-encoding" enc
/// <summary>Extensions to use for this element</summary>
/// <param name="exts">A list of extensions to apply to this element</param>
/// <returns>A configured <c>hx-ext</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-ext/">Documentation</seealso>
let _hxExt exts =
attr "hx-ext" exts
/// <summary>Issues a <c>GET</c> to the specified URL</summary>
/// <param name="url">The URL to which the <c>GET</c> request should be sent</param>
/// <returns>A configured <c>hx-get</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-get/">Documentation</seealso>
let _hxGet url =
attr "hx-get" url
/// <summary>Adds to the headers that will be submitted with the request</summary>
/// <param name="hdrs">The headers to include with the request</param>
/// <returns>A configured <c>hx-headers</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-headers/">Documentation</seealso>
let _hxHeaders hdrs =
attr "hx-headers" hdrs
/// <summary>
/// Set to "false" to prevent pages with sensitive information from being stored in the history cache
/// </summary>
/// <param name="shouldStore">Whether the page should be stored in the history cache</param>
/// <returns>A configured <c>hx-history</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-history/">Documentation</seealso>
let _hxHistory shouldStore =
attr "hx-history" (toLowerBool shouldStore)
/// <summary>The element to snapshot and restore during history navigation</summary>
/// <seealso href="https://htmx.org/attributes/hx-history-elt/">Documentation</seealso>
let _hxHistoryElt =
flag "hx-history-elt"
/// <summary>Includes additional data in AJAX requests</summary>
/// <param name="spec">The specification of what should be included in the request</param>
/// <returns>A configured <c>hx-include</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-include/">Documentation</seealso>
let _hxInclude spec =
attr "hx-include" spec
/// <summary>The element to put the <c>htmx-request</c> class on during the AJAX request</summary>
/// <param name="selector">The selector for the indicator element</param>
/// <returns>A configured <c>hx-indicator</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-indicator/">Documentation</seealso>
let _hxIndicator selector =
attr "hx-indicator" selector
/// <summary>Overrides a previous <c>hx-boost</c> (hx-boost="false")</summary>
/// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso>
let _hxNoBoost =
attr "hx-boost" "false"
/// <summary>Attach an event handler for DOM events</summary>
/// <param name="evtName">The name of the event</param>
/// <param name="handler">The script to be executed when the event occurs</param>
/// <returns>A configured <c>hx-on</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-on/">Documentation</seealso>
let _hxOnEvent evtName handler =
attr $"hx-on:%s{evtName}" handler
/// <summary>Attach an event handler for htmx events</summary>
/// <param name="hxEvent">The <c>HxEvent</c> to be handled</param>
/// <param name="handler">The script to be executed when the event occurs</param>
/// <returns>A configured <c>hx-on::</c> attribute</returns>
/// <seealso cref="HxEvent" />
/// <seealso href="https://htmx.org/attributes/hx-on/">Documentation</seealso>
let _hxOnHxEvent (hxEvent: HxEvent) handler =
_hxOnEvent $":{hxEvent.ToHxOnString()}" handler
/// <summary>Filters the parameters that will be submitted with a request</summary>
/// <param name="toInclude">The fields to include (use <c>HxParams</c> to generate this value)</param>
/// <returns>A configured <c>hx-params</c> attribute</returns>
/// <seealso cref="HxParams" />
/// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso>
let _hxParams toInclude =
attr "hx-params" toInclude
/// <summary>Issues a <c>PATCH</c> to the specified URL</summary>
/// <param name="url">The URL to which the request should be directed</param>
/// <returns>A configured <c>hx-patch</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-patch/">Documentation</seealso>
let _hxPatch url =
attr "hx-patch" url
/// <summary>Issues a <c>POST</c> to the specified URL</summary>
/// <param name="url">The URL to which the request should be directed</param>
/// <returns>A configured <c>hx-post</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-post/">Documentation</seealso>
let _hxPost url =
attr "hx-post" url
/// <summary>Preserves an element between requests</summary>
/// <seealso href="https://htmx.org/attributes/hx-preserve/">Documentation</seealso>
let _hxPreserve =
flag "hx-preserve"
/// <summary>Shows a <c>prompt()</c> dialog before submitting a request</summary>
/// <param name="text">The text for the prompt</param>
/// <returns>A configured <c>hx-prompt</c> attribute</returns>
/// <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>
let _hxPrompt text =
attr "hx-prompt" text
/// <summary>Pushes the URL into the location bar, creating a new history entry</summary>
/// <param name="spec">
/// <ul>
/// <li>"true" to push the fetched URL</li>
/// <li>"false" to explicitly not push the fetched URL</li>
/// <li>A specific URL to push</li>
/// </ul>
/// </param>
/// <returns>A configured <c>hx-push-url</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-push-url/">Documentation</seealso>
let _hxPushUrl spec =
attr "hx-push-url" spec
/// <summary>Issues a <c>PUT</c> to the specified URL</summary>
/// <param name="url">The URL to which the request should be directed</param>
/// <returns>A configured <c>hx-put</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-put/">Documentation</seealso>
let _hxPut url =
attr "hx-put" url
/// <summary>Replaces the current URL in the browser's history stack</summary>
/// <param name="spec">
/// <ul>
/// <li>"true" to replace the current URL with the fetched one</li>
/// <li>"false" to explicitly replace nothing</li>
/// <li>A specific URL to replace in the browser's history</li>
/// </ul>
/// </param>
/// <returns>A configured <c>hx-replace-url</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-replace-url/">Documentation</seealso>
let _hxReplaceUrl spec =
attr "hx-replace-url" spec
/// <summary>Configures various aspects of the request</summary>
/// <param name="spec">The configuration spec (use <c>HxRequest.Configure</c> to create value)</param>
/// <returns>A configured <c>hx-request</c> attribute</returns>
/// <seealso cref="HxRequest.Configure" />
/// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso>
let _hxRequest spec =
attr "hx-request" spec
/// <summary>Selects a subset of the server response to process</summary>
/// <param name="selector">A CSS selector for the content to be selected</param>
/// <returns>A configured <c>hx-select</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-select/">Documentation</seealso>
let _hxSelect selector =
attr "hx-select" selector
/// <summary>Selects a subset of an out-of-band server response</summary>
/// <param name="selectors">One or more comma-delimited CSS selectors for the content to be selected</param>
/// <returns>A configured <c>hx-select-oob</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-select-oob/">Documentation</seealso>
let _hxSelectOob selectors =
attr "hx-select-oob" selectors
/// <summary>
/// Controls how the response content is swapped into the DOM (e.g. <c>outerHTML</c> or <c>beforeEnd</c>)
/// </summary>
/// <param name="swap">The type of swap to perform (use <c>HxSwap</c> values)</param>
/// <returns>A configured <c>hx-swap</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-swap/">Documentation</seealso>
let _hxSwap swap =
attr "hx-swap" swap
/// <summary>
/// Controls how the response content is swapped into the DOM (e.g. <c>outerHTML</c> or <c>beforeEnd</c>), enabling
/// CSS transitions
/// </summary>
/// <param name="swap">The type of swap to perform (use <c>HxSwap</c> values)</param>
/// <returns>A configured <c>hx-swap</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-swap/">Documentation</seealso>
let _hxSwapWithTransition swap =
_hxSwap $"%s{swap} transition:true"
/// <summary>
/// Marks content in a response as being "Out of Band", i.e. swapped somewhere other than the target
let _hxSwapOob = attr "hx-swap-oob"
/// Specifies the target element to be swapped
let _hxTarget = attr "hx-target"
/// Specifies the event that triggers the request
let _hxTrigger = attr "hx-trigger"
/// Adds to the parameters that will be submitted with the request
let _hxVals = attr "hx-vals"
/// Establishes a WebSocket or sends information to one
let _hxWs = attr "hx-ws"
/// </summary>
/// <param name="swap">
/// <ul>
/// <li>"true" to mark this as an OOB swap</li>
/// <li>Any <c>HxSwap</c> value</li>
/// <li>Any <c>HxSwap</c> value, followed by a colon (<c>:</c>) and a CSS selector</li>
/// </ul>
/// </param>
/// <returns>A configured <c>hx-swap-oob</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-swap-oob/">Documentation</seealso>
let _hxSwapOob swap =
attr "hx-swap-oob" swap
/// <summary>Synchronize events based on another element</summary>
/// <param name="selector">A CSS selector for the element with which this one should sync</param>
/// <param name="action">The request synchronization action to perform (use <c>HxSync</c> values)</param>
/// <returns>A configured <c>hx-sync</c> attribute</returns>
/// <seealso cref="HxSync" />
/// <seealso href="https://htmx.org/attributes/hx-sync/">Documentation</seealso>
let _hxSync selector action =
attr "hx-sync" $"%s{selector}:%s{action}"
/// <summary>Specifies the target element to be swapped</summary>
/// <param name="selector">A CSS selector or relative reference (or both) to identify the target</param>
/// <returns>A configured <c>hx-target</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-target/">Documentation</seealso>
let _hxTarget selector =
attr "hx-target" selector
/// <summary>Specifies the event that triggers the request</summary>
/// <param name="spec">The trigger specification (use <c>HxTrigger</c> to create)</param>
/// <returns>A configured <c>hx-trigger</c> attribute</returns>
/// <seealso cref="HxTrigger" />
/// <seealso href="https://htmx.org/attributes/hx-trigger/">Documentation</seealso>
let _hxTrigger spec =
attr "hx-trigger" spec
/// <summary>Validate an input element (uses HTML5 validation API)</summary>
/// <seealso href="https://htmx.org/attributes/hx-validate/">Documentation</seealso>
let _hxValidate =
flag "hx-validate"
/// <summary>Adds to the parameters that will be submitted with the request</summary>
/// <param name="values">The values for the parameters (use <c>HxVals.From</c> to create)</param>
/// <returns>A configured <c>hx-vals</c> attribute</returns>
/// <seealso cref="HxVals.From" />
/// <seealso href="https://htmx.org/attributes/hx-vals/">Documentation</seealso>
let _hxVals values =
attr "hx-vals" values
/// <summary>The URL of the SSE server</summary>
/// <param name="url">The URL from which events will be received</param>
/// <returns>A configured <c>sse-connect</c> attribute</returns>
/// <seealso href="https://htmx.org/extensions/sse/#usage">Extension Docs</seealso>
let _sseConnect url =
attr "sse-connect" url
/// <summary>The name(s) of the message(s) to swap into the DOM</summary>
/// <param name="messages">The message names (comma-delimited) to swap (use "message" for unnamed events)</param>
/// <returns>A configured <c>sse-swap</c> attribute</returns>
/// <seealso href="https://htmx.org/extensions/sse/#usage">Extension Docs</seealso>
let _sseSwap messages =
attr "sse-swap" messages
/// <summary>Script tags to pull htmx into a web page</summary>
module Script =
/// <summary>Script tag to load the minified version from unpkg.com</summary>
let minified =
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@2.0.6/dist/htmx.min.js"
_integrity "sha384-Akqfrbj/HpNVo8k11SXBb6TlBWmXXlYQrCSqEWmyKJe+hDm3Z/B2WVG4smwBkRVm"
_crossorigin "anonymous" ] []
/// <summary>Script tag to load the unminified version from unpkg.com</summary>
let unminified =
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@2.0.6/dist/htmx.js"
_integrity "sha384-ksKjJrwjL5VxqAkAZAVOPXvMkwAykMaNYegdixAESVr+KqLkKE8XBDoZuwyWVUDv"
_crossorigin "anonymous" ] []
/// <summary>Functions to extract and render an HTML fragment from a document</summary>
[<RequireQualifiedAccess>]
module RenderFragment =
/// Does this element have an ID matching the requested ID name?
let private isIdElement nodeId (elt: XmlElement) =
snd elt
|> Array.exists (fun attr ->
match attr with
| KeyValue (name, value) -> name = "id" && value = nodeId
| Boolean _ -> false)
/// Generate a message if the requested ID node is not found
let private nodeNotFound (nodeId: string) =
$"<em>&ndash; ID {nodeId} not found &ndash;</em>"
/// <summary>Find the node with the named ID</summary>
/// <param name="nodeId">The <c>id</c> attribute to find</param>
/// <param name="node">The node tree to search</param>
/// <returns>The node with the requested <c>id</c> attribute, or <c>None</c> if it was not found</returns>
let rec findIdNode nodeId (node: XmlNode) : XmlNode option =
match node with
| Text _ -> None
| VoidElement elt -> if isIdElement nodeId elt then Some node else None
| ParentNode (elt, children) ->
if isIdElement nodeId elt then Some node else children |> List.tryPick (findIdNode nodeId)
/// <summary>Functions to render a fragment as a string</summary>
[<RequireQualifiedAccess>]
module AsString =
/// <summary>Render to HTML for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="nodes">The node trees to search</param>
/// <returns>The HTML for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNodes nodeId (nodes: XmlNode list) =
match nodes |> List.tryPick (findIdNode nodeId) with
| Some idNode -> RenderView.AsString.htmlNode idNode
| None -> nodeNotFound nodeId
/// <summary>Render to HTML for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="node">The node tree to search</param>
/// <returns>The HTML for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNode nodeId node =
match findIdNode nodeId node with
| Some idNode -> RenderView.AsString.htmlNode idNode
| None -> nodeNotFound nodeId
/// <summary>Functions to render a fragment as bytes</summary>
[<RequireQualifiedAccess>]
module AsBytes =
let private utf8 = System.Text.Encoding.UTF8
/// <summary>Render to bytes for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="nodes">The node trees to search</param>
/// <returns>The bytes for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNodes nodeId (nodes: XmlNode list) =
match nodes |> List.tryPick (findIdNode nodeId) with
| Some idNode -> RenderView.AsBytes.htmlNode idNode
| None -> nodeNotFound nodeId |> utf8.GetBytes
/// <summary>Render to bytes for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="node">The node tree to search</param>
/// <returns>The bytes for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNode nodeId node =
match findIdNode nodeId node with
| Some idNode -> RenderView.AsBytes.htmlNode idNode
| None -> nodeNotFound nodeId |> utf8.GetBytes
/// <summary>Functions to render a fragment into a StringBuilder</summary>
[<RequireQualifiedAccess>]
module IntoStringBuilder =
/// <summary>Render HTML into a <c>StringBuilder</c> for the given ID</summary>
/// <param name="sb">The <c>StringBuilder</c> into which the bytes will be rendered</param>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="nodes">The node trees to search</param>
let htmlFromNodes sb nodeId (nodes: XmlNode list) =
match nodes |> List.tryPick (findIdNode nodeId) with
| Some idNode -> RenderView.IntoStringBuilder.htmlNode sb idNode
| None -> nodeNotFound nodeId |> sb.Append |> ignore
/// <summary>Render HTML into a <c>StringBuilder</c> for the given ID</summary>
/// <param name="sb">The <c>StringBuilder</c> into which the bytes will be rendered</param>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="node">The node tree to search</param>
let htmlFromNode sb nodeId node =
match findIdNode nodeId node with
| Some idNode -> RenderView.IntoStringBuilder.htmlNode sb idNode
| None -> nodeNotFound nodeId |> sb.Append |> ignore

View File

@@ -0,0 +1,63 @@
## Giraffe.ViewEngine.Htmx
This package enables [htmx](https://htmx.org) support within the [Giraffe](https://giraffe.wiki) view engine.
**htmx version: 2.0.6**
_Upgrading from v1.x: see [the migration guide](https://htmx.org/migration-guide-htmx-1/) for changes_
### Setup
1. Install the package.
2. Prior to using the attribute or support modules, `open Giraffe.ViewEngine.Htmx`.
### Use
Following Giraffe View Engine's lead, there are a set of attribute functions for htmx; for many of the attributes, there are also helper modules to assist with typing the values. The example below utilizes both:
```fsharp
let autoload =
div [ _hxGet "/this/data"; _hxTrigger HxTrigger.Load ] [ str "Loading..." ]
```
Support modules include:
- `HxEncoding`
- `HxHeaders`
- `HxParams`
- `HxRequest`
- `HxSwap` (requires `open Giraffe.Htmx`)
- `HxTrigger`
- `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).
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).
### Learn
htmx's attributes and these attribute functions map one-to-one. There are two exceptions:
- `_hxBoost` implies `true`; use `_hxNoBoost` to set it to `false`.
- `_hxSwapWithTransition` renders the standard `hx-swap` attribute and appends `transition:true` to the specified swap value.
The htmx `hx-on` attribute supports multiple events if they are separated with a newline (`\n`) character. The value provided to this attribute will be attribute-escaped, but in testing, it was interpreted correctly.
The support modules contain named properties for known values (as illustrated with `HxTrigger.Load` above). A few of the modules are more than collections of names, though:
- `HxRequest` has a `Configure` function, which takes a list of strings; the other functions in the module allow for configuring the request.
```fsharp
HxRequest.Configure [ HxRequest.Timeout 500 ] |> _hxRequest
```
- `HxTrigger` is _(by far)_ the most complex of these modules. Most uses won't need that complexity; however, complex triggers can be defined by piping into or composing with other functions. For example, to define an event that responds to a shift-click anywhere on the document, with a delay of 3 seconds before firing:
```fsharp
HxTrigger.Click
|> HxTrigger.Filter.Shift
|> HxTrigger.FromDocument
|> HxTrigger.Delay "3s"
|> _hxTrigger
// or
(HxTrigger.Filter.Shift >> HxTrigger.FromDocument >> HxTrigger.Delay "3s") HxTrigger.Click
|> _hxTrigger
```

BIN
src/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

7
src/pack.sh Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
dotnet pack Common/Giraffe.Htmx.Common.fsproj -c Release
dotnet pack Htmx/Giraffe.Htmx.fsproj -c Release
dotnet pack ViewEngine.Htmx/Giraffe.ViewEngine.Htmx.fsproj -c Release
cp Common/bin/Release/Giraffe.Htmx.Common.*.nupkg .
cp Htmx/bin/Release/Giraffe.Htmx.*.nupkg .
cp ViewEngine.Htmx/bin/Release/Giraffe.ViewEngine.Htmx.*.nupkg .