1use askama::Template;
8use axum::body::Body;
9use axum::extract::{FromRequestParts, Request};
10use axum::http::HeaderValue;
11use axum::http::header::{CONTENT_LENGTH, CONTENT_TYPE};
12use axum::middleware::Next;
13use axum::response::Response;
14use axum_messages::{Level, Message, Messages};
15
16#[derive(Debug, Clone)]
18pub struct Flash {
19 pub level: &'static str,
20 pub icon: &'static str,
21 pub dismiss_ms: Option<u32>,
22 pub text: String,
23}
24
25pub fn drain(messages: Messages) -> Vec<Flash> {
27 messages.map(Flash::from).collect()
28}
29
30impl Flash {
31 fn from_level(level: Level, text: String) -> Self {
32 let (level, icon, dismiss_ms) = style(level);
33 Self {
34 level,
35 icon,
36 dismiss_ms,
37 text,
38 }
39 }
40
41 pub fn success(text: impl Into<String>) -> Self {
44 Self::from_level(Level::Success, text.into())
45 }
46
47 pub fn info(text: impl Into<String>) -> Self {
49 Self::from_level(Level::Info, text.into())
50 }
51}
52
53#[derive(Template)]
57#[template(path = "flash_oob.html")]
58pub struct FlashOob {
59 pub flashes: Vec<Flash>,
60}
61
62impl From<Message> for Flash {
63 fn from(message: Message) -> Self {
64 Self::from_level(message.level, message.message)
65 }
66}
67
68fn style(level: Level) -> (&'static str, &'static str, Option<u32>) {
73 match level {
74 Level::Debug => ("info", "info", Some(4_000)),
75 Level::Info => ("info", "info", Some(6_000)),
76 Level::Success => ("success", "check-circle", None),
77 Level::Warning => ("warning", "warning", None),
78 Level::Error => ("error", "warning-circle", None),
79 }
80}
81
82pub async fn htmx_flash(req: Request, next: Next) -> Response {
90 let (mut parts, body) = req.into_parts();
91 let is_htmx = parts.headers.contains_key("hx-request");
92 let messages = Messages::from_request_parts(&mut parts, &()).await.ok();
93 let res = next.run(Request::from_parts(parts, body)).await;
94
95 if !is_htmx
96 || res.headers().contains_key("hx-redirect")
97 || res.headers().contains_key("hx-location")
98 {
99 return res;
100 }
101
102 let Some(messages) = messages else {
103 return res;
104 };
105 let flashes = drain(messages.load());
106 if flashes.is_empty() {
107 return res;
108 }
109
110 let oob = match (FlashOob { flashes }).render() {
111 Ok(html) => html,
112 Err(err) => {
113 tracing::error!(error = %err, "rendering flash OOB fragment");
114 return res;
115 }
116 };
117
118 let (mut parts, body) = res.into_parts();
119 let existing = axum::body::to_bytes(body, usize::MAX)
120 .await
121 .unwrap_or_default();
122 let mut combined = existing.to_vec();
123 combined.extend_from_slice(oob.as_bytes());
124
125 parts.headers.insert(
126 CONTENT_TYPE,
127 HeaderValue::from_static("text/html; charset=utf-8"),
128 );
129 parts.headers.remove(CONTENT_LENGTH);
130 Response::from_parts(parts, Body::from(combined))
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 #[test]
139 fn every_level_has_a_style() {
140 for level in [
141 Level::Debug,
142 Level::Info,
143 Level::Success,
144 Level::Warning,
145 Level::Error,
146 ] {
147 let (class, icon, _) = style(level);
148 assert!(!class.is_empty(), "{level:?} has an empty alert class");
149 assert!(!icon.is_empty(), "{level:?} has an empty icon");
150 }
151 }
152
153 #[test]
154 fn info_flash_auto_dismisses() {
155 let f = Flash::info("Now viewing Big League");
156 assert_eq!(f.level, "info");
157 assert!(f.dismiss_ms.is_some(), "info toasts auto-dismiss");
158 }
159
160 #[test]
161 fn flash_oob_renders_oob_swap_with_message() {
162 let html = FlashOob {
163 flashes: vec![Flash::success("Saved.")],
164 }
165 .render()
166 .expect("render oob");
167 assert!(html.contains(r#"id="flash""#));
168 assert!(html.contains(r#"hx-swap-oob="beforeend""#));
169 assert!(html.contains("Saved."));
170 assert!(html.contains("alert-success"));
171 }
172
173 #[test]
174 fn flash_oob_empty_renders_container_only() {
175 let html = FlashOob { flashes: vec![] }.render().expect("render empty");
176 assert!(html.contains(r#"id="flash""#));
177 assert!(!html.contains("alert-"));
178 }
179}