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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use crate::{Action, Alert, AlertGroup, Type};

use chrono::{DateTime, Utc};
use core::cmp::Reverse;
use std::collections::BinaryHeap;
use std::{collections::HashSet, time::Duration};
use yew::prelude::*;
use yew::services::timeout::*;
use yew::worker::*;
use yew::{agent::Dispatcher, utils::window, virtual_dom::VChild};

/// Toasts are small alerts that get shown on the top right corner of the page.
///
/// A toast can be triggered by every component. The toast fill get sent to an agent, the Toaster.
/// The toaster will delegate displaying the toast to an instance of a ToastViewer component.
///
/// In order for Toasts to be displayed your application must have exactly one [ToastViewer](`ToastViewer`) **before**
/// creating the first Toast.
///
/// For example:
/// ```
/// # use yew::prelude::*;
/// # use patternfly_yew::*;
/// pub struct App{
///   link: ComponentLink<Self>
/// };
/// pub enum Msg {
///   Toast(Toast),
/// }
/// # impl Component for App {
/// type Message = Msg;
/// # type Properties = ();
/// # fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
/// #   unimplemented!()
/// # }
///
/// fn update(&mut self, msg: Self::Message) -> bool {
///   match msg {
///     Msg::Toast(toast) => {
///       ToastDispatcher::new().toast(toast);
///       false
///     }
///   }
/// }
///
/// # fn change(&mut self,_props: Self::Properties) -> bool {
/// #   unimplemented!()
/// # }
///
/// fn view(&self) -> Html {
///  html!{
///     <>
///       <ToastViewer/>
///       <div>
///         <button onclick=self.link.callback(|_|{
///             Msg::Toast("Toast Title".into())
///         })>
///           { "Click me" }  
///         </button>
///       </div>
///     </>
///   }
/// }
/// # }
/// ```
#[derive(Clone, Debug, Default)]
pub struct Toast {
    pub title: String,
    pub r#type: Type,
    /// The timeout when the toast will be removed automatically.
    ///
    /// If no timeout is set, the toast will get a close button.
    pub timeout: Option<Duration>,
    pub body: Html,
    pub actions: Vec<Action>,
}

/// Allows to convert a string into a toast by using the string as title.
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),
}

/// An agent for displaying toasts.
pub struct Toaster {
    link: AgentLink<Self>,
    /// The toast viewer.
    ///
    /// While we can handle more than one, we will only send toasts to one viewer. Registering
    /// more than one viewer will produce unexpected results.
    viewer: HashSet<HandlerId>,
}

impl Agent for Toaster {
    type Reach = Context<Self>;
    type Message = ();
    type Input = ToasterRequest;
    type Output = ToastAction;

    fn create(link: AgentLink<Self>) -> Self {
        Self {
            link,
            viewer: HashSet::new(),
        }
    }

    fn update(&mut self, _: Self::Message) {}

    fn connected(&mut self, id: HandlerId) {
        if id.is_respondable() {
            self.viewer.insert(id);
        }
    }

    fn handle_input(&mut self, msg: Self::Input, _: HandlerId) {
        match msg {
            ToasterRequest::Toast(msg) => {
                self.show_toast(msg);
            }
        }
    }

    fn disconnected(&mut self, id: HandlerId) {
        if id.is_respondable() {
            self.viewer.remove(&id);
        }
    }
}

impl Toaster {
    fn show_toast(&self, toast: Toast) {
        let viewer = self.viewer.iter().next();
        if let Some(viewer) = viewer {
            self.link.respond(*viewer, ToastAction::ShowToast(toast));
        } else {
            window()
                .alert_with_message(&format!(
                    "Dropped toast. No toast component registered. Message was: {}",
                    toast.title
                ))
                .ok();
        }
    }
}

/// Client to the toast agent which can be used to request toasts.
pub struct ToastDispatcher(Dispatcher<Toaster>);

impl ToastDispatcher {
    pub fn new() -> Self {
        ToastDispatcher(Toaster::dispatcher())
    }

