htmx_types/
lib.rs

1//! Types for working with [htmx](https://htmx.org/).
2
3use http::HeaderValue;
4use serde::{Deserialize, Serialize};
5
6/// htmx headers which implement the [`headers_core::Header`] trait.
7pub mod headers;
8
9/// The hx-swap attribute allows you to specify how the response will be swapped in relative to the [target](https://htmx.org/attributes/hx-target/) of an AJAX request.
10///
11/// [htmx docs](https://htmx.org/attributes/hx-swap/)
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub enum Swap {
14    /// Replace the inner html of the target element
15    #[serde(rename = "innerHtml")]
16    InnerHtml,
17
18    /// Replace the entire target element with the response
19    #[serde(rename = "outerHtml")]
20    OuterHtml,
21
22    /// Insert the response before the target element
23    #[serde(rename = "beforebegin")]
24    BeforeBegin,
25
26    /// Insert the response before the first child of the target element
27    #[serde(rename = "afterbegin")]
28    AfterBegin,
29
30    /// Insert the response after the last child of the target element
31    #[serde(rename = "beforeend")]
32    BeforeEnd,
33
34    /// Insert the response after the target element
35    #[serde(rename = "afterend")]
36    AfterEnd,
37
38    /// Deletes the target element regardless of the response
39    #[serde(rename = "delete")]
40    Delete,
41
42    /// Does not append content from response (out of band items will still be
43    /// processed).
44    #[serde(rename = "none")]
45    None,
46}
47
48impl From<Swap> for HeaderValue {
49    fn from(swap: Swap) -> Self {
50        match swap {
51            Swap::InnerHtml => Self::from_static("innerHtml"),
52            Swap::OuterHtml => Self::from_static("outerHtml"),
53            Swap::BeforeBegin => Self::from_static("beforebegin"),
54            Swap::AfterBegin => Self::from_static("afterbegin"),
55            Swap::BeforeEnd => Self::from_static("beforeend"),
56            Swap::AfterEnd => Self::from_static("afterend"),
57            Swap::Delete => Self::from_static("delete"),
58            Swap::None => Self::from_static("none"),
59        }
60    }
61}
62
63impl TryFrom<&[u8]> for Swap {
64    type Error = ();
65
66    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
67        match bytes {
68            b"innerHtml" => Ok(Self::InnerHtml),
69            b"outerHtml" => Ok(Self::OuterHtml),
70            b"beforebegin" => Ok(Self::BeforeBegin),
71            b"afterbegin" => Ok(Self::AfterBegin),
72            b"beforeend" => Ok(Self::BeforeEnd),
73            b"afterend" => Ok(Self::AfterEnd),
74            b"delete" => Ok(Self::Delete),
75            b"none" => Ok(Self::None),
76            _ => Err(()),
77        }
78    }
79}