Files
Giraffe.Htmx/src/ViewEngine.Htmx/Htmx.fs
2026-01-07 11:37:26 +00:00

1095 lines
52 KiB
Forth

/// <summary>Types and functions supporting htmx attributes in Giraffe View Engine</summary>
module Giraffe.ViewEngine.Htmx
/// <summary>Helpers to define <c>hx-config</c> attribute values</summary>
/// <seealso href="https://four.htmx.org/attributes/hx-config/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxConfig =
open Giraffe.Htmx.Common
/// <summary>Configure the request with various options</summary>
/// <param name="opts">The options to configure</param>
/// <returns>A string with the configured options</returns>
let Configure (opts: string list) =
opts
|> String.concat ", "
|> sprintf "{ %s }"
/// <summary>Set a timeout (in milliseconds)</summary>
/// <param name="ms">The milliseconds for the request timeout</param>
/// <returns>A string with the configured request timeout</returns>
let Timeout (ms: int) =
$"\"timeout\": {ms}"
/// <summary>Include or exclude credentials from the request</summary>
/// <param name="send"><c>true</c> if credentials should be sent, <c>false</c> if not</param>
/// <returns>A string with the configured credential options</returns>
let Credentials send =
(toLowerBool >> sprintf "\"credentials\": %s") send
/// <summary>Exclude or include headers from the request</summary>
/// <param name="exclude">
/// <c>true</c> if no headers should be sent; <c>false</c> if headers should be sent
/// </param>
/// <returns>A string with the configured header options</returns>
let NoHeaders exclude =
(toLowerBool >> sprintf "\"noHeaders\": %s") exclude
/// <summary>Valid values for the <c>hx-encoding</c> attribute</summary>
[<RequireQualifiedAccess>]
module HxEncoding =
/// <summary>A standard HTTP form</summary>
[<Literal>]
let Form = "application/x-www-form-urlencoded"
/// <summary>A multipart form (used for file uploads)</summary>
[<Literal>]
let MultipartForm = "multipart/form-data"
#nowarn 44 // Obsolete elements still have entries in the conversion map; will be removed for v4 final
/// <summary>The events recognized by htmx</summary>
/// <seealso href="https://four.htmx.org/events/">Documentation</seealso>
[<Struct>]
type HxEvent =
/// <summary>Send this event to an element to abort a request</summary>
| Abort
/// <summary>Triggered after htmx disables an element or removes it from the DOM</summary>
| AfterCleanup
/// <summary>Triggered after content is saved to the history cache</summary>
| AfterHistoryUpdate
/// <summary>Triggered after a request has initialized</summary>
| AfterInit
/// <summary>Triggered after an AJAX request has completed processing a successful response</summary>
| [<System.Obsolete "Removed in v4; use AfterInit">] AfterOnLoad
/// <summary>Triggered after htmx has initialized a node</summary>
| [<System.Obsolete "Removed in v4; use AfterInit">] AfterProcessNode
/// <summary>Triggered after new content is saved to the history cache</summary>
| AfterPushIntoHistory
/// <summary>Triggered after updated content is saved to the history cache</summary>
| AfterReplaceIntoHistory
/// <summary>Triggered after an HTTP request has completed successfully</summary>
| AfterRequest
/// <summary>Triggered after the DOM has settled</summary>
| [<System.Obsolete "Removed in v4; use AfterSwap">] AfterSettle
/// <summary>Triggered after a Server Sent Events (SSE) message is read</summary>
| AfterSseMessage
/// <summary>Triggered after a Server Sent Events (SSE) stream is closed</summary>
| AfterSseStream
/// <summary>Triggered after new content has been swapped in</summary>
| AfterSwap
/// <summary>Triggered after a CSS view transition completes</summary>
| AfterViewTransition
/// <summary>Triggered before htmx disables an element or removes it from the DOM</summary>
| BeforeCleanup
/// <summary>Triggered before htmx disables an element or removes it from the DOM</summary>
| [<System.Obsolete "Removed in v4; use BeforeCleanup">] BeforeCleanupElement
/// <summary>Triggered before content is saved to the history cache</summary>
| [<System.Obsolete "Removed in v4; use BeforeHistoryUpdate">] BeforeHistorySave
/// <summary>Triggered before content is saved to the history cache</summary>
| BeforeHistoryUpdate
/// <summary>Triggered before htmx initializes a node</summary>
| BeforeInit
/// <summary>Triggered before any response processing occurs</summary>
| [<System.Obsolete "Removed in v4; use BeforeInit">] BeforeOnLoad
/// <summary>Triggered before htmx initializes a node</summary>
| [<System.Obsolete "Removed in v4; use BeforeInit">] BeforeProcessNode
/// <summary>Triggered before an HTTP request is made</summary>
| BeforeRequest
/// <summary>Triggered before a history restore request is made</summary>
| BeforeRestoreHistory
/// <summary>Triggered just before an ajax request is sent</summary>
| [<System.Obsolete "Removed in v4; use BeforeRequest">] BeforeSend
/// <summary>Triggered before a Server Sent Events (SSE) message is read</summary>
| BeforeSseMessage
/// <summary>Triggered before a Server Sent Events (SSE) connection is reconnected</summary>
| BeforeSseReconnect
/// <summary>Triggered before a Server Sent Events (SSE) stream is opened</summary>
| BeforeSseStream
/// <summary>Triggered before a swap is done, allows you to configure the swap</summary>
| BeforeSwap
/// <summary>Triggered before a CSS view transition starts</summary>
| BeforeViewTransition
/// <summary>Triggered before the request, allows you to customize parameters, headers</summary>
| ConfigRequest
/// <summary>
/// Triggered after a trigger occurs on an element, allows you to cancel (or delay) issuing the AJAX request
/// </summary>
| Confirm
/// <summary>Triggered when an error occurs</summary>
| Error
/// <summary>Triggered after an HTTP request is made, whether it was successful or not</summary>
| FinallyRequest
/// <summary>Triggered on an error during cache writing</summary>
| [<System.Obsolete "Removed in v4; history no longer uses localStorage">] HistoryCacheError
/// <summary>Triggered on a cache miss in the history subsystem</summary>
| [<System.Obsolete "Removed in v4; use BeforeRestoreHistory">] HistoryCacheMiss
/// <summary>Triggered on a unsuccessful remote retrieval</summary>
| [<System.Obsolete "Removed in v4; history no longer uses localStorage">] HistoryCacheMissError
/// <summary>Triggered on a successful remote retrieval</summary>
| [<System.Obsolete "Removed in v4; use BeforeRestoreHistory">] HistoryCacheMissLoad
/// <summary>Triggered when htmx handles a history restoration action</summary>
| [<System.Obsolete "Removed in v4; use BeforeRestoreHistory">] HistoryRestore
/// <summary>Triggered when new content is added to the DOM</summary>
| [<System.Obsolete "Removed in v4; use AfterInit">] Load
/// <summary>
/// Triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined
/// </summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] NoSseSourceError
/// <summary>Triggered when an exception occurs during the onLoad handling in htmx</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] OnLoadError
/// <summary>Triggered after an out of band element as been swapped in</summary>
| [<System.Obsolete "Removed in v4; use AfterSwap (no separate OOB event)">] OobAfterSwap
/// <summary>Triggered before an out of band element swap is done, allows you to configure the swap</summary>
| [<System.Obsolete "Removed in v4; use BeforeSwap (no separate OOB event)">] OobBeforeSwap
/// <summary>Triggered when an out of band element does not have a matching ID in the current DOM</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] OobErrorNoTarget
/// <summary>Triggered after a prompt is shown</summary>
| [<System.Obsolete "Removed in v4; use Confirm with custom JavaScript">] Prompt
/// <summary>Triggered after an url is pushed into history</summary>
| [<System.Obsolete "Removed in v4; use AfterPushIntoHistory (or AfterHistoryUpdate to catch new and updated content)">] PushedIntoHistory
/// <summary>Triggered when an HTTP response error (non-200 or 300 response code) occurs</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] ResponseError
/// <summary>Triggered when a network error prevents an HTTP request from happening</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] SendError
/// <summary>Triggered when an error occurs with a SSE source</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] SseError
/// <summary>Triggered when an SSE source is opened</summary>
| [<System.Obsolete "Removed in v4; use fetch event listener">] SseOpen
/// <summary>Triggered when an error occurs during the swap phase</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] SwapError
/// <summary>Triggered when an invalid target is specified</summary>
| [<System.Obsolete "Removed in v4; use Error (all errors consolidated)">] TargetError
/// <summary>Triggered when a request timeout occurs</summary>
| [<System.Obsolete "Removed in v4; use Error (timeout is exposed as an error)">] Timeout
/// <summary>Triggered before an element is validated</summary>
| [<System.Obsolete "Removed in v4; use native validation API">] ValidationValidate
/// <summary>Triggered when an element fails validation</summary>
| [<System.Obsolete "Removed in v4; use native validation API">] ValidationFailed
/// <summary>Triggered when a request is halted due to validation errors</summary>
| [<System.Obsolete "Removed in v4; use native validation API">] ValidationHalted
/// <summary>Triggered when an ajax request aborts</summary>
| [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrAbort
/// <summary>Triggered when an ajax request ends</summary>
| [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrLoadEnd
/// <summary>Triggered when an ajax request starts</summary>
| [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrLoadStart
/// <summary>Triggered periodically during an ajax request that supports progress events</summary>
| [<System.Obsolete "Removed in v4; use fetch event listeners">] XhrProgress
/// The htmx event name (fst) and kebab-case name (snd, for use with hx-on)
static member private Values = Map [
Abort, ("abort", "abort")
AfterCleanup, ("afterCleanup", "after:cleanup")
AfterHistoryUpdate, ("afterHistoryUpdate", "after:history:update")
AfterInit, ("afterInit", "after:init")
AfterOnLoad, ("afterOnLoad", "after:init")
AfterProcessNode, ("afterProcessNode", "after:init")
AfterPushIntoHistory, ("afterPushIntoHistory", "after:push:into:history")
AfterReplaceIntoHistory, ("afterReplaceIntoHistory", "after:replace:into:history")
AfterRequest, ("afterRequest", "after:request")
AfterSettle, ("afterSettle", "after:swap")
AfterSseMessage, ("afterSseMessage", "after:sse:message")
AfterSseStream, ("afterSseStream", "after:sse:stream")
AfterSwap, ("afterSwap", "after:swap")
AfterViewTransition, ("afterViewTransition", "after:viewTransition")
BeforeCleanup, ("beforeCleanup", "before:cleanup")
BeforeCleanupElement, ("beforeCleanupElement", "before:cleanup")
BeforeHistorySave, ("beforeHistorySave", "before:history:update")
BeforeHistoryUpdate, ("beforeHistoryUpdate", "before:history:update")
BeforeInit, ("beforeInit", "before:init")
BeforeOnLoad, ("beforeOnLoad", "before:init")
BeforeProcessNode, ("beforeProcessNode", "before:init")
BeforeRestoreHistory, ("beforeRestoreHistory", "before:restore:history")
BeforeRequest, ("beforeRequest", "before:request")
BeforeSend, ("beforeSend", "before:request")
BeforeSseMessage, ("beforeSseMessage", "before:sse:message")
BeforeSseReconnect, ("beforeSseReconnect", "before:sse:reconnect")
BeforeSseStream, ("beforeSseStream", "before:sse:stream")
BeforeSwap, ("beforeSwap", "before:swap")
BeforeViewTransition, ("beforeTransition", "before:viewTransition")
ConfigRequest, ("configRequest", "config:request")
Confirm, ("confirm", "confirm")
Error, ("error", "error")
FinallyRequest, ("finallyRequest", "finally:request")
HistoryCacheError, ("historyCacheError", "history-cache-error")
HistoryCacheMiss, ("historyCacheMiss", "before:history:restore")
HistoryCacheMissError, ("historyCacheMissError", "history-cache-miss-error")
HistoryCacheMissLoad, ("historyCacheMissLoad", "before:history:restore")
HistoryRestore, ("historyRestore", "before:history:restore")
Load, ("load", "after:init")
NoSseSourceError, ("noSSESourceError", "error")
OnLoadError, ("onLoadError", "error")
OobAfterSwap, ("oobAfterSwap", "after:swap")
OobBeforeSwap, ("oobBeforeSwap", "before:swap")
OobErrorNoTarget, ("oobErrorNoTarget", "error")
Prompt, ("prompt", "prompt")
PushedIntoHistory, ("pushedIntoHistory", "after:push:into:history")
ResponseError, ("responseError", "error")
SendError, ("sendError", "error")
SseError, ("sseError", "error")
SseOpen, ("sseOpen", "sse-open")
SwapError, ("swapError", "error")
TargetError, ("targetError", "error")
Timeout, ("timeout", "error")
ValidationValidate, ("validation:validate", "validation:validate")
ValidationFailed, ("validation:failed", "validation:failed")
ValidationHalted, ("validation:halted", "validation:halted")
XhrAbort, ("xhr:abort", "xhr:abort")
XhrLoadEnd, ("xhr:loadend", "xhr:loadend")
XhrLoadStart, ("xhr:loadstart", "xhr:loadstart")
XhrProgress, ("xhr:progress", "xhr:progress")
]
/// <summary>The htmx event name</summary>
override this.ToString() = fst HxEvent.Values[this]
/// <summary>The <c>hx-on</c> variant of the htmx event name</summary>
member this.ToHxOnString() = snd HxEvent.Values[this]
#warn 44 // restore obsolete warning
/// <summary>Helper to create the <c>hx-headers</c> attribute</summary>
[<RequireQualifiedAccess>]
module HxHeaders =
/// <summary>Create headers from a list of key/value pairs</summary>
let From = Giraffe.Htmx.Common.toJson
/// <summary>Values / helpers for the <c>hx-params</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso>
[<RequireQualifiedAccess>]
[<System.Obsolete "Removed in v4; filter parameters via JavaScript in configRequest event">]
module HxParams =
/// <summary>Include all parameters</summary>
[<Literal>]
let All = "*"
/// <summary>Include no parameters</summary>
[<Literal>]
let None = "none"
/// <summary>Include the specified parameters</summary>
/// <param name="fields">One or more fields to include in the request</param>
/// <returns>The list of fields for the <c>hx-params</c> attribute value</returns>
let With fields =
match fields with [] -> "" | _ -> fields |> List.reduce (fun acc it -> $"{acc},{it}")
/// <summary>Exclude the specified parameters</summary>
/// <param name="fields">One or more fields to exclude from the request</param>
/// <returns>The list of fields for the <c>hx-params</c> attribute value prefixed with "not"</returns>
let Except fields =
With fields |> sprintf "not %s"
/// <summary>Helpers to define <c>hx-request</c> attribute values</summary>
/// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso>
[<RequireQualifiedAccess>]
[<System.Obsolete "Removed in v4; change to HxConfig">]
module HxRequest =
open Giraffe.Htmx.Common
/// <summary>Configure the request with various options</summary>
/// <param name="opts">The options to configure</param>
/// <returns>A string with the configured options</returns>
let Configure (opts: string list) =
opts
|> String.concat ", "
|> sprintf "{ %s }"
/// <summary>Set a timeout (in milliseconds)</summary>
/// <param name="ms">The milliseconds for the request timeout</param>
/// <returns>A string with the configured request timeout</returns>
let Timeout (ms: int) =
$"\"timeout\": {ms}"
/// <summary>Include or exclude credentials from the request</summary>
/// <param name="send"><c>true</c> if credentials should be sent, <c>false</c> if not</param>
/// <returns>A string with the configured credential options</returns>
let Credentials send =
(toLowerBool >> sprintf "\"credentials\": %s") send
/// <summary>Exclude or include headers from the request</summary>
/// <param name="exclude">
/// <c>true</c> if no headers should be sent; <c>false</c> if headers should be sent
/// </param>
/// <returns>A string with the configured header options</returns>
let NoHeaders exclude =
(toLowerBool >> sprintf "\"noHeaders\": %s") exclude
/// <summary>Helpers for the <c>hx-sync</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-sync/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxSync =
/// <summary>Drop (ignore) this request if a request is already in flight</summary>
/// <remarks>This is the default for <c>hx-sync</c></remarks>
[<Literal>]
let Drop = "drop"
/// <summary>
/// Drop (ignore) this request if a request is already in flight, and if another request occurs while this one is in
/// flight, abort this request
/// </summary>
[<Literal>]
let Abort = "abort"
/// <summary>Abort any current in-flight request and replace it with this one</summary>
[<Literal>]
let Replace = "replace"
/// <summary>Place this request in an element-associated queue</summary>
[<Literal>]
let Queue = "queue"
/// <summary>Queue only the first request received while another request is in flight</summary>
[<Literal>]
let QueueFirst = "queue first"
/// <summary>Queue only the last request received while another request is in flight</summary>
[<Literal>]
let QueueLast = "queue last"
/// <summary>Queue all requests received while another request is in flight</summary>
[<Literal>]
let QueueAll = "queue all"
/// <summary>Helpers for the <c>hx-trigger</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-trigger/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxTrigger =
/// Append a filter to a trigger
let private appendFilter filter (trigger : string) =
match trigger.Contains "[" with
| true ->
let parts = trigger.Split ('[', ']')
$"{parts[0]}[{parts[1]}&&{filter}]"
| false -> $"{trigger}[{filter}]"
/// <summary>Trigger the event on a click</summary>
[<Literal>]
let Click = "click"
/// <summary>Trigger the event on page load</summary>
[<Literal>]
let Load = "load"
/// <summary>Trigger the event when the item is visible</summary>
[<Literal>]
let Revealed = "revealed"
/// <summary>Trigger this event every [timing declaration]</summary>
/// <param name="duration">The duration on which this trigger should fire (e.g., "1s", "500ms")</param>
/// <returns>A trigger timing specification</returns>
let Every duration =
$"every %s{duration}"
/// <summary>Helpers for defining filters</summary>
module Filter =
/// <summary>Only trigger the event if the <c>ALT</c> key is pressed</summary>
let Alt = appendFilter "altKey"
/// <summary>Only trigger the event if the <c>CTRL</c> key is pressed</summary>
let Ctrl = appendFilter "ctrlKey"
/// <summary>Only trigger the event if the <c>SHIFT</c> key is pressed</summary>
let Shift = appendFilter "shiftKey"
/// <summary>Only trigger the event if <c>CTRL</c> and <c>ALT</c> are pressed</summary>
let CtrlAlt = Ctrl >> Alt
/// <summary>Only trigger the event if <c>CTRL</c> and <c>SHIFT</c> are pressed</summary>
let CtrlShift = Ctrl >> Shift
/// <summary>Only trigger the event if <c>CTRL</c>, <c>ALT</c>, and <c>SHIFT</c> are pressed</summary>
let CtrlAltShift = CtrlAlt >> Shift
/// <summary>Only trigger the event if <c>ALT</c> and <c>SHIFT</c> are pressed</summary>
let AltShift = Alt >> Shift
/// Append a modifier to the current trigger
let private appendModifier modifier current =
if current = "" then modifier else $"{current} {modifier}"
/// <summary>Only trigger once</summary>
/// <param name="action">The action which should only be fired once</param>
/// <returns>A trigger spec to fire the given action once</returns>
let Once action =
appendModifier "once" action
/// <summary>Trigger when changed</summary>
/// <param name="elt">The element from which the <c>onchange</c> event will be emitted</param>
/// <returns>A trigger spec to fire when the given element changes</returns>
let Changed elt =
appendModifier "changed" elt
/// <summary>Delay execution; resets every time the event is seen</summary>
/// <param name="duration">The duration for the delay (e.g., "1s", "500ms")</param>
/// <param name="action">The action which should be fired after the given delay</param>
/// <returns>A trigger spec to fire the given action after the specified delay</returns>
let Delay duration action =
appendModifier $"delay:%s{duration}" action
/// <summary>Throttle execution; ignore other events, fire when duration passes</summary>
/// <param name="duration">The duration for the throttling (e.g., "1s", "500ms")</param>
/// <param name="action">The action which should be fired after the given duration</param>
/// <returns>A trigger spec to fire the given action after the specified duration</returns>
let Throttle duration action =
appendModifier $"throttle:%s{duration}" action
/// <summary>Trigger this event from a CSS selector</summary>
/// <param name="selector">A CSS selector to identify elements which may fire this trigger</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the given element(s)</returns>
let From selector action =
appendModifier $"from:%s{selector}" action
/// <summary>Trigger this event from the <c>document</c> object</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the <c>document</c> element</returns>
let FromDocument action =
From "document" action
/// <summary>Trigger this event from the <c>window</c> object</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the <c>window</c> object</returns>
let FromWindow action =
From "window" action
/// <summary>Trigger this event from the closest parent CSS selector</summary>
/// <param name="selector">The CSS selector from which the action should be fired</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the closest element</returns>
let FromClosest selector action =
From $"closest %s{selector}" action
/// <summary>Trigger this event from the closest child CSS selector</summary>
/// <param name="selector">The child CSS selector from which the action should be fired</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire from the closest child element</returns>
let FromFind selector action =
From $"find %s{selector}" action
/// <summary>Target the given CSS selector with the results of this event</summary>
/// <param name="selector">The CSS selector to which the result of the action will be applied</param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to target the given selector</returns>
let Target selector action =
appendModifier $"target:%s{selector}" action
/// <summary>Prevent any further events from occurring after this one fires</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to fire the given action and prevent further events</returns>
let Consume action =
appendModifier "consume" action
/// <summary>
/// Configure queueing when events fire when others are in flight; if unspecified, the default is <c>last</c>
/// </summary>
/// <param name="how">
/// How the request should be queued (consider <see cref="QueueFirst" />, <see cref="QueueLast" />,
/// <see cref="QueueAll" />, and <see cref="QueueNone" />)
/// </param>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let Queue how action =
let qSpec = if how = "" then "" else $":{how}"
appendModifier $"queue{qSpec}" action
/// <summary>Queue the first event, discard all others (i.e., a FIFO queue of 1)</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueFirst action =
Queue "first" action
/// <summary>Queue the last event; discards current when another is received (i.e., a LIFO queue of 1)</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueLast action =
Queue "last" action
/// <summary>Queue all events; discard none</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueAll action =
Queue "all" action
/// <summary>Queue no events; discard all</summary>
/// <param name="action">The action to be fired</param>
/// <returns>A trigger spec to queue the given action</returns>
let QueueNone action =
Queue "none" action
/// <summary>Helper to create the <c>hx-vals</c> attribute</summary>
/// <seealso href="https://htmx.org/attributes/hx-vals/">Documentation</seealso>
[<RequireQualifiedAccess>]
module HxVals =
/// <summary>Create values from a list of key/value pairs</summary>
let From = Giraffe.Htmx.Common.toJson
open System.Net.Http
open Giraffe.Htmx
/// <summary>Attributes and flags for htmx</summary>
[<AutoOpen>]
module HtmxAttrs =
/// <summary>The URL which will receive the request (use with <c>_hxMethod</c>)</summary>
/// <param name="url">The URL for the attribute</param>
/// <seealso href="https://four.htmx.org/attributes/hx-action/">Documentation</seealso>
let _hxAction url = attr "hx-action" url
/// <summary>Progressively enhances anchors and forms to use AJAX requests</summary>
/// <remarks>Use <c>_hxNoBoost</c> to set to false</remarks>
/// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso>
let _hxBoost = attr "hx-boost" "true"
/// <summary>Configure request behavior</summary>
/// <param name="config">The configuration parameters to use for the request</param>
/// <returns>A configured <c>hx-config</c> attribute</returns>
/// <seealso cref="https://four.htmx.org/attributes/hx-config/">Documentation</seealso>
let _hxConfig config =
attr "hx-config" (toJson config)
/// <summary>Shows a <c>confirm()</c> dialog before issuing a request</summary>
/// <param name="prompt">The prompt to present to the user when seeking their confirmation</param>
/// <returns>A configured <c>hx-confirm</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-confirm/">Documentation</seealso>
let _hxConfirm prompt =
attr "hx-confirm" prompt
/// <summary>Issues a <c>DELETE</c> to the specified URL</summary>
/// <param name="url">The URL to which the <c>DELETE</c> request should be sent</param>
/// <returns>A configured <c>hx-delete</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-delete/">Documentation</seealso>
let _hxDelete url =
attr "hx-delete" url
/// <summary>Specifies elements that should be disabled when an htmx request is in flight</summary>
/// <param name="elt">The element to disable when an htmx request is in flight</param>
/// <returns>A configured <c>hx-disable</c> attribute</returns>
/// <remarks>This behavior changed in v4
/// <ul><li>For the v2 behavior of <c>hx-disable</c> (which will manifest as compile errors), change instances to
/// <c>_hxIgnore</c></li>
/// <li>For v4 behavior, changing <c>_hxDisabledElt</c> to <c>_hxDisable</c> should be sufficient</li></ul>
/// </remarks>
/// <seealso href="https://four.htmx.org/attributes/hx-disable/">Documentation</seealso>
let _hxDisable elt =
attr "hx-disable" 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 <c>hx-disabled-elt</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-disabled-elt/">Documentation</seealso>
[<System.Obsolete "hx-disabled-elt has become hx-disable in v4">]
let _hxDisabledElt elt =
attr "hx-disabled-elt" elt
/// <summary>Disinherit all ("*") or specific htmx attributes</summary>
/// <param name="hxAttrs">The htmx attributes to disinherit (should start with "hx-")</param>
/// <returns>A configured <c>hx-disinherit</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-disinherit/">Documentation</seealso>
[<System.Obsolete "hx-disinherit removed in v4; use explicit inheritance">]
let _hxDisinherit hxAttrs =
attr "hx-disinherit" hxAttrs
/// <summary>Changes the request encoding type</summary>
/// <param name="enc">The encoding type (use <c>HxEncoding</c> constants)</param>
/// <returns>A configured <c>hx-encoding</c> attribute</returns>
/// <seealso cref="HxEncoding" />
/// <seealso href="https://htmx.org/attributes/hx-encoding/">Documentation</seealso>
let _hxEncoding enc =
attr "hx-encoding" enc
/// <summary>Extensions to use for this element</summary>
/// <param name="exts">A list of extensions to apply to this element</param>
/// <returns>A configured <c>hx-ext</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-ext/">Documentation</seealso>
[<System.Obsolete "hx-ext removed in v4; extensions register via JavaScript">]
let _hxExt exts =
attr "hx-ext" exts
/// <summary>Issues a <c>GET</c> to the specified URL</summary>
/// <param name="url">The URL to which the <c>GET</c> request should be sent</param>
/// <returns>A configured <c>hx-get</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-get/">Documentation</seealso>
let _hxGet url =
attr "hx-get" url
/// <summary>Adds to the headers that will be submitted with the request</summary>
/// <param name="hdrs">The headers to include with the request</param>
/// <returns>A configured <c>hx-headers</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-headers/">Documentation</seealso>
let _hxHeaders hdrs =
attr "hx-headers" hdrs
/// <summary>
/// Set to "false" to prevent pages with sensitive information from being stored in the history cache
/// </summary>
/// <param name="shouldStore">Whether the page should be stored in the history cache</param>
/// <returns>A configured <c>hx-history</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-history/">Documentation</seealso>
[<System.Obsolete "hx-history removed in v4; history does not use localStorage">]
let _hxHistory shouldStore =
attr "hx-history" (toLowerBool shouldStore)
/// <summary>The element to snapshot and restore during history navigation</summary>
/// <seealso href="https://htmx.org/attributes/hx-history-elt/">Documentation</seealso>
[<System.Obsolete "hx-history-elt removed in v4; history based on target element">]
let _hxHistoryElt =
flag "hx-history-elt"
/// <summary>Disables htmx processing for the given node and any children nodes</summary>
/// <seealso href="https://four.htmx.org/attributes/hx-ignore/">Documentation</seealso>
let _hxIgnore =
flag "hx-ignore"
/// <summary>Includes additional data in AJAX requests</summary>
/// <param name="spec">The specification of what should be included in the request</param>
/// <returns>A configured <c>hx-include</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-include/">Documentation</seealso>
let _hxInclude spec =
attr "hx-include" spec
/// <summary>The element to put the <c>htmx-request</c> class on during the AJAX request</summary>
/// <param name="selector">The selector for the indicator element</param>
/// <returns>A configured <c>hx-indicator</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-indicator/">Documentation</seealso>
let _hxIndicator selector =
attr "hx-indicator" selector
/// <summary>The HTTP method to use for the request(use with <c>_hxAction</c>)</summary>
/// <param name="method">The method to use</param>
/// <seealso href="https://four.htmx.org/attributes/hx-method/">Documentation</seealso>
let _hxMethod (method: HttpMethod) =
attr "hx-method" (method.Method.ToLowerInvariant())
/// <summary>Overrides a previous <c>hx-boost</c> (hx-boost="false")</summary>
/// <seealso href="https://htmx.org/attributes/hx-boost/">Documentation</seealso>
let _hxNoBoost =
attr "hx-boost" "false"
/// <summary>Attach an event handler for DOM events</summary>
/// <param name="evtName">The name of the event</param>
/// <param name="handler">The script to be executed when the event occurs</param>
/// <returns>A configured <c>hx-on</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-on/">Documentation</seealso>
let _hxOnEvent evtName handler =
attr $"hx-on:%s{evtName}" handler
/// <summary>Attach an event handler for htmx events</summary>
/// <param name="hxEvent">The <c>HxEvent</c> to be handled</param>
/// <param name="handler">The script to be executed when the event occurs</param>
/// <returns>A configured <c>hx-on::</c> attribute</returns>
/// <seealso cref="HxEvent" />
/// <seealso href="https://htmx.org/attributes/hx-on/">Documentation</seealso>
let _hxOnHxEvent (hxEvent: HxEvent) handler =
_hxOnEvent $":{hxEvent.ToHxOnString()}" handler
/// <summary>Filters the parameters that will be submitted with a request</summary>
/// <param name="toInclude">The fields to include (use <c>HxParams</c> to generate this value)</param>
/// <returns>A configured <c>hx-params</c> attribute</returns>
/// <seealso cref="HxParams" />
/// <seealso href="https://htmx.org/attributes/hx-params/">Documentation</seealso>
[<System.Obsolete "hx-params removed in v4; use htmx:config:request to filter parameter">]
let _hxParams toInclude =
attr "hx-params" toInclude
/// <summary>Issues a <c>PATCH</c> to the specified URL</summary>
/// <param name="url">The URL to which the request should be directed</param>
/// <returns>A configured <c>hx-patch</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-patch/">Documentation</seealso>
let _hxPatch url =
attr "hx-patch" url
/// <summary>Issues a <c>POST</c> to the specified URL</summary>
/// <param name="url">The URL to which the request should be directed</param>
/// <returns>A configured <c>hx-post</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-post/">Documentation</seealso>
let _hxPost url =
attr "hx-post" url
/// <summary>Preserves an element between requests</summary>
/// <seealso href="https://htmx.org/attributes/hx-preserve/">Documentation</seealso>
let _hxPreserve =
flag "hx-preserve"
/// <summary>Shows a <c>prompt()</c> dialog before submitting a request</summary>
/// <param name="text">The text for the prompt</param>
/// <returns>A configured <c>hx-prompt</c> attribute</returns>
/// <remarks>The value provided will be in the <c>HX-Prompt</c> request header</remarks>
/// <seealso href="https://htmx.org/attributes/hx-prompt/">Documentation</seealso>
[<System.Obsolete "hx-prompt removed in v4; use hx-confirm with async JavaScript function">]
let _hxPrompt text =
attr "hx-prompt" text
/// <summary>Pushes the URL into the location bar, creating a new history entry</summary>
/// <param name="spec">
/// <ul>
/// <li>"true" to push the fetched URL</li>
/// <li>"false" to explicitly not push the fetched URL</li>
/// <li>A specific URL to push</li>
/// </ul>
/// </param>
/// <returns>A configured <c>hx-push-url</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-push-url/">Documentation</seealso>
let _hxPushUrl spec =
attr "hx-push-url" spec
/// <summary>Issues a <c>PUT</c> to the specified URL</summary>
/// <param name="url">The URL to which the request should be directed</param>
/// <returns>A configured <c>hx-put</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-put/">Documentation</seealso>
let _hxPut url =
attr "hx-put" url
/// <summary>Replaces the current URL in the browser's history stack</summary>
/// <param name="spec">
/// <ul>
/// <li>"true" to replace the current URL with the fetched one</li>
/// <li>"false" to explicitly replace nothing</li>
/// <li>A specific URL to replace in the browser's history</li>
/// </ul>
/// </param>
/// <returns>A configured <c>hx-replace-url</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-replace-url/">Documentation</seealso>
let _hxReplaceUrl spec =
attr "hx-replace-url" spec
/// <summary>Configures various aspects of the request</summary>
/// <param name="spec">The configuration spec (use <c>HxRequest.Configure</c> to create value)</param>
/// <returns>A configured <c>hx-request</c> attribute</returns>
/// <seealso cref="HxRequest.Configure" />
/// <seealso href="https://htmx.org/attributes/hx-request/">Documentation</seealso>
[<System.Obsolete "hx-request removed in v4; use hx-config instead">]
let _hxRequest spec =
attr "hx-request" spec
/// <summary>Selects a subset of the server response to process</summary>
/// <param name="selector">A CSS selector for the content to be selected</param>
/// <returns>A configured <c>hx-select</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-select/">Documentation</seealso>
let _hxSelect selector =
attr "hx-select" selector
/// <summary>Selects a subset of an out-of-band server response</summary>
/// <param name="selectors">One or more comma-delimited CSS selectors for the content to be selected</param>
/// <returns>A configured <c>hx-select-oob</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-select-oob/">Documentation</seealso>
let _hxSelectOob selectors =
attr "hx-select-oob" selectors
/// <summary>
/// Controls how the response content is swapped into the DOM (e.g. <c>outerHTML</c> or <c>beforeEnd</c>)
/// </summary>
/// <param name="swap">The type of swap to perform (use <c>HxSwap</c> values)</param>
/// <returns>A configured <c>hx-swap</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-swap/">Documentation</seealso>
let _hxSwap swap =
attr "hx-swap" swap
/// <summary>
/// Controls how the response content is swapped into the DOM (e.g. <c>outerHTML</c> or <c>beforeEnd</c>), enabling
/// CSS transitions
/// </summary>
/// <param name="swap">The type of swap to perform (use <c>HxSwap</c> values)</param>
/// <returns>A configured <c>hx-swap</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-swap/">Documentation</seealso>
let _hxSwapWithTransition swap =
_hxSwap $"%s{swap} transition:true"
/// <summary>
/// Marks content in a response as being "Out of Band", i.e. swapped somewhere other than the target
/// </summary>
/// <param name="swap">
/// <ul>
/// <li>"true" to mark this as an OOB swap</li>
/// <li>Any <c>HxSwap</c> value</li>
/// <li>Any <c>HxSwap</c> value, followed by a colon (<c>:</c>) and a CSS selector</li>
/// </ul>
/// </param>
/// <returns>A configured <c>hx-swap-oob</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-swap-oob/">Documentation</seealso>
let _hxSwapOob swap =
attr "hx-swap-oob" swap
/// <summary>Synchronize events based on another element</summary>
/// <param name="selector">A CSS selector for the element with which this one should sync</param>
/// <param name="action">The request synchronization action to perform (use <c>HxSync</c> values)</param>
/// <returns>A configured <c>hx-sync</c> attribute</returns>
/// <seealso cref="HxSync" />
/// <seealso href="https://htmx.org/attributes/hx-sync/">Documentation</seealso>
let _hxSync selector action =
attr "hx-sync" $"%s{selector}:%s{action}"
/// <summary>Specifies the target element to be swapped</summary>
/// <param name="selector">A CSS selector or relative reference (or both) to identify the target</param>
/// <returns>A configured <c>hx-target</c> attribute</returns>
/// <seealso href="https://htmx.org/attributes/hx-target/">Documentation</seealso>
let _hxTarget selector =
attr "hx-target" selector
/// <summary>Specifies the event that triggers the request</summary>
/// <param name="spec">The trigger specification (use <c>HxTrigger</c> to create)</param>
/// <returns>A configured <c>hx-trigger</c> attribute</returns>
/// <seealso cref="HxTrigger" />
/// <seealso href="https://htmx.org/attributes/hx-trigger/">Documentation</seealso>
let _hxTrigger spec =
attr "hx-trigger" spec
/// <summary>Validate an input element (uses HTML5 validation API)</summary>
/// <seealso href="https://htmx.org/attributes/hx-validate/">Documentation</seealso>
let _hxValidate =
flag "hx-validate"
/// <summary>Adds to the parameters that will be submitted with the request</summary>
/// <param name="values">The values for the parameters (use <c>HxVals.From</c> to create)</param>
/// <returns>A configured <c>hx-vals</c> attribute</returns>
/// <seealso cref="HxVals.From" />
/// <seealso href="https://htmx.org/attributes/hx-vals/">Documentation</seealso>
let _hxVals values =
attr "hx-vals" values
/// <summary>The URL of the SSE server</summary>
/// <param name="url">The URL from which events will be received</param>
/// <returns>A configured <c>sse-connect</c> attribute</returns>
/// <seealso href="https://htmx.org/extensions/sse/#usage">Extension Docs</seealso>
let _sseConnect url =
attr "sse-connect" url
/// <summary>The name(s) of the message(s) to swap into the DOM</summary>
/// <param name="messages">The message names (comma-delimited) to swap (use "message" for unnamed events)</param>
/// <returns>A configured <c>sse-swap</c> attribute</returns>
/// <seealso href="https://htmx.org/extensions/sse/#usage">Extension Docs</seealso>
let _sseSwap messages =
attr "sse-swap" messages
/// <summary>Modifiers for htmx attributes</summary>
[<AutoOpen>]
module HxModifiers =
/// <summary>Append this value to any inherited value of the attribute</summary>
/// <param name="attrib">The attribute to which <c>:append</c> should be applied</param>
/// <returns>The given attribute with <c>:append</c> applied</returns>
let hxAppend attrib =
match attrib with
| KeyValue (name, value) -> attr $"{name}:append" value
| Boolean name -> flag $"{name}:append"
/// <summary>Explicitly propagate inheritance for the value for this attribute</summary>
/// <param name="attrib">The attribute whose value should be inherited</param>
/// <returns>The given attribute with <c>:inherited</c> applied</returns>
let hxInherited attrib =
match attrib with
| KeyValue (name, value) -> attr $"{name}:inherited" value
| Boolean name -> flag $"{name}:inherited"
/// <summary>htmx-specific HTML tags</summary>
[<AutoOpen>]
module HxTags =
/// <summary>An <c>hx-partial</c> tag</summary>
let hxPartial = tag "hx-partial"
/// <summary>Script tags to pull htmx into a web page</summary>
module Script =
open System
/// <summary>Script tag to load the package-provided version of htmx</summary>
let local = script [ _src htmxLocalScript ] []
/// <summary>Script tag to load the minified version from jsdelivr.net</summary>
/// <remarks>Ensure <c>cdn.jsdelivr.net</c> is in your CSP <c>script-src</c> list (if applicable)</remarks>
let cdnMinified =
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@4.0.0-alpha6/dist/htmx.min.js"
_integrity "sha384-/5n21KGM472oBhvzUrvju8FRDq/4WNMS3TGw5RWFkZR/kq+sCevqNXFcakqRtaHu"
_crossorigin "anonymous" ] []
/// <summary>Script tag to load the unminified version from jsdelivr.net</summary>
/// <remarks>Ensure <c>cdn.jsdelivr.net</c> is in your CSP <c>script-src</c> list (if applicable)</remarks>
let cdnUnminified =
script [ _src "https://cdn.jsdelivr.net/npm/htmx.org@4.0.0-alpha6/dist/htmx.js"
_integrity "sha384-I3uRy2RjSNcS8Oi2SNWZD9IrafyrrrBb4QaHNA9pWVWfJuKtL0p8qAwHSrEyXoKh"
_crossorigin "anonymous" ] []
/// <summary>Script tag to load the minified version from jsdelivr.net</summary>
[<Obsolete "Use cdnMinified instead; this will be removed in v4">]
let minified = cdnMinified
/// <summary>Script tag to load the unminified version from jsdelivr.net</summary>
[<Obsolete "Use cdnUnminified instead; this will be removed in v4">]
let unminified = cdnUnminified
/// <summary>Functions to extract and render an HTML fragment from a document</summary>
[<RequireQualifiedAccess>]
module RenderFragment =
/// Does this element have an ID matching the requested ID name?
let private isIdElement nodeId (elt: XmlElement) =
snd elt
|> Array.exists (fun attr ->
match attr with
| KeyValue (name, value) -> name = "id" && value = nodeId
| Boolean _ -> false)
/// Generate a message if the requested ID node is not found
let private nodeNotFound (nodeId: string) =
$"<em>&ndash; ID {nodeId} not found &ndash;</em>"
/// <summary>Find the node with the named ID</summary>
/// <param name="nodeId">The <c>id</c> attribute to find</param>
/// <param name="node">The node tree to search</param>
/// <returns>The node with the requested <c>id</c> attribute, or <c>None</c> if it was not found</returns>
let rec findIdNode nodeId (node: XmlNode) : XmlNode option =
match node with
| Text _ -> None
| VoidElement elt -> if isIdElement nodeId elt then Some node else None
| ParentNode (elt, children) ->
if isIdElement nodeId elt then Some node else children |> List.tryPick (findIdNode nodeId)
/// <summary>Functions to render a fragment as a string</summary>
[<RequireQualifiedAccess>]
module AsString =
/// <summary>Render to HTML for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="nodes">The node trees to search</param>
/// <returns>The HTML for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNodes nodeId (nodes: XmlNode list) =
match nodes |> List.tryPick (findIdNode nodeId) with
| Some idNode -> RenderView.AsString.htmlNode idNode
| None -> nodeNotFound nodeId
/// <summary>Render to HTML for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="node">The node tree to search</param>
/// <returns>The HTML for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNode nodeId node =
match findIdNode nodeId node with
| Some idNode -> RenderView.AsString.htmlNode idNode
| None -> nodeNotFound nodeId
/// <summary>Functions to render a fragment as bytes</summary>
[<RequireQualifiedAccess>]
module AsBytes =
let private utf8 = System.Text.Encoding.UTF8
/// <summary>Render to bytes for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="nodes">The node trees to search</param>
/// <returns>The bytes for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNodes nodeId (nodes: XmlNode list) =
match nodes |> List.tryPick (findIdNode nodeId) with
| Some idNode -> RenderView.AsBytes.htmlNode idNode
| None -> nodeNotFound nodeId |> utf8.GetBytes
/// <summary>Render to bytes for the given ID</summary>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="node">The node tree to search</param>
/// <returns>The bytes for the given <c>id</c> node, or an error message if it was not found</returns>
let htmlFromNode nodeId node =
match findIdNode nodeId node with
| Some idNode -> RenderView.AsBytes.htmlNode idNode
| None -> nodeNotFound nodeId |> utf8.GetBytes
/// <summary>Functions to render a fragment into a StringBuilder</summary>
[<RequireQualifiedAccess>]
module IntoStringBuilder =
/// <summary>Render HTML into a <c>StringBuilder</c> for the given ID</summary>
/// <param name="sb">The <c>StringBuilder</c> into which the bytes will be rendered</param>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="nodes">The node trees to search</param>
let htmlFromNodes sb nodeId (nodes: XmlNode list) =
match nodes |> List.tryPick (findIdNode nodeId) with
| Some idNode -> RenderView.IntoStringBuilder.htmlNode sb idNode
| None -> nodeNotFound nodeId |> sb.Append |> ignore
/// <summary>Render HTML into a <c>StringBuilder</c> for the given ID</summary>
/// <param name="sb">The <c>StringBuilder</c> into which the bytes will be rendered</param>
/// <param name="nodeId">The <c>id</c> attribute for the node to be rendered</param>
/// <param name="node">The node tree to search</param>
let htmlFromNode sb nodeId node =
match findIdNode nodeId node with
| Some idNode -> RenderView.IntoStringBuilder.htmlNode sb idNode
| None -> nodeNotFound nodeId |> sb.Append |> ignore