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
use failure::Fallible;
use serde::{Deserialize, Serialize};
use std::{collections::HashSet, fmt::Debug, marker::PhantomData};
use stdweb::{
    unstable::TryFrom,
    web::{
        event::PopStateEvent, window, EventListenerHandle, History,
        IEventTarget, Location,
    },
    JsSerialize, Value,
};
use yew::{callback::Callback, prelude::worker::*};

/// A service that facilitates manipulation of the browser's URL bar and
/// responding to browser 'forward' and 'back' events.
///
/// The `T` determines what route state can be stored in the route service.
pub struct RouterService<T> {
    history: History,
    location: Location,
    event_listener: Option<EventListenerHandle>,
    phantom_data: PhantomData<T>,
}

impl<T> RouterService<T>
where
    T: JsSerialize + Clone + TryFrom<Value> + 'static,
{
    /// Creates the route service.
    pub fn new() -> RouterService<T> {
        let location = window()
            .location()
            .expect("browser does not support location API");
        Self {
            history: window().history(),
            location,
            event_listener: None,
            phantom_data: PhantomData,
        }
    }

    /// Registers a callback to the route service. Callbacks will be called
    /// when the History API experiences a change such as popping a state off
    /// of its stack when the forward or back buttons are pressed.
    pub fn register_callback(&mut self, callback: Callback<(String, T)>) {
        self.event_listener =
            Some(window().add_event_listener(move |event: PopStateEvent| {
                let state_value: Value = event.state();

                if let Ok(state) = T::try_from(state_value) {
                    if let Some(location) = window().location() {
                        let route: String =
                            Self::get_route_from_location(&location);
                        callback.emit((route.clone(), state.clone()))
                    }
                } else {
                    eprintln!(
                        "Nothing farther back in history, not calling routing \
                         callback."
                    );
                }
            }));
    }

    /// Sets the browser's url bar to contain the provided route, and creates a
    /// history entry that can be navigated via the forward and back buttons.
    /// The route should be a relative path that starts with a '/'. A state
    /// object be stored with the url.
    pub fn set_route(&mut self, route: &str, state: T) {
        self.history.push_state(state, "", Some(route));
    }

    fn get_route_from_location(location: &Location) -> String {
        let path = location.pathname().unwrap_or_else(|_| "".to_owned());
        let query = location.search().unwrap_or_else(|_| "".to_owned());
        let fragment = location.hash().unwrap_or_else(|_| "".to_owned());
        format!(
            "{path}{query}{fragment}",
            path = path,
            query = query,
            fragment = fragment
        )
    }

    /// Gets the concatenated path, query, and fragment strings
    pub fn get_route(&self) -> String {
        Self::get_route_from_location(&self.location)
    }

    /// Gets the path name of the current url.
    pub fn get_path(&self) -> Fallible<String> {
        Ok(self.location.pathname()?)
    }

    /// Gets the query string of the current url.
    pub fn get_query(&self) -> Fallible<String> {
        Ok(self.location.search()?)
    }

    /// Gets the fragment of the current url.
    pub fn get_fragment(&self) -> Fallible<String> {
        Ok(self.location.hash()?)
    }
}

