//! Tiny hash-based router. //! //! - `#/` — root picker / single-root browser //! - `#/r/{root_id}/{segment/...}` — a user's folder //! - `#/s/{token}/{segment/...}` — a public share (no login) //! //! The URL hash is the single source of truth; the `Location` signal in the //! app mirrors it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Location { /// None = the top-level "folders" view (root picker). pub root_id: Option, /// Path segments relative to the current root (or share target). pub path: Vec, /// Present when the location is a public share (`#/s/{token}/...`). pub share_token: Option, } impl Location { pub const fn root() -> Self { Self { root_id: None, path: Vec::new(), share_token: None, } } } /// Percent-encode one path segment for the URL hash. Without this a name /// containing `#`, `%` or `/` would break the round trip. fn encode_segment(seg: &str) -> String { js_sys::encode_uri_component(seg).into() } fn decode_segment(seg: &str) -> String { // A hand-typed hash can hold invalid escapes; keep it verbatim then. js_sys::decode_uri_component(seg) .map(String::from) .unwrap_or_else(|_| seg.to_string()) } pub fn parse_location() -> Location { let hash = web_sys::window() .and_then(|w| w.location().hash().ok()) .unwrap_or_default(); let h = hash.trim_start_matches('#'); let h = h.trim_start_matches('/'); let mut parts = h.split('/').filter(|s| !s.is_empty()); match parts.next() { Some("r") => match parts.next().and_then(|s| s.parse().ok()) { Some(root_id) => Location { root_id: Some(root_id), path: parts.map(decode_segment).collect(), share_token: None, }, None => Location::root(), }, Some("s") => match parts.next() { Some(token) => Location { root_id: None, path: parts.map(decode_segment).collect(), share_token: Some(token.to_string()), }, None => Location::root(), }, _ => Location::root(), } } pub fn location_to_hash(loc: &Location) -> String { if let Some(token) = &loc.share_token { let mut s = format!("#/s/{token}"); for seg in &loc.path { s.push('/'); s.push_str(&encode_segment(seg)); } return s; } match loc.root_id { None => "#/".to_string(), Some(id) => { let mut s = format!("#/r/{id}"); for seg in &loc.path { s.push('/'); s.push_str(&encode_segment(seg)); } s } } } /// Change the app location (updates the hash; the app listens for hashchange). pub fn navigate(loc: &Location) { if let Some(w) = web_sys::window() { let _ = w.location().set_hash(&location_to_hash(loc)); } } /// Build the share link for a token, relative to the current page origin. pub fn share_url(token: &str) -> String { let base = web_sys::window() .and_then(|w| w.location().href().ok()) .unwrap_or_default(); // Cut off any existing hash, then append the share hash. let cut = base.find('#').unwrap_or(base.len()); format!("{}#/s/{token}", &base[..cut]) }