use wasm_bindgen::JsValue;
use web_sys::Url;
use web_sys::UrlSearchParams;
fn current_window() -> web_sys::Window { web_sys::window().unwrap() }
fn current_url() -> Url {
let href = current_window().location().href().unwrap();
Url::new(&href).unwrap()
}
fn replace_url(url: &Url) {
let history = current_window().history().unwrap();
history
.replace_state_with_url(&JsValue::UNDEFINED, "", Some(&url.href()))
.unwrap();
}
pub fn has(key: &str) -> bool {
let search = current_window().location().search().unwrap();
let params = UrlSearchParams::new_with_str(search.as_str()).unwrap();
params.has(key)
}
pub fn get(key: &str) -> Option<String> {
let search = current_window().location().search().unwrap();
let params = UrlSearchParams::new_with_str(search.as_str()).unwrap();
params.get(key)
}
pub fn get_all(key: &str) -> Vec<String> {
let search = current_window().location().search().unwrap();
let params = UrlSearchParams::new_with_str(search.as_str()).unwrap();
params
.get_all(key)
.iter()
.map(|v| v.as_string().unwrap())
.collect()
}
pub fn set(key: &str, value: &str) {
if let Some(curr) = get(key) {
if curr == value {
return;
}
}
let url = current_url();
let params = url.search_params();
params.set(key, value);
replace_url(&url);
}
pub fn get_flag(key: &str) -> bool {
match get(key) {
Some(val) => val != "0" && val.to_ascii_lowercase() != "false",
None => false,
}
}
pub fn set_flag(key: &str, val: bool) {
if val {
set(key, "1");
} else {
remove(key);
}
}
pub fn remove(key: &str) {
if get(key).is_none() {
return;
}
let url = current_url();
let params = url.search_params();
params.delete(key);
replace_url(&url);
}
pub fn path_name() -> String { current_window().location().pathname().unwrap() }
#[cfg(test)]
#[cfg(target_arch = "wasm32")]
mod tests {
use crate::prelude::*;
use wasm_bindgen::JsValue;
use web_sys::Url;
use web_sys::window;
fn set_url_query(qs: &str) {
let win = window().unwrap();
let href = win.location().href().unwrap();
let url = Url::new(&href).unwrap();
url.set_search(qs);
win.history()
.unwrap()
.replace_state_with_url(&JsValue::UNDEFINED, "", Some(&url.href()))
.unwrap();
}
#[test]
#[ignore = "requires dom"]
fn works() {
let _ = window().unwrap();
}
#[crate::test]
#[ignore = "requires dom"]
async fn read_write_params() {
set_url_query("");
search_params_ext::set("color", "red");
search_params_ext::get("color").xpect_eq(Some("red".to_string()));
search_params_ext::set_flag("debug", true);
search_params_ext::get_flag("debug").xpect_true();
search_params_ext::set("color", "blue");
search_params_ext::get("color").xpect_eq(Some("blue".to_string()));
search_params_ext::remove("color");
search_params_ext::get("color").xpect_eq(None);
set_url_query("?tag=a&tag=b&tag=c");
let tags = search_params_ext::get_all("tag");
tags.len().xpect_eq(3usize);
tags[0].xpect_eq("a".to_string());
tags[1].xpect_eq("b".to_string());
tags[2].xpect_eq("c".to_string());
}
}