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
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;
#[derive(PartialEq, Debug)]
pub enum EventSourceStatus {
Open,
Error,
}
#[derive(PartialEq, Debug)]
pub enum ReadyState {
Connecting,
Open,
Closed,
}
pub struct EventSourceTask {
event_source: EventSource,
_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));
}
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>,
{
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);
}
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")
}
}
#[derive(Default, Debug)]
pub struct EventSourceService {}
impl EventSourceService {
pub fn new() -> Self {
Self {}
}
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()
}
}
}