use axum::{
http::HeaderMap,
response::{Html, IntoResponse, Response},
};
#[must_use]
pub fn is_htmx_request(headers: &HeaderMap) -> bool {
headers.contains_key("hx-request")
}
#[must_use]
pub fn is_boosted_request(headers: &HeaderMap) -> bool {
headers
.get("hx-boosted")
.and_then(|v| v.to_str().ok())
.is_some_and(|s| s == "true")
}
pub fn fragment_or_full<F>(is_htmx: bool, fragment: impl Into<String>, full_page_fn: F) -> Response
where
F: FnOnce() -> String,
{
if is_htmx {
Html(fragment.into()).into_response()
} else {
Html(full_page_fn()).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
#[test]
fn test_is_htmx_request() {
let mut headers = HeaderMap::new();
assert!(!is_htmx_request(&headers));
headers.insert("hx-request", HeaderValue::from_static("true"));
assert!(is_htmx_request(&headers));
}
#[test]
fn test_is_boosted_request() {
let mut headers = HeaderMap::new();
assert!(!is_boosted_request(&headers));
headers.insert("hx-boosted", HeaderValue::from_static("true"));
assert!(is_boosted_request(&headers));
headers.insert("hx-boosted", HeaderValue::from_static("false"));
assert!(!is_boosted_request(&headers));
}
#[test]
fn test_fragment_or_full() {
let response = fragment_or_full(true, "<p>Fragment</p>", || {
"<html><body><p>Full</p></body></html>".to_string()
});
assert_eq!(response.status(), axum::http::StatusCode::OK);
let response = fragment_or_full(false, "<p>Fragment</p>", || {
"<html><body><p>Full</p></body></html>".to_string()
});
assert_eq!(response.status(), axum::http::StatusCode::OK);
}
}