improv(toaster): API consistency improvements

This commit is contained in:
Michael Aaron Murphy 2024-07-22 15:34:26 +02:00
parent 1e5828e01c
commit ece6edac8d
No known key found for this signature in database
GPG key ID: B2732D4240C9212C
2 changed files with 40 additions and 59 deletions

View file

@ -317,6 +317,10 @@ pub use text_input::{
editable_input, inline_input, search_input, secure_input, text_input, TextInput, editable_input, inline_input, search_input, secure_input, text_input, TextInput,
}; };
pub mod toaster;
#[doc(inline)]
pub use toaster::{toaster, Toast, Toasts};
mod toggler; mod toggler;
#[doc(inline)] #[doc(inline)]
pub use toggler::toggler; pub use toggler::toggler;
@ -349,6 +353,3 @@ pub mod tooltip {
pub mod warning; pub mod warning;
#[doc(inline)] #[doc(inline)]
pub use warning::*; pub use warning::*;
#[cfg(any(feature = "winit", feature = "wayland"))]
pub mod toaster;

View file

@ -4,11 +4,10 @@
//! A widget that displays toasts. //! A widget that displays toasts.
use std::collections::VecDeque; use std::collections::VecDeque;
use std::time::Duration;
use crate::app::Command;
use crate::widget::container; use crate::widget::container;
use crate::widget::Column; use crate::widget::Column;
use crate::Command;
use iced_core::Element; use iced_core::Element;
use widget::Toaster; use widget::Toaster;
@ -20,34 +19,30 @@ use super::{button, icon, row, text};
mod widget; mod widget;
/// Create a new Toaster widget. /// Create a new Toaster widget.
pub fn toaster<'a, Message>( pub fn toaster<'a, Message: Clone + 'static>(
toasts: &'a Toasts<Message>, toasts: &'a Toasts<Message>,
content: impl Into<Element<'a, Message, crate::Theme, iced::Renderer>>, content: impl Into<Element<'a, Message, crate::Theme, iced::Renderer>>,
) -> Element<'a, Message, crate::Theme, iced::Renderer> ) -> Element<'a, Message, crate::Theme, iced::Renderer> {
where
Message: From<ToastMessage> + Clone + 'static,
{
let theme = crate::theme::active(); let theme = crate::theme::active();
let cosmic_theme::Spacing { let cosmic_theme::Spacing {
space_xxxs, space_xxxs,
space_xxs, space_xxs,
space_xs,
space_s, space_s,
space_m, space_m,
.. ..
} = theme.cosmic().spacing; } = theme.cosmic().spacing;
let make_toast = |toast: &'a Toast<Message>| { let make_toast = move |(id, toast): (usize, &'a Toast<Message>)| {
let row = row() let row = row()
.push(text(&toast.message)) .push(text(&toast.message))
.push( .push(
row() row()
.push_maybe(toast.action.as_ref().map(|action| { .push_maybe(toast.action.as_ref().map(|action| {
button::text(&action.description).on_press(action.message.clone()) button::text(&action.description).on_press((action.message)(id))
})) }))
.push( .push(
button::icon(icon::from_name("window-close-symbolic")) button::icon(icon::from_name("window-close-symbolic"))
.on_press(ToastMessage(toast.id).into()), .on_press((toasts.on_close)(id)),
) )
.align_items(iced::Alignment::Center) .align_items(iced::Alignment::Center)
.spacing(space_xxs), .spacing(space_xxs),
@ -63,6 +58,7 @@ where
let col = toasts let col = toasts
.toasts .toasts
.iter() .iter()
.enumerate()
.rev() .rev()
.map(make_toast) .map(make_toast)
.fold(column::with_capacity(toasts.toasts.len()), Column::push) .fold(column::with_capacity(toasts.toasts.len()), Column::push)
@ -73,25 +69,25 @@ where
/// Duration for the [`Toast`] /// Duration for the [`Toast`]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum ToastDuration { pub enum Duration {
#[default] #[default]
Short, Short,
Long, Long,
Custom(Duration), Custom(std::time::Duration),
} }
impl ToastDuration { impl Duration {
fn duration(&self) -> Duration { fn duration(&self) -> std::time::Duration {
match self { match self {
ToastDuration::Short => Duration::from_millis(2000), Duration::Short => std::time::Duration::from_millis(5000),
ToastDuration::Long => Duration::from_millis(3500), Duration::Long => std::time::Duration::from_millis(15000),
ToastDuration::Custom(duration) => *duration, Duration::Custom(duration) => *duration,
} }
} }
} }
impl From<Duration> for ToastDuration { impl From<std::time::Duration> for Duration {
fn from(value: Duration) -> Self { fn from(value: std::time::Duration) -> Self {
Self::Custom(value) Self::Custom(value)
} }
} }
@ -100,18 +96,17 @@ impl From<Duration> for ToastDuration {
/// ///
/// Example: `undo` /// Example: `undo`
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ToastAction<Message> { pub struct Action<Message> {
pub description: String, pub description: String,
pub message: Message, pub message: fn(usize) -> Message,
} }
/// Represent the data used to display a [`Toast`] /// Represent the data used to display a [`Toast`]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Toast<Message> { pub struct Toast<Message> {
message: String, message: String,
action: Option<ToastAction<Message>>, action: Option<Action<Message>>,
duration: ToastDuration, duration: Duration,
id: u32,
} }
impl<Message> Toast<Message> { impl<Message> Toast<Message> {
@ -120,21 +115,20 @@ impl<Message> Toast<Message> {
Self { Self {
message: message.into(), message: message.into(),
action: None, action: None,
duration: ToastDuration::default(), duration: Duration::default(),
id: 0,
} }
} }
/// Set the [`ToastAction`] of this [`Toast`] /// Set the [`Action`] of this [`Toast`]
#[must_use] #[must_use]
pub fn action(mut self, action: ToastAction<Message>) -> Self { pub fn action(mut self, action: Action<Message>) -> Self {
self.action.replace(action); self.action.replace(action);
self self
} }
/// Set the [`ToastDuration`] of this [`Toast`] /// Set the [`Duration`] of this [`Toast`]
#[must_use] #[must_use]
pub fn duration(mut self, duration: impl Into<ToastDuration>) -> Self { pub fn duration(mut self, duration: impl Into<Duration>) -> Self {
self.duration = duration.into(); self.duration = duration.into();
self self
} }
@ -142,55 +136,41 @@ impl<Message> Toast<Message> {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Toasts<Message> { pub struct Toasts<Message> {
id_count: u32,
toasts: VecDeque<Toast<Message>>, toasts: VecDeque<Toast<Message>>,
on_close: fn(usize) -> Message,
limit: usize, limit: usize,
} }
// need custom impl to not require Message: Clone impl<Message: Clone + Send + 'static> Toasts<Message> {
impl<M> Default for Toasts<M> { pub fn new(on_close: fn(usize) -> Message) -> Self {
fn default() -> Self {
Self { Self {
id_count: 0,
toasts: VecDeque::new(), toasts: VecDeque::new(),
on_close,
limit: 5, limit: 5,
} }
} }
}
#[derive(Debug, Clone)]
pub struct ToastMessage(u32);
impl<Message> Toasts<Message> {
/// Add a new [`Toast`] /// Add a new [`Toast`]
pub fn push(&mut self, mut toast: Toast<Message>) -> Command<Message> pub fn push(&mut self, toast: Toast<Message>) -> Command<Message> {
where
Message: From<ToastMessage>,
{
while self.toasts.len() >= self.limit { while self.toasts.len() >= self.limit {
self.toasts.pop_front(); self.toasts.pop_front();
} }
toast.id = self.id_count;
self.id_count += 1;
let message = ToastMessage(toast.id);
let duration = toast.duration.duration(); let duration = toast.duration.duration();
let id = self.toasts.len();
self.toasts.push_back(toast); self.toasts.push_back(toast);
let on_close = self.on_close;
crate::command::future(async move { crate::command::future(async move {
#[cfg(feature = "tokio")] #[cfg(feature = "tokio")]
tokio::time::sleep(duration).await; tokio::time::sleep(duration).await;
crate::app::Message::App(Message::from(message)) on_close(id)
}) })
} }
/// Handle the [`ToastMessage`] /// Remove a [`Toast`]
pub fn handle_message(&mut self, message: &ToastMessage) { pub fn remove(&mut self, id: usize) {
self.toasts self.toasts.remove(id);
.iter()
.position(|e| e.id == message.0)
.map(|index| self.toasts.remove(index));
} }
} }