1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright 2024 wiiznokes
// SPDX-License-Identifier: MPL-2.0

//! A widget that displays toasts.

use std::collections::VecDeque;
use std::rc::Rc;

use crate::widget::container;
use crate::widget::Column;
use iced::{Padding, Task};
use iced_core::Element;
use slotmap::new_key_type;
use slotmap::SlotMap;
use widget::Toaster;

use crate::ext::CollectionWidget;

use super::column;
use super::{button, icon, row, text};

mod widget;

/// Create a new Toaster widget.
pub fn toaster<'a, Message: Clone + 'static>(
    toasts: &'a Toasts<Message>,
    content: impl Into<Element<'a, Message, crate::Theme, iced::Renderer>>,
) -> Element<'a, Message, crate::Theme, iced::Renderer> {
    let theme = crate::theme::active();
    let cosmic_theme::Spacing {
        space_xxxs,
        space_xxs,
        space_s,
        space_m,
        ..
    } = theme.cosmic().spacing;

    let make_toast = move |(id, toast): (ToastId, &'a Toast<Message>)| {
        let row = row()
            .push(text(&toast.message))
            .push(
                row()
                    .push_maybe(toast.action.as_ref().map(|action| {
                        button::text(&action.description).on_press((action.message)(id))
                    }))
                    .push(
                        button::icon(icon::from_name("window-close-symbolic"))
                            .on_press((toasts.on_close)(id)),
                    )
                    .align_y(iced::Alignment::Center)
                    .spacing(space_xxs),
            )
            .align_y(iced::Alignment::Center)
            .spacing(space_s);

        container(row)
            .padding([space_xxs, space_s, space_xxs, space_m])
            .class(crate::style::Container::Tooltip)
    };

    let col = toasts
        .queue
        .iter()
        .filter_map(|id| Some((*id, toasts.toasts.get(*id)?)))
        .rev()
        .map(make_toast)
        .fold(column::with_capacity(toasts.toasts.len()), Column::push)
        .spacing(space_xxxs);

    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 Duration {
    #[default]
    Short,
    Long,
    Custom(std::time::Duration),
}

impl Duration {
    #[cfg(feature = "tokio")]
    fn duration(&self) -> std::time::Duration {
        match self {
            Duration::Short => std::time::Duration::from_millis(5000),
            Duration::Long => std::time::Duration::from_millis(15000),
            Duration::Custom(duration) => *duration,
        }
    }
}

impl From<std::time::Duration> for Duration {
    fn from(value: std::time::Duration) -> Self {
        Self::Custom(value)
    }
}

/// Action that can be triggered by the user.
///
/// Example: `undo`
#[derive(Clone)]
pub struct Action<Message> {
    pub description: String,
    pub message: Rc<dyn Fn(ToastId) -> Message>,
}

impl<Message> std::fmt::Debug for Action<Message> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Action")
            .field("description", &self.description)
            .finish()
    }
}

/// Represent the data used to display a [`Toast`]
#[derive(Debug, Clone)]
pub struct Toast<Message> {
    message: String,
    action: Option<Action<Message>>,
    duration: Duration,
}

impl<Message> Toast<Message> {
    /// Construct a new [`Toast`] with the provided message.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            action: None,
            duration: Duration::default(),
        }
    }

    /// Set the [`Action`] of this [`Toast`]
    #[must_use]
    pub fn action(
        mut self,
        description: String,
        message: impl Fn(ToastId) -> Message + 'static,
    ) -> Self {
        self.action.replace(Action {
            description,
            message: Rc::new(message),
        });
        self
    }

    /// Set the [`Duration`] of this [`Toast`]
    #[must_use]
    pub fn duration(mut self, duration: impl Into<Duration>) -> Self {
        self.duration = duration.into();
        self
    }
}

new_key_type! { pub struct ToastId; }

#[derive(Debug, Clone)]
pub struct Toasts<Message> {
    toasts: SlotMap<ToastId, Toast<Message>>,
    queue: VecDeque<ToastId>,
    on_close: fn(ToastId) -> Message,
    limit: usize,
}

impl<Message: Clone + Send + 'static> Toasts<Message> {
    pub fn new(on_close: fn(ToastId) -> Message) -> Self {
        let limit = 5;
        Self {
            toasts: SlotMap::with_capacity_and_key(limit),
            queue: VecDeque::new(),
            on_close,
            limit,
        }
    }

    /// Add a new [`Toast`]
    pub fn push(&mut self, toast: Toast<Message>) -> Task<Message> {
        while self.toasts.len() >= self.limit {
            self.toasts.remove(
                self.queue
                    .pop_front()
                    .expect("Queue must contain all toast ids"),
            );
        }

        #[cfg(feature = "tokio")]
        let duration = toast.duration.duration();

        let id = self.toasts.insert(toast);
        self.queue.push_back(id);

        #[cfg(feature = "tokio")]
        {
            let on_close = self.on_close;
            crate::task::future(async move {
                tokio::time::sleep(duration).await;
                on_close(id)
            })
        }
        #[cfg(not(feature = "tokio"))]
        {
            Task::none()
        }
    }

    /// Remove a [`Toast`]
    pub fn remove(&mut self, id: ToastId) {
        self.toasts.remove(id);
        if let Some(pos) = self.queue.iter().position(|key| *key == id) {
            self.queue.remove(pos);
        }
    }
}