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
use failure::Fallible;
use serde::{Deserialize, Serialize};
use std::{collections::HashSet, fmt::Debug, marker::PhantomData};
use stdweb::{
js,
unstable::TryFrom,
web::{event::PopStateEvent, window, EventListenerHandle, History, IEventTarget, Location},
JsSerialize, Value,
};
use yew::{callback::Callback, prelude::worker::*};
pub struct RouterService<T> {
history: History,
location: Location,
event_listener: Option<EventListenerHandle>,
phantom_data: PhantomData<T>,
}
impl<T> RouterService<T>
where
T: JsSerialize + Clone + TryFrom<Value> + 'static,
{
pub fn new() -> RouterService<T> {
let location = window()
.location()
.expect("browser does not support location API");
Self {
history: window().history(),
location,
event_listener: None,
phantom_data: PhantomData,
}
}
pub fn register_callback(&mut self, callback: Callback<()>) {
self.event_listener =
Some(window().add_event_listener(move |_event: PopStateEvent| callback.emit(())));
}
pub fn set_route(&mut self, route: &str, state: T) {
self.history.push_state(state, "", Some(route));
}
fn get_route_from_location(location: &Location) -> String {
let path = location.pathname().unwrap_or_else(|_| "".to_owned());
let query = location.search().unwrap_or_else(|_| "".to_owned());
let fragment = location.hash().unwrap_or_else(|_| "".to_owned());
format!(
"{path}{query}{fragment}",
path = path,
query = query,
fragment = fragment
)
}
pub fn get_route(&self) -> String {
Self::get_route_from_location(&self.location)
}
pub fn get_path(&self) -> Fallible<String> {
Ok(self.location.pathname()?)
}
pub fn get_query(&self) -> Fallible<String> {
Ok(self.location.search()?)
}
pub fn get_fragment(&self) -> Fallible<String> {
Ok(self.location.hash()?)
}
pub fn get_state(&self) -> T
where
T: Default,
{
T::try_from(js! { return history.state; }).unwrap_or_default()
}
}
impl<T> Default for RouterService<T>
where
T: JsSerialize + Clone + TryFrom<Value> + 'static,
{
fn default() -> Self {
RouterService::new()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Route<T> {
pub path_segments: Vec<String>,
pub query: Option<String>,
pub fragment: Option<String>,
pub state: T,
}
impl<T> Route<T>
where
T: JsSerialize + Clone + TryFrom<Value> + Default + 'static,
{
pub fn to_route_string(&self) -> String {
let path = self.path_segments.join("/");
let mut path = format!("/{}", path);
if let Some(ref query) = self.query {
path = format!("{}?{}", path, query);
}
if let Some(ref fragment) = self.fragment {
path = format!("{}#{}", path, fragment)
}
path
}
pub fn current_route(route_service: &RouterService<T>) -> Fallible<Self> {
let path = route_service.get_path()?;
let mut path_segments: Vec<String> = path.split('/').map(String::from).collect();
path_segments.remove(0);
let mut query: String = route_service.get_query()?;
let query: Option<String> = if query.len() > 1 {
query.remove(0);
Some(query)
} else {
None
};
let mut fragment: String = route_service.get_fragment()?;
let fragment: Option<String> = if fragment.len() > 1 {
fragment.remove(0);
Some(fragment)
} else {
None
};
Ok(Route {
path_segments,
query,
fragment,
state: route_service.get_state(),
})
}
}
pub enum Message {
BrowserNavigationRouteChanged(()),
}
impl<T> Transferable for Route<T> where for<'de> T: Serialize + Deserialize<'de> {}
#[derive(Serialize, Deserialize, Debug)]
pub enum Request<T> {
ChangeRoute(Route<T>),
GetCurrentRoute,
}
impl<T> Transferable for Request<T> where for<'de> T: Serialize + Deserialize<'de> {}
pub struct RouterAgent<T>
where
for<'de> T: JsSerialize
+ Clone
+ Debug
+ TryFrom<Value>
+ Default
+ Serialize
+ Deserialize<'de>
+ 'static,
{
link: AgentLink<RouterAgent<T>>,
route_service: RouterService<T>,
subscribers: HashSet<HandlerId>,
}
impl<T> Agent for RouterAgent<T>
where
for<'de> T: JsSerialize
+ Clone
+ Debug
+ TryFrom<Value>
+ Default
+ Serialize
+ Deserialize<'de>
+ 'static,
{
type Input = Request<T>;
type Message = Message;
type Output = Route<T>;
type Reach = Context;
fn create(link: AgentLink<Self>) -> Self {
let callback = link.send_back(Message::BrowserNavigationRouteChanged);
let mut route_service = RouterService::default();
route_service.register_callback(callback);
Self {
link,
route_service,
subscribers: HashSet::new(),
}
}
fn update(&mut self, msg: Self::Message) {
match msg {
Message::BrowserNavigationRouteChanged(()) => {
if let Ok(route) = Route::current_route(&self.route_service) {
for sub in &self.subscribers {
self.link.response(*sub, route.clone());
}
}
}
}
}
fn handle(&mut self, msg: Self::Input, who: HandlerId) {
match msg {
Request::ChangeRoute(route) => {
let route_string: String = route.to_route_string();
self.route_service.set_route(&route_string, route.state);
if let Ok(route) = Route::current_route(&self.route_service) {
for sub in &self.subscribers {
self.link.response(*sub, route.clone());
}
}
}
Request::GetCurrentRoute => {
if let Ok(route) = Route::current_route(&self.route_service) {
self.link.response(who, route.clone());
}
}
}
}
fn connected(&mut self, id: HandlerId) {
self.subscribers.insert(id);
}
fn disconnected(&mut self, id: HandlerId) {
self.subscribers.remove(&id);
}
}