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
//! Event stream handling for the yew framework
use std::fmt;

use gloo_events::EventListener;
use std::borrow::Cow;
use wasm_bindgen::JsCast;
use web_sys::{Event, EventSource, MessageEvent};
use yew::callback::Callback;
use yew::format::{FormatError, Text};
use yew::services::Task;

/// A status of an event source connection. Used for status notification.
#[derive(PartialEq, Debug)]
pub enum EventSourceStatus {
    /// Fired when an event source connection was opened.
    Open,
    /// Fired when an event source connection had an error.
    Error,
}

/// Ready state of an event source
///
/// [Documented at MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/readyState)
#[derive(PartialEq, Debug)]
pub enum ReadyState {
    /// The event source connection is connecting.
    Connecting,
    /// The event source connection is open.
    Open,
    /// The event source connection is closed.
    Closed,
}

/// A handle to control current event source connection. Implements `Task` and could be canceled.
pub struct EventSourceTask {
    event_source: EventSource,
    // We need to keep this else it is cleaned up on drop.
    _notification: Callback<EventSourceStatus>,
    listeners: Vec<EventListener>,
}

impl EventSourceTask {
    #![allow(clippy::unnecessary_wraps)]
    fn new(
        event_source: EventSource,
        notification: Callback<EventSourceStatus>,
    ) -> Result<EventSourceTask, &'static str> {
        Ok(EventSourceTask {
            event_source,
            _notification: notification,
            listeners: vec![],
        })
    }

    fn add_unwrapped_event_listener<S, F>(&mut self, event_type: S, callback: F)
    where
        S: Into<Cow<'static, str>>,
        F: FnMut(&Event) + 'static,
    {
        self.listeners
            .push(EventListener::new(&self.event_source, event_type, callback));
    }

    /// Register a callback for events of a given type
    ///
    /// This registers an event listener, which will fire `callback` when an
    /// event of `event_type` occurs.
    pub fn add_event_listener<S, OUT: 'static>(&mut self, event_type: S, callback: Callback<OUT>)
    where
        S: Into<Cow<'static, str>>,
        OUT: From<Text>,
    {
        // This will convert from a generic `Event` into a `MessageEvent` taking
        // text, as is required by an event source.
        let wrapped_callback = move |event: &Event| {
            let event = event.dyn_ref::<MessageEvent>().unwrap();
            let text = event.data().as_string();

            let data = if let Some(text) = text {
                Ok(text)
            } else {
                Err(FormatError::ReceivedBinaryForText.into())
            };

            let out = OUT::from(data);
            callback.emit(out);
        };
        self.add_unwrapped_event_listener(event_type, wrapped_callback);
    }

    /// Query the ready state of the event source.
    pub fn ready_state(&self) -> ReadyState {
        match self.event_source.ready_state() {
            web_sys::EventSource::CONNECTING => ReadyState::Connecting,
            web_sys::EventSource::OPEN => ReadyState::Open,
            web_sys::EventSource::CLOSED => ReadyState::Closed,
            _ => panic!("unexpected ready state"),
        }
    }
}

impl fmt::Debug for EventSourceTask {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("EventSourceTask")
    }
}

/// An event source service attached to a user context.
#[derive(Default, Debug)]
pub struct EventSourceService {}

impl EventSourceService {
    /// Creates a new service instance.
    pub fn new() -> Self {
        Self {}
    }

    /// Connects to a server at `url` by an event source connection.
    ///
    /// The `notification` callback is fired when either an open or error event
    /// happens.
    pub fn connect(
        &mut self,
        url: &str,
        notification: Callback<EventSourceStatus>,
    ) -> Result<EventSourceTask, &str> {
        let event_source = EventSource::new(url);
        if event_source.is_err() {
            return Err("Failed to created event source with given URL");
        }

        let event_source = event_source.map_err(|_| "failed to build event source")?;

        let notify = notification.clone();
        let listener_open = move |_: &Event| {
            notify.emit(EventSourceStatus::Open);
        };
        let notify = notification.clone();
        let listener_error = move |_: &Event| {
            notify.emit(EventSourceStatus::Error);
        };

        let mut result = EventSourceTask::new(event_source, notification)?;
        result.add_unwrapped_event_listener("open", listener_open);
        result.add_unwrapped_event_listener("error", listener_error);
        Ok(result)
    }
}

impl Task for EventSourceTask {
    fn is_active(&self) -> bool {
        self.ready_state() == ReadyState::Open
    }
}

impl Drop for EventSourceTask {
    fn drop(&mut self) {
        if self.is_active() {
            self.event_source.close()
        }
    }
}