Skip to content

Integrate crate Url + routing refactor #253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ wasm-bindgen-futures = "0.3.22"
# @TODO: remove once we can use entities without `Debug` in `log!` and `error!` on `stable` Rust.
# https://github.com/Centril/rfcs/blob/rfc/quick-debug-macro/text/0000-quick-debug-macro.md#types-which-are-not-debug
dbg = "1.0.4"
url = "2.1.0"

[dependencies.web-sys]
version = "0.3.27"
Expand Down
29 changes: 29 additions & 0 deletions examples/server_integration/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

103 changes: 39 additions & 64 deletions src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

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

/// Repeated here from `seed::util`, to make this module standalone. Once we have a Gloo module
Expand Down Expand Up @@ -73,65 +74,35 @@ impl Url {
}
}

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;
}
impl TryFrom<&str> for Url {
type Error = url::ParseError;

if in_hash {
hash.push(c);
} else if in_search {
search.push(c);
} else {
last_path.push(c);
}
fn try_from(url: &str) -> Result<Self, Self::Error> {
let parsed_url = match url::Url::parse(url) {
Ok(parsed_url) => parsed_url,
Err(url::ParseError::RelativeUrlWithoutBase) => {
url::Url::parse("http://dummy").unwrap().join(url)?
}
}

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

Self {
path,
hash: if hash.is_empty() { None } else { Some(hash) },
search: if search.is_empty() {
None
} else {
Some(search)
},
Ok(Self {
path: parsed_url
.path_segments()
.map(|segments| segments.map(ToString::to_string).collect())
.unwrap_or_default(),
hash: parsed_url.fragment().map(ToString::to_string),
search: parsed_url.query().map(ToString::to_string),
title: None,
}
})
}
}

impl TryFrom<String> for Url {
type Error = url::ParseError;

fn try_from(url: String) -> Result<Self, Self::Error> {
Url::try_from(url.as_str())
}
}

Expand Down Expand Up @@ -303,7 +274,7 @@ pub fn setup_hashchange_listener<Ms>(
.dyn_ref::<web_sys::HashChangeEvent>()
.expect("Problem casting as hashchange event");

let url: Url = ev.new_url().into();
let url: Url = ev.new_url().try_into().expect("cannot parse `new_url`");

if let Some(routing_msg) = routes(url) {
update(routing_msg);
Expand Down Expand Up @@ -352,7 +323,7 @@ where
event.prevent_default(); // Prevent page refresh
} else {
// Only update when requested for an update by the user.
let url = clean_url(Url::from(href));
let url = clean_url(Url::try_from(href).expect("cannot parse `href`"));
if let Some(redirect_msg) = routes(url.clone()) {
// Route internally, overriding the default history
push_route(url);
Expand All @@ -372,9 +343,13 @@ where

#[cfg(test)]
mod tests {
use wasm_bindgen_test::*;

use super::*;

#[test]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to leave this annotation in as well so that both test and wasm_bindgen_test are available? Just curious.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With both:

  • cargo make test_h_firefox seems to work.
  • cargo test seems to run test successfully, then fails on some errors

So it seems to work at least for tests which doesn't need browser to run.

wasm_bindgen_test_configure!(run_in_browser);

#[wasm_bindgen_test]
fn parse_url_simple() {
let expected = Url {
path: vec!["path1".into(), "path2".into()],
Expand All @@ -383,11 +358,11 @@ mod tests {
title: None,
};

let actual: Url = "/path1/path2".to_string().into();
let actual: Url = "/path1/path2".try_into().unwrap();
assert_eq!(expected, actual)
}

#[test]
#[wasm_bindgen_test]
fn parse_url_with_hash_search() {
let expected = Url {
path: vec!["path".into()],
Expand All @@ -396,11 +371,11 @@ mod tests {
title: None,
};

let actual: Url = "/path/#hash?sea=rch".to_string().into();
let actual: Url = "/path?sea=rch#hash".try_into().unwrap();
assert_eq!(expected, actual)
}

#[test]
#[wasm_bindgen_test]
fn parse_url_with_hash_only() {
let expected = Url {
path: vec!["path".into()],
Expand All @@ -409,7 +384,7 @@ mod tests {
title: None,
};

let actual: Url = "/path/#hash".to_string().into();
let actual: Url = "/path#hash".try_into().unwrap();
assert_eq!(expected, actual)
}
}