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
use crate::provided::Provided;
use crate::Route;
use std::any::Any;
use std::any::TypeId;
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem::Discriminant;
use std::rc::Rc;
use virtual_dom_rs::prelude::*;
pub type ProvidedMap = Rc<RefCell<HashMap<TypeId, Box<dyn Any>>>>;
#[derive(Default)]
pub struct Router {
route_handlers: Vec<Box<dyn RouteHandler>>,
pub(crate) provided: ProvidedMap,
}
pub trait RouteHandler {
fn route(&self) -> &Route;
fn view(&self, incoming_route: &str) -> VirtualNode;
fn set_provided(&mut self, provided: ProvidedMap);
fn provided(&self) -> &ProvidedMap;
fn matches(&self, incoming_path: &str) -> bool {
self.route().matches(incoming_path)
}
}
impl Router {
pub fn set_route_handlers(&mut self, route_handlers: Vec<Box<dyn RouteHandler>>) {
let mut route_handlers = route_handlers;
for router_handler in route_handlers.iter_mut() {
router_handler.set_provided(Rc::clone(&self.provided));
}
self.route_handlers = route_handlers;
}
pub fn view(&self, incoming_route: &str) -> Option<VirtualNode> {
for route_handler in self.route_handlers.iter() {
if route_handler.matches(incoming_route) {
return Some(route_handler.view(incoming_route));
}
}
None
}
}