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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! This module is decoupled / independent.

use crate::util::ClosureNew;
use serde::{Deserialize, Serialize};
use std::convert::identity;
use wasm_bindgen::{closure::Closure, JsCast, JsValue};

/// Repeated here from `seed::util`, to make this module standalone.  Once we have a Gloo module
/// that handles this, use it.
mod util {
    /// Convenience function to avoid repeating expect logic.
    pub fn window() -> web_sys::Window {
        web_sys::window().expect("Can't find the global Window")
    }

    /// Convenience function to access the `web_sys` DOM document.
    pub fn document() -> web_sys::Document {
        window().document().expect("Can't find document")
    }

    /// Convenience function to access `web_sys` history
    pub fn history() -> web_sys::History {
        window().history().expect("Can't find history")
    }
}

/// Contains all information used in pushing and handling routes.
/// Based on [React-Reason's router](https://github.com/reasonml/reason-react/blob/master/docs/router.md).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Url {
    pub path: Vec<String>,
    pub search: Option<String>,
    pub hash: Option<String>,
    pub title: Option<String>,
}

impl Url {
    /// Helper that ignores hash, search and title, and converts path to Strings.
    ///
    /// # Refenences
    /// * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/History_API)
    pub fn new<T: ToString>(path: Vec<T>) -> Self {
        let result = Self {
            path: path.into_iter().map(|p| p.to_string()).collect(),
            hash: None,
            search: None,
            title: None,
        };
        clean_url(result)
    }

    /// Builder-pattern method for defining hash.
    ///
    /// # Refenences
    /// * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash)
    pub fn hash(mut self, hash: &str) -> Self {
        self.hash = Some(hash.into());
        self
    }

    /// Builder-pattern method for defining search.
    ///
    /// # Refenences
    /// * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search)
    pub fn search(mut self, search: &str) -> Self {
        self.search = Some(search.into());
        self
    }

    pub fn title(mut self, title: &str) -> Self {
        self.title = Some(title.into());
        self
    }
}

impl From<String> for Url {
    fn from(s: String) -> Self {
        // This could be done more elegantly with regex, but adding it as a dependency
        // causes a big increase in WASM size.
        let mut path: Vec<String> = s.split('/').map(ToString::to_string).collect();
        if let Some(first) = path.get(0) {
            if first.is_empty() {
                path.remove(0); // Remove a leading empty string.
            }
        }

        // We assume hash and search terms are at the end of the path, and hash comes before search.
        let last = path.pop();

        let mut last_path = String::new();
        let mut hash = String::new();
        let mut search = String::new();

        if let Some(l) = last {
            let mut in_hash = false;
            let mut in_search = false;
            for c in l.chars() {
                if c == '#' {
                    in_hash = true;
                    in_search = false;
                    continue;
                }

                if c == '?' {
                    in_hash = false;
                    in_search = true;
                    continue;
                }

                if in_hash {
                    hash.push(c);
                } else if in_search {
                    search.push(c);
                } else {
                    last_path.push(c);
                }
            }
        }

        // Re-add the pre-`#` and pre-`?` part of the path.
        if !last_path.is_empty() {
            path.push(last_path);
        }

        Self {
            path,
            hash: if hash.is_empty() { None } else { Some(hash) },
            search: if search.is_empty() {
                None
            } else {
                Some(search)
            },
            title: None,
        }
    }
}

impl From<Vec<String>> for Url {
    fn from(path: Vec<String>) -> Self {
        Url::new(path)
    }
}

// todo: Do we need both from Vec<&str> and Vec<String> ?
impl From<Vec<&str>> for Url {
    fn from(path: Vec<&str>) -> Self {
        Url::new(path)
    }
}

/// Get the current url path, without a prepended /
fn get_path() -> String {
    let path = util::window()
        .location()
        .pathname()
        .expect("Can't find pathname");
    path[1..path.len()].to_string() // Remove leading /
}

fn get_hash() -> String {
    util::window()
        .location()
        .hash()
        .expect("Can't find hash")
        .replace("#", "")
}

