Added a toaster system, and custom theme coloring for toasters
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m32s

This commit is contained in:
Squid committed 2026-11-06 22:39:33 +01:00
1 parent 8d9f4584dd
commit 891bb85d92
2 files changed
+927 -19

No files matched your search

+495
View File
@@ -0,0 +1,495 @@
//! Reusable in-app notification manager and toast rendering.
//!
//! The manager owns notification state independently from the widgets that
//! render it, so it can later be shared by more than one window.
use std::time::Duration;
use iced::time::Instant;
use iced::widget::{button, column, container, opaque, responsive, row, scrollable, text};
use iced::{Alignment, Border, Color, Element, Length, Shadow, Theme, Vector};
/// Default lifetime of a timed notification.
pub const DEFAULT_DURATION: Duration = Duration::from_secs(5);
const FADE_IN: Duration = Duration::from_millis(160);
const FADE_OUT: Duration = Duration::from_millis(140);
const MAX_WIDTH: f32 = 340.0;
const MARGIN: f32 = 16.0;
const SPACING: f32 = 8.0;
/// Colors used to render toasts. The defaults follow the active iced theme;
/// a theme can override every field.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ToastColors {
pub background: Color,
pub text: Color,
pub title: Color,
pub border: Color,
pub info: Color,
pub success: Color,
pub warning: Color,
pub error: Color,
pub dismiss: Color,
}
impl ToastColors {
pub fn default_for(theme: &Theme) -> Self {
let palette = theme.extended_palette();
Self {
background: mix(
palette.background.weak.color,
palette.primary.base.color,
0.06,
),
text: palette.background.weak.text,
title: palette.background.weak.text,
border: palette.background.strong.color,
info: palette.primary.base.color,
success: palette.success.base.color,
warning: palette.warning.base.color,
error: palette.danger.base.color,
dismiss: palette.background.weak.text,
}
}
pub fn as_array(self) -> [Color; 9] {
[
self.background,
self.text,
self.title,
self.border,
self.info,
self.success,
self.warning,
self.error,
self.dismiss,
]
}
pub fn from_array(colors: [Color; 9]) -> Self {
Self {
background: colors[0],
text: colors[1],
title: colors[2],
border: colors[3],
info: colors[4],
success: colors[5],
warning: colors[6],
error: colors[7],
dismiss: colors[8],
}
}
}
/// Unique identifier for a notification within a manager.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NotificationId(u64);
/// The four supported notification severities.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationKind {
Info,
Success,
Warning,
Error,
}
impl NotificationKind {
fn icon(self) -> &'static str {
match self {
Self::Info => "ℹ",
Self::Success => "✓",
Self::Warning => "⚠",
Self::Error => "✕",
}
}
fn accent(self, colors: ToastColors) -> Color {
match self {
Self::Info => colors.info,
Self::Success => colors.success,
Self::Warning => colors.warning,
Self::Error => colors.error,
}
}
}
/// How long a notification stays visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationLifetime {
Timed(Duration),
Persistent,
}
impl Default for NotificationLifetime {
fn default() -> Self {
Self::Timed(DEFAULT_DURATION)
}
}
/// A single notification. Create it with [`Notification::new`] and configure
/// it with the builder methods before handing it to a manager.
#[derive(Debug, Clone)]
pub struct Notification {
id: NotificationId,
kind: NotificationKind,
title: Option<String>,
message: String,
lifetime: NotificationLifetime,
born: Instant,
closing: Option<Instant>,
}
impl Notification {
pub fn new(kind: NotificationKind, message: impl Into<String>) -> Self {
Self {
id: NotificationId(0),
kind,
title: None,
message: message.into(),
lifetime: NotificationLifetime::default(),
born: Instant::now(),
closing: None,
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn persistent(mut self) -> Self {
self.lifetime = NotificationLifetime::Persistent;
self
}
pub fn timed(mut self, duration: Duration) -> Self {
self.lifetime = NotificationLifetime::Timed(duration);
self
}
fn expires_at(&self) -> Option<Instant> {
match self.lifetime {
NotificationLifetime::Timed(duration) => Some(self.born + duration),
NotificationLifetime::Persistent => None,
}
}
fn opacity(&self, now: Instant) -> f32 {
let fade_in = (now.saturating_duration_since(self.born).as_secs_f32()
/ FADE_IN.as_secs_f32())
.clamp(0.0, 1.0);
let fade_out = self
.closing
.map(|at| {
1.0 - (now.saturating_duration_since(at).as_secs_f32() / FADE_OUT.as_secs_f32())
.clamp(0.0, 1.0)
})
.unwrap_or(1.0);
fade_in.min(fade_out)
}
fn is_finished(&self, now: Instant) -> bool {
self.closing
.is_some_and(|at| now.saturating_duration_since(at) >= FADE_OUT)
}
}
/// Owns all live notifications. New entries are inserted at the top.
#[derive(Debug)]
pub struct NotificationManager {
next_id: u64,
notifications: Vec<Notification>,
}
impl Default for NotificationManager {
fn default() -> Self {
Self {
next_id: 1,
notifications: Vec::new(),
}
}
}
impl NotificationManager {
pub fn add(&mut self, notification: Notification) -> NotificationId {
self.add_at(Instant::now(), notification)
}
fn add_at(&mut self, now: Instant, mut notification: Notification) -> NotificationId {
let id = NotificationId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
notification.id = id;
notification.born = now;
notification.closing = None;
self.notifications.insert(0, notification);
id
}
/// Starts dismissing a notification; it is removed after the fade-out.
pub fn dismiss(&mut self, id: NotificationId) {
self.dismiss_at(id, Instant::now());
}
fn dismiss_at(&mut self, id: NotificationId, now: Instant) {
if let Some(notification) = self
.notifications
.iter_mut()
.find(|notification| notification.id == id)
&& notification.closing.is_none()
{
notification.closing = Some(now);
}
}
/// Expires due timed notifications and removes finished fade-outs.
pub fn remove_expired(&mut self, now: Instant) {
for notification in &mut self.notifications {
if notification.closing.is_none()
&& notification.expires_at().is_some_and(|at| now >= at)
{
notification.closing = Some(now);
}
}
self.notifications
.retain(|notification| !notification.is_finished(now));
}
#[allow(dead_code)] // Public manager API for future call sites.
pub fn clear(&mut self) {
self.notifications.clear();
}
pub fn is_empty(&self) -> bool {
self.notifications.is_empty()
}
#[allow(dead_code)] // Public manager API for future call sites.
pub fn len(&self) -> usize {
self.notifications.len()
}
/// Whether another timed notification still needs an expiry timer.
pub fn has_timed(&self) -> bool {
self.notifications.iter().any(|notification| {
notification.closing.is_none()
&& matches!(notification.lifetime, NotificationLifetime::Timed(_))
})
}
/// Whether any notification is fading in or out and needs frame updates.
pub fn is_animating(&self, now: Instant) -> bool {
self.notifications.iter().any(|notification| {
notification.closing.is_some()
|| now.saturating_duration_since(notification.born) < FADE_IN
})
}
/// Renders the toast stack in the bottom-right corner.
pub fn view(&self, now: Instant, colors: Option<ToastColors>) -> Element<'_, Message> {
responsive(move |size| {
let mut list = column![].spacing(SPACING).width(Length::Fill);
for notification in &self.notifications {
let opacity = notification.opacity(now);
if opacity > 0.0 {
list = list.push(toast(notification, opacity, colors));
}
}
let width = (size.width - MARGIN * 2.0).clamp(220.0, MAX_WIDTH);
let max_height = (size.height * 0.6).clamp(160.0, 480.0);
let stack = container(scrollable(list).width(Length::Fill))
.width(Length::Fixed(width))
.max_height(max_height);
container(opaque(stack))
.width(Length::Fill)
.height(Length::Fill)
.align_x(Alignment::End)
.align_y(Alignment::End)
.padding(MARGIN)
.into()
})
.into()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Message {
Dismiss(NotificationId),
}
fn toast(
notification: &Notification,
opacity: f32,
colors: Option<ToastColors>,
) -> Element<'_, Message> {
let kind = notification.kind;
let mut body = column![].spacing(2).width(Length::Fill);
if let Some(title) = &notification.title {
let title = container(text(title).size(14).width(Length::Fill)).style(move |theme| {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
container::Style {
text_color: Some(colors.title.scale_alpha(opacity)),
..container::Style::default()
}
});
body = body.push(title);
}
body = body.push(text(&notification.message).size(13).width(Length::Fill));
let icon = container(text(kind.icon()).size(16)).style(move |theme| {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
container::Style {
text_color: Some(kind.accent(colors).scale_alpha(opacity)),
..container::Style::default()
}
});
let dismiss = button(text("✕").size(14))
.on_press(Message::Dismiss(notification.id))
.padding([2, 6])
.style(move |theme, status| dismiss_style(theme, status, opacity, colors));
container(
row![icon, body, dismiss]
.spacing(8)
.align_y(Alignment::Start),
)
.width(Length::Fill)
.padding(10)
.style(move |theme| {
panel_style(
colors.unwrap_or_else(|| ToastColors::default_for(theme)),
opacity,
)
})
.into()
}
fn dismiss_style(
theme: &Theme,
status: button::Status,
opacity: f32,
colors: Option<ToastColors>,
) -> button::Style {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
let mut style = button::text(theme, status);
style.text_color = colors.dismiss.scale_alpha(opacity);
style
}
fn panel_style(colors: ToastColors, opacity: f32) -> container::Style {
container::Style {
background: Some(colors.background.scale_alpha(opacity).into()),
text_color: Some(colors.text.scale_alpha(opacity)),
border: Border {
color: colors.border.scale_alpha(opacity * 0.7),
width: 1.0,
radius: 6.0.into(),
},
shadow: Shadow {
color: Color::BLACK.scale_alpha(0.18 * opacity),
offset: Vector::new(0.0, 2.0),
blur_radius: 8.0,
},
..container::Style::default()
}
}
fn mix(left: Color, right: Color, amount: f32) -> Color {
Color {
r: left.r + (right.r - left.r) * amount,
g: left.g + (right.g - left.g) * amount,
b: left.b + (right.b - left.b) * amount,
a: left.a + (right.a - left.a) * amount,
}
}
#[cfg(test)]
mod tests {
use super::{
DEFAULT_DURATION, Notification, NotificationKind, NotificationLifetime, NotificationManager,
};
use iced::time::{Duration, Instant};
#[test]
fn new_notifications_are_unique_and_stack_newest_first() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let first = manager.add_at(now, Notification::new(NotificationKind::Info, "first"));
let second = manager.add_at(now, Notification::new(NotificationKind::Error, "second"));
assert_ne!(first, second);
assert_eq!(manager.len(), 2);
assert_eq!(manager.notifications[0].id, second);
assert_eq!(manager.notifications[1].id, first);
}
#[test]
fn timed_notifications_expire_but_persistent_ones_do_not() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let timed = manager.add_at(
now,
Notification::new(NotificationKind::Success, "timed").timed(Duration::from_secs(2)),
);
let persistent = manager.add_at(
now,
Notification::new(NotificationKind::Warning, "persistent").persistent(),
);
manager.remove_expired(now + Duration::from_secs(1));
assert_eq!(manager.len(), 2);
assert!(manager.notifications.iter().any(|n| n.id == timed));
assert!(manager.notifications.iter().any(|n| n.id == persistent));
// Expiry starts a fade-out, then the entry is removed.
manager.remove_expired(now + Duration::from_secs(2));
assert_eq!(manager.len(), 2);
manager.remove_expired(now + Duration::from_secs(3));
assert!(manager.notifications.iter().all(|n| n.id != timed));
assert!(manager.notifications.iter().any(|n| n.id == persistent));
}
#[test]
fn dismissing_starts_the_fade_out_and_clear_removes_everything() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let id = manager.add_at(now, Notification::new(NotificationKind::Info, "hello"));
manager.dismiss_at(id, now);
assert_eq!(manager.len(), 1);
manager.remove_expired(now + Duration::from_secs(1));
assert!(manager.is_empty());
manager.add_at(now, Notification::new(NotificationKind::Info, "one"));
manager.add_at(now, Notification::new(NotificationKind::Info, "two"));
manager.clear();
assert!(manager.is_empty());
}
#[test]
fn default_lifetime_is_five_seconds() {
let notification = Notification::new(NotificationKind::Info, "hello");
assert_eq!(
notification.lifetime,
NotificationLifetime::Timed(DEFAULT_DURATION)
);
}
}