1use topcoat::{
5 context::{Cx, try_context},
6 cookie::{CookieJar, CookieJarCell, Cookies, cookie_store, cookies},
7};
8
9use crate::outcome::Notification;
10
11pub(crate) const COOKIE_NAME: &str = "__Host-tablo_notification";
12
13fn hardened(jar: &CookieJar) -> impl Cookies + '_ {
16 jar.default_path("/")
17 .default_http_only(true)
18 .default_secure(true)
19 .default_same_site(topcoat::cookie::SameSite::Lax)
20}
21
22pub fn set_notification(cx: &Cx, notification: Notification) {
24 if try_context::<CookieJarCell>(cx).is_none() {
25 return;
26 }
27 if let Err(error) = cookie_store::<Notification, _>(hardened(cookies(cx)), COOKIE_NAME)
28 .set(notification)
29 .commit()
30 {
31 tracing::error!(error = %error, "flash notification commit failed");
32 }
33}
34
35pub(crate) fn notify_write_failure(cx: &Cx, failure: &'static str) {
39 set_notification(
40 cx,
41 Notification::error(crate::t!(cx, failure))
42 .description(crate::t!(cx, "tablo-failed-description")),
43 );
44}
45
46pub fn take_notification(cx: &Cx) -> Option<Notification> {
48 try_context::<CookieJarCell>(cx)?;
49 let unparsed = cookie_store::<Notification, _>(hardened(cookies(cx)), COOKIE_NAME);
50 match unparsed.parse() {
51 Ok(Some(store)) => {
52 let notification = store.get();
53 store.remove();
54 Some(notification)
55 }
56 Err(_) => {
58 cookie_store::<Notification, _>(hardened(cookies(cx)), COOKIE_NAME).remove();
59 None
60 }
61 Ok(None) => None,
62 }
63}
64
65#[cfg(test)]
66mod tests;