yew_router_nested/
route.rs

1//! Wrapper around route url string, and associated history state.
2use cfg_if::cfg_if;
3#[cfg(feature = "service")]
4use serde::de::DeserializeOwned;
5
6cfg_if! {
7    if #[cfg(feature = "std_web")] {
8        use stdweb::{unstable::TryFrom, Value};
9    }
10}
11
12use serde::{Deserialize, Serialize};
13use std::{
14    fmt::{self, Debug},
15    ops::Deref,
16};
17
18/// Any state that can be used in the router agent must meet the criteria of this trait.
19#[cfg(all(feature = "service", feature = "std_web"))]
20pub trait RouteState:
21    Serialize + DeserializeOwned + Debug + Clone + Default + TryFrom<Value> + 'static
22{
23}
24#[cfg(all(feature = "service", feature = "std_web"))]
25impl<T> RouteState for T where
26    T: Serialize + DeserializeOwned + Debug + Clone + Default + TryFrom<Value> + 'static
27{
28}
29
30/// Any state that can be used in the router agent must meet the criteria of this trait.
31#[cfg(all(feature = "service", feature = "web_sys"))]
32pub trait RouteState: Serialize + DeserializeOwned + Debug + Clone + Default + 'static {}
33#[cfg(all(feature = "service", feature = "web_sys"))]
34impl<T> RouteState for T where T: Serialize + DeserializeOwned + Debug + Clone + Default + 'static {}
35
36/// The representation of a route, segmented into different sections for easy access.
37#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
38pub struct Route<STATE = ()> {
39    /// The route string
40    pub route: String,
41    /// The state stored in the history api
42    pub state: STATE,
43}
44
45impl Route<()> {
46    /// Creates a new route with no state out of a string.
47    ///
48    /// This Route will have `()` for its state.
49    pub fn new_no_state<T: AsRef<str>>(route: T) -> Self {
50        Route {
51            route: route.as_ref().to_string(),
52            state: (),
53        }
54    }
55}
56
57impl<STATE: Default> Route<STATE> {
58    /// Creates a new route out of a string, setting the state to its default value.
59    pub fn new_default_state<T: AsRef<str>>(route: T) -> Self {
60        Route {
61            route: route.as_ref().to_string(),
62            state: STATE::default(),
63        }
64    }
65}
66
67impl<STATE> fmt::Display for Route<STATE> {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        std::fmt::Display::fmt(&self.route, f)
70    }
71}
72
73impl<STATE> Deref for Route<STATE> {
74    type Target = String;
75
76    fn deref(&self) -> &Self::Target {
77        &self.route
78    }
79}