use std::time::{Duration, Instant};
use ratatui::{
Frame,
layout::Rect,
style::Modifier,
text::Span,
widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap},
};
use super::style;
use crate::theme::{Color, Skin};
const DEFAULT_TTL: Duration = Duration::from_secs(4);
const TOAST_WIDTH: u16 = 32;
const TOAST_HEIGHT: u16 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToastKind {
Info,
Success,
Warning,
Error,
}
impl ToastKind {
fn color(self, skin: &Skin) -> Color {
match self {
ToastKind::Info => skin.palette.info,
ToastKind::Success => skin.palette.success,
ToastKind::Warning => skin.palette.warning,
ToastKind::Error => skin.palette.error,
}
}
fn label(self) -> &'static str {
match self {
ToastKind::Info => "info",
ToastKind::Success => "success",
ToastKind::Warning => "warning",
ToastKind::Error => "error",
}
}
}
struct Toast {
kind: ToastKind,
message: String,
expires: Instant,
}
#[derive(Default)]
pub struct Toasts {
items: Vec<Toast>,
}
impl Toasts {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, kind: ToastKind, message: impl Into<String>) {
self.push_with_ttl(kind, message, DEFAULT_TTL);
}
pub fn push_with_ttl(
&mut self,
kind: ToastKind,
message: impl Into<String>,
ttl: Duration,
) {
self.items.push(Toast {
kind,
message: message.into(),
expires: Instant::now() + ttl,
});
}
pub fn prune(&mut self) {
let now = Instant::now();
self.items.retain(|toast| toast.expires > now);
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn render(&self, frame: &mut Frame, area: Rect, skin: &Skin) {
let now = Instant::now();
let width = TOAST_WIDTH.min(area.width);
let mut y = area.y;
for toast in self.items.iter().filter(|t| t.expires > now) {
if y + TOAST_HEIGHT > area.y + area.height {
break;
}
let rect = Rect {
x: area.x + area.width.saturating_sub(width),
y,
width,
height: TOAST_HEIGHT,
};
let color = toast.kind.color(skin);
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(style::fg(color))
.style(style::bg(skin.palette.background))
.title(Span::styled(
format!("\u{2500} {} ", toast.kind.label()),
style::fg(color).add_modifier(Modifier::BOLD),
));
frame.render_widget(Clear, rect);
frame.render_widget(
Paragraph::new(toast.message.clone())
.block(block)
.wrap(Wrap { trim: true }),
rect,
);
y += TOAST_HEIGHT;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prune_drops_expired_but_keeps_fresh() {
let mut toasts = Toasts::new();
toasts.push_with_ttl(ToastKind::Error, "boom", Duration::ZERO);
toasts.push(ToastKind::Info, "hello");
toasts.prune();
assert!(!toasts.is_empty()); }
#[test]
fn prune_empties_when_all_expired() {
let mut toasts = Toasts::new();
toasts.push_with_ttl(ToastKind::Warning, "x", Duration::ZERO);
toasts.prune();
assert!(toasts.is_empty());
}
}