    /// Request a toast from the toast agent.
    pub fn toast(&mut self, toast: Toast) {
        self.0.send(ToasterRequest::Toast(toast))
    }
}

impl Default for ToastDispatcher {
    fn default() -> Self {
        Self::new()
    }
}

/// A client for implementing a toast viewer.
///
/// This is used by the (ToastViewer)[`ToastViewer`]. It is only needed if you want to implement
/// your own toast viewer.
pub struct ToastBridge(Box<dyn Bridge<Toaster>>);

impl ToastBridge {
    pub fn new(callback: Callback<<Toaster as Agent>::Output>) -> Self {
        let router_agent = Toaster::bridge(callback);
        ToastBridge(router_agent)
    }
}

#[derive(Clone, PartialEq, Properties)]
pub struct Props {}

pub struct ToastEntry {
    id: usize,
    alert: VChild<Alert>,
    timeout: Option<DateTime<Utc>>,
}

/// A component to view toast alerts.
///
/// Exactly one instance is required in your page in order to actually show the toasts. The instance
/// must be on the body level of the HTML document.
pub struct ToastViewer {
    props: Props,
    link: ComponentLink<Self>,
    alerts: Vec<ToastEntry>,
    _bridge: ToastBridge,
    counter: usize,

    task: Option<TimeoutTask>,
    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(props: Self::Properties, link: ComponentLink<Self>) -> Self {
        let bridge = ToastBridge::new(link.callback(|action| ToastViewerMsg::Perform(action)));
        Self {
            props,
            link,
            _bridge: bridge,
            alerts: Vec::new(),
            counter: 0,
            task: None,
            timeouts: BinaryHeap::new(),
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            ToastViewerMsg::Perform(action) => self.perform(action),
            ToastViewerMsg::Cleanup => self.cleanup(),
            ToastViewerMsg::Close(id) => self.remove_toast(id),
        }
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        if self.props != props {
            self.props = props;
            true
        } else {
            false
        }
    }

    fn view(&self) -> Html {
        html! {
            <AlertGroup toast=true>
                { for self.alerts.iter().map(|entry|entry.alert.clone()) }
            </AlertGroup>
        }
    }
}

impl ToastViewer {
    fn now() -> DateTime<Utc> {
        Utc::now()
    }

    fn perform(&mut self, action: ToastAction) -> ShouldRender {
        match action {
            ToastAction::ShowToast(toast) => self.add_toast(toast),
        }
        true
    }

    fn add_toast(&mut 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(self.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(timeout);
        }
    }

    fn schedule_cleanup(&mut self, timeout: DateTime<Utc>) {
        log::debug!("Schedule cleanup: {:?}", timeout);

        self.timeouts.push(Reverse(timeout));
        self.trigger_next_cleanup();
    }

    fn trigger_next_cleanup(&mut self) {
        if self.task.is_some() {
            log::debug!("Already have a task");
            return;
        }

        // We poll timeouts from the heap until we find one that is in the future, or we run
        // out of candidates.
        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 {
                self.task = Some(TimeoutService::spawn(
                    duration,
                    self.link.callback(|_| ToastViewerMsg::Cleanup),
                ));
                log::debug!("Scheduled cleanup: {:?}", duration);
                break;
            }
        }
    }

    fn remove_toast(&mut self, id: usize) -> ShouldRender {
        self.retain_alert(|entry| entry.id != id)
    }

    fn cleanup(&mut self) -> ShouldRender {
        self.task = None;
        self.trigger_next_cleanup();

        let now = Self::now();

        self.retain_alert(|alert| {
            if let Some(timeout) = alert.timeout {
                timeout > now
            } else {
                true
            }
        })
    }

    fn retain_alert<F>(&mut self, f: F) -> ShouldRender
    where
        F: Fn(&ToastEntry) -> bool,
    {
        let before = self.alerts.len();
        self.alerts.retain(f);
        before != self.alerts.len()
    }
}