Compare commits

..

1 Commits

Author SHA1 Message Date
125853b2a7 Update script tags to pull v1.9.12
- Update Git repo paths in package metadata
2024-04-17 22:29:32 -04:00
17 changed files with 497 additions and 981 deletions

3
.gitignore vendored
View File

@ -6,6 +6,3 @@
.idea .idea
*.user *.user
.vscode .vscode
src/*.nupkg
src/tests*.txt

View File

@ -21,23 +21,22 @@ 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.
@ -49,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.)_
@ -60,10 +57,10 @@ _(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 load htmx from unpkg, `Htmx.Script.minified` or `Htmx.Script.unminified` can be used to load the script in your HTML trees. If you want to load htmx from unpkg, `Htmx.Script.minified` or `Htmx.Script.unminified` can be used to load the script in your HTML trees.

View File

@ -1,53 +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>Serialize a list of key/value pairs to JSON (very rudimentary)</summary> /// Valid values for the `hx-swap` attribute / `HX-Reswap` header (may be combined with swap/settle/scroll/show config)
/// <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>] [<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>Insert the response before the target element</summary> /// Insert the response before the target element
[<Literal>]
let BeforeBegin = "beforebegin" let BeforeBegin = "beforebegin"
/// <summary>Insert the response before the first child of the target element</summary> /// Insert the response before the first child of the target element
[<Literal>]
let AfterBegin = "afterbegin" let AfterBegin = "afterbegin"
/// <summary>Insert the response after the last child of the target element</summary> /// Insert the response after the last child of the target element
[<Literal>]
let BeforeEnd = "beforeend" let BeforeEnd = "beforeend"
/// <summary>Insert the response after the target element</summary> /// Insert the response after the target element
[<Literal>]
let AfterEnd = "afterend" let AfterEnd = "afterend"
/// <summary>Does not append content from response (out of band items will still be processed).</summary> /// Does not append content from response (out of band items will still be processed).
[<Literal>]
let None = "none" let None = "none"

View File

@ -4,7 +4,6 @@
<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>
@ -16,9 +15,5 @@
<ItemGroup> <ItemGroup>
<PackageReference Update="FSharp.Core" Version="6.0.0" /> <PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Giraffe.Htmx" />
<InternalsVisibleTo Include="Giraffe.ViewEngine.Htmx" />
</ItemGroup>
</Project> </Project>

View File

@ -2,4 +2,4 @@
This package contains common code shared between [`Giraffe.Htmx`](https://www.nuget.org/packages/Giraffe.Htmx) and [`Giraffe.ViewEngine.Htmx`](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx), and will be automatically installed when you install either one. This package contains common code shared between [`Giraffe.Htmx`](https://www.nuget.org/packages/Giraffe.Htmx) and [`Giraffe.ViewEngine.Htmx`](https://www.nuget.org/packages/Giraffe.ViewEngine.Htmx), and will be automatically installed when you install either one.
**htmx version: 2.0.6** **htmx version: 1.9.12**

View File

@ -1,16 +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</TargetFrameworks> <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<VersionPrefix>2.0.6</VersionPrefix> <VersionPrefix>1.9.12</VersionPrefix>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <PackageReleaseNotes>Update script tags to pull htmx 1.9.12</PackageReleaseNotes>
<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> <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>

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,7 +13,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" Version="6.4.0" /> <PackageReference Include="Giraffe" Version="6.2.0" />
<PackageReference Update="FSharp.Core" Version="6.0.0" /> <PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup> </ItemGroup>

View File

@ -11,162 +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`
member this.HxPrompt member this.HxPrompt with get () = hdr this "HX-Prompt"
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 <c>id</c> attribute of the target element if it exists</summary> /// The `id` of the target element if it exists
member this.HxTarget member this.HxTarget with get () = hdr this "HX-Target"
with get () = hdr this "HX-Target"
/// <summary>The <c>id</c> attribute of the triggered element if it exists</summary> /// The `id` of the triggered element if it exists
member this.HxTrigger member this.HxTrigger with get () = hdr this "HX-Trigger"
with get () = hdr this "HX-Trigger"
/// <summary>The <c>name</c> attribute of the triggered element if it exists</summary> /// The `name` of the triggered element if it exists
member this.HxTriggerName member this.HxTriggerName with get () = hdr this "HX-Trigger-Name"
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) =
/// <summary>Instruct htmx to perform a client-side redirect for content</summary> (string trueOrFalse).ToLowerInvariant ()
/// <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
/// <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
/// <summary>Explicitly do not push a new URL into the history stack</summary> /// Serialize a list of key/value pairs to JSON (very rudimentary)
/// <returns>An HTTP handler with the <c>HX-Push-Url</c> header set to <c>false</c></returns> let private toJson (evts : (string * string) list) =
/// <seealso href="https://htmx.org/headers/hx-push-url/">Documentation</seealso> evts
|> List.map (fun evt -> sprintf "\"%s\": \"%s\"" (fst evt) ((snd evt).Replace ("\"", "\\\"")))
|> String.concat ", "
|> sprintf "{ %s }"
/// Pushes a new url into the history stack
let withHxPushUrl : string -> HttpHandler =
setHttpHeader "HX-Push-Url"
/// Explicitly do not push a new URL into the history stack
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 = /// Explicitly do not push a new URL into the history stack
setHttpHeader "HX-Redirect" url [<Obsolete "Use withHxNoPushUrl; HX-Push was replaced by HX-Push-Url in v1.8.0">]
let withHxNoPush = withHxNoPushUrl
/// Can be used to do a client-side redirect to a new location
let withHxRedirect : string -> HttpHandler =
setHttpHeader "HX-Redirect"
/// <summary>If set to <c>true</c> the client side will do a full refresh of the page</summary> /// If set to `true` the client side will do a a full refresh of the page
/// <param name="shouldRefresh">Whether the client should refresh their page</param> let withHxRefresh : bool -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Refresh</c> header set</returns> toLowerBool >> setHttpHeader "HX-Refresh"
let withHxRefresh shouldRefresh : HttpHandler =
(toLowerBool >> setHttpHeader "HX-Refresh") shouldRefresh
/// <summary>Replaces the current URL in the history stack</summary> /// Replaces the current URL in the history stack
/// <param name="url">The URL to place in the history stack in place of the current one</param> let withHxReplaceUrl : string -> HttpHandler =
/// <returns>An HTTP handler with the <c>HX-Replace-URL</c> header set</returns> setHttpHeader "HX-Replace-Url"
/// <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> /// Explicitly do not replace the current URL in the history stack
/// <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 = 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>
let withHxTriggerAfterSettle (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger-After-Settle" 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>
let withHxTriggerManyAfterSettle evts : HttpHandler = let withHxTriggerManyAfterSettle evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger-After-Settle" 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>
let withHxTriggerAfterSwap (evt: string) : HttpHandler =
setHttpHeader "HX-Trigger-After-Swap" 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>
let withHxTriggerManyAfterSwap evts : HttpHandler = let withHxTriggerManyAfterSwap evts : HttpHandler =
toJson evts |> setHttpHeader "HX-Trigger-After-Swap" toJson evts |> setHttpHeader "HX-Trigger-After-Swap"

View File

@ -2,9 +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: 2.0.6** **htmx version: 1.9.12**
_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 ### Setup
@ -16,20 +14,20 @@ _Upgrading from v1.x: the [migration guide](https://htmx.org/migration-guide-htm
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.HxPrompt with match ctx.HxPrompt with
| Some prompt -> ... // do something with the text the user provided | Some prompt -> ... // do something with the text the user provided
| None -> ... // no text 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.

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,22 +51,22 @@ 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
@ -75,14 +75,14 @@ let dictExtensions =
] ]
testList "HxPrompt" [ testList "HxPrompt" [
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.HxPrompt "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxPrompt "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-Prompt", "of course") dic.Add ("HX-Prompt", "of course")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxPrompt "There should be a header present" 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" Expect.equal ctx.Request.Headers.HxPrompt.Value "of course" "The header value was incorrect"
@ -90,22 +90,22 @@ let dictExtensions =
] ]
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"
@ -113,14 +113,14 @@ let dictExtensions =
] ]
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" { 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", "#leItem") dic.Add ("HX-Target", "#leItem")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTarget "There should be a header present" 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" Expect.equal ctx.Request.Headers.HxTarget.Value "#leItem" "The header value was incorrect"
@ -128,14 +128,14 @@ let dictExtensions =
] ]
testList "HxTrigger" [ testList "HxTrigger" [
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.HxTrigger "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxTrigger "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-Trigger", "#trig") dic.Add ("HX-Trigger", "#trig")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTrigger "There should be a header present" 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" Expect.equal ctx.Request.Headers.HxTrigger.Value "#trig" "The header value was incorrect"
@ -143,14 +143,14 @@ let dictExtensions =
] ]
testList "HxTriggerName" [ testList "HxTriggerName" [
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.HxTriggerName "There should not have been a header returned" Expect.isNone ctx.Request.Headers.HxTriggerName "There should not have been a header returned"
} }
test "HxTriggerName succeeds when the header is present" { test "HxTriggerName 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-Trigger-Name", "click") dic.Add ("HX-Trigger-Name", "click")
ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore ctx.Request.Headers.ReturnsForAnyArgs dic |> ignore
Expect.isSome ctx.Request.Headers.HxTriggerName "There should be a header present" 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" Expect.equal ctx.Request.Headers.HxTriggerName.Value "click" "The header value was incorrect"
@ -163,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"
} }
@ -202,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"
@ -241,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"
@ -258,56 +250,56 @@ 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"
@ -315,8 +307,8 @@ let handlers =
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"
} }
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 Expect.isTrue
@ -324,8 +316,8 @@ let handlers =
Expect.equal dic["HX-Trigger-After-Settle"].[0] "byTheWay" "The HX-Trigger-After-Settle value was incorrect" 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 Expect.isTrue
@ -335,16 +327,16 @@ let handlers =
"The HX-Trigger-After-Settle value was incorrect" "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-After-Swap") "The HX-Trigger-After-Swap 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-After-Swap"].[0] "justASec" "The HX-Trigger-After-Swap 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-After-Swap") "The HX-Trigger-After-Swap header should be present" Expect.isTrue (dic.ContainsKey "HX-Trigger-After-Swap") "The HX-Trigger-After-Swap header should be present"

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

View File

@ -18,9 +18,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Expecto" Version="10.2.1" /> <PackageReference Include="Expecto" Version="9.0.4" />
<PackageReference Include="NSubstitute" Version="5.1.0" /> <PackageReference Include="NSubstitute" Version="5.0.0" />
<PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -406,8 +406,8 @@ let hxEvent =
Expect.equal (XhrProgress.ToHxOnString()) "xhr:progress" "XhrProgress hx-on event name not correct" Expect.equal (XhrProgress.ToHxOnString()) "xhr:progress" "XhrProgress hx-on event name not correct"
} }
] ]
] ]
/// Tests for the HxHeaders module /// Tests for the HxHeaders module
let hxHeaders = let hxHeaders =
testList "HxHeaders" [ testList "HxHeaders" [
@ -497,32 +497,6 @@ let hxRequest =
] ]
] ]
/// Tests for the HxSync module
let hxSync =
testList "HxSync" [
test "Drop is correct" {
Expect.equal HxSync.Drop "drop" "Drop is incorrect"
}
test "Abort is correct" {
Expect.equal HxSync.Abort "abort" "Abort is incorrect"
}
test "Replace is correct" {
Expect.equal HxSync.Replace "replace" "Replace is incorrect"
}
test "Queue is correct" {
Expect.equal HxSync.Queue "queue" "Queue is incorrect"
}
test "QueueFirst is correct" {
Expect.equal HxSync.QueueFirst "queue first" "QueueFirst is incorrect"
}
test "QueueLast is correct" {
Expect.equal HxSync.QueueLast "queue last" "QueueLast is incorrect"
}
test "QueueAll is correct" {
Expect.equal HxSync.QueueAll "queue all" "QueueAll is incorrect"
}
]
/// Tests for the HxTrigger module /// Tests for the HxTrigger module
let hxTrigger = let hxTrigger =
testList "HxTrigger" [ testList "HxTrigger" [
@ -662,9 +636,6 @@ let hxTrigger =
test "succeeds when it is not the first modifier" { test "succeeds when it is not the first modifier" {
Expect.equal (HxTrigger.Queue "def" "click") "click queue:def" "Queue modifier incorrect" Expect.equal (HxTrigger.Queue "def" "click") "click queue:def" "Queue modifier incorrect"
} }
test "succeeds when no type of queueing is given" {
Expect.equal (HxTrigger.Queue "" "blur") "blur queue" "Queue modifier incorrect"
}
] ]
testList "QueueFirst" [ testList "QueueFirst" [
test "succeeds when it is the first modifier" { test "succeeds when it is the first modifier" {
@ -755,7 +726,7 @@ let attributes =
|> shouldRender """<figure hx-headers="{ &quot;X-Special-Header&quot;: &quot;some-header&quot; }"></figure>""" |> shouldRender """<figure hx-headers="{ &quot;X-Special-Header&quot;: &quot;some-header&quot; }"></figure>"""
} }
test "_hxHistory succeeds" { test "_hxHistory succeeds" {
span [ _hxHistory false ] [] |> shouldRender """<span hx-history="false"></span>""" span [ _hxHistory "false" ] [] |> shouldRender """<span hx-history="false"></span>"""
} }
test "_hxHistoryElt succeeds" { test "_hxHistoryElt succeeds" {
table [ _hxHistoryElt ] [] |> shouldRender """<table hx-history-elt></table>""" table [ _hxHistoryElt ] [] |> shouldRender """<table hx-history-elt></table>"""
@ -786,7 +757,7 @@ let attributes =
hr [ _hxPost "/hear-ye-hear-ye" ] |> shouldRender """<hr hx-post="/hear-ye-hear-ye">""" hr [ _hxPost "/hear-ye-hear-ye" ] |> shouldRender """<hr hx-post="/hear-ye-hear-ye">"""
} }
test "_hxPreserve succeeds" { test "_hxPreserve succeeds" {
img [ _hxPreserve ] |> shouldRender """<img hx-preserve>""" img [ _hxPreserve ] |> shouldRender """<img hx-preserve="true">"""
} }
test "_hxPrompt succeeds" { test "_hxPrompt succeeds" {
strong [ _hxPrompt "Who goes there?" ] [] strong [ _hxPrompt "Who goes there?" ] []
@ -810,6 +781,10 @@ let attributes =
test "_hxSelectOob succeeds" { test "_hxSelectOob succeeds" {
section [ _hxSelectOob "#oob" ] [] |> shouldRender """<section hx-select-oob="#oob"></section>""" section [ _hxSelectOob "#oob" ] [] |> shouldRender """<section hx-select-oob="#oob"></section>"""
} }
test "_hxSse succeeds" {
footer [ _hxSse "connect:/my-events" ] []
|> shouldRender """<footer hx-sse="connect:/my-events"></footer>"""
}
test "_hxSwap succeeds" { test "_hxSwap succeeds" {
del [ _hxSwap "innerHTML" ] [] |> shouldRender """<del hx-swap="innerHTML"></del>""" del [ _hxSwap "innerHTML" ] [] |> shouldRender """<del hx-swap="innerHTML"></del>"""
} }
@ -821,8 +796,7 @@ let attributes =
li [ _hxSwapOob "true" ] [] |> shouldRender """<li hx-swap-oob="true"></li>""" li [ _hxSwapOob "true" ] [] |> shouldRender """<li hx-swap-oob="true"></li>"""
} }
test "_hxSync succeeds" { test "_hxSync succeeds" {
nav [ _hxSync "closest form" HxSync.Abort ] [] nav [ _hxSync "closest form:abort" ] [] |> shouldRender """<nav hx-sync="closest form:abort"></nav>"""
|> shouldRender """<nav hx-sync="closest form:abort"></nav>"""
} }
test "_hxTarget succeeds" { test "_hxTarget succeeds" {
header [ _hxTarget "#somewhereElse" ] [] |> shouldRender """<header hx-target="#somewhereElse"></header>""" header [ _hxTarget "#somewhereElse" ] [] |> shouldRender """<header hx-target="#somewhereElse"></header>"""
@ -834,11 +808,8 @@ let attributes =
dt [ _hxVals """{ "extra": "values" }""" ] [] dt [ _hxVals """{ "extra": "values" }""" ] []
|> shouldRender """<dt hx-vals="{ &quot;extra&quot;: &quot;values&quot; }"></dt>""" |> shouldRender """<dt hx-vals="{ &quot;extra&quot;: &quot;values&quot; }"></dt>"""
} }
test "_sseSwap succeeds" { test "_hxWs succeeds" {
ul [ _sseSwap "sseMessageName" ] [] |> shouldRender """<ul sse-swap="sseMessageName"></ul>""" ul [ _hxWs "connect:/web-socket" ] [] |> shouldRender """<ul hx-ws="connect:/web-socket"></ul>"""
}
test "_sseConnect succeeds" {
div [ _sseConnect "/gps/sse" ] [] |> shouldRender """<div sse-connect="/gps/sse"></div>"""
} }
] ]
@ -849,14 +820,14 @@ let script =
let html = RenderView.AsString.htmlNode Script.minified let html = RenderView.AsString.htmlNode Script.minified
Expect.equal Expect.equal
html html
"""<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.6/dist/htmx.min.js" integrity="sha384-Akqfrbj/HpNVo8k11SXBb6TlBWmXXlYQrCSqEWmyKJe+hDm3Z/B2WVG4smwBkRVm" crossorigin="anonymous"></script>""" """<script src="https://unpkg.com/htmx.org@1.9.12" integrity="sha384-ujb1lZYygJmzgSwoxRggbCHcjc0rB2XoQrxeTUQyRjrOnlCoYta87iKBWq3EsdM2" crossorigin="anonymous"></script>"""
"Minified script tag is incorrect" "Minified script tag is incorrect"
} }
test "unminified succeeds" { test "unminified succeeds" {
let html = RenderView.AsString.htmlNode Script.unminified let html = RenderView.AsString.htmlNode Script.unminified
Expect.equal Expect.equal
html html
"""<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.6/dist/htmx.js" integrity="sha384-ksKjJrwjL5VxqAkAZAVOPXvMkwAykMaNYegdixAESVr+KqLkKE8XBDoZuwyWVUDv" crossorigin="anonymous"></script>""" """<script src="https://unpkg.com/htmx.org@1.9.12/dist/htmx.js" integrity="sha384-qbtR4rS9RrUMECUWDWM2+YGgN3U4V4ZncZ0BvUcg9FGct0jqXz3PUdVpU1p0yrXS" crossorigin="anonymous"></script>"""
"Unminified script tag is incorrect" "Unminified script tag is incorrect"
} }
] ]
@ -869,7 +840,7 @@ let renderFragment =
/// Validate that the two object references are the same object /// Validate that the two object references are the same object
let isSame obj1 obj2 message = let isSame obj1 obj2 message =
Expect.isTrue (obj.ReferenceEquals(obj1, obj2)) message Expect.isTrue (obj.ReferenceEquals (obj1, obj2)) message
testList "findIdNode" [ testList "findIdNode" [
test "fails with a Text node" { test "fails with a Text node" {
@ -951,7 +922,7 @@ let renderFragment =
} }
test "fails when an ID is not matched" { test "fails when an ID is not matched" {
Expect.equal Expect.equal
(RenderFragment.AsBytes.htmlFromNodes "whiff" []) (utf8.GetBytes(nodeNotFound "whiff")) (RenderFragment.AsBytes.htmlFromNodes "whiff" []) (utf8.GetBytes (nodeNotFound "whiff"))
"HTML bytes are incorrect" "HTML bytes are incorrect"
} }
] ]
@ -968,7 +939,7 @@ let renderFragment =
} }
test "fails when an ID is not matched" { test "fails when an ID is not matched" {
Expect.equal Expect.equal
(RenderFragment.AsBytes.htmlFromNode "foo" (hr [])) (utf8.GetBytes(nodeNotFound "foo")) (RenderFragment.AsBytes.htmlFromNode "foo" (hr [])) (utf8.GetBytes (nodeNotFound "foo"))
"HTML bytes are incorrect" "HTML bytes are incorrect"
} }
] ]
@ -976,31 +947,31 @@ let renderFragment =
testList "IntoStringBuilder" [ testList "IntoStringBuilder" [
testList "htmlFromNodes" [ testList "htmlFromNodes" [
test "succeeds when an ID is matched" { test "succeeds when an ID is matched" {
let sb = StringBuilder() let sb = StringBuilder ()
RenderFragment.IntoStringBuilder.htmlFromNodes sb "find-me" RenderFragment.IntoStringBuilder.htmlFromNodes sb "find-me"
[ p [] []; p [ _id "peekaboo" ] [ str "bzz"; str "nope"; span [ _id "find-me" ] [ str ";)" ] ]] [ p [] []; p [ _id "peekaboo" ] [ str "bzz"; str "nope"; span [ _id "find-me" ] [ str ";)" ] ]]
Expect.equal (string sb) """<span id="find-me">;)</span>""" "HTML is incorrect" Expect.equal (string sb) """<span id="find-me">;)</span>""" "HTML is incorrect"
} }
test "fails when an ID is not matched" { test "fails when an ID is not matched" {
let sb = StringBuilder() let sb = StringBuilder ()
RenderFragment.IntoStringBuilder.htmlFromNodes sb "missing" [] RenderFragment.IntoStringBuilder.htmlFromNodes sb "missing" []
Expect.equal (string sb) (nodeNotFound "missing") "HTML is incorrect" Expect.equal (string sb) (nodeNotFound "missing") "HTML is incorrect"
} }
] ]
testList "htmlFromNode" [ testList "htmlFromNode" [
test "succeeds when ID is matched at top level" { test "succeeds when ID is matched at top level" {
let sb = StringBuilder() let sb = StringBuilder ()
RenderFragment.IntoStringBuilder.htmlFromNode sb "top" (p [ _id "top" ] [ str "pinnacle" ]) RenderFragment.IntoStringBuilder.htmlFromNode sb "top" (p [ _id "top" ] [ str "pinnacle" ])
Expect.equal (string sb) """<p id="top">pinnacle</p>""" "HTML is incorrect" Expect.equal (string sb) """<p id="top">pinnacle</p>""" "HTML is incorrect"
} }
test "succeeds when ID is matched in child element" { test "succeeds when ID is matched in child element" {
let sb = StringBuilder() let sb = StringBuilder ()
div [] [ p [] [ str "nada" ]; p [ _id "it" ] [ str "is here" ]] div [] [ p [] [ str "nada" ]; p [ _id "it" ] [ str "is here" ]]
|> RenderFragment.IntoStringBuilder.htmlFromNode sb "it" |> RenderFragment.IntoStringBuilder.htmlFromNode sb "it"
Expect.equal (string sb) """<p id="it">is here</p>""" "HTML is incorrect" Expect.equal (string sb) """<p id="it">is here</p>""" "HTML is incorrect"
} }
test "fails when an ID is not matched" { test "fails when an ID is not matched" {
let sb = StringBuilder() let sb = StringBuilder ()
RenderFragment.IntoStringBuilder.htmlFromNode sb "bar" (hr []) RenderFragment.IntoStringBuilder.htmlFromNode sb "bar" (hr [])
Expect.equal (string sb) (nodeNotFound "bar") "HTML is incorrect" Expect.equal (string sb) (nodeNotFound "bar") "HTML is incorrect"
} }
@ -1008,6 +979,18 @@ let renderFragment =
] ]
] ]
#nowarn "44"
/// Tests for the HtmxAttrs module
let deprecatedAttributes =
testList "Deprecated Attributes" [
test "_hxOn succeeds" {
let newLine = "\n"
strong [ _hxOn "submit: alert('oops')\nclick: alert('howdy!')" ] []
|> shouldRender $"""<strong hx-on="submit: alert(&#39;oops&#39;){newLine}click: alert(&#39;howdy!&#39;)"></strong>"""
}
]
/// All tests in this module /// All tests in this module
let allTests = let allTests =
testList "ViewEngine.Htmx" [ testList "ViewEngine.Htmx" [
@ -1016,10 +999,10 @@ let allTests =
hxHeaders hxHeaders
hxParams hxParams
hxRequest hxRequest
hxSync
hxTrigger hxTrigger
hxVals hxVals
attributes attributes
script script
renderFragment renderFragment
deprecatedAttributes
] ]

View File

@ -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>

File diff suppressed because it is too large Load Diff

View File

@ -2,9 +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: 2.0.6** **htmx version: 1.9.12**
_Upgrading from v1.x: see [the migration guide](https://htmx.org/migration-guide-htmx-1/) for changes_
### Setup ### Setup
@ -16,7 +14,7 @@ _Upgrading from v1.x: see [the migration guide](https://htmx.org/migration-guide
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..." ]
``` ```
@ -29,7 +27,7 @@ Support modules include:
- `HxTrigger` - `HxTrigger`
- `HxVals` - `HxVals`
There are two `XmlNode`s that will load the htmx script from jsdelivr; `Htmx.Script.minified` loads the minified version, and `Htmx.Script.unminified` loads the unminified version (useful for debugging). 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).
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).
@ -45,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
``` ```

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 .