use super::*;
impl Default for Router {
fn default() -> Self {
Self::at(DEFAULT_ROUTE_PATH.to_string())
}
}
impl Router {
#[must_use]
pub fn at(initial_path: String) -> Self {
let normalized: String = if initial_path.starts_with('/') {
initial_path
} else {
format!("/{initial_path}")
};
Self {
current: Signal::new(normalized.clone()),
history: vec![normalized],
cursor: 0,
}
}
#[must_use]
pub fn path(&self) -> String {
self.get_current().get()
}
pub fn push(&mut self, path: String) {
let normalized: String = if path.starts_with('/') {
path
} else {
format!("/{path}")
};
if self.get_current().get_untracked() == normalized {
return;
}
let next_len: usize = self.get_cursor() + 1;
self.get_mut_history().truncate(next_len);
self.get_mut_history().push(normalized.clone());
self.set_cursor(next_len);
let _: bool = self.get_current().set(normalized);
}
pub fn back(&mut self) -> bool {
if self.get_cursor() == 0 {
return false;
}
let next_idx: usize = self.get_cursor() - 1;
if let Some(target) = self.get_history().get(next_idx).cloned() {
self.set_cursor(next_idx);
let _: bool = self.get_current().set(target);
true
} else {
false
}
}
pub fn forward(&mut self) -> bool {
let next_idx: usize = self.get_cursor() + 1;
if let Some(target) = self.get_history().get(next_idx).cloned() {
self.set_cursor(next_idx);
let _: bool = self.get_current().set(target);
true
} else {
false
}
}
#[must_use]
pub fn can_go_back(&self) -> bool {
self.get_cursor() > 0
}
}