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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use crate::{Action, Alert, AlertGroup, Type};
use chrono::{DateTime, Utc};
use core::cmp::Reverse;
use gloo_timers::callback::Timeout;
use std::{collections::BinaryHeap, time::Duration};
use yew::{prelude::*, virtual_dom::VChild};
#[derive(Clone, Debug, Default)]
pub struct Toast {
pub title: String,
pub r#type: Type,
pub timeout: Option<Duration>,
pub body: Html,
pub actions: Vec<Action>,
}
impl<S: ToString> From<S> for Toast {
fn from(message: S) -> Self {
Toast {
title: message.to_string(),
timeout: None,
body: Default::default(),
r#type: Default::default(),
actions: Vec::new(),
}
}
}
#[doc(hidden)]
#[derive(Debug)]
pub enum ToasterRequest {
Toast(Toast),
}
#[doc(hidden)]
pub enum ToastAction {
ShowToast(Toast),
}
#[derive(Clone, PartialEq)]
pub struct Toaster {
callback: Callback<ToastAction>,
}
impl Toaster {
pub fn toast(&self, toast: Toast) {
self.callback.emit(ToastAction::ShowToast(toast))
}
}
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
pub children: Children,
}
pub struct ToastEntry {
id: usize,
alert: VChild<Alert>,
timeout: Option<DateTime<Utc>>,
}
pub struct ToastViewer {
context: Toaster,
alerts: Vec<ToastEntry>,
counter: usize,
task: Option<Timeout>,
timeouts: BinaryHeap<Reverse<DateTime<Utc>>>,
}
pub enum ToastViewerMsg {
Perform(ToastAction),
Cleanup,
Close(usize),
}
impl Component for ToastViewer {
type Message = ToastViewerMsg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let context = Toaster {
callback: ctx.link().callback(ToastViewerMsg::Perform),
};
Self {
context,
alerts: Vec::new(),
counter: 0,
task: None,
timeouts: BinaryHeap::new(),
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
ToastViewerMsg::Perform(action) => self.perform(ctx, action),
ToastViewerMsg::Cleanup => self.cleanup(ctx),
ToastViewerMsg::Close(id) => self.remove_toast(id),
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let context = self.context.clone();
html! {
<ContextProvider<Toaster> {context}>
<AlertGroup toast=true>
{ for self.alerts.iter().map(|entry|entry.alert.clone()) }
</AlertGroup>
{ for ctx.props().children.iter() }
</ContextProvider<Toaster>>
}
}
}
impl ToastViewer {
fn now() -> DateTime<Utc> {
Utc::now()
}
fn perform(&mut self, ctx: &Context<Self>, action: ToastAction) -> bool {
match action {
ToastAction::ShowToast(toast) => self.add_toast(ctx, toast),
}
true
}
fn add_toast(&mut self, ctx: &Context<Self>, toast: Toast) {
let now = Self::now();
let timeout = toast
.timeout
.and_then(|timeout| chrono::Duration::from_std(timeout).ok())
.map(|timeout| now + timeout);
let id = self.counter;
self.counter += 1;
let onclose = match toast.timeout {
None => Some(ctx.link().callback(move |_| ToastViewerMsg::Close(id))),
Some(_) => None,
};
self.alerts.push(ToastEntry {
id,
alert: html_nested! {
<Alert r#type={toast.r#type} title={toast.title} onclose={onclose} actions={toast.actions}>
{ toast.body }
</Alert>
},
timeout,
});
if let Some(timeout) = timeout {
self.schedule_cleanup(ctx, timeout);
}
}
fn schedule_cleanup(&mut self, ctx: &Context<Self>, timeout: DateTime<Utc>) {
log::debug!("Schedule cleanup: {:?}", timeout);
self.timeouts.push(Reverse(timeout));
self.trigger_next_cleanup(ctx);
}
fn trigger_next_cleanup(&mut self, ctx: &Context<Self>) {
if self.task.is_some() {
log::debug!("Already have a task");
return;
}
while let Some(next) = self.timeouts.pop() {
let timeout = next.0;
log::debug!("Next timeout: {:?}", timeout);
let duration = timeout - Self::now();
let duration = duration.to_std();
log::debug!("Duration: {:?}", duration);
if let Ok(duration) = duration {
let link = ctx.link().clone();
self.task = Some(Timeout::new(duration.as_millis() as u32, move || {
link.send_message(ToastViewerMsg::Cleanup);
}));
log::debug!("Scheduled cleanup: {:?}", duration);
break;
}
}
}
fn remove_toast(&mut self, id: usize) -> bool {
self.retain_alert(|entry| entry.id != id)
}
fn cleanup(&mut self, ctx: &Context<Self>) -> bool {
let now = Self::now();
self.task = None;
self.trigger_next_cleanup(ctx);
self.retain_alert(|alert| {
if let Some(timeout) = alert.timeout {
timeout > now
} else {
true
}
})
}
fn retain_alert<F>(&mut self, f: F) -> bool
where
F: Fn(&ToastEntry) -> bool,
{
let before = self.alerts.len();
self.alerts.retain(f);
before != self.alerts.len()
}
}
#[hook]
pub fn use_toaster() -> Option<Toaster> {
use_context()
}