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
use super::super::{
url,
util::{self, ClosureNew},
Url,
};
use std::convert::{identity, TryFrom, TryInto};
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
pub fn push_route<U: Into<Url>>(url: U) -> Url {
let url = url.into();
let data =
JsValue::from_str(&serde_json::to_string(&url).expect("Problem serializing route data"));
let title = match &url.title {
Some(t) => t,
None => "",
};
let mut path = String::from("/") + &url.path.join("/");
if let Some(search) = &url.search {
path = path + "?" + search;
}
if let Some(hash) = &url.hash {
path = path + "#" + hash;
}
util::history()
.push_state_with_url(&data, title, Some(&path))
.expect("Problem pushing state");
url
}
pub fn setup_popstate_listener<Ms>(
update: impl Fn(Ms) + 'static,
updated_listener: impl Fn(Closure<dyn FnMut(web_sys::Event)>) + 'static,
routes: fn(Url) -> Option<Ms>,
) where
Ms: 'static,
{
let closure = Closure::new(move |ev: web_sys::Event| {
let ev = ev
.dyn_ref::<web_sys::PopStateEvent>()
.expect("Problem casting as Popstate event");
let url = match ev.state().as_string() {
Some(state_str) => {
serde_json::from_str(&state_str).expect("Problem deserializing popstate state")
}
None => url::current(),
};
if let Some(routing_msg) = routes(url) {
update(routing_msg);
}
});
(util::window().as_ref() as &web_sys::EventTarget)
.add_event_listener_with_callback("popstate", closure.as_ref().unchecked_ref())
.expect("Problem adding popstate listener");
updated_listener(closure);
}
pub fn setup_hashchange_listener<Ms>(
update: impl Fn(Ms) + 'static,
updated_listener: impl Fn(Closure<dyn FnMut(web_sys::Event)>) + 'static,
routes: fn(Url) -> Option<Ms>,
) where
Ms: 'static,
{
let closure = Closure::new(move |ev: web_sys::Event| {
let ev = ev
.dyn_ref::<web_sys::HashChangeEvent>()
.expect("Problem casting as hashchange event");
let url: Url = ev
.new_url()
.try_into()
.expect("cast hashchange event url to `Url`");
if let Some(routing_msg) = routes(url) {
update(routing_msg);
}
});
(util::window().as_ref() as &web_sys::EventTarget)
.add_event_listener_with_callback("hashchange", closure.as_ref().unchecked_ref())
.expect("Problem adding hashchange listener");
updated_listener(closure);
}
#[allow(clippy::option_map_unit_fn)]
pub fn setup_link_listener<Ms>(update: impl Fn(Ms) + 'static, routes: fn(Url) -> Option<Ms>)
where
Ms: 'static,
{
let closure = Closure::new(move |event: web_sys::Event| {
event.target()
.and_then(|et| et.dyn_into::<web_sys::Element>().ok())
.and_then(|el| el.closest("[href]").ok())
.and_then(identity)
.and_then(|href_el| match href_el.tag_name().as_str() {
"Base" | "Link" => None,
_ => Some(href_el)
})
.and_then(|href_el| href_el.get_attribute("href"))
.and_then(|href| {
if href.is_empty() || href.starts_with('/') {
Some(href)
} else {
None
}
})
.map(|href| {
if href.is_empty() {
event.prevent_default();
} else {
let url = Url::try_from(href).expect("cast link href to `Url`");
if let Some(redirect_msg) = routes(url.clone()) {
push_route(url);
event.prevent_default();
update(redirect_msg);
}
}
});
});
(util::document().as_ref() as &web_sys::EventTarget)
.add_event_listener_with_callback("click", closure.as_ref().unchecked_ref())
.expect("Problem setting up link interceptor");
closure.forget();
}
#[cfg(test)]
mod tests {
use wasm_bindgen_test::*;
use super::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn parse_url_simple() {
let expected = Url {
path: vec!["path1".into(), "path2".into()],
hash: None,
search: None,
title: None,
};
let actual: Url = "/path1/path2".to_string().try_into().unwrap();
assert_eq!(expected, actual)
}
#[wasm_bindgen_test]
fn parse_url_with_hash_search() {
let expected = Url {
path: vec!["path".into()],
hash: Some("hash".into()),
search: Some("search=query".into()),
title: None,
};
let actual: Url = "/path?search=query#hash".to_string().try_into().unwrap();
assert_eq!(expected, actual)
}
#[wasm_bindgen_test]
fn parse_url_with_hash_only() {
let expected = Url {
path: vec!["path".into()],
hash: Some("hash".into()),
search: None,
title: None,
};
let actual: Url = "/path#hash".to_string().try_into().unwrap();
assert_eq!(expected, actual)
}
#[wasm_bindgen_test]
fn parse_url_with_hash_routing() {
let expected = Url {
path: vec!["".into()],
hash: Some("/discover".into()),
search: None,
title: None,
};
let actual: Url = "/#/discover".to_string().try_into().unwrap();
assert_eq!(expected, actual)
}
}