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
use std::any::Any;
use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;

use gloo_events::EventListener;
use gloo_utils::window;
#[cfg(feature = "query")]
use serde::Serialize;
use wasm_bindgen::{JsValue, UnwrapThrowExt};
use web_sys::Url;

#[cfg(feature = "query")]
use crate::error::HistoryResult;
use crate::history::History;
use crate::listener::HistoryListener;
use crate::location::Location;
use crate::state::{HistoryState, StateMap};
use crate::utils::WeakCallback;

/// A [`History`] that is implemented with [`web_sys::History`] that provides native browser
/// history and state access.
#[derive(Clone)]
pub struct BrowserHistory {
    inner: web_sys::History,
    states: Rc<RefCell<StateMap>>,
    callbacks: Rc<RefCell<Vec<WeakCallback>>>,
}

impl fmt::Debug for BrowserHistory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BrowserHistory").finish()
    }
}

impl PartialEq for BrowserHistory {
    fn eq(&self, _rhs: &Self) -> bool {
        // All browser histories are created equal.
        true
    }
}

impl History for BrowserHistory {
    fn len(&self) -> usize {
        self.inner.length().expect_throw("failed to get length.") as usize
    }

    fn go(&self, delta: isize) {
        self.inner
            .go_with_delta(delta as i32)
            .expect_throw("failed to call go.")
    }

    fn push<'a>(&self, route: impl Into<Cow<'a, str>>) {
        let url = route.into();
        self.inner
            .push_state_with_url(&Self::create_history_state().1, "", Some(&url))
            .expect_throw("failed to push state.");

        self.notify_callbacks();
    }

    fn replace<'a>(&self, route: impl Into<Cow<'a, str>>) {
        let url = route.into();
        self.inner
            .replace_state_with_url(&Self::create_history_state().1, "", Some(&url))
            .expect_throw("failed to replace history.");

        self.notify_callbacks();
    }

    fn push_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T)
    where
        T: 'static,
    {
        let url = route.into();

        let (id, history_state) = Self::create_history_state();

        let mut states = self.states.borrow_mut();
        states.insert(id, Rc::new(state) as Rc<dyn Any>);

        self.inner
            .push_state_with_url(&history_state, "", Some(&url))
            .expect_throw("failed to push state.");

        drop(states);
        self.notify_callbacks();
    }

    fn replace_with_state<'a, T>(&self, route: impl Into<Cow<'a, str>>, state: T)
    where
        T: 'static,
    {
        let url = route.into();

        let (id, history_state) = Self::create_history_state();

        let mut states = self.states.borrow_mut();
        states.insert(id, Rc::new(state) as Rc<dyn Any>);

        self.inner
            .replace_state_with_url(&history_state, "", Some(&url))
            .expect_throw("failed to replace state.");

        drop(states);
        self.notify_callbacks();
    }

    #[cfg(feature = "query")]
    fn push_with_query<'a, Q>(&self, route: impl Into<Cow<'a, str>>, query: Q) -> HistoryResult<()>
    where
        Q: Serialize,
    {
        let route = route.into();
        let query = serde_urlencoded::to_string(query)?;

        let url = Self::combine_url(&route, &query);

        self.inner
            .push_state_with_url(&Self::create_history_state().1, "", Some(&url))
            .expect_throw("failed to push history.");

        self.notify_callbacks();
        Ok(())
    }

    #[cfg(feature = "query")]
    fn replace_with_query<'a, Q>(
        &self,
        route: impl Into<Cow<'a, str>>,
        query: Q,
    ) -> HistoryResult<()>
    where
        Q: Serialize,
    {
        let route = route.into();
        let query = serde_urlencoded::to_string(query)?;

        let url = Self::combine_url(&route, &query);

        self.inner
            .replace_state_with_url(&Self::create_history_state().1, "", Some(&url))
            .expect_throw("failed to replace history.");

        self.notify_callbacks();
        Ok(())
    }

    #[cfg(feature = "query")]
    fn push_with_query_and_state<'a, Q, T>(
        &self,
        route: impl Into<Cow<'a, str>>,
        query: Q,
        state: T,
    ) -> HistoryResult<()>
    where
        Q: Serialize,
        T: 'static,
    {
        let (id, history_state) = Self::create_history_state();

        let mut states = self.states.borrow_mut();
        states.insert(id, Rc::new(state) as Rc<dyn Any>);

        let route = route.into();
        let query = serde_urlencoded::to_string(query)?;

        let url = Self::combine_url(&route, &query);

        self.inner
            .push_state_with_url(&history_state, "", Some(&url))
            .expect_throw("failed to push history.");

        drop(states);
        self.notify_callbacks();
        Ok(())
    }

    #[cfg(feature = "query")]
    fn replace_with_query_and_state<'a, Q, T>(
        &self,
        route: impl Into<Cow<'a, str>>,
        query: Q,
        state: T,
    ) -> HistoryResult<()>
    where
        Q: Serialize,
        T: 'static,
    {
        let (id, history_state) = Self::create_history_state();

        let mut states = self.states.borrow_mut();
        states.insert(id, Rc::new(state) as Rc<dyn Any>);

        let route = route.into();
        let query = serde_urlencoded::to_string(query)?;

        let url = Self::combine_url(&route, &query);

        self.inner
            .replace_state_with_url(&history_state, "", Some(&url))
            .expect_throw("failed to replace history.");

        drop(states);
        self.notify_callbacks();
        Ok(())
    }

    fn listen<CB>(&self, callback: CB) -> HistoryListener
    where
        CB: Fn() + 'static,
    {
        // Callbacks do not receive a copy of [`History`] to prevent reference cycle.
        let cb = Rc::new(callback) as Rc<dyn Fn()>;

        self.callbacks.borrow_mut().push(Rc::downgrade(&cb));

        HistoryListener { _listener: cb }
    }

    fn location(&self) -> Location {
        let loc = window().location();

        let history_state = self.inner.state().expect_throw("failed to get state");
        let history_state = serde_wasm_bindgen::from_value::<HistoryState>(history_state).ok();

        let id = history_state.map(|m| m.id());

        let states = self.states.borrow();

        Location {
            path: loc.pathname().expect_throw("failed to get pathname").into(),
            query_str: loc
                .search()
                .expect_throw("failed to get location query.")
                .into(),
            hash: loc
                .hash()
                .expect_throw("failed to get location hash.")
                .into(),
            state: id.and_then(|m| states.get(&m).cloned()),
            id,
        }
    }
}

