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
//! Wrapper around route url string, and associated history state.
use cfg_if::cfg_if;
#[cfg(feature = "service")]
use serde::de::DeserializeOwned;

cfg_if! {
    if #[cfg(feature = "std_web")] {
        use stdweb::{unstable::TryFrom, Value};
    }
}

use serde::{Deserialize, Serialize};
use std::{
    fmt::{self, Debug},
    ops::Deref,
};

/// Any state that can be used in the router agent must meet the criteria of this trait.
#[cfg(all(feature = "service", feature = "std_web"))]
pub trait RouteState:
    Serialize + DeserializeOwned + Debug + Clone + Default + TryFrom<Value> + 'static
{
}
#[cfg(all(feature = "service", feature = "std_web"))]
impl<T> RouteState for T where
    T: Serialize + DeserializeOwned + Debug + Clone + Default + TryFrom<Value> + 'static
{
}

/// Any state that can be used in the router agent must meet the criteria of this trait.
#[cfg(all(feature = "service", feature = "web_sys"))]
pub trait RouteState: Serialize + DeserializeOwned + Debug + Clone + Default + 'static {}
#[cfg(all(feature = "service", feature = "web_sys"))]
impl<T> RouteState for T where T: Serialize + DeserializeOwned + Debug + Clone + Default + 'static {}

/// The representation of a route, segmented into different sections for easy access.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Route<STATE = ()> {
    /// The route string
    pub route: String,
    /// The state stored in the history api
    pub state: STATE,
}

impl Route<()> {
    /// Creates a new route with no state out of a string.
    ///
    /// This Route will have `()` for its state.
    pub fn new_no_state<T: AsRef<str>>(route: T) -> Self {
        Route {
            route: route.as_ref().to_string(),
            state: (),
        }
    }
}

impl<STATE: Default> Route<STATE> {
    /// Creates a new route out of a string, setting the state to its default value.
    pub fn new_default_state<T: AsRef<str>>(route: T) -> Self {
        Route {
            route: route.as_ref().to_string(),
            state: STATE::default(),
        }
    }
}

impl<STATE> fmt::Display for Route<STATE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        std::fmt::Display::fmt(&self.route, f)
    }
}

impl<STATE> Deref for Route<STATE> {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.route
    }
}