final impl

This commit is contained in:
wiiznokes 2024-06-28 00:23:22 +02:00
parent d76911c294
commit 2dff73b8b2
3 changed files with 129 additions and 42 deletions

View file

@ -350,6 +350,4 @@ pub mod warning;
#[doc(inline)] #[doc(inline)]
pub use warning::*; pub use warning::*;
mod toaster; pub mod toaster;
#[doc(inline)]
pub use toaster::toaster;

View file

@ -1,11 +1,14 @@
// Copyright 2024 wiiznokes // Copyright 2024 wiiznokes
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//! A widget that display toats.
use std::collections::VecDeque;
use std::time::Duration; use std::time::Duration;
use crate::widget::container; use crate::widget::container;
use crate::widget::Column; use crate::widget::Column;
use iced::{Command, Length}; use iced::Command;
use iced_core::Element; use iced_core::Element;
use widget::Toaster; use widget::Toaster;
@ -15,81 +18,155 @@ use super::{button, row, text};
mod widget; mod widget;
/// Create a new Toaster widget.
pub fn toaster<'a, Message>( pub fn toaster<'a, Message>(
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 where
Message: Clone + 'a, Message: From<ToastMessage> + Clone + 'a,
{ {
let make_toast = |toast: &'a Toast<Message>| { let make_toast = |toast: &'a Toast<Message>| {
let row = row().push(text(&toast.message)).push_maybe( let row = row()
toast .push(text(&toast.message))
.action .push_maybe(toast.action.as_ref().map(|action| {
.as_ref() button(text(action.description.clone())).on_press(action.message.clone())
.map(|t| button(text(t.0.clone())).on_press(t.1.clone())), }))
); .push(button("close").on_press(ToastMessage(toast.id).into()))
.align_items(iced::Alignment::Center);
container(row).into() container(row)
.padding(10)
.style(crate::style::Container::Card)
}; };
let col = Column::with_children(toasts.toasts.iter().map(make_toast)); let col =
Column::with_children(toasts.toasts.iter().rev().map(|t| make_toast(t).into())).spacing(5);
Toaster::new(col.into(), content.into(), toasts.toasts.is_empty()).into() Toaster::new(col.into(), content.into(), toasts.toasts.is_empty()).into()
} }
/// Duration for the [`Toast`]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum ToastDuration { pub enum ToastDuration {
#[default]
Short, Short,
Medium,
Long, Long,
Custom(Duration),
} }
impl ToastDuration { impl ToastDuration {
fn duration(&self) -> Duration { fn duration(&self) -> Duration {
match self { match self {
ToastDuration::Short => Duration::from_millis(200), ToastDuration::Short => Duration::from_millis(2000),
ToastDuration::Medium => Duration::from_millis(1000), ToastDuration::Long => Duration::from_millis(3500),
ToastDuration::Long => Duration::from_millis(5000), ToastDuration::Custom(duration) => *duration,
} }
} }
} }
impl From<Duration> for ToastDuration {
fn from(value: Duration) -> Self {
Self::Custom(value)
}
}
/// Action that can be triggered by the user.
///
/// Example: `undo`
#[derive(Debug, Clone)]
pub struct ToastAction<Message> {
pub description: String,
pub message: Message,
}
/// Represent the data used to display a [`Toast`]
#[derive(Debug, Clone)]
pub struct Toast<Message> { pub struct Toast<Message> {
message: String, message: String,
/// (Description, message) action: Option<ToastAction<Message>>,
action: Option<(String, Message)>,
duration: ToastDuration, duration: ToastDuration,
id: u32, id: u32,
} }
pub struct Toasts<Message> { impl<Message> Toast<Message> {
id_count: u32, /// Construct a new [`Toast`] with the provided message.
toasts: Vec<Toast<Message>>, pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
action: None,
duration: ToastDuration::default(),
id: 0,
}
} }
/// Set the [`ToastAction`] of this [`Toast`]
#[must_use]
pub fn action(mut self, action: ToastAction<Message>) -> Self {
self.action.replace(action);
self
}
/// Set the [`ToastDuration`] of this [`Toast`]
#[must_use]
pub fn duration(mut self, duration: impl Into<ToastDuration>) -> Self {
self.duration = duration.into();
self
}
}
#[derive(Debug, Clone)]
pub struct Toasts<Message> {
id_count: u32,
toasts: VecDeque<Toast<Message>>,
limit: usize,
}
// need custom impl to not require Message: Clone
impl<M> Default for Toasts<M> {
fn default() -> Self {
Self {
id_count: 0,
toasts: VecDeque::new(),
limit: 5,
}
}
}
#[derive(Debug, Clone)]
pub struct ToastMessage(u32); pub struct ToastMessage(u32);
impl<Message> Toasts<Message> { impl<Message> Toasts<Message> {
pub fn push(&mut self, mut toast: Toast<Message>) -> Command<ToastMessage> { /// Add a new [`Toast`]
pub fn push(
&mut self,
mut toast: Toast<Message>,
) -> Command<crate::app::message::Message<Message>>
where
Message: From<ToastMessage>,
{
while self.toasts.len() >= self.limit {
self.toasts.pop_front();
}
toast.id = self.id_count; toast.id = self.id_count;
self.id_count += 1; self.id_count += 1;
let message = ToastMessage(toast.id); let message = ToastMessage(toast.id);
let duration = toast.duration.duration(); let duration = toast.duration.duration();
self.toasts.push(toast); self.toasts.push_back(toast);
Command::perform( Command::perform(
async move { async move {
tokio::time::sleep(duration).await; tokio::time::sleep(duration).await;
}, },
|_| message, |_| crate::app::Message::App(message.into()),
) )
} }
pub fn handle_message(&mut self, message: ToastMessage) { /// Handle the [`ToastMessage`]
pub fn handle_message(&mut self, message: &ToastMessage) {
self.toasts self.toasts
.iter() .iter()
.position(|e| e.id == message.0) .position(|e| e.id == message.0)

View file

@ -3,22 +3,18 @@
use iced::{Limits, Size}; use iced::{Limits, Size};
use iced_core::layout::Node; use iced_core::layout::Node;
use iced_runtime::core::widget::Id;
use iced_runtime::{keyboard, Command};
use iced_core::event::{self, Event}; use iced_core::event::{self, Event};
use iced_core::renderer::{self, Quad, Renderer}; use iced_core::layout;
use iced_core::widget::tree::{self, Tree}; use iced_core::mouse;
use iced_core::overlay;
use iced_core::renderer::{self};
use iced_core::widget::tree::Tree;
use iced_core::widget::Operation; use iced_core::widget::Operation;
use iced_core::Element; use iced_core::Element;
use iced_core::{layout, svg}; use iced_core::Overlay;
use iced_core::{mouse, Border}; use iced_core::{Clipboard, Layout, Length, Point, Rectangle, Shell, Vector, Widget};
use iced_core::{overlay, Shadow}; use iced_renderer::core::widget::OperationOutputWrapper;
use iced_core::{touch, Overlay};
use iced_core::{
Background, Clipboard, Color, Layout, Length, Padding, Point, Rectangle, Shell, Vector, Widget,
};
use iced_renderer::core::widget::{operation, OperationOutputWrapper};
pub struct Toaster<'a, Message, Theme, Renderer> { pub struct Toaster<'a, Message, Theme, Renderer> {
toasts: Element<'a, Message, Theme, Renderer>, toasts: Element<'a, Message, Theme, Renderer>,
@ -145,7 +141,7 @@ where
&'b mut self, &'b mut self,
state: &'b mut Tree, state: &'b mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, _renderer: &Renderer,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
if self.is_empty { if self.is_empty {
None None
@ -189,7 +185,23 @@ where
position: Point, position: Point,
_translation: Vector, _translation: Vector,
) -> Node { ) -> Node {
todo!() let limits = Limits::new(Size::ZERO, bounds);
let mut node = self
.element
.as_widget()
.layout(self.state, renderer, &limits);
let offset = 15.;
let position = Point::new(
(bounds.width / 2.) - (node.size().width / 2.),
bounds.height - (node.size().height + offset),
);
node.move_to_mut(position);
node
} }
fn draw( fn draw(