fn get_search() -> String {
    util::window()
        .location()
        .search()
        .expect("Can't find search")
        .replace("?", "")
}

/// For setting up landing page routing. Unlike normal routing, we can't rely
/// on the popstate state, so must go off path, hash, and search directly.
pub fn initial_url() -> Url {
    let raw_path = get_path();
    let path_ref: Vec<&str> = raw_path.split('/').collect();
    let path: Vec<String> = path_ref.into_iter().map(ToString::to_string).collect();

    let raw_hash = get_hash();
    let hash = match raw_hash.len() {
        0 => None,
        _ => Some(raw_hash),
    };

    let raw_search = get_search();
    let search = match raw_search.len() {
        0 => None,
        _ => Some(raw_search),
    };

    Url {
        path,
        hash,
        search,
        title: None,
    }
}

fn remove_first(s: &str) -> Option<&str> {
    s.chars().next().map(|c| &s[c.len_utf8()..])
}

/// Remove prepended / from all items in the Url's path.
fn clean_url(mut url: Url) -> Url {
    let mut cleaned_path = vec![];
    for part in &url.path {
        if let Some(first) = part.chars().next() {
            if first == '/' {
                cleaned_path.push(remove_first(part).unwrap().to_string());
            } else {
                cleaned_path.push(part.to_string());
            }
        }
    }

    url.path = cleaned_path;
    url
}

/// Add a new route using history's `push_state` method.
///
/// # Refenences
/// * [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/History_API)
pub fn push_route<U: Into<Url>>(url: U) -> Url {
    let mut url = url.into();
    // Purge leading / from each part, if it exists, eg passed by user.
    url = clean_url(url);

    // We use data to evaluate the path instead of the path displayed in the url.
    let data =
        JsValue::from_serde(&serde_json::to_string(&url).expect("Problem serializing route data"))
            .expect("Problem converting route data to JsValue");

    // title is currently unused by Firefox.
    let title = match &url.title {
        Some(t) => t,
        None => "",
    };

    // Prepending / means replace
    // the existing path. Not doing so will add the path to the existing one.
    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
}

/// Add a listener that handles routing for navigation events like forward and back.
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");

        if let Some(state_str) = ev.state().as_string() {
            let url: Url =
                serde_json::from_str(&state_str).expect("Problem deserializing popstate state");
            // Only update when requested for an update by the user.
            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);
}

/// Add a listener that handles routing when the url hash is changed.
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,
{
    // todo: DRY with popstate listener
    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().into();

        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);
}

/// Set up a listener that intercepts clicks on elements containing an Href attribute,
/// so we can prevent page refresh for internal links, and route internally.  Run this on load.
#[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)  // Option::flatten not stable (https://github.com/rust-lang/rust/issues/60258)
            .and_then(|href_el| match href_el.tag_name().as_str() {
                // Base and Link tags use href for something other than navigation.
                "Base" | "Link" => None,
                _ => Some(href_el)
            })
            .and_then(|href_el| href_el.get_attribute("href"))
            // The first character being / or empty href indicates a rel link, which is what
            // we're intercepting.
            // @TODO: Resolve it properly, see Elm implementation:
            // @TODO: https://github.com/elm/browser/blob/9f52d88b424dd12cab391195d5b090dd4639c3b0/src/Elm/Kernel/Browser.js#L157
            .and_then(|href| {
                if href.is_empty() || href.starts_with('/') {
                    Some(href)
                } else {
                    None
                }
            })
            .map(|href| {
                // @TODO should be empty href ignored?
                if href.is_empty() {
                    event.prevent_default(); // Prevent page refresh
                } else {
                    // Only update when requested for an update by the user.
                    let url = clean_url(Url::from(href));
                    if let Some(redirect_msg) = routes(url.clone()) {
                        // Route internally, overriding the default history
                        push_route(url);
                        event.prevent_default(); // Prevent page refresh
                        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(); // todo: Can we store the closure somewhere to avoid using 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().into();
        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("sea=rch".into()),
            title: None,
        };

        let actual: Url = "/path/#hash?sea=rch".to_string().into();
        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().into();
        assert_eq!(expected, actual)
    }
}