router.rs
⎇
Raw
1//! Tiny hash-based router.
2//!
3//! - `#/` — root picker / single-root browser
4//! - `#/files/{root_id}/{segment/...}` — a user's folder
5//! - `#/shares/{token}/{segment/...}` — a public share (no login)
6//! - `#/shares`, `#/users`, `#/settings` — the signed-in shell's manage views
7//!
8//! (`#/shares` with a token is the public share; without one it is the
9//! manage view that lists your own shares.)
10//!
11//! The URL hash is the single source of truth; the `Location` signal in the
12//! app mirrors it.
13
14/// Which section of the signed-in shell a location points at. `Files` is the
15/// browser; the rest are the manage views, each with its own URL.
16#[derive(Clone, Copy, PartialEq, Eq, Debug)]
17pub enum Section {
18 Files,
19 Shares,
20 Users,
21 Settings,
22}
23
24impl Section {
25 /// The URL segment for this section, or `None` for `Files` (which has no
26 /// segment of its own — the browser is the default view).
27 const fn segment(self) -> Option<&'static str> {
28 match self {
29 Section::Files => None,
30 Section::Shares => Some("shares"),
31 Section::Users => Some("users"),
32 Section::Settings => Some("settings"),
33 }
34 }
35}
36
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Location {
39 /// None = the top-level "folders" view (root picker).
40 pub root_id: Option<i64>,
41 /// Path segments relative to the current root (or share target).
42 pub path: Vec<String>,
43 /// Present when the location is a public share (`#/s/{token}/...`).
44 pub share_token: Option<String>,
45 /// Which shell section the location points at.
46 pub section: Section,
47}
48
49impl Location {
50 pub const fn root() -> Self {
51 Self {
52 root_id: None,
53 path: Vec::new(),
54 share_token: None,
55 section: Section::Files,
56 }
57 }
58}
59
60/// Percent-encode one path segment for the URL hash. Without this a name
61/// containing `#`, `%` or `/` would break the round trip.
62fn encode_segment(seg: &str) -> String {
63 js_sys::encode_uri_component(seg).into()
64}
65
66fn decode_segment(seg: &str) -> String {
67 // A hand-typed hash can hold invalid escapes; keep it verbatim then.
68 js_sys::decode_uri_component(seg)
69 .map(String::from)
70 .unwrap_or_else(|_| seg.to_string())
71}
72
73pub fn parse_location() -> Location {
74 let hash = web_sys::window()
75 .and_then(|w| w.location().hash().ok())
76 .unwrap_or_default();
77 let h = hash.trim_start_matches('#');
78 let h = h.trim_start_matches('/');
79 let mut parts = h.split('/').filter(|s| !s.is_empty());
80 match parts.next() {
81 Some("files") => match parts.next().and_then(|s| s.parse().ok()) {
82 Some(root_id) => Location {
83 root_id: Some(root_id),
84 path: parts.map(decode_segment).collect(),
85 share_token: None,
86 section: Section::Files,
87 },
88 None => Location::root(),
89 },
90 Some("shares") => match parts.next() {
91 // `#/shares/{token}/...` — public share page.
92 Some(token) => Location {
93 root_id: None,
94 path: parts.map(decode_segment).collect(),
95 share_token: Some(token.to_string()),
96 section: Section::Files,
97 },
98 // `#/shares` — the signed-in shares manage view.
99 None => Location {
100 root_id: None,
101 path: Vec::new(),
102 share_token: None,
103 section: Section::Shares,
104 },
105 },
106 Some("users") => Location {
107 root_id: None,
108 path: Vec::new(),
109 share_token: None,
110 section: Section::Users,
111 },
112 Some("settings") => Location {
113 root_id: None,
114 path: Vec::new(),
115 share_token: None,
116 section: Section::Settings,
117 },
118 _ => Location::root(),
119 }
120}
121
122pub fn location_to_hash(loc: &Location) -> String {
123 if let Some(token) = &loc.share_token {
124 let mut s = format!("#/shares/{token}");
125 for seg in &loc.path {
126 s.push('/');
127 s.push_str(&encode_segment(seg));
128 }
129 return s;
130 }
131 if let Some(segment) = loc.section.segment() {
132 return format!("#/{segment}");
133 }
134 match loc.root_id {
135 None => "#/".to_string(),
136 Some(id) => {
137 let mut s = format!("#/files/{id}");
138 for seg in &loc.path {
139 s.push('/');
140 s.push_str(&encode_segment(seg));
141 }
142 s
143 }
144 }
145}
146
147/// Change the app location (updates the hash; the app listens for hashchange).
148pub fn navigate(loc: &Location) {
149 if let Some(w) = web_sys::window() {
150 let _ = w.location().set_hash(&location_to_hash(loc));
151 }
152}
153
154/// Build the share link for a token, relative to the current page origin.
155pub fn share_url(token: &str) -> String {
156 let base = web_sys::window()
157 .and_then(|w| w.location().href().ok())
158 .unwrap_or_default();
159 // Cut off any existing hash, then append the share hash.
160 let cut = base.find('#').unwrap_or(base.len());
161 format!("{}#/shares/{token}", &base[..cut])
162}
163