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
16 changed files with 258 additions and 392 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,45 +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 <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>] [<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
let InnerHtml = "innerHTML" let InnerHtml = "innerHTML"
/// <summary>Replace the entire target element with the response</summary> /// Replace the entire target element with the response
let OuterHtml = "outerHTML" let OuterHtml = "outerHTML"
/// <summary>Insert the response before the target element</summary> /// Insert the response before the target element
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
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
let BeforeEnd = "beforeend" let BeforeEnd = "beforeend"
/// <summary>Insert the response after the target element</summary> /// Insert the response after the target element
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).
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.4** **htmx version: 1.9.12**

View File

@@ -1,10 +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.5</VersionPrefix> <VersionPrefix>1.9.12</VersionPrefix>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <PackageReleaseNotes>Update script tags to pull htmx 1.9.12</PackageReleaseNotes>
<PackageReleaseNotes>Add full packaged XML documentation; update script tags to pull htmx 2.0.5 (no header or attribute changes)</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,67 +11,62 @@ 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 <tt>hx-boost</tt></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> /// `true` if the request is for history restoration after a miss in the local history cache
/// <tt>true</tt> 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>
member this.HxHistoryRestoreRequest
with get () = hdr this "HX-History-Restore-Request" |> Option.map bool.Parse
/// <summary>The user response to an <tt>hx-prompt</tt></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><tt>true</tt> 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 <tt>id</tt> 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 <tt>id</tt> 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 <tt>name</tt> 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>Pushes a new url into the history stack</summary> (string trueOrFalse).ToLowerInvariant ()
/// <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
/// <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 <tt>HX-Push-Url</tt> header set to <tt>false</tt></returns> let private toJson (evts : (string * string) list) =
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
@@ -83,80 +78,54 @@ module Handlers =
[<Obsolete "Use withHxNoPushUrl; HX-Push was replaced by HX-Push-Url in v1.8.0">] [<Obsolete "Use withHxNoPushUrl; HX-Push was replaced by HX-Push-Url in v1.8.0">]
let withHxNoPush = withHxNoPushUrl let withHxNoPush = withHxNoPushUrl
/// <summary>Can be used to do a client-side redirect to a new location</summary> /// Can be used to do a client-side redirect to a new location
/// <param name="url">The URL to which the client should be redirected</param> let withHxRedirect : string -> HttpHandler =
/// <returns>An HTTP handler with the <tt>HX-Redirect</tt> header set</returns> setHttpHeader "HX-Redirect"
let withHxRedirect (url: string) : HttpHandler =
setHttpHeader "HX-Redirect" url
/// <summary>If set to <tt>true</tt> 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 <tt>HX-Refresh</tt> 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 <tt>HX-Replace-URL</tt> header set</returns> setHttpHeader "HX-Replace-Url"
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 <tt>HX-Replace-URL</tt> header set to <tt>false</tt></returns>
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 <tt>HX-Reselect</tt> header set</returns> setHttpHeader "HX-Reselect"
let withHxReselect (target: string) : HttpHandler =
setHttpHeader "HX-Reselect" target
/// <summary>Override the <tt>hx-swap</tt> 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 <tt>HX-Reswap</tt> 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 <tt>hx-target</tt> 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 <tt>HX-Retarget</tt> 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 <tt>HX-Trigger</tt> header set</returns> setHttpHeader "HX-Trigger"
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 <tt>HX-Trigger</tt> header set for all given events</returns>
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 <tt>HX-Trigger-After-Settle</tt> header set</returns> setHttpHeader "HX-Trigger-After-Settle"
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 <tt>HX-Trigger-After-Settle</tt> header set for all given events</returns>
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 <tt>HX-Trigger-After-Swap</tt> header set</returns> setHttpHeader "HX-Trigger-After-Swap"
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 <tt>HX-Trigger-After-Swap</tt> header set for all given events</returns>
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.4** **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

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

@@ -781,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>"""
} }
@@ -804,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>"""
} }
] ]
@@ -819,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://unpkg.com/htmx.org@2.0.4" integrity="sha384-HGfztofotfshcF7+8n44JQL2oJmowVChPTg48S+jvZoztPfvwD79OC/LTtG6dMp+" 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://unpkg.com/htmx.org@2.0.4/dist/htmx.js" integrity="sha384-oeUn82QNXPuVkGCkcrInrS1twIxKhkZiFfr2TdiuObZ3n3yIeMiqcRzkIcguaof1" 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"
} }
] ]
@@ -978,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" [
@@ -991,4 +1004,5 @@ let allTests =
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>

View File

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

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.4** **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..." ]
``` ```
@@ -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 .