impl<T> Default for RouterService<T>
where
    T: JsSerialize + Clone + TryFrom<Value> + 'static,
{
    fn default() -> Self {
        RouterService::new()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
/// A single route abstraction
pub struct Route<T> {
    /// The URL path segments
    pub path_segments: Vec<String>,

    /// The URL query part
    pub query: Option<String>,

    /// The URL fragment part
    pub fragment: Option<String>,

    /// The routes state
    pub state: T,
}

impl<T> Route<T>
where
    T: JsSerialize + Clone + TryFrom<Value> + Default + 'static,
{
    /// Convert to a String
    pub fn to_route_string(&self) -> String {
        let path = self.path_segments.join("/");
        let mut path = format!("/{}", path);
        if let Some(ref query) = self.query {
            path = format!("{}?{}", path, query);
        }
        if let Some(ref fragment) = self.fragment {
            path = format!("{}#{}", path, fragment)
        }
        path
    }

    /// Retrieve the current route
    pub fn current_route(route_service: &RouterService<T>) -> Fallible<Self> {
        // guaranteed to always start with a '/'
        let path = route_service.get_path()?;
        let mut path_segments: Vec<String> =
            path.split('/').map(String::from).collect();
        // remove empty string that is split from the first '/'
        path_segments.remove(0);

        let mut query: String = route_service.get_query()?; // The first character will be a '?'
        let query: Option<String> = if query.len() > 1 {
            query.remove(0);
            Some(query)
        } else {
            None
        };

        let mut fragment: String = route_service.get_fragment()?; // The first character will be a '#'
        let fragment: Option<String> = if fragment.len() > 1 {
            fragment.remove(0);
            Some(fragment)
        } else {
            None
        };

        Ok(Route {
            path_segments,
            query,
            fragment,
            state: T::default(),
        })
    }
}

/// Messages of the RouterAgent
pub enum Message<T>
where
    T: JsSerialize + Clone + Debug + TryFrom<Value> + 'static,
{
    /// The browser URL has changed
    BrowserNavigationRouteChanged((String, T)),
}

impl<T> Transferable for Route<T> where for<'de> T: Serialize + Deserialize<'de> {}

#[derive(Serialize, Deserialize, Debug)]
/// The request to the RouterAgent
pub enum Request<T> {
    /// Changes the route using a RouteInfo struct and alerts connected
    /// components to the route change.
    ChangeRoute(Route<T>),

    /// Retrieve the current route request
    GetCurrentRoute,
}

impl<T> Transferable for Request<T> where
    for<'de> T: Serialize + Deserialize<'de>
{
}

/// The RouterAgent worker holds on to the RouterService singleton and mediates
/// access to it.
pub struct RouterAgent<T>
where
    for<'de> T: JsSerialize
        + Clone
        + Debug
        + TryFrom<Value>
        + Default
        + Serialize
        + Deserialize<'de>
        + 'static,
{
    link: AgentLink<RouterAgent<T>>,
    route_service: RouterService<T>,
    /// A list of all entities connected to the RouterAgent. When a route
    /// changes, either initiated by the browser or by the app, the route
    /// change will be broadcast to all listening entities.
    subscribers: HashSet<HandlerId>,
}

impl<T> Agent for RouterAgent<T>
where
    for<'de> T: JsSerialize
        + Clone
        + Debug
        + TryFrom<Value>
        + Default
        + Serialize
        + Deserialize<'de>
        + 'static,
{
    type Input = Request<T>;
    type Message = Message<T>;
    type Output = Route<T>;
    type Reach = Context;

    fn create(link: AgentLink<Self>) -> Self {
        let callback = link.send_back(Message::BrowserNavigationRouteChanged);
        let mut route_service = RouterService::default();
        route_service.register_callback(callback);

        Self {
            link,
            route_service,
            subscribers: HashSet::new(),
        }
    }

    fn update(&mut self, msg: Self::Message) {
        match msg {
            Message::BrowserNavigationRouteChanged((_route_string, state)) => {
                if let Ok(mut route) = Route::current_route(&self.route_service)
                {
                    route.state = state;
                    for sub in &self.subscribers {
                        self.link.response(*sub, route.clone());
                    }
                }
            }
        }
    }

    fn handle(&mut self, msg: Self::Input, who: HandlerId) {
        match msg {
            Request::ChangeRoute(route) => {
                let route_string: String = route.to_route_string();
                // set the route
                self.route_service.set_route(&route_string, route.state);
                // get the new route. This will contain a default state
                if let Ok(route) = Route::current_route(&self.route_service) {
                    // broadcast it to all listening components
                    for sub in &self.subscribers {
                        self.link.response(*sub, route.clone());
                    }
                }
            }
            Request::GetCurrentRoute => {
                if let Ok(route) = Route::current_route(&self.route_service) {
                    self.link.response(who, route.clone());
                }
            }
        }
    }

    /// Add a client to the pool of connections of this agent
    fn connected(&mut self, id: HandlerId) {
        self.subscribers.insert(id);
    }

    /// Remove a client from the pool of connections of this agent
    fn disconnected(&mut self, id: HandlerId) {
        self.subscribers.remove(&id);
    }
}