use crate::*;
pub fn current_route() -> String {
let window: Window = window().expect("no global window exists");
let hash: String = window.location().hash().unwrap_or_default();
let route: String = hash.strip_prefix('#').unwrap_or(&hash).to_string();
if route.is_empty() {
"/".to_string()
} else {
route
}
}
pub fn navigate(route: &str) {
let window: Window = window().expect("no global window exists");
let location: Location = window.location();
let new_hash: String = format!("#{}", route);
let _ = location.set_hash(&new_hash);
}
pub fn link_handler(route: String) -> NativeEventHandler {
NativeEventHandler::new(NativeEventName::Click, move |_event: NativeEvent| {
navigate(&route);
})
}
pub fn use_hash_change(route_signal: Signal<String>) {
let window: Window = window().expect("no global window exists");
let closure: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
let new_route: String = current_route();
route_signal.set(new_route);
}));
let _ = window.add_event_listener_with_callback(
&NativeEventName::HashChange.to_string(),
closure.as_ref().unchecked_ref(),
);
closure.forget();
}