9 Commits

Author SHA1 Message Date
5e28714215 WIP on docs
- bump version
2024-12-30 22:06:27 -05:00
28cec1cb70 Drop .NET 6 support (#14) 2024-12-30 22:05:52 -05:00
10c31d77b5 Update version in READMEs 2024-12-13 17:02:28 -05:00
f4cd184a15 Update script and version to 2.0.4; add .NET 9 support 2024-12-13 16:57:27 -05:00
5626031593 Update script tags and package version to 2.0.3 2024-10-18 09:36:28 -04:00
f0de18845f Update script tags and package version to 2.0.2 2024-08-12 21:36:47 -04:00
961307fd99 Update htmx script to 2.0.1 2024-07-29 18:06:19 -04:00
a2960a79c6 Add pack script; drop beta tag 2024-06-18 19:38:28 -04:00
541384a92f htmx v2
- Drop `hx-sse` and `hx-ws` attributes
- Drop explicit .NET 7 support
- Update deps to latest versions
2024-06-18 19:16:10 -04:00
15 changed files with 347 additions and 215 deletions

3
.gitignore vendored
View File

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

View File

@@ -1,28 +1,45 @@
/// Common definitions shared between attribute values and response headers
/// <summary>Common definitions shared between attribute values and response headers</summary>
[<AutoOpen>]
module Giraffe.Htmx.Common
/// Valid values for the `hx-swap` attribute / `HX-Reswap` header (may be combined with swap/settle/scroll/show config)
/// <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 <tt>true</tt> or <tt>false</tt></summary>
/// <param name="boolValue">The boolean value to convert</param>
/// <returns>"true" for <tt>true</tt>, "false" for <tt>false</tt></returns>
let internal toLowerBool (boolValue: bool) =
(string boolValue).ToLowerInvariant()
/// <summary>Valid values for the <tt>hx-swap</tt> attribute / <tt>HX-Reswap</tt> header</summary>
/// <remarks>May be combined with <tt>swap</tt> / <tt>settle</tt> / <tt>scroll</tt> / <tt>show</tt> config)</remarks>
[<RequireQualifiedAccess>]
module HxSwap =
/// The default, replace the inner html of the target element
/// <summary>The default, replace the inner HTML of the target element</summary>
let InnerHtml = "innerHTML"
/// Replace the entire target element with the response
/// <summary>Replace the entire target element with the response</summary>
let OuterHtml = "outerHTML"
/// Insert the response before the target element
/// <summary>Insert the response before the target element</summary>
let BeforeBegin = "beforebegin"
/// Insert the response before the first child of the target element
/// <summary>Insert the response before the first child of the target element</summary>
let AfterBegin = "afterbegin"
/// Insert the response after the last child of the target element
/// <summary>Insert the response after the last child of the target element</summary>
let BeforeEnd = "beforeend"
/// Insert the response after the target element
/// <summary>Insert the response after the target element</summary>
let AfterEnd = "afterend"
/// 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).</summary>
let None = "none"

View File

@@ -4,6 +4,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>Common definitions for Giraffe.Htmx</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
@@ -16,4 +17,8 @@
<PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Giraffe.Htmx" />
<InternalsVisibleTo Include="Giraffe.ViewEngine.Htmx" />
</ItemGroup>
</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.
**htmx version: 2.0.0-beta4**
**htmx version: 2.0.4**

View File

@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<VersionPrefix>2.0.0</VersionPrefix>
<VersionSuffix>beta4</VersionSuffix>
<PackageReleaseNotes>Update script tags to pull htmx 2.0.0-beta4; add SSE attributes</PackageReleaseNotes>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
<VersionPrefix>2.0.5</VersionPrefix>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReleaseNotes>Add full packaged XML documentation; update script tags to pull htmx 2.0.5 (no header or attribute changes)</PackageReleaseNotes>
<Authors>danieljsummers</Authors>
<Company>Bit Badger Solutions</Company>
<PackageProjectUrl>https://git.bitbadger.solutions/bit-badger/Giraffe.Htmx</PackageProjectUrl>
@@ -13,6 +13,6 @@
<RepositoryType>Git</RepositoryType>
<Copyright>MIT License</Copyright>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>Giraffe htmx beta</PackageTags>
<PackageTags>Giraffe htmx</PackageTags>
</PropertyGroup>
</Project>

View File

@@ -4,6 +4,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>htmx header extensions and helpers for Giraffe</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
@@ -13,7 +14,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Giraffe" Version="6.2.0" />
<PackageReference Include="Giraffe" Version="6.4.0" />
<PackageReference Update="FSharp.Core" Version="6.0.0" />
</ItemGroup>

View File

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

View File

@@ -2,13 +2,13 @@
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.0-beta4**
**htmx version: 2.0.4**
_Note that htmx 2.0 is a BETA release. The [migration guide](https://v2-0v2-0.htmx.org/migration-guide-htmx-1/) does not currently specify any request or response header changes. This means that, as of this release, there are no required code changes in moving to this major version._
_Upgrading from v1.x: the [migration guide](https://htmx.org/migration-guide-htmx-1/) does not currently specify any request or response header changes. This means that there are no required code changes in moving from v1.* to v2.*._
### Setup
1. Install the package (must use `--Prerelease` flag).
1. Install the package.
2. Prior to using the request header extension properties or the header-setting `HttpHandler`s, `open Giraffe.Htmx`.
### Use

View File

@@ -3,4 +3,4 @@ open Expecto
let allTests = testList "Giraffe" [ Common.allTests; Htmx.allTests; ViewEngine.allTests ]
[<EntryPoint>]
let main args = runTestsWithArgs defaultConfig args allTests
let main args = runTestsWithCLIArgs [] args allTests

View File

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

View File

@@ -781,10 +781,6 @@ let attributes =
test "_hxSelectOob succeeds" {
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" {
del [ _hxSwap "innerHTML" ] [] |> shouldRender """<del hx-swap="innerHTML"></del>"""
}
@@ -808,9 +804,6 @@ let attributes =
dt [ _hxVals """{ "extra": "values" }""" ] []
|> shouldRender """<dt hx-vals="{ &quot;extra&quot;: &quot;values&quot; }"></dt>"""
}
test "_hxWs succeeds" {
ul [ _hxWs "connect:/web-socket" ] [] |> shouldRender """<ul hx-ws="connect:/web-socket"></ul>"""
}
test "_sseSwap succeeds" {
ul [ _sseSwap "sseMessageName" ] [] |> shouldRender """<ul sse-swap="sseMessageName"></ul>"""
}
@@ -826,14 +819,14 @@ let script =
let html = RenderView.AsString.htmlNode Script.minified
Expect.equal
html
"""<script src="https://unpkg.com/htmx.org@2.0.0-beta4" integrity="sha384-QprZjU1JKuXu/TnlURCTYppToUjigoOZCrzQtRXAjHttxoV9gkqiizVeAwjeGy1f" crossorigin="anonymous"></script>"""
"""<script src="https://unpkg.com/htmx.org@2.0.4" integrity="sha384-HGfztofotfshcF7+8n44JQL2oJmowVChPTg48S+jvZoztPfvwD79OC/LTtG6dMp+" crossorigin="anonymous"></script>"""
"Minified script tag is incorrect"
}
test "unminified succeeds" {
let html = RenderView.AsString.htmlNode Script.unminified
Expect.equal
html
"""<script src="https://unpkg.com/htmx.org@2.0.0-beta4/dist/htmx.js" integrity="sha384-n/53Us+nZur0snldc6yl7W3paw5/sbtpXhImQJk9JZf0KQjzCP6lbBWmAtFsCSb9" crossorigin="anonymous"></script>"""
"""<script src="https://unpkg.com/htmx.org@2.0.4/dist/htmx.js" integrity="sha384-oeUn82QNXPuVkGCkcrInrS1twIxKhkZiFfr2TdiuObZ3n3yIeMiqcRzkIcguaof1" crossorigin="anonymous"></script>"""
"Unminified script tag is incorrect"
}
]

