Skip to main content

sunday_slate/
flash.rs

1//! Flash messages rendered as daisyUI toast alerts in `_flash.html`.
2//!
3//! Handlers push messages via [`axum_messages::Messages`]; the next page's
4//! `_flash.html` partial drains them at render time via [`crate::context::flashes`]
5//! and they're cleared from the session on response write — one-shot, never in the URL.
6
7use 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/// One message for `_flash.html`.
17#[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
25/// Drain pending messages into template-ready flashes.
26pub 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    /// Build a success flash directly, bypassing the session message store.
42    /// Used for one-off htmx toast fragments where there's no redirect.
43    pub fn success(text: impl Into<String>) -> Self {
44        Self::from_level(Level::Success, text.into())
45    }
46
47    /// Build an info flash directly, bypassing the session message store.
48    pub fn info(text: impl Into<String>) -> Self {
49        Self::from_level(Level::Info, text.into())
50    }
51}
52
53/// Renders pending flashes as an htmx out-of-band swap appended to `#flash`.
54/// Used by [`htmx_flash`] for in-place htmx responses that never re-render the
55/// layout. The per-alert markup mirrors `layout.html` by design.
56#[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
68/// daisyUI alert class, Phosphor icon, and auto-dismiss delay per message level.
69///
70/// Success is sticky (no auto-dismiss): these flashes carry instructions acted
71/// on after reading ("check your email"), making auto-hide unrecoverable.
72fn 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
82/// Append pending flash messages to in-place htmx responses as an OOB swap.
83///
84/// Mounted between `request_ctx` and `MessagesManagerLayer`. On a full-page
85/// render the layout has already drained the messages by the time this runs, so
86/// it finds none and returns the response untouched. On an in-place htmx swap
87/// (htmx request, no `HX-Redirect`/`HX-Location`) it drains the pending messages
88/// and appends `flash_oob.html` to the body, which htmx applies out-of-band.
89pub 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    /// Every level must map to a non-empty daisyUI modifier and icon.
138    #[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}