use std::time::Duration; use leptos::prelude::*; use wasm_bindgen_futures::spawn_local; /// Context type: read/write access to the current toast message. #[derive(Copy, Clone)] pub struct ToastMsg(pub RwSignal>); pub fn provide_toast() -> ToastMsg { let toast = RwSignal::new(Option::::None); let t = ToastMsg(toast); provide_context(t); t } /// Show a toast that disappears after ~3 seconds. pub fn show(toast: ToastMsg, msg: impl Into) { let msg = msg.into(); toast.0.set(Some(msg.clone())); spawn_local(async move { gloo_timers::future::sleep(Duration::from_secs(3)).await; if toast.0.get().as_deref() == Some(msg.as_str()) { toast.0.set(None); } }); } #[component] pub fn ToastView(toast: ToastMsg) -> impl IntoView { view! {
{move || toast.0.get().unwrap_or_default()}
} }