impl Default for BrowserHistory {
    fn default() -> Self {
        // We create browser history only once.
        thread_local! {
            static BROWSER_HISTORY: (BrowserHistory, EventListener) = {
                let window = window();

                let inner = window
                    .history()
                    .expect_throw("Failed to create browser history. Are you using a browser?");
                let callbacks = Rc::default();

                let history = BrowserHistory {
                    inner,
                    callbacks,
                    states: Rc::default(),
                };

                let listener = {
                    let history = history.clone();

                    // Listens to popstate.
                    EventListener::new(&window, "popstate", move |_| {
                        history.notify_callbacks();
                    })
                };

                (history, listener)
            };
        }

        BROWSER_HISTORY.with(|(history, _)| history.clone())
    }
}

impl BrowserHistory {
    /// Creates a new [`BrowserHistory`]
    pub fn new() -> Self {
        Self::default()
    }

    fn notify_callbacks(&self) {
        crate::utils::notify_callbacks(self.callbacks.clone());
    }

    fn create_history_state() -> (u32, JsValue) {
        let history_state = HistoryState::new();

        (
            history_state.id(),
            serde_wasm_bindgen::to_value(&history_state)
                .expect_throw("fails to create history state."),
        )
    }

    pub(crate) fn combine_url(route: &str, query: &str) -> String {
        let href = window()
            .location()
            .href()
            .expect_throw("Failed to read location href");

        let url = Url::new_with_base(route, &href).expect_throw("current url is not valid.");

        url.set_search(query);

        url.href()
    }
}