Compare commits

..

1 Commits

Author SHA1 Message Date
danieljsummers 125853b2a7 Update script tags to pull v1.9.12
- Update Git repo paths in package metadata
2024-04-17 22:29:32 -04:00
23 changed files with 1059 additions and 2368 deletions
-3
View File
@@ -6,6 +6,3 @@
.idea .idea
*.user *.user
.vscode .vscode
src/*.nupkg
src/tests*.txt
+15 -22
View File
@@ -14,8 +14,6 @@ htmx uses attributes and HTTP headers to attain its interactivity; the libraries
|---|---| |---|---|
|[![Nuget](https://img.shields.io/nuget/v/Giraffe.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.Htmx/)|[![Nuget](https://img.shields.io/nuget/v/Giraffe.ViewEngine.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx/)| |[![Nuget](https://img.shields.io/nuget/v/Giraffe.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.Htmx/)|[![Nuget](https://img.shields.io/nuget/v/Giraffe.ViewEngine.Htmx?style=plastic)](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx/)|
Both of these packages will also install `Giraffe.Htmx.Common`, which has some common definitions and provides a local-to-your-project version of the htmx JavaScript _(as of v2.0.8)_.
## Server Side (`Giraffe.Htmx`) ## Server Side (`Giraffe.Htmx`)
In addition to the regular HTTP request payloads, htmx sets [one or more headers](https://htmx.org/docs/#request_headers) along with the request. Once `Giraffe.Htmx` is opened, these are available as properties on `HttpContext.Request.Headers`. These consist of the header name, translated to a .NET name (ex. `HX-Current-URL` becomes `HxCurrentUrl`), and a strongly-typed property based on the expected value of that header. Additionally, they are all exposed as `Option`s, as they may or may not be present for any given request. In addition to the regular HTTP request payloads, htmx sets [one or more headers](https://htmx.org/docs/#request_headers) along with the request. Once `Giraffe.Htmx` is opened, these are available as properties on `HttpContext.Request.Headers`. These consist of the header name, translated to a .NET name (ex. `HX-Current-URL` becomes `HxCurrentUrl`), and a strongly-typed property based on the expected value of that header. Additionally, they are all exposed as `Option`s, as they may or may not be present for any given request.
@@ -23,29 +21,26 @@ In addition to the regular HTTP request payloads, htmx sets [one or more headers
A server may want to respond to a request that originated from htmx differently than a regular request. One way htmx can provide the same feel as a Single Page Application (SPA) is by swapping out the `body` content (or an element within it) instead of reloading the entire page. In this case, the developer can provide a partial layout to be used for these responses, while returning the full page for regular requests. The `IsHtmx` property makes this easy... A server may want to respond to a request that originated from htmx differently than a regular request. One way htmx can provide the same feel as a Single Page Application (SPA) is by swapping out the `body` content (or an element within it) instead of reloading the entire page. In this case, the developer can provide a partial layout to be used for these responses, while returning the full page for regular requests. The `IsHtmx` property makes this easy...
```fsharp ```fsharp
// "partial" and "full" are handlers that return the contents; // "partial" and "full" are handlers that return the contents;
// "view" can be whatever your view engine needs for the body of the page // "view" can be whatever your view engine needs for the body of the page
let result view : HttpHandler = let result view : HttpHandler =
fun next ctx -> fun next ctx ->
if ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh then match ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh with
partial view | true -> partial view
else | false -> full view
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. 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.
```fsharp ```fsharp
let theHandler : HttpHandler = let theHandler : HttpHandler =
fun next ctx -> fun next ctx ->
// some interesting stuff // some interesting stuff
withHxRedirect "/the-new-url" >=> Successful.OK withHxRedirect "/the-new-url" >=> Successful.OK
``` ```
Of note is that the `HX-Trigger` headers can take either one or more events. For a single event with no parameters, use `withHxTrigger`; for a single event with parameters, or multiple events, use `withHxTriggerMany`. Both these have `AfterSettle` and `AfterSwap` versions as well. Of note is that the `HX-Trigger` headers can take either one or more events. For a single event with no parameters, use `withHxTrigger`; for a single event with parameters, or multiple events, use `withHxTriggerMany`. Both these have `AfterSettle` and `AfterSwap` versions as well.
`HtmxScript.local` provides an `HtmlString` with a script tag to load the package-provided htmx library. This can be used in code, Razor templates, etc. (If you're using Giraffe.ViewEngine, see below.)
## View Engine (`Giraffe.ViewEngine.Htmx`) ## View Engine (`Giraffe.ViewEngine.Htmx`)
As htmx uses [attributes](https://htmx.org/docs/#attributes) to extend HTML, the primary part of this library defines attributes that can be used within Giraffe views. Simply open `Giraffe.ViewEngine.Htmx`, and these attributes, along with support modules, will be visible. As htmx uses [attributes](https://htmx.org/docs/#attributes) to extend HTML, the primary part of this library defines attributes that can be used within Giraffe views. Simply open `Giraffe.ViewEngine.Htmx`, and these attributes, along with support modules, will be visible.
@@ -53,10 +48,8 @@ As htmx uses [attributes](https://htmx.org/docs/#attributes) to extend HTML, the
As an example, creating a `div` that loads data once the HTML is rendered: As an example, creating a `div` that loads data once the HTML is rendered:
```fsharp ```fsharp
let autoload = let autoload =
div [ _hxGet "/lazy-load-data"; _hxTrigger HxTrigger.Load ] [ div [ _hxGet "/lazy-load-data"; _hxTrigger "load" ] [ str "Loading..." ]
str "Loading..."
]
``` ```
_(As `hx-boost="true"` is the usual desire for boosting, `_hxBoost` implies true. To disable it for an element, use `_hxNoBoost` instead.)_ _(As `hx-boost="true"` is the usual desire for boosting, `_hxBoost` implies true. To disable it for an element, use `_hxNoBoost` instead.)_
@@ -64,13 +57,13 @@ _(As `hx-boost="true"` is the usual desire for boosting, `_hxBoost` implies true
Some attributes have known values, such as `hx-trigger` and `hx-swap`; for these, there are modules with those values. For example, `HxTrigger.Load` could be used in the example above, to ensure that the known values are spelled correctly. `hx-trigger` can also take modifiers, such as an action that only responds to `Ctrl`+click. The `HxTrigger` module has a `Filter` submodule to assist with defining these actions. Some attributes have known values, such as `hx-trigger` and `hx-swap`; for these, there are modules with those values. For example, `HxTrigger.Load` could be used in the example above, to ensure that the known values are spelled correctly. `hx-trigger` can also take modifiers, such as an action that only responds to `Ctrl`+click. The `HxTrigger` module has a `Filter` submodule to assist with defining these actions.
```fsharp ```fsharp
let shiftClick = let shiftClick =
p [ _hxGet = "/something"; _hxTrigger (HxTrigger.Filter.Shift HxTrigger.Click) ] [ p [ _hxGet = "/something"; _hxTrigger (HxTrigger.Filter.Shift HxTrigger.Click) ] [
str "hold down Shift and click me" str "hold down Shift and click me"
] ]
``` ```
If you want to use the package-provided htmx library, `Htmx.Script.local` will create the `script` tag for you. To load htmx from jsDelivr, `Htmx.Script.cdnMinified` or `Htmx.Script.cdnUnminified` can be used to load the script in your HTML trees. In this case, if you are using a Content Security Policy (CSP) header, `cdn.jsdelivr.net` will need to be added to the `script-src` list. 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 ## Feedback / Help
+13 -85
View File
@@ -1,100 +1,28 @@
/// <summary>Common definitions shared between attribute values and response headers</summary> /// Common definitions shared between attribute values and response headers
[<AutoOpen>] [<AutoOpen>]
module Giraffe.Htmx.Common module Giraffe.Htmx.Common
/// <summary>The version of htmx embedded in the package</summary> /// Valid values for the `hx-swap` attribute / `HX-Reswap` header (may be combined with swap/settle/scroll/show config)
let HtmxVersion = "4.0.0-beta4"
/// <summary>The path for the provided htmx script</summary>
let internal htmxLocalScript = $"/_content/Giraffe.Htmx.Common/htmx.min.js?ver={HtmxVersion}"
/// <summary>The path for the provided htmax script</summary>
let internal htmaxLocalScript = $"/_content/Giraffe.Htmx.Common/htmax.min.js?ver={HtmxVersion}"
/// <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>scroll</c> / <c>show</c> config)</remarks>
/// <seealso href="https://four.htmx.org/attributes/hx-swap/">Documentation</seealso>
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module HxSwap = module HxSwap =
/// <summary>The default, replace the inner HTML of the target element</summary> /// The default, replace the inner html of the target element
[<Literal>]
let InnerHtml = "innerHTML" let InnerHtml = "innerHTML"
/// <summary>Replace the entire target element with the response</summary> /// Replace the entire target element with the response
[<Literal>]
let OuterHtml = "outerHTML" let OuterHtml = "outerHTML"
/// <summary>Morph the inner HTML of the target to the new content</summary> /// Insert the response before the target element
[<Literal>] let BeforeBegin = "beforebegin"
let InnerMorph = "innerMorph"
/// <summary>Morph the outer HTML of the target to the new content</summary> /// Insert the response before the first child of the target element
[<Literal>] let AfterBegin = "afterbegin"
let OuterMorph = "outerMorph"
/// <summary>Replace the text content of the target without parsing the response as HTML</summary> /// Insert the response after the last child of the target element
[<Literal>] let BeforeEnd = "beforeend"
let TextContent = "textContent"
/// <summary>Insert the response before the target element</summary> /// Insert the response after the target element
[<Literal>] let AfterEnd = "afterend"
let Before = "before"
/// <summary>Insert the response before the target element (pre-v4 name)</summary> /// Does not append content from response (out of band items will still be processed).
[<Literal>]
let BeforeBegin = Before
/// <summary>Insert the response before the first child of the target element</summary>
[<Literal>]
let Prepend = "prepend"
/// <summary>Insert the response before the first child of the target element (pre-v4 name)</summary>
[<Literal>]
let AfterBegin = Prepend
/// <summary>Insert the response after the last child of the target element</summary>
[<Literal>]
let Append = "append"
/// <summary>Insert the response after the last child of the target element (pre-v4 name)</summary>
[<Literal>]
let BeforeEnd = Append
/// <summary>Insert the response after the target element</summary>
[<Literal>]
let After = "after"
/// <summary>Insert the response after the target element (pre-v4 name)</summary>
[<Literal>]
let AfterEnd = After
/// <summary>Delete the target element regardless of response</summary>
[<Literal>]
let Delete = "delete"
/// <summary>Does not append content from response (out of band items will still be processed)</summary>
[<Literal>]
let None = "none" let None = "none"
/// <summary>Update existing elements by <c>id</c> and add new ones</summary>
/// <remarks>This requires the <c>upsert</c> extension</remarks>
/// <seealso href="https://four.htmx.org/extensions/upsert">Extension</seealso>
[<Literal>]
let Upsert = "upsert"
+2 -7
View File
@@ -1,10 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Razor"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>Common definitions for Giraffe.Htmx</Description> <Description>Common definitions for Giraffe.Htmx</Description>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -14,11 +13,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FSharp.Core" /> <PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Giraffe.Htmx" />
<InternalsVisibleTo Include="Giraffe.ViewEngine.Htmx" />
</ItemGroup>
</Project> </Project>
+2 -4
View File
@@ -1,7 +1,5 @@
## Giraffe.Htmx.Common ## Giraffe.Htmx.Common
This package contains common code shared between [`Giraffe.Htmx`](https://www.nuget.org/packages/Giraffe.Htmx) and [`Giraffe.ViewEngine.Htmx`](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx), and will be automatically installed when you install either one. It also contains htmx as a static web asset, allowing it to be loaded from your local (or published) project. 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: 4.0.0-beta4** **htmx version: 1.9.12**
_**NOTE:** Pay special attention to breaking changes highlighted in the packages listed above._
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -14
View File
@@ -1,20 +1,9 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?> <?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks> <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<VersionPrefix>4.0.0</VersionPrefix> <VersionPrefix>1.9.12</VersionPrefix>
<VersionSuffix>beta4</VersionSuffix> <PackageReleaseNotes>Update script tags to pull htmx 1.9.12</PackageReleaseNotes>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>Update htmx 4 to beta4
- [Common] Update provided htmx 4 to 4.0.0-beta4
- [Common] Add htmax bundle to provided version
- [Server] Update HX-Target header to return tag and ID (similar to HX-Source)
- [Server] Add support for HX-Request-Type header
- [View Engine] Add hx-status attribute
- [View Engine] Updated script tags to pull htmx 4.0.0-beta4, added "max" bundle links for local and CDN
See package and prior alpha release READMEs; v2 to v4 is not an update-and-forget-it release
</PackageReleaseNotes>
<Authors>danieljsummers</Authors> <Authors>danieljsummers</Authors>
<Company>Bit Badger Solutions</Company> <Company>Bit Badger Solutions</Company>
<PackageProjectUrl>https://git.bitbadger.solutions/bit-badger/Giraffe.Htmx</PackageProjectUrl> <PackageProjectUrl>https://git.bitbadger.solutions/bit-badger/Giraffe.Htmx</PackageProjectUrl>
-13
View File
@@ -1,13 +0,0 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Expecto" Version="11.0.0" />
<PackageVersion Include="Giraffe" Version="8.2.0" />
<PackageVersion Include="Giraffe.ViewEngine" Version="1.4.0" />
<PackageVersion Include="NSubstitute" Version="5.3.0" />
<PackageVersion Include="FSharp.Core" Version="10.1.301" />
<!-- <PackageVersion Update="FSharp.Core" Version="10.0.0" /> -->
</ItemGroup>
</Project>
+40
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
-6
View File
@@ -1,6 +0,0 @@
<Solution>
<Project Path="Common/Giraffe.Htmx.Common.fsproj" />
<Project Path="Htmx/Giraffe.Htmx.fsproj" />
<Project Path="Tests/Tests.fsproj" />
<Project Path="ViewEngine.Htmx/Giraffe.ViewEngine.Htmx.fsproj" />
</Solution>
+2 -3
View File
@@ -4,7 +4,6 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>htmx header extensions and helpers for Giraffe</Description> <Description>htmx header extensions and helpers for Giraffe</Description>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -14,8 +13,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" /> <PackageReference Include="Giraffe" Version="6.2.0" />
<PackageReference Include="FSharp.Core" /> <PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+76 -181
View File
@@ -4,14 +4,6 @@ open Microsoft.AspNetCore.Http
open Microsoft.Extensions.Primitives open Microsoft.Extensions.Primitives
open System open System
/// <summary>The request types which may be set in the <c>HX-Request</c> header</summary>
type HxRequestTypes =
/// <summary>A request targeting the <c>body</c> tag or using an <c>hx-select</c> attribute</summary>
| HxFullRequest
/// <summary>A request for partial content</summary>
| HxPartialRequest
/// Determine if the given header is present /// Determine if the given header is present
let private hdr (headers : IHeaderDictionary) hdr = 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]
@@ -19,218 +11,121 @@ let private hdr (headers : IHeaderDictionary) hdr =
/// Extensions to the header dictionary /// Extensions to the header dictionary
type IHeaderDictionary with type IHeaderDictionary with
/// <summary>Indicates that the request is via an element using <c>hx-boost</c></summary> /// Indicates that the request is via an element using `hx-boost`
member this.HxBoosted member this.HxBoosted with get () = hdr this "HX-Boosted" |> Option.map bool.Parse
with get () = hdr this "HX-Boosted" |> Option.map bool.Parse
/// <summary>The current URL of the browser <em>(note that this does not update until after settle)</em></summary> /// The current URL of the browser _(note that this does not update until after settle)_
member this.HxCurrentUrl member this.HxCurrentUrl with get () = hdr this "HX-Current-URL" |> Option.map Uri
with get () = hdr this "HX-Current-URL" |> Option.map Uri
/// <summary><c>true</c> if the request is for history restoration after a miss in the local history cache</summary> /// `true` if the request is for history restoration after a miss in the local history cache
member this.HxHistoryRestoreRequest member this.HxHistoryRestoreRequest with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse
with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse
/// <summary>The user response to an <c>hx-prompt</c></summary> /// The user response to an `hx-prompt`
[<Obsolete "hx-prompt is removed in v4">] member this.HxPrompt with get () = hdr this "HX-Prompt"
member this.HxPrompt
with get () = hdr this "HX-Prompt"
/// <summary><c>true</c> if the request came from htmx</summary> /// `true` if the request came from HTMX
member this.HxRequest member this.HxRequest with get () = hdr this "HX-Request" |> Option.map bool.Parse
with get () = hdr this "HX-Request" |> Option.map bool.Parse
/// <summary>The request type sent by htmx</summary> /// The `id` of the target element if it exists
/// <seealso cref="HxRequestTypes" /> member this.HxTarget with get () = hdr this "HX-Target"
member this.HxRequestType
with get () =
match hdr this "HX-Request-Type" with
| Some typ when typ = "full" -> Some HxFullRequest
| Some typ when typ = "partial" -> Some HxPartialRequest
| Some _ -> None
| None -> None
/// <summary>The tag name (fst) and <c>id</c> attribute (snd) of the element triggering this request</summary> /// The `id` of the triggered element if it exists
member this.HxSource member this.HxTrigger with get () = hdr this "HX-Trigger"
with get () =
match hdr this "HX-Source" with
| Some src ->
let parts = src.Split "#"
if parts.Length = 1 then
Some (parts[0], None)
else
Some (parts[0], if parts[1] <> "" then Some parts[1] else None)
| None -> None
/// <summary>The <c>id</c> attribute of the target element if it exists</summary> /// The `name` of the triggered element if it exists
/// <remarks> member this.HxTriggerName with get () = hdr this "HX-Trigger-Name"
/// In v4, this changed to tag name (fst) and <c>id</c> (snd); to resolve build errors, and restore the prior
/// behavior of <c>[id] option</c>, replace
/// <code>ctx.HxTarget</code>
/// with
/// <code>ctx.HxTarget |> Option.iter snd</code>
/// </remarks>
member this.HxTarget
with get () =
match hdr this "HX-Target" with
| Some src ->
let parts = src.Split "#"
if parts.Length = 1 then
Some (parts[0], None)
else
Some (parts[0], if parts[1] <> "" then Some parts[1] else None)
| None -> None
/// <summary>The <c>id</c> attribute of the triggered element if it exists</summary>
[<Obsolete "HX-Trigger is removed in v4; use the second item of HX-Source">]
member this.HxTrigger
with get () = hdr this "HX-Trigger"
/// <summary>The <c>name</c> attribute of the triggered element if it exists</summary>
[<Obsolete "HX-Trigger-Name is removed in v4; may be available via extension, but will be removed from this library">]
member this.HxTriggerName
with get () = hdr this "HX-Trigger-Name"
/// Extensions for the request object /// Extensions for the request object
type HttpRequest with type HttpRequest with
/// <summary>Whether this request was initiated from htmx</summary> /// Whether this request was initiated from htmx
member this.IsHtmx member this.IsHtmx with get () = this.Headers.HxRequest |> Option.defaultValue false
with get () = this.Headers.HxRequest |> Option.defaultValue false
/// <summary>Whether this request is an htmx history-miss refresh request</summary> /// Whether this request is an htmx history-miss refresh request
member this.IsHtmxRefresh member this.IsHtmxRefresh with get () =
with get () = this.IsHtmx && (this.Headers.HxHistoryRestoreRequest |> Option.defaultValue false) this.IsHtmx && (this.Headers.HxHistoryRestoreRequest |> Option.defaultValue false)
/// <summary>HTTP handlers for setting output headers</summary> /// HTTP handlers for setting output headers
[<AutoOpen>] [<AutoOpen>]
module Handlers = module Handlers =
open Giraffe.Htmx.Common /// Convert a boolean to lowercase `true` or `false`
let private toLowerBool (trueOrFalse : bool) =
(string trueOrFalse).ToLowerInvariant ()
/// <summary>Instruct htmx to perform a client-side redirect for content</summary> /// Serialize a list of key/value pairs to JSON (very rudimentary)
/// <param name="path">The path where the content should be found</param> let private toJson (evts : (string * string) list) =
/// <returns>An HTTP handler with the <c>HX-Location</c> header set</returns> evts
/// <seealso href="https://htmx.org/headers/hx-location/">Documentation</seealso> |> List.map (fun evt -> sprintf "\"%s\": \"%s\"" (fst evt) ((snd evt).Replace ("\"", "\\\"")))
let withHxLocation (path: string) : HttpHandler = |> String.concat ", "
setHttpHeader "HX-Location" path |> sprintf "{ %s }"
/// <summary>Pushes a new url into the history stack</summary> /// Pushes a new url into the history stack
/// <param name="url">The URL to be pushed</param> let withHxPushUrl : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Push-Url</c> header set</returns> setHttpHeader "HX-Push-Url"
/// <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
/// <summary>Explicitly do not push a new URL into the history stack</summary> /// Explicitly do not push a new URL into the history stack
/// <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 = let withHxNoPushUrl : HttpHandler =
toLowerBool false |> withHxPushUrl toLowerBool false |> withHxPushUrl
/// <summary>Can be used to do a client-side redirect to a new location</summary> /// Pushes a new url into the history stack
/// <param name="url">The URL to which the client should be redirected</param> [<Obsolete "Use withHxPushUrl; HX-Push was replaced by HX-Push-Url in v1.8.0">]
/// <returns>An HTTP handler with the <c>HX-Redirect</c> header set</returns> let withHxPush = withHxPushUrl
/// <seealso href="https://htmx.org/headers/hx-redirect/">Documentation</seealso>
let withHxRedirect (url: string) : HttpHandler =
setHttpHeader "HX-Redirect" url
/// <summary>If set to <c>true</c> the client side will do a full refresh of the page</summary> /// Explicitly do not push a new URL into the history stack
/// <param name="shouldRefresh">Whether the client should refresh their page</param> [<Obsolete "Use withHxNoPushUrl; HX-Push was replaced by HX-Push-Url in v1.8.0">]
/// <returns>An HTTP handler with the <c>HX-Refresh</c> header set</returns> let withHxNoPush = withHxNoPushUrl
let withHxRefresh shouldRefresh : HttpHandler =
(toLowerBool >> setHttpHeader "HX-Refresh") shouldRefresh
/// <summary>Replaces the current URL in the history stack</summary> /// Can be used to do a client-side redirect to a new location
/// <param name="url">The URL to place in the history stack in place of the current one</param> let withHxRedirect : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Replace-URL</c> header set</returns> setHttpHeader "HX-Redirect"
/// <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> /// If set to `true` the client side will do a a full refresh of the page
/// <returns>An HTTP handler with the <c>HX-Replace-URL</c> header set to <c>false</c></returns> let withHxRefresh : bool -> HttpHandler =
/// <seealso href="https://htmx.org/headers/hx-replace-url/">Documentation</seealso> toLowerBool >> setHttpHeader "HX-Refresh"
/// Replaces the current URL in the history stack
let withHxReplaceUrl : string -> HttpHandler =
setHttpHeader "HX-Replace-Url"
/// Explicitly do not replace the current URL in the history stack
let withHxNoReplaceUrl : HttpHandler = let withHxNoReplaceUrl : HttpHandler =
toLowerBool false |> withHxReplaceUrl toLowerBool false |> withHxReplaceUrl
/// <summary>Override which portion of the response will be swapped into the target document</summary> /// Override which portion of the response will be swapped into the target document
/// <param name="target">The selector for the new response target</param> let withHxReselect : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Reselect</c> header set</returns> setHttpHeader "HX-Reselect"
let withHxReselect (target: string) : HttpHandler =
setHttpHeader "HX-Reselect" target
/// <summary>Override the <c>hx-swap</c> attribute from the initiating element</summary> /// Override the `hx-swap` attribute from the initiating element
/// <param name="swap">The swap value to override</param> let withHxReswap : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Reswap</c> header set</returns> setHttpHeader "HX-Reswap"
/// <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> /// Allows you to override the `hx-target` attribute
/// <param name="target">The new target for the response</param> let withHxRetarget : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Retarget</c> header set</returns> setHttpHeader "HX-Retarget"
let withHxRetarget (target: string) : HttpHandler =
setHttpHeader "HX-Retarget" target
/// <summary>Allows you to trigger a single client side event</summary> /// Allows you to trigger a single client side event
/// <param name="evt">The call to the event that should be triggered</param> let withHxTrigger : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Trigger</c> header set</returns> setHttpHeader "HX-Trigger"
/// <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> /// Allows you to trigger multiple client side events
/// <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 = let withHxTriggerMany evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger" toJson evts |> setHttpHeader "HX-Trigger"
/// <summary>Allows you to trigger a single client side event after changes have settled</summary> /// Allows you to trigger a single client side event after changes have settled
/// <param name="evt">The call to the event that should be triggered</param> let withHxTriggerAfterSettle : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Trigger-After-Settle</c> header set</returns> setHttpHeader "HX-Trigger-After-Settle"
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
[<Obsolete "Removed in v4; use withHxTrigger">]
let withHxTriggerAfterSettle (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger" evt
/// <summary>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
/// <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>
[<Obsolete "Removed in v4; use withHxTrigger">]
let withHxTriggerManyAfterSettle evts : HttpHandler = let withHxTriggerManyAfterSettle evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger" toJson evts |> setHttpHeader "HX-Trigger-After-Settle"
/// <summary>Allows you to trigger a single client side event after DOM swapping occurs</summary> /// Allows you to trigger a single client side event after DOM swapping occurs
/// <param name="evt">The call to the event that should be triggered</param> let withHxTriggerAfterSwap : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Trigger-After-Swap</c> header set</returns> setHttpHeader "HX-Trigger-After-Swap"
/// <seealso href="https://htmx.org/headers/hx-trigger/">Documentation</seealso>
[<Obsolete "Removed in v4; use withHxTrigger">]
let withHxTriggerAfterSwap (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger" evt
/// <summary>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
/// <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>
[<Obsolete "Removed in v4; use withHxTrigger">]
let withHxTriggerManyAfterSwap evts : HttpHandler = let withHxTriggerManyAfterSwap evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger" toJson evts |> setHttpHeader "HX-Trigger-After-Swap"
/// <summary>Load the package-provided version of the htmx script</summary>
[<RequireQualifiedAccess>]
module HtmxScript =
open Giraffe.Htmx.Common
open Microsoft.AspNetCore.Html
/// <summary><c>script</c> tag to load the package-provided version of the htmx script</summary>
let local = HtmlString $"""<script src="{htmxLocalScript}"></script>"""
+8 -14
View File
@@ -2,11 +2,7 @@
This package enables server-side support for [htmx](https://htmx.org) within [Giraffe](https://giraffe.wiki) and ASP.NET's `HttpContext`. This package enables server-side support for [htmx](https://htmx.org) within [Giraffe](https://giraffe.wiki) and ASP.NET's `HttpContext`.
**htmx version: 4.0.0-beta4** **htmx version: 1.9.12**
_Upgrading from v2.x: the [migration guide](https://four.htmx.org/docs/get-started/migration) lists changes for v4. For this package, the `HX-Trigger` and `HX-Trigger-Name` headers are marked obsolete. They are replaced by `HX-Source`, which provides the triggering tag name and `id` attribute. The `HX-Prompt` header has also been marked as obsolete, as the `hx-prompt` attribute which generated its content has been removed._
_Obsolete elements will be removed in the first production v4 release._
### Setup ### Setup
@@ -18,26 +14,24 @@ _Obsolete elements will be removed in the first production v4 release._
To obtain a request header, using the `IHeaderDictionary` extension properties: To obtain a request header, using the `IHeaderDictionary` extension properties:
```fsharp ```fsharp
let myHandler : HttpHander = let myHandler : HttpHander =
fun next ctx -> fun next ctx ->
match ctx.Target with match ctx.HxPrompt with
| Some elt -> ... // do something with id of the target element | Some prompt -> ... // do something with the text the user provided
| None -> ... // no target element provided | None -> ... // no text provided
``` ```
To set a response header: To set a response header:
```fsharp ```fsharp
let myHandler : HttpHander = let myHandler : HttpHander =
fun next ctx -> fun next ctx ->
// some meaningful work // some meaningful work
withHxPushUrl "/some/new/url" >=> [other handlers] 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. The `HxSwap` module has constants to use for the `HX-Reswap` header. These may be extended with settle, show, and other qualifiers; see the htmx documentation for the `hx-swap` attribute for more information.
To load the package-provided htmx library without using Giraffe.ViewEngine, use `HtmxScript.local`.
### Learn ### Learn
The naming conventions of this library were selected to mirror those provided by htmx. The header properties become `Hx*` on the `ctx.Request.Headers` object, and the response handlers are `withHx*` based on the header being set. The only part that does not line up is `withHxTrigger*` and `withHxTriggerMany`; the former set work with a single string (to trigger a single event with no arguments), while the latter set supports both arguments and multiple events. The naming conventions of this library were selected to mirror those provided by htmx. The header properties become `Hx*` on the `ctx.Request.Headers` object, and the response handlers are `withHx*` based on the header being set. The only part that does not line up is `withHxTrigger*` and `withHxTriggerMany`; the former set work with a single string (to trigger a single event with no arguments), while the latter set supports both arguments and multiple events.
+6 -39
View File
@@ -3,12 +3,6 @@ module Common
open Expecto open Expecto
open Giraffe.Htmx open Giraffe.Htmx
/// Test to ensure the version was updated
let version =
test "HtmxVersion is correct" {
Expect.equal HtmxVersion "4.0.0-beta4" "htmx version incorrect"
}
/// Tests for the HxSwap module /// Tests for the HxSwap module
let swap = let swap =
testList "HxSwap" [ testList "HxSwap" [
@@ -18,49 +12,22 @@ let swap =
test "OuterHtml is correct" { test "OuterHtml is correct" {
Expect.equal HxSwap.OuterHtml "outerHTML" "Outer HTML swap value incorrect" Expect.equal HxSwap.OuterHtml "outerHTML" "Outer HTML swap value incorrect"
} }
test "InnerMorph is correct" {
Expect.equal HxSwap.InnerMorph "innerMorph" "Inner Morph swap value incorrect"
}
test "OuterMorph is correct" {
Expect.equal HxSwap.OuterMorph "outerMorph" "Outer Morph swap value incorrect"
}
test "TextContent is correct" {
Expect.equal HxSwap.TextContent "textContent" "Text Content swap value incorrect"
}
test "Before is correct" {
Expect.equal HxSwap.Before "before" "Before swap value incorrect"
}
test "BeforeBegin is correct" { test "BeforeBegin is correct" {
Expect.equal HxSwap.BeforeBegin HxSwap.Before "Before Begin swap value incorrect" Expect.equal HxSwap.BeforeBegin "beforebegin" "Before Begin swap value incorrect"
}
test "Prepend is correct" {
Expect.equal HxSwap.Prepend "prepend" "Prepend swap value incorrect"
}
test "AfterBegin is correct" {
Expect.equal HxSwap.AfterBegin HxSwap.Prepend "Prepend swap value incorrect"
}
test "Append is correct" {
Expect.equal HxSwap.Append "append" "Append swap value incorrect"
} }
test "BeforeEnd is correct" { test "BeforeEnd is correct" {
Expect.equal HxSwap.BeforeEnd HxSwap.Append "Before End swap value incorrect" Expect.equal HxSwap.BeforeEnd "beforeend" "Before End swap value incorrect"
} }
test "After is correct" { test "AfterBegin is correct" {
Expect.equal HxSwap.After "after" "After swap value incorrect" Expect.equal HxSwap.AfterBegin "afterbegin" "After Begin swap value incorrect"
} }
test "AfterEnd is correct" { test "AfterEnd is correct" {
Expect.equal HxSwap.AfterEnd HxSwap.After "After End swap value incorrect" Expect.equal HxSwap.AfterEnd "afterend" "After End swap value incorrect"
}
test "Delete is correct" {
Expect.equal HxSwap.Delete "delete" "Delete swap value incorrect"
} }
test "None is correct" { test "None is correct" {
Expect.equal HxSwap.None "none" "None swap value incorrect" Expect.equal HxSwap.None "none" "None swap value incorrect"
} }
test "Upsert is correct" {
Expect.equal HxSwap.Upsert "upsert" "Upsert swap value incorrect"
}
] ]
/// All tests for this module /// All tests for this module
let allTests = testList "Htmx.Common" [ version; swap ] let allTests = testList "Htmx.Common" [ swap ]
+141 -254
View File
@@ -11,22 +11,22 @@ let dictExtensions =
testList "IHeaderDictionaryExtensions" [ testList "IHeaderDictionaryExtensions" [
testList "HxBoosted" [ testList "HxBoosted" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxBoosted "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxBoosted "There should not have been a header returned"
} }
test "succeeds when the header is present and true" { test "succeeds when the header is present and true" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Boosted", "true") dic.Add ("HX-Boosted", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxBoosted "There should be a header present" 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" Expect.isTrue ctx.Request.Headers.HxBoosted.Value "The header value should have been true"
} }
test "succeeds when the header is present and false" { test "succeeds when the header is present and false" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Boosted", "false") dic.Add ("HX-Boosted", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxBoosted "There should be a header present" 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" Expect.isFalse ctx.Request.Headers.HxBoosted.Value "The header value should have been false"
@@ -34,14 +34,14 @@ let dictExtensions =
] ]
testList "HxCurrentUrl" [ testList "HxCurrentUrl" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxCurrentUrl "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxCurrentUrl "There should not have been a header returned"
} }
test "succeeds when the header is present" { test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Current-URL", "http://localhost/test.htm") dic.Add ("HX-Current-URL", "http://localhost/test.htm")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxCurrentUrl "There should be a header present" Expect.isSome ctx.Request.Headers.HxCurrentUrl "There should be a header present"
Expect.equal Expect.equal
@@ -51,155 +51,109 @@ let dictExtensions =
] ]
testList "HxHistoryRestoreRequest" [ testList "HxHistoryRestoreRequest" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxHistoryRestoreRequest "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxHistoryRestoreRequest "There should not have been a header returned"
} }
test "succeeds when the header is present and true" { test "succeeds when the header is present and true" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-History-Restore-Request", "true") dic.Add ("HX-History-Restore-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxHistoryRestoreRequest "There should be a header present" 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" Expect.isTrue ctx.Request.Headers.HxHistoryRestoreRequest.Value "The header value should have been true"
} }
test "succeeds when the header is present and false" { test "succeeds when the header is present and false" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-History-Restore-Request", "false") dic.Add ("HX-History-Restore-Request", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxHistoryRestoreRequest "There should be a header present" Expect.isSome ctx.Request.Headers.HxHistoryRestoreRequest "There should be a header present"
Expect.isFalse Expect.isFalse
ctx.Request.Headers.HxHistoryRestoreRequest.Value "The header should have been false" ctx.Request.Headers.HxHistoryRestoreRequest.Value "The header should have been false"
} }
] ]
testList "HxPrompt" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxPrompt "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary ()
dic.Add ("HX-Prompt", "of course")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxPrompt "There should be a header present"
Expect.equal ctx.Request.Headers.HxPrompt.Value "of course" "The header value was incorrect"
}
]
testList "HxRequest" [ testList "HxRequest" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxRequest "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxRequest "There should not have been a header returned"
} }
test "succeeds when the header is present and true" { test "succeeds when the header is present and true" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Request", "true") dic.Add ("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxRequest "There should be a header present" 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" Expect.isTrue ctx.Request.Headers.HxRequest.Value "The header should have been true"
} }
test "succeeds when the header is present and false" { test "succeeds when the header is present and false" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Request", "false") dic.Add ("HX-Request", "false")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxRequest "There should be a header present" 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" Expect.isFalse ctx.Request.Headers.HxRequest.Value "The header should have been false"
} }
] ]
testList "HxRequestType" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxRequestType "There should not have been a header returned"
}
test "succeeds when the header is invalid" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request-Type", "relaxed")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isNone ctx.Request.Headers.HxRequestType "There should not have been a header returned"
}
test "succeeds for a full request" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request-Type", "full")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxRequestType "There have been a header returned"
Expect.equal ctx.Request.Headers.HxRequestType.Value HxFullRequest "The header value is incorrect"
}
test "succeeds for a partial request" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Request-Type", "partial")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxRequestType "There have been a header returned"
Expect.equal ctx.Request.Headers.HxRequestType.Value HxPartialRequest "The header value is incorrect"
}
]
testList "HxSource" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxSource "There should not have been a header returned"
}
test "succeeds when the header is present and both parts exist" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Source", "button#theId")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxSource
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "button" "The source tag was incorrect"
Expect.isSome (snd hdr.Value) "There should be a source ID present"
Expect.equal (snd hdr.Value).Value "theId" "The source ID was incorrect"
}
test "succeeds when the header is present and ID is blank" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Source", "a#")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxSource
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "a" "The source tag was incorrect"
Expect.isNone (snd hdr.Value) "There should not be a source ID present"
}
test "succeeds when the header is present and ID is missing" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Source", "form")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxSource
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "form" "The source tag was incorrect"
Expect.isNone (snd hdr.Value) "There should not be a source ID present"
}
]
testList "HxTarget" [ testList "HxTarget" [
test "succeeds when the header is not present" { test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxTarget "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxTarget "There should not have been a header returned"
} }
test "succeeds when the header is present and both parts exist" { test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Target", "div#leItem") dic.Add ("HX-Target", "#leItem")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxTarget Expect.isSome ctx.Request.Headers.HxTarget "There should be a header present"
Expect.isSome hdr "There should be a header present" Expect.equal ctx.Request.Headers.HxTarget.Value "#leItem" "The header value was incorrect"
Expect.equal (fst hdr.Value) "div" "The target tag was incorrect"
Expect.isSome (snd hdr.Value) "There should be a target ID present"
Expect.equal (snd hdr.Value).Value "leItem" "The header value was incorrect"
} }
test "succeeds when the header is present and ID is blank" { ]
let ctx = Substitute.For<HttpContext>() testList "HxTrigger" [
let dic = HeaderDictionary() test "succeeds when the header is not present" {
dic.Add("HX-Target", "span#") let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
let hdr = ctx.Request.Headers.HxTarget Expect.isNone ctx.Request.Headers.HxTrigger "There should not have been a header returned"
Expect.isSome hdr "There should be a header present"
Expect.equal (fst hdr.Value) "span" "The target tag was incorrect"
Expect.isNone (snd hdr.Value) "There should not be a target ID present"
} }
test "succeeds when the header is present and ID is missing" { test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Target", "aside") dic.Add ("HX-Trigger", "#trig")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
let hdr = ctx.Request.Headers.HxTarget Expect.isSome ctx.Request.Headers.HxTrigger "There should be a header present"
Expect.isSome hdr "There should be a header present" Expect.equal ctx.Request.Headers.HxTrigger.Value "#trig" "The header value was incorrect"
Expect.equal (fst hdr.Value) "aside" "The target tag was incorrect" }
Expect.isNone (snd hdr.Value) "There should not be a target ID present" ]
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"
} }
] ]
] ]
@@ -209,36 +163,36 @@ let reqExtensions =
testList "HttpRequestExtensions" [ testList "HttpRequestExtensions" [
testList "IsHtmx" [ testList "IsHtmx" [
test "succeeds when request is not from htmx" { test "succeeds when request is not from htmx" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isFalse ctx.Request.IsHtmx "The request should not be an htmx request" Expect.isFalse ctx.Request.IsHtmx "The request should not be an htmx request"
} }
test "succeeds when request is from htmx" { test "succeeds when request is from htmx" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Request", "true") dic.Add ("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isTrue ctx.Request.IsHtmx "The request should have been an htmx request" Expect.isTrue ctx.Request.IsHtmx "The request should have been an htmx request"
} }
] ]
testList "IsHtmxRefresh" [ testList "IsHtmxRefresh" [
test "succeeds when request is not from htmx" { test "succeeds when request is not from htmx" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isFalse ctx.Request.IsHtmxRefresh "The request should not have been an htmx refresh" 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" { test "succeeds when request is from htmx, but not a refresh" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Request", "true") dic.Add ("HX-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isFalse ctx.Request.IsHtmxRefresh "The request should not have been an htmx refresh" 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" { test "IsHtmxRefresh succeeds when request is from htmx and is a refresh" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
dic.Add("HX-Request", "true") dic.Add ("HX-Request", "true")
dic.Add("HX-History-Restore-Request", "true") dic.Add ("HX-History-Restore-Request", "true")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isTrue ctx.Request.IsHtmxRefresh "The request should have been an htmx refresh" Expect.isTrue ctx.Request.IsHtmxRefresh "The request should have been an htmx refresh"
} }
@@ -248,38 +202,30 @@ let reqExtensions =
open System.Threading.Tasks open System.Threading.Tasks
/// Dummy "next" parameter to get the pipeline to execute/terminate /// Dummy "next" parameter to get the pipeline to execute/terminate
let next (ctx: HttpContext) = Task.FromResult(Some ctx) let next (ctx : HttpContext) = Task.FromResult (Some ctx)
/// Tests for the HttpHandler functions provided in the Handlers module /// Tests for the HttpHandler functions provided in the Handlers module
let handlers = let handlers =
testList "HandlerTests" [ 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" { testTask "withHxPushUrl succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxPushUrl "/a-new-url" next ctx let! _ = withHxPushUrl "/a-new-url" next ctx
Expect.isTrue (dic.ContainsKey "HX-Push-Url") "The HX-Push-Url header should be present" 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" Expect.equal dic["HX-Push-Url"].[0] "/a-new-url" "The HX-Push-Url value was incorrect"
} }
testTask "withHxNoPushUrl succeeds" { testTask "withHxNoPushUrl succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxNoPushUrl next ctx let! _ = withHxNoPushUrl next ctx
Expect.isTrue (dic.ContainsKey "HX-Push-Url") "The HX-Push-Url header should be present" 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" Expect.equal dic["HX-Push-Url"].[0] "false" "The HX-Push-Url value was incorrect"
} }
testTask "withHxRedirect succeeds" { testTask "withHxRedirect succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRedirect "/somewhere-else" next ctx let! _ = withHxRedirect "/somewhere-else" next ctx
Expect.isTrue (dic.ContainsKey "HX-Redirect") "The HX-Redirect header should be present" Expect.isTrue (dic.ContainsKey "HX-Redirect") "The HX-Redirect header should be present"
@@ -287,16 +233,16 @@ let handlers =
} }
testList "withHxRefresh" [ testList "withHxRefresh" [
testTask "succeeds when set to true" { testTask "succeeds when set to true" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRefresh true next ctx let! _ = withHxRefresh true next ctx
Expect.isTrue (dic.ContainsKey "HX-Refresh") "The HX-Refresh header should be present" 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" Expect.equal dic["HX-Refresh"].[0] "true" "The HX-Refresh value was incorrect"
} }
testTask "succeeds when set to false" { testTask "succeeds when set to false" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRefresh false next ctx let! _ = withHxRefresh false next ctx
Expect.isTrue (dic.ContainsKey "HX-Refresh") "The HX-Refresh header should be present" Expect.isTrue (dic.ContainsKey "HX-Refresh") "The HX-Refresh header should be present"
@@ -304,160 +250,101 @@ let handlers =
} }
] ]
testTask "withHxReplaceUrl succeeds" { testTask "withHxReplaceUrl succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxReplaceUrl "/a-substitute-url" next ctx let! _ = withHxReplaceUrl "/a-substitute-url" next ctx
Expect.isTrue (dic.ContainsKey "HX-Replace-Url") "The HX-Replace-Url header should be present" 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" Expect.equal dic["HX-Replace-Url"].[0] "/a-substitute-url" "The HX-Replace-Url value was incorrect"
} }
testTask "withHxNoReplaceUrl succeeds" { testTask "withHxNoReplaceUrl succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxNoReplaceUrl next ctx let! _ = withHxNoReplaceUrl next ctx
Expect.isTrue (dic.ContainsKey "HX-Replace-Url") "The HX-Replace-Url header should be present" 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" Expect.equal dic["HX-Replace-Url"].[0] "false" "The HX-Replace-Url value was incorrect"
} }
testTask "withHxReselect succeeds" { testTask "withHxReselect succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxReselect "#test" next ctx let! _ = withHxReselect "#test" next ctx
Expect.isTrue (dic.ContainsKey "HX-Reselect") "The HX-Reselect header should be present" 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" Expect.equal dic["HX-Reselect"].[0] "#test" "The HX-Reselect value was incorrect"
} }
testTask "withHxReswap succeeds" { testTask "withHxReswap succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxReswap HxSwap.BeforeEnd next ctx let! _ = withHxReswap HxSwap.BeforeEnd next ctx
Expect.isTrue (dic.ContainsKey "HX-Reswap") "The HX-Reswap header should be present" 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" Expect.equal dic["HX-Reswap"].[0] HxSwap.BeforeEnd "The HX-Reswap value was incorrect"
} }
testTask "withHxRetarget succeeds" { testTask "withHxRetarget succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxRetarget "#somewhereElse" next ctx let! _ = withHxRetarget "#somewhereElse" next ctx
Expect.isTrue (dic.ContainsKey "HX-Retarget") "The HX-Retarget header should be present" 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" Expect.equal dic["HX-Retarget"].[0] "#somewhereElse" "The HX-Retarget value was incorrect"
} }
testTask "withHxTrigger succeeds" { testTask "withHxTrigger succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTrigger "doSomething" next ctx let! _ = withHxTrigger "doSomething" next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present" 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" Expect.equal dic["HX-Trigger"].[0] "doSomething" "The HX-Trigger value was incorrect"
} }
testTask "withHxTriggerMany succeeds" { testTask "withHxTriggerMany succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerMany [ "blah", "foo"; "bleh", "bar" ] next ctx let! _ = withHxTriggerMany [ "blah", "foo"; "bleh", "bar" ] next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present" Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present"
Expect.equal Expect.equal
dic["HX-Trigger"].[0] """{ "blah": "foo", "bleh": "bar" }""" "The HX-Trigger value was incorrect" dic["HX-Trigger"].[0] """{ "blah": "foo", "bleh": "bar" }""" "The HX-Trigger value was incorrect"
} }
]
/// Tests for the HtmxScript module
let script =
testList "HtmxScript" [
test "local generates correct link" {
Expect.equal
(string HtmxScript.local)
$"""<script src="/_content/Giraffe.Htmx.Common/htmx.min.js?ver={HtmxVersion}"></script>"""
"htmx script link is incorrect"
}
]
#nowarn 44 // Obsolete items still have tests
let dictExtensionsObs =
testList "IHeaderDictionaryExtensions (Obsolete)" [
testList "HxPrompt" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxPrompt "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Prompt", "of course")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxPrompt "There should be a header present"
Expect.equal ctx.Request.Headers.HxPrompt.Value "of course" "The header value was incorrect"
}
]
testList "HxTrigger" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs (HeaderDictionary ()) |> ignore
Expect.isNone ctx.Request.Headers.HxTrigger "There should not have been a header returned"
}
test "succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Trigger", "#trig")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTrigger "There should be a header present"
Expect.equal ctx.Request.Headers.HxTrigger.Value "#trig" "The header value was incorrect"
}
]
testList "HxTriggerName" [
test "succeeds when the header is not present" {
let ctx = Substitute.For<HttpContext>()
ctx.Request.Headers.ReturnsForAnyArgs(HeaderDictionary()) |> ignore
Expect.isNone ctx.Request.Headers.HxTriggerName "There should not have been a header returned"
}
test "HxTriggerName succeeds when the header is present" {
let ctx = Substitute.For<HttpContext>()
let dic = HeaderDictionary()
dic.Add("HX-Trigger-Name", "click")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTriggerName "There should be a header present"
Expect.equal ctx.Request.Headers.HxTriggerName.Value "click" "The header value was incorrect"
}
]
]
let handlerObs =
testList "Handler Tests (Obsolete)" [
testTask "withHxTriggerAfterSettle succeeds" { testTask "withHxTriggerAfterSettle succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerAfterSettle "byTheWay" next ctx let! _ = withHxTriggerAfterSettle "byTheWay" next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present" Expect.isTrue
Expect.equal dic["HX-Trigger"].[0] "byTheWay" "The HX-Trigger value was incorrect" (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" { testTask "withHxTriggerManyAfterSettle succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerManyAfterSettle [ "oof", "ouch"; "hmm", "uh" ] next ctx let! _ = withHxTriggerManyAfterSettle [ "oof", "ouch"; "hmm", "uh" ] next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present" Expect.isTrue
Expect.equal dic["HX-Trigger"].[0] """{ "oof": "ouch", "hmm": "uh" }""" "The HX-Trigger value was incorrect" (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" { testTask "withHxTriggerAfterSwap succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerAfterSwap "justASec" next ctx let! _ = withHxTriggerAfterSwap "justASec" next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present" Expect.isTrue (dic.ContainsKey "HX-Trigger-After-Swap") "The HX-Trigger-After-Swap header should be present"
Expect.equal dic["HX-Trigger"].[0] "justASec" "The HX-Trigger value was incorrect" Expect.equal dic["HX-Trigger-After-Swap"].[0] "justASec" "The HX-Trigger-After-Swap value was incorrect"
} }
testTask "withHxTriggerManyAfterSwap succeeds" { testTask "withHxTriggerManyAfterSwap succeeds" {
let ctx = Substitute.For<HttpContext>() let ctx = Substitute.For<HttpContext> ()
let dic = HeaderDictionary() let dic = HeaderDictionary ()
ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore ctx.Response.Headers.ReturnsForAnyArgs dic |> ignore
let! _ = withHxTriggerManyAfterSwap [ "this", "1"; "that", "2" ] next ctx let! _ = withHxTriggerManyAfterSwap [ "this", "1"; "that", "2" ] next ctx
Expect.isTrue (dic.ContainsKey "HX-Trigger") "The HX-Trigger header should be present" Expect.isTrue (dic.ContainsKey "HX-Trigger-After-Swap") "The HX-Trigger-After-Swap header should be present"
Expect.equal dic["HX-Trigger"].[0] """{ "this": "1", "that": "2" }""" "The HX-Trigger value was incorrect" 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 /// All tests for this module
let allTests = testList "Htmx" [ dictExtensions; reqExtensions; handlers; script; dictExtensionsObs; handlerObs ] let allTests = testList "Htmx" [ dictExtensions; reqExtensions; handlers ]
+1 -1
View File
@@ -3,4 +3,4 @@ open Expecto
let allTests = testList "Giraffe" [ Common.allTests; Htmx.allTests; ViewEngine.allTests ] let allTests = testList "Giraffe" [ Common.allTests; Htmx.allTests; ViewEngine.allTests ]
[<EntryPoint>] [<EntryPoint>]
let main args = runTestsWithCLIArgs [] args allTests let main args = runTestsWithArgs defaultConfig args allTests
+2 -3
View File
@@ -18,9 +18,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Expecto" /> <PackageReference Include="Expecto" Version="9.0.4" />
<PackageReference Include="NSubstitute" /> <PackageReference Include="NSubstitute" Version="5.0.0" />
<PackageReference Include="FSharp.Core" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+423 -764
View File
File diff suppressed because it is too large Load Diff
@@ -4,7 +4,6 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>Extensions to Giraffe View Engine to support htmx attributes and their values</Description> <Description>Extensions to Giraffe View Engine to support htmx attributes and their values</Description>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -14,8 +13,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe.ViewEngine" /> <PackageReference Include="Giraffe.ViewEngine" Version="1.4.0" />
<PackageReference Include="FSharp.Core" /> <PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
File diff suppressed because it is too large Load Diff
+14 -23
View File
@@ -2,13 +2,7 @@
This package enables [htmx](https://htmx.org) support within the [Giraffe](https://giraffe.wiki) view engine. This package enables [htmx](https://htmx.org) support within the [Giraffe](https://giraffe.wiki) view engine.
**htmx version: 4.0.0-beta4** **htmx version: 1.9.12**
_Upgrading from v2.x: see [the migration guide](https://four.htmx.org/docs/get-started/migration) for changes, which are plentiful. htmx switches from `XMLHTTPRequest` to `fetch`, and many changes are related to the new event cycle._
_Inheritance is now explicit; to have an attribute's value inherited to its children, wrap the attribute in `hxInherited` (ex. `hxInherited (_hxTarget "#main")`). Values can be appended to inherited values as well using the `hxAppend` modifier._
_Several constructs have been marked obsolete in this release, and will be removed from the first production release of v4. With the exception of `_hxDisable`, though (which now functions as the deprecated `_hxDisabledElt` did), this should not introduce compile errors. Rather, this package will raise warnings for deprecated constructs, along with suggestions of what to use instead._
### Setup ### Setup
@@ -20,23 +14,20 @@ _Several constructs have been marked obsolete in this release, and will be remov
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: 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 ```fsharp
let autoload = let autoload =
div [ _hxGet "/this/data"; _hxTrigger HxTrigger.Load ] [ str "Loading..." ] div [ _hxGet "/this/data"; _hxTrigger HxTrigger.Load ] [ str "Loading..." ]
``` ```
Support modules include: Support modules include:
- `HxConfig` _(new in v4)_
- `HxEncoding` - `HxEncoding`
- `HxHeaders` - `HxHeaders`
- ~~`HxParams`~~ _(removed in v4)_ - `HxParams`
- ~~`HxRequest`~~ _(renamed to `HxConfig`)_ - `HxRequest`
- `HxSwap` (requires `open Giraffe.Htmx`) - `HxSwap` (requires `open Giraffe.Htmx`)
- `HxTrigger` - `HxTrigger`
- `HxVals` - `HxVals`
`Htmx.Script.local` creates an `XmlNode` to load the package-provided htmx library. There are also two `XmlNode`s that will load the htmx script from jsdelivr; `Htmx.Script.cdnMinified` loads the minified version, and `Htmx.Script.cdnUnminified` loads the unminified version (useful for debugging). htmx v4 also distributes a "max" bundle which contains some common extensions; these are available as `Htmx.Script.localMax`, `Htmx.Script.cdnMaxMinified`, and `Htmx.Script.cdnMaxUnminified`. There are two `XmlNode`s that will load the htmx script from unpkg; `Htmx.Script.minified` loads the minified version, and `Htmx.Script.unminified` loads the unminified version (useful for debugging).
_NOTE: When using the CDN nodes and a Content Security Policy (CSP) header, `cdn.jsdelivr.net` needs to be listed as an allowable `script-src`._
This also supports [fragment rendering](https://bitbadger.solutions/blog/2022/fragment-rendering-in-giraffe-view-engine.html), providing the flexibility to render an entire template, or only a portion of it (based on the element's `id` attribute). This also supports [fragment rendering](https://bitbadger.solutions/blog/2022/fragment-rendering-in-giraffe-view-engine.html), providing the flexibility to render an entire template, or only a portion of it (based on the element's `id` attribute).
@@ -52,19 +43,19 @@ The support modules contain named properties for known values (as illustrated wi
- `HxRequest` has a `Configure` function, which takes a list of strings; the other functions in the module allow for configuring the request. - `HxRequest` has a `Configure` function, which takes a list of strings; the other functions in the module allow for configuring the request.
```fsharp ```fsharp
HxRequest.Configure [ HxRequest.Timeout 500 ] |> _hxRequest 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: - `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 ```fsharp
HxTrigger.Click HxTrigger.Click
|> HxTrigger.Filter.Shift |> HxTrigger.Filter.Shift
|> HxTrigger.FromDocument |> HxTrigger.FromDocument
|> HxTrigger.Delay "3s" |> HxTrigger.Delay "3s"
|> _hxTrigger |> _hxTrigger
// or // or
(HxTrigger.Filter.Shift >> HxTrigger.FromDocument >> HxTrigger.Delay "3s") HxTrigger.Click (HxTrigger.Filter.Shift >> HxTrigger.FromDocument >> HxTrigger.Delay "3s") HxTrigger.Click
|> _hxTrigger |> _hxTrigger
``` ```
-7
View File
@@ -1,7 +0,0 @@
#!/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 .