Skip to main content

topcoat_htmx/
swap.rs

1use http::HeaderValue;
2use serde::Serialize;
3
4/// How htmx swaps a response into the DOM.
5///
6/// Mirrors the values accepted by the `hx-swap` attribute. Used by
7/// [`HxReswap`](crate::HxReswap) and as the `swap` field of an
8/// [`HxLocation`](crate::HxLocation).
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
10pub enum SwapOption {
11    /// Replace the inner HTML of the target element.
12    #[serde(rename = "innerHTML")]
13    InnerHtml,
14    /// Replace the entire target element.
15    #[serde(rename = "outerHTML")]
16    OuterHtml,
17    /// Insert the response before the target element.
18    #[serde(rename = "beforebegin")]
19    BeforeBegin,
20    /// Insert the response before the first child of the target element.
21    #[serde(rename = "afterbegin")]
22    AfterBegin,
23    /// Insert the response after the last child of the target element.
24    #[serde(rename = "beforeend")]
25    BeforeEnd,
26    /// Insert the response after the target element.
27    #[serde(rename = "afterend")]
28    AfterEnd,
29    /// Delete the target element regardless of the response.
30    #[serde(rename = "delete")]
31    Delete,
32    /// Do not append the response to the target element.
33    #[serde(rename = "none")]
34    None,
35}
36
37impl SwapOption {
38    /// Returns the htmx string for this swap option (e.g. `"innerHTML"`).
39    #[must_use]
40    pub const fn as_str(self) -> &'static str {
41        match self {
42            Self::InnerHtml => "innerHTML",
43            Self::OuterHtml => "outerHTML",
44            Self::BeforeBegin => "beforebegin",
45            Self::AfterBegin => "afterbegin",
46            Self::BeforeEnd => "beforeend",
47            Self::AfterEnd => "afterend",
48            Self::Delete => "delete",
49            Self::None => "none",
50        }
51    }
52}
53
54impl From<SwapOption> for HeaderValue {
55    fn from(option: SwapOption) -> Self {
56        HeaderValue::from_static(option.as_str())
57    }
58}