View File

@@ -4,6 +4,7 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Description>Extensions to Giraffe View Engine to support htmx attributes and their values</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>

View File

@@ -1,110 +1,149 @@
/// <summary>Types and functions supporting htmx attributes in Giraffe View Engine</summary>
module Giraffe.ViewEngine.Htmx
/// Serialize a list of key/value pairs to JSON (very rudimentary)
let private toJson (kvps : (string * string) list) =
kvps
|> List.map (fun kvp -> sprintf "\"%s\": \"%s\"" (fst kvp) ((snd kvp).Replace ("\"", "\\\"")))
|> String.concat ", "
|> sprintf "{ %s }"
/// Valid values for the `hx-encoding` attribute
/// <summary>Valid values for the <tt>hx-encoding</tt> attribute</summary>
[<RequireQualifiedAccess>]
module HxEncoding =
/// A standard HTTP form
/// <summary>A standard HTTP form</summary>
let Form = "application/x-www-form-urlencoded"
/// A multipart form (used for file uploads)
/// <summary>A multipart form (used for file uploads)</summary>
let MultipartForm = "multipart/form-data"
/// The events recognized by htmx
/// <summary>The events recognized by htmx</summary>
[<Struct>]
type HxEvent =
/// Send this event to an element to abort a request
/// <summary>Send this event to an element to abort a request</summary>
| Abort
/// Triggered after an AJAX request has completed processing a successful response
/// <summary>Triggered after an AJAX request has completed processing a successful response</summary>
| AfterOnLoad
/// Triggered after htmx has initialized a node
/// <summary>Triggered after htmx has initialized a node</summary>
| AfterProcessNode
/// Triggered after an AJAX request has completed
/// <summary>Triggered after an AJAX request has completed</summary>
| AfterRequest
/// Triggered after the DOM has settled
/// <summary>Triggered after the DOM has settled</summary>
| AfterSettle
/// Triggered after new content has been swapped in
/// <summary>Triggered after new content has been swapped in</summary>
| AfterSwap
/// Triggered before htmx disables an element or removes it from the DOM
/// <summary>Triggered before htmx disables an element or removes it from the DOM</summary>
| BeforeCleanupElement
/// Triggered before any response processing occurs
/// <summary>Triggered before any response processing occurs</summary>
| BeforeOnLoad
/// Triggered before htmx initializes a node
/// <summary>Triggered before htmx initializes a node</summary>
| BeforeProcessNode
/// Triggered before an AJAX request is made
/// <summary>Triggered before an AJAX request is made</summary>
| BeforeRequest
/// Triggered before a swap is done, allows you to configure the swap
/// <summary>Triggered before a swap is done, allows you to configure the swap</summary>
| BeforeSwap
/// Triggered just before an ajax request is sent
/// <summary>Triggered just before an ajax request is sent</summary>
| BeforeSend
/// Triggered before the request, allows you to customize parameters, headers
/// <summary>Triggered before the request, allows you to customize parameters, headers</summary>
| ConfigRequest
/// <summary>
/// Triggered after a trigger occurs on an element, allows you to cancel (or delay) issuing the AJAX request
/// </summary>
| Confirm
/// Triggered on an error during cache writing
/// <summary>Triggered on an error during cache writing</summary>
| HistoryCacheError
/// Triggered on a cache miss in the history subsystem
/// <summary>Triggered on a cache miss in the history subsystem</summary>
| HistoryCacheMiss
/// Triggered on a unsuccessful remote retrieval
/// <summary>Triggered on a unsuccessful remote retrieval</summary>
| HistoryCacheMissError
/// Triggered on a successful remote retrieval
/// <summary>Triggered on a successful remote retrieval</summary>
| HistoryCacheMissLoad
/// Triggered when htmx handles a history restoration action
/// <summary>Triggered when htmx handles a history restoration action</summary>
| HistoryRestore
/// Triggered before content is saved to the history cache
/// <summary>Triggered before content is saved to the history cache</summary>
| BeforeHistorySave
/// Triggered when new content is added to the DOM
/// <summary>Triggered when new content is added to the DOM</summary>
| Load
/// <summary>
/// Triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined
/// </summary>
| NoSseSourceError
/// Triggered when an exception occurs during the onLoad handling in htmx
/// <summary>Triggered when an exception occurs during the onLoad handling in htmx</summary>
| OnLoadError
/// Triggered after an out of band element as been swapped in
/// <summary>Triggered after an out of band element as been swapped in</summary>
| OobAfterSwap
/// Triggered before an out of band element swap is done, allows you to configure the swap
/// <summary>Triggered before an out of band element swap is done, allows you to configure the swap</summary>
| OobBeforeSwap
/// Triggered when an out of band element does not have a matching ID in the current DOM
/// <summary>Triggered when an out of band element does not have a matching ID in the current DOM</summary>
| OobErrorNoTarget
/// Triggered after a prompt is shown
/// <summary>Triggered after a prompt is shown</summary>
| Prompt
/// Triggered after an url is pushed into history
/// <summary>Triggered after an url is pushed into history</summary>
| PushedIntoHistory
/// Triggered when an HTTP response error (non-200 or 300 response code) occurs
/// <summary>Triggered when an HTTP response error (non-200 or 300 response code) occurs</summary>
| ResponseError
/// Triggered when a network error prevents an HTTP request from happening
/// <summary>Triggered when a network error prevents an HTTP request from happening</summary>
| SendError
/// Triggered when an error occurs with a SSE source
/// <summary>Triggered when an error occurs with a SSE source</summary>
| SseError
/// Triggered when a SSE source is opened
/// <summary>Triggered when a SSE source is opened</summary>
| SseOpen
/// Triggered when an error occurs during the swap phase
/// <summary>Triggered when an error occurs during the swap phase</summary>
| SwapError
/// Triggered when an invalid target is specified
/// <summary>Triggered when an invalid target is specified</summary>
| TargetError
/// Triggered when a request timeout occurs
/// <summary>Triggered when a request timeout occurs</summary>
| Timeout
/// Triggered before an element is validated
/// <summary>Triggered before an element is validated</summary>
| ValidationValidate
/// Triggered when an element fails validation
/// <summary>Triggered when an element fails validation</summary>
| ValidationFailed
/// Triggered when a request is halted due to validation errors
/// <summary>Triggered when a request is halted due to validation errors</summary>
| ValidationHalted
/// Triggered when an ajax request aborts
/// <summary>Triggered when an ajax request aborts</summary>
| XhrAbort
/// Triggered when an ajax request ends
/// <summary>Triggered when an ajax request ends</summary>
| XhrLoadEnd
/// Triggered when an ajax request starts
/// <summary>Triggered when an ajax request starts</summary>
| XhrLoadStart
/// Triggered periodically during an ajax request that supports progress events
/// <summary>Triggered periodically during an ajax request that supports progress events</summary>
| XhrProgress
/// The htmx event name (fst) and kebab-case name (snd, for use with hx-on)
@@ -153,60 +192,77 @@ type HxEvent =
XhrProgress, ("xhr:progress", "xhr:progress")
]
/// The htmx event name
/// <summary>The htmx event name</summary>
override this.ToString() = fst HxEvent.Values[this]
/// The hx-on variant of the htmx event name
/// <summary>The <tt>hx-on</tt> variant of the htmx event name</summary>
member this.ToHxOnString() = snd HxEvent.Values[this]
/// Helper to create the `hx-headers` attribute
/// <summary>Helper to create the <tt>hx-headers</tt> attribute</summary>
[<RequireQualifiedAccess>]
module HxHeaders =
/// Create headers from a list of key/value pairs
let From = toJson
/// <summary>Create headers from a list of key/value pairs</summary>
let From = Giraffe.Htmx.Common.toJson
/// Values / helpers for the `hx-params` attribute
/// <summary>Values / helpers for the <tt>hx-params</tt> attribute</summary>
[<RequireQualifiedAccess>]
module HxParams =
/// Include all parameters
/// <summary>Include all parameters</summary>
let All = "*"
/// Include no parameters
/// <summary>Include no parameters</summary>
let None = "none"
/// Include the specified parameters
let With fields = match fields with [] -> "" | _ -> fields |> List.reduce (fun acc it -> $"{acc},{it}")
/// <summary>Include the specified parameters</summary>
/// <param name="fields">One or more fields to include in the request</param>
/// <returns>The list of fields for the <tt>hx-params</tt> attribute value</returns>
let With fields =
match fields with [] -> "" | _ -> fields |> List.reduce (fun acc it -> $"{acc},{it}")
/// Exclude the specified parameters
let Except fields = With fields |> sprintf "not %s"
/// <summary>Exclude the specified parameters</summary>
/// <param name="fields">One or more fields to exclude from the request</param>
/// <returns>The list of fields for the <tt>hx-params</tt> attribute value prefixed with "not"</returns>
let Except fields =
With fields |> sprintf "not %s"
/// Helpers to define `hx-request` attribute values
/// <summary>Helpers to define <tt>hx-request</tt> attribute values</summary>
[<RequireQualifiedAccess>]
module HxRequest =
/// Convert a boolean to its lowercase string equivalent
let private toLowerBool (it : bool) =
(string it).ToLowerInvariant ()
open Giraffe.Htmx.Common
/// Configure the request with various options
/// <summary>Configure the request with various options</summary>
/// <param name="opts">The options to configure</param>
/// <returns>A string with the configured options</returns>
let Configure (opts: string list) =
opts
|> String.concat ", "
|> sprintf "{ %s }"
/// Set a timeout (in milliseconds)
let Timeout (ms : int) = $"\"timeout\": {ms}"
/// <summary>Set a timeout (in milliseconds)</summary>
/// <param name="ms">The milliseconds for the request timeout</param>
/// <returns>A string with the configured request timeout</returns>
let Timeout (ms: int) =
$"\"timeout\": {ms}"
/// Include or exclude credentials from the request
let Credentials = toLowerBool >> sprintf "\"credentials\": %s"
/// <summary>Include or exclude credentials from the request</summary>
/// <param name="send"><tt>true</tt> if credentials should be sent, <tt>false</tt> if not</param>
/// <returns>A string with the configured credential options</returns>
let Credentials send =
(toLowerBool >> sprintf "\"credentials\": %s") send
/// Exclude or include headers from the request
let NoHeaders = toLowerBool >> sprintf "\"noHeaders\": %s"
/// <summary>Exclude or include headers from the request</summary>
/// <param name="exclude">
/// <tt>true</tt> if no headers should be sent; <tt>false</tt> if headers should be sent
/// </param>
/// <returns>A string with the configured header options</returns>
let NoHeaders exclude =
(toLowerBool >> sprintf "\"noHeaders\": %s") exclude
/// Helpers for the `hx-trigger` attribute
@@ -310,46 +366,69 @@ module HxTrigger =
let QueueNone = Queue "none"
/// Helper to create the `hx-vals` attribute
/// <summary>Helper to create the `hx-vals` attribute</summary>
[<RequireQualifiedAccess>]
module HxVals =
/// Create values from a list of key/value pairs
let From = toJson
/// <summary>Create values from a list of key/value pairs</summary>
let From = Giraffe.Htmx.Common.toJson
/// Attributes and flags for htmx
/// <summary>Attributes and flags for htmx</summary>
[<AutoOpen>]
module HtmxAttrs =
/// Progressively enhances anchors and forms to use AJAX requests (use `_hxNoBoost` to set to false)
/// <summary>Progressively enhances anchors and forms to use AJAX requests</summary>
/// <remarks>Use <tt>_hxNoBoost</tt> to set to false</remarks>
let _hxBoost = attr "hx-boost" "true"
/// Shows a confirm() dialog before issuing a request
let _hxConfirm = attr "hx-confirm"
/// <summary>Shows a <tt>confirm()</tt> dialog before issuing a request</summary>
/// <param name="prompt">The prompt to present to the user when seeking their confirmation</param>
/// <returns>A configured <tt>hx-confirm</tt> attribute</returns>
let _hxConfirm prompt =
attr "hx-confirm" prompt
/// Issues a DELETE to the specified URL
let _hxDelete = attr "hx-delete"
/// <summary>Issues a <tt>DELETE</tt> to the specified URL</summary>
/// <param name="url">The URL to which the <tt>DELETE</tt> request should be sent</param>
/// <returns>A configured <tt>hx-delete</tt> attribute</returns>
let _hxDelete url =
attr "hx-delete" url
/// Disables htmx processing for the given node and any children nodes
/// <summary>Disables htmx processing for the given node and any children nodes</summary>
let _hxDisable = flag "hx-disable"
/// Specifies elements that should be disabled when an htmx request is in flight
let _hxDisabledElt = attr "hx-disabled-elt"
/// <summary>Specifies elements that should be disabled when an htmx request is in flight</summary>
/// <param name="elt">The element to disable when an htmx request is in flight</param>
/// <returns>A configured <tt>hx-disabled-elt</tt> attribute</returns>
let _hxDisabledElt elt =
attr "hx-disabled-elt" elt
/// Disinherit all ("*") or specific htmx attributes
let _hxDisinherit = attr "hx-disinherit"
/// <summary>Disinherit all ("*") or specific htmx attributes</summary>
/// <param name="hxAttrs">The htmx attributes to disinherit (should start with "hx-")</param>
/// <returns>A configured <tt>hx-disinherit</tt> attribute</returns>
let _hxDisinherit hxAttrs =
attr "hx-disinherit" hxAttrs
/// Changes the request encoding type
let _hxEncoding = attr "hx-encoding"
/// <summary>Changes the request encoding type</summary>
/// <param name="enc">The encoding type (use <tt>HxEncoding</tt> constants)</param>
/// <returns>A configured <tt>hx-encoding</tt> attribute</returns>
let _hxEncoding enc =
attr "hx-encoding" enc
/// Extensions to use for this element
let _hxExt = attr "hx-ext"
/// <summary>Extensions to use for this element</summary>
/// <param name="exts">A list of extensions to apply to this element</param>
/// <returns>A configured <tt>hx-ext</tt> attribute</returns>
let _hxExt exts =
attr "hx-ext" exts
/// Issues a GET to the specified URL
let _hxGet = attr "hx-get"
/// <summary>Issues a <tt>GET</tt> to the specified URL</summary>
/// <param name="url">The URL to which the <tt>GET</tt> request should be sent</param>
/// <returns>A configured <tt>hx-get</tt> attribute</returns>
let _hxGet url =
attr "hx-get" url
/// Adds to the headers that will be submitted with the request
/// <summary>Adds to the headers that will be submitted with the request</summary>
[<System.Obsolete "Convert this parameter">]
let _hxHeaders = attr "hx-headers"
/// Set to "false" to prevent pages with sensitive information from being stored in the history cache
@@ -408,9 +487,6 @@ module HtmxAttrs =
/// Selects a subset of an out-of-band server response
let _hxSelectOob = attr "hx-select-oob"
/// Establishes and listens to Server Sent Event (SSE) sources for events
let _hxSse = attr "hx-sse"
/// Controls how the response content is swapped into the DOM (e.g. 'outerHTML' or 'beforeEnd')
let _hxSwap = attr "hx-swap"
@@ -436,9 +512,6 @@ module HtmxAttrs =
/// Adds to the parameters that will be submitted with the request
let _hxVals = attr "hx-vals"
/// Establishes a WebSocket or sends information to one
let _hxWs = attr "hx-ws"
/// The name of the message to swap into the DOM.
let _sseSwap = attr "sse-swap"
@@ -446,19 +519,19 @@ module HtmxAttrs =
let _sseConnect = attr "sse-connect"
/// Script tags to pull htmx into an web page
/// Script tags to pull htmx into a web page
module Script =
/// Script tag to load the minified version from unpkg.com
let minified =
script [ _src "https://unpkg.com/htmx.org@2.0.0-beta4"
_integrity "sha384-QprZjU1JKuXu/TnlURCTYppToUjigoOZCrzQtRXAjHttxoV9gkqiizVeAwjeGy1f"
script [ _src "https://unpkg.com/htmx.org@2.0.4"
_integrity "sha384-HGfztofotfshcF7+8n44JQL2oJmowVChPTg48S+jvZoztPfvwD79OC/LTtG6dMp+"
_crossorigin "anonymous" ] []
/// Script tag to load the unminified version from unpkg.com
let unminified =
script [ _src "https://unpkg.com/htmx.org@2.0.0-beta4/dist/htmx.js"
_integrity "sha384-n/53Us+nZur0snldc6yl7W3paw5/sbtpXhImQJk9JZf0KQjzCP6lbBWmAtFsCSb9"
script [ _src "https://unpkg.com/htmx.org@2.0.4/dist/htmx.js"
_integrity "sha384-oeUn82QNXPuVkGCkcrInrS1twIxKhkZiFfr2TdiuObZ3n3yIeMiqcRzkIcguaof1"
_crossorigin "anonymous" ] []

View File

@@ -2,13 +2,13 @@
This package enables [htmx](https://htmx.org) support within the [Giraffe](https://giraffe.wiki) view engine.
**htmx version: 2.0.0-beta4**
**htmx version: 2.0.4**
_Note that this is a BETA release of htmx 2.0; see [the migration guide](https://v2-0v2-0.htmx.org/migration-guide-htmx-1/) for changes_
_Upgrading from v1.x: see [the migration guide](https://htmx.org/migration-guide-htmx-1/) for changes_
### Setup
1. Install the package (must use `--Prerelease` flag).
1. Install the package.
2. Prior to using the attribute or support modules, `open Giraffe.ViewEngine.Htmx`.
### Use

7
src/pack.sh Executable file
View File

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