1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// todo: how does router work in multi-window contexts?
// does each window have its own router? probably, lol

use crate::cfg::RouterCfg;
use dioxus_core::ScopeId;
use futures_channel::mpsc::UnboundedSender;
use std::any::Any;
use std::{
    cell::{Cell, RefCell},
    collections::{HashMap, HashSet},
    rc::Rc,
    sync::Arc,
};
use url::Url;

/// An abstraction over the platform's history API.
///
/// The history is denoted using web-like semantics, with forward slashes delmitiing
/// routes and question marks denoting optional parameters.
///
/// This RouterService is exposed so you can modify the history directly. It
/// does not provide a high-level ergonomic API for your components. Instead,
/// you should consider using the components and hooks instead.
/// - [`Route`](struct.Route.html)
/// - [`Link`](struct.Link.html)
/// - [`UseRoute`](struct.UseRoute.html)
/// - [`Router`](struct.Router.html)
///
///
/// # Example
///
/// ```rust, ignore
/// let router = Router::new();
/// router.push_route("/home/custom");
/// cx.provide_context(router);
/// ```
///
/// # Platform Specific
///
/// - On the web, this is a [`BrowserHistory`](https://docs.rs/gloo/0.3.0/gloo/history/struct.BrowserHistory.html).
/// - On desktop, mobile, and SSR, this is just a Vec of Strings. Currently on
///   desktop, there is no way to tap into forward/back for the app unless explicitly set.
pub struct RouterCore {
    pub(crate) route_found: Cell<Option<ScopeId>>,

    pub(crate) stack: RefCell<Vec<Arc<ParsedRoute>>>,

    pub(crate) tx: UnboundedSender<RouteEvent>,

    pub(crate) slots: Rc<RefCell<HashMap<ScopeId, String>>>,

    pub(crate) onchange_listeners: Rc<RefCell<HashSet<ScopeId>>>,

    pub(crate) history: Box<dyn RouterProvider>,

    pub(crate) cfg: RouterCfg,
}

/// A shared type for the RouterCore.
pub type RouterService = Arc<RouterCore>;

/// A route is a combination of window title, saved state, and a URL.
#[derive(Debug, Clone)]
pub struct ParsedRoute {
    /// The URL of the route.
    pub url: Url,

    /// The title of the route.
    pub title: Option<String>,

    /// The serialized state of the route.
    pub serialized_state: Option<String>,
}

#[derive(Debug)]
pub(crate) enum RouteEvent {
    Push {
        route: String,
        title: Option<String>,
        serialized_state: Option<String>,
    },
    Replace {
        route: String,
        title: Option<String>,
        serialized_state: Option<String>,
    },
    Pop,
}

impl RouterCore {
    pub(crate) fn new(tx: UnboundedSender<RouteEvent>, cfg: RouterCfg) -> Arc<Self> {
        #[cfg(feature = "web")]
        let history = Box::new(web::new(tx.clone()));

        #[cfg(not(feature = "web"))]
        let history = Box::new(hash::new());

        let route = Arc::new(history.init_location());

        Arc::new(Self {
            cfg,
            tx,
            route_found: Cell::new(None),
            stack: RefCell::new(vec![route]),
            slots: Default::default(),
            onchange_listeners: Default::default(),
            history,
        })
    }

    /// Push a new route to the history.
    ///
    /// This will trigger a route change event.
    ///
    /// This does not modify the current route
    pub fn push_route(&self, route: &str, title: Option<String>, serialized_state: Option<String>) {
        let _ = self.tx.unbounded_send(RouteEvent::Push {
            route: route.to_string(),
            title,
            serialized_state,
        });
    }

    /// Pop the current route from the history.
    pub fn pop_route(&self) {
        let _ = self.tx.unbounded_send(RouteEvent::Pop);
    }

    /// Instead of pushing a new route, replaces the current route.
    pub fn replace_route(
        &self,
        route: &str,
        title: Option<String>,
        serialized_state: Option<String>,
    ) {
        let _ = self.tx.unbounded_send(RouteEvent::Replace {
            route: route.to_string(),
            title,
            serialized_state,
        });
    }

    /// Get the current location of the Router
    pub fn current_location(&self) -> Arc<ParsedRoute> {
        self.stack.borrow().last().unwrap().clone()
    }

    /// Get the current native location of the Router
    pub fn native_location<T: 'static>(&self) -> Option<Box<T>> {
        self.history.native_location().downcast::<T>().ok()
    }

    /// Registers a scope to regenerate on route change.
    ///
    /// This is useful if you've built some abstraction on top of the router service.
    pub fn subscribe_onchange(&self, id: ScopeId) {
        self.onchange_listeners.borrow_mut().insert(id);
    }

    /// Unregisters a scope to regenerate on route change.
    ///
    /// This is useful if you've built some abstraction on top of the router service.
    pub fn unsubscribe_onchange(&self, id: ScopeId) {
        self.onchange_listeners.borrow_mut().remove(&id);
    }

    pub(crate) fn register_total_route(&self, route: String, scope: ScopeId) {
        let clean = clean_route(route);
        self.slots.borrow_mut().insert(scope, clean);
    }

    pub(crate) fn should_render(&self, scope: ScopeId) -> bool {
        if let Some(root_id) = self.route_found.get() {
            return root_id == scope;
        }

        let roots = self.slots.borrow();

        if let Some(route) = roots.get(&scope) {
            if route_matches_path(
                &self.current_location().url,
                route,
                self.cfg.base_url.as_ref(),
            ) || route.is_empty()
            {
                self.route_found.set(Some(scope));
                true
            } else {
                false
            }
        } else {
            false
        }
    }
}

fn clean_route(route: String) -> String {
    if route.as_str() == "/" {
        return route;
    }
    route.trim_end_matches('/').to_string()
}

fn clean_path(path: &str) -> &str {
    if path == "/" {
        return path;
    }
    let sub = path.trim_end_matches('/');

    if sub.starts_with('/') {
        &path[1..]
    } else {
        sub
    }
}

fn route_matches_path(cur: &Url, attempt: &str, base_url: Option<&String>) -> bool {
    let cur_piece_iter = cur.path_segments().unwrap();

    let cur_pieces = match base_url {
        // baseurl is naive right now and doesn't support multiple nesting levels
        Some(_) => cur_piece_iter.skip(1).collect::<Vec<_>>(),
        None => cur_piece_iter.collect::<Vec<_>>(),
    };

    let attempt_pieces = clean_path(attempt).split('/').collect::<Vec<_>>();

    if attempt == "/" && cur_pieces.len() == 1 && cur_pieces[0].is_empty() {
        return true;
    }

    if attempt_pieces.len() != cur_pieces.len() {
        return false;
    }

    for (i, r) in attempt_pieces.iter().enumerate() {
        // If this is a parameter then it matches as long as there's
        // _any_thing in that spot in the path.
        if r.starts_with(':') {
            continue;
        }

        if cur_pieces[i] != *r {
            return false;
        }
    }

    true
}

pub(crate) trait RouterProvider {
    fn push(&self, route: &ParsedRoute);
    fn replace(&self, route: &ParsedRoute);
    fn native_location(&self) -> Box<dyn Any>;
    fn init_location(&self) -> ParsedRoute;
}

#[cfg(not(feature = "web"))]
mod hash {
    use super::*;

    pub fn new() -> HashRouter {
        HashRouter {}
    }

    /// a simple cross-platform hash-based router
    pub struct HashRouter {}

    impl RouterProvider for HashRouter {
        fn push(&self, _route: &ParsedRoute) {}

        fn native_location(&self) -> Box<dyn Any> {
            Box::new(())
        }

        fn init_location(&self) -> ParsedRoute {
            ParsedRoute {
                url: Url::parse("app:///").unwrap(),
                title: None,
                serialized_state: None,
            }
        }

        fn replace(&self, _route: &ParsedRoute) {}
    }
}

#[cfg(feature = "web")]
mod web {
    use super::RouterProvider;
    use crate::{ParsedRoute, RouteEvent};

    use futures_channel::mpsc::UnboundedSender;
    use gloo_events::EventListener;
    use std::any::Any;
    use web_sys::History;

    pub struct WebRouter {
        // keep it around so it drops when the router is dropped
        _listener: gloo_events::EventListener,

        window: web_sys::Window,
        history: History,
    }

    impl RouterProvider for WebRouter {
        fn push(&self, route: &ParsedRoute) {
            let ParsedRoute {
                url,
                title,
                serialized_state,
            } = route;

            let _ = self.history.push_state_with_url(
                &wasm_bindgen::JsValue::from_str(serialized_state.as_deref().unwrap_or("")),
                title.as_deref().unwrap_or(""),
                Some(url.as_str()),
            );
        }

        fn replace(&self, route: &ParsedRoute) {
            let ParsedRoute {
                url,
                title,
                serialized_state,
            } = route;

            let _ = self.history.replace_state_with_url(
                &wasm_bindgen::JsValue::from_str(serialized_state.as_deref().unwrap_or("")),
                title.as_deref().unwrap_or(""),
                Some(url.as_str()),
            );
        }

        fn native_location(&self) -> Box<dyn Any> {
            Box::new(self.window.location())
        }

        fn init_location(&self) -> ParsedRoute {
            ParsedRoute {
                url: url::Url::parse(&web_sys::window().unwrap().location().href().unwrap())
                    .unwrap(),
                title: web_sys::window()
                    .unwrap()
                    .document()
                    .unwrap()
                    .title()
                    .into(),
                serialized_state: None,
            }
        }
    }

    pub(crate) fn new(tx: UnboundedSender<RouteEvent>) -> WebRouter {
        WebRouter {
            history: web_sys::window().unwrap().history().unwrap(),
            window: web_sys::window().unwrap(),
            _listener: EventListener::new(&web_sys::window().unwrap(), "popstate", move |_| {
                let _ = tx.unbounded_send(RouteEvent::Pop);
            }),
        }
    }
}