use crate::{
computed::Value,
get_driver,
Computed,
};
#[derive(Clone, PartialEq)]
pub struct Router<T: Clone + ToString + From<String> + PartialEq + 'static> {
use_history_api: bool,
pub route: Computed<T>,
}
impl<T: Clone + ToString + From<String> + PartialEq + 'static> Router<T> {
pub fn new_hash_router() -> Router<T> {
Self::new(false)
}
pub fn new_history_router() -> Router<T> {
Self::new(true)
}
fn new(use_history_api: bool) -> Self {
let driver = get_driver();
let init_value = match use_history_api {
false => T::from(driver.inner.api.get_hash_location()),
true => T::from(driver.inner.api.get_history_location()),
};
let route = Value::with_connect(init_value, move |value| {
let value = value.clone();
let callback = move |url: String| {
value.set_value_and_compare(T::from(url));
};
match use_history_api {
false => driver.inner.api.on_hash_change(callback),
true => driver.inner.api.on_history_change(callback),
}
});
Self {
use_history_api,
route,
}
}
pub fn set(&self, route: T) {
let driver = get_driver();
match self.use_history_api {
false => driver.inner.api.push_hash_location(&route.to_string()),
true => driver.inner.api.push_history_location(&route.to_string()),
};
}
}