#[cfg(target_arch = "wasm32")]
use std::{cell::Cell, sync::Arc};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
#[cfg(target_arch = "wasm32")]
use super::handle::{HistoryChange, RouterHandle};
const TOKEN: &str = "lurq-router";
fn token(load: u32, entry: u64) -> String {
format!("{TOKEN}:{load}:{entry}")
}
fn entry_of(state: &str, load: u32) -> Option<u64> {
let (made_by, entry) = state.strip_prefix(TOKEN)?.strip_prefix(':')?.split_once(':')?;
(made_by.parse::<u32>().ok()? == load).then(|| entry.parse().ok())?
}
fn path_of(fragment: &str) -> Option<&str> {
let path = fragment.strip_prefix('#').unwrap_or(fragment);
path.starts_with('/').then_some(path)
}
#[cfg(target_arch = "wasm32")]
thread_local! {
static LOAD: u32 = (js_sys::Math::random() * f64::from(u32::MAX)) as u32;
static FROM_ADDRESS: Cell<bool> = const { Cell::new(false) };
}
#[cfg(target_arch = "wasm32")]
fn load() -> u32 {
LOAD.with(|load| *load)
}
#[cfg(target_arch = "wasm32")]
fn from_address(navigate: impl FnOnce()) {
FROM_ADDRESS.with(|flag| flag.set(true));
navigate();
FROM_ADDRESS.with(|flag| flag.set(false));
}
#[cfg(target_arch = "wasm32")]
fn address_path(window: &web_sys::Window) -> Option<String> {
let fragment = window.location().hash().ok()?;
let decoded = js_sys::decode_uri(&fragment).ok().map(String::from);
path_of(decoded.as_deref().unwrap_or(&fragment)).map(str::to_owned)
}
#[cfg(target_arch = "wasm32")]
fn address_of(path: &str) -> Option<String> {
if path.is_empty() {
return None;
}
let encoded = js_sys::encode_uri(path);
Some(format!("#{}", String::from(encoded)))
}
#[cfg(target_arch = "wasm32")]
fn mark_current(window: &web_sys::Window, handle: &RouterHandle) {
let Ok(history) = window.history() else {
return;
};
let state = JsValue::from_str(&token(load(), handle.current_entry()));
let address = address_of(&handle.inner.current_path.get_untracked());
let _ = history.replace_state_with_url(&state, "", address.as_deref());
}
#[cfg(target_arch = "wasm32")]
pub(super) fn follow(handle: &RouterHandle) {
use std::sync::atomic::Ordering;
if handle.inner.follows_address.swap(true, Ordering::Relaxed) {
return;
}
let Some(window) = web_sys::window() else {
return;
};
let path = address_path(&window).unwrap_or_else(|| handle.inner.current_path.get_untracked());
from_address(|| handle.replace(path));
mark_current(&window, handle);
let router = Arc::downgrade(&handle.inner);
let listener = Closure::<dyn FnMut(web_sys::PopStateEvent)>::new(move |event: web_sys::PopStateEvent| {
if let Some(inner) = router.upgrade() {
arrived(&RouterHandle { inner }, &event.state());
}
});
let _ = window.add_event_listener_with_callback("popstate", listener.as_ref().unchecked_ref());
listener.forget();
}
#[cfg(target_arch = "wasm32")]
pub(super) fn record(handle: &RouterHandle, change: HistoryChange) {
if FROM_ADDRESS.with(Cell::get) {
return;
}
let Some(history) = web_sys::window().and_then(|window| window.history().ok()) else {
return;
};
let state = JsValue::from_str(&token(load(), handle.current_entry()));
let address = address_of(&handle.inner.current_path.get_untracked());
let _ = match change {
HistoryChange::Pushed => history.push_state_with_url(&state, "", address.as_deref()),
HistoryChange::Replaced => history.replace_state_with_url(&state, "", address.as_deref()),
HistoryChange::Moved(entries) => history.go_with_delta(entries),
};
}
#[cfg(target_arch = "wasm32")]
fn arrived(handle: &RouterHandle, state: &JsValue) {
let Some(window) = web_sys::window() else {
return;
};
let entry = state.as_string().and_then(|state| entry_of(&state, load()));
if let Some(entry) = entry
&& let Some(command) = handle.command_to(entry)
&& let Some(mounted) = handle.window()
{
let router = handle.clone();
let delta = match command {
crate::app::events::NavigationCommand::Back => -1,
crate::app::events::NavigationCommand::Forward => 1,
};
mounted.request_navigation(crate::app::window::NavigationRequest {
command,
source: crate::app::events::NavigationSource::Browser,
origin: crate::app::window::NavigationOrigin::Focus,
done: Some(Box::new(move |_| {
if router.current_entry() != entry
&& let Some(history) = web_sys::window().and_then(|window| window.history().ok())
{
let _ = history.go_with_delta(-delta);
}
})),
});
return;
}
if entry.is_some_and(|entry| handle.go_to_entry(entry)) {
return;
}
let path = address_path(&window).unwrap_or_else(|| "/".to_owned());
from_address(|| {
if state.is_null() || state.is_undefined() {
handle.push(path);
} else {
handle.restart_at(path);
}
});
mark_current(&window, handle);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_token_names_an_entry_of_the_load_that_made_it() {
let state = token(7, 42);
assert_eq!(entry_of(&state, 7), Some(42));
assert_eq!(entry_of(&state, 8), None, "an entry from before a reload");
assert_eq!(entry_of("something else", 7), None);
assert_eq!(entry_of("lurq-router:7:", 7), None);
assert_eq!(entry_of("lurq-router:7", 7), None);
}
#[test]
fn a_fragment_is_a_path_when_it_starts_as_one() {
assert_eq!(path_of("#/settings"), Some("/settings"));
assert_eq!(path_of("#/search?q=a b"), Some("/search?q=a b"));
assert_eq!(path_of("#/"), Some("/"));
assert_eq!(path_of("#section"), None, "an anchor of the page");
assert_eq!(path_of("#"), None);
assert_eq!(path_of(""), None);
}
}