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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! URL based routing.
//!
//! Get the URL path with [`url_path`], and set it with [`set_url_path`] or a
//! link to a fragment like `<a href="#anchor" ...>`.
//!
//! # Example
//!
//! ```no_run
//! # use html::{button, div, p, Div};
//! # use silkenweb::{prelude::*, router};
//! # let doc: Div =
//! div()
//!     .child(
//!         button()
//!             .on_click(|_, _| router::set_url_path("route_1"))
//!             .text("Go to route 1"),
//!     )
//!     .child(
//!         button()
//!             .on_click(|_, _| router::set_url_path("route_2"))
//!             .text("Go to route 2"),
//!     )
//!     .child(p().text(Sig(
//!         router::url_path().signal_ref(|url_path| format!("URL Path is: {url_path}")),
//!     )));
//! ```
use std::{collections::HashMap, fmt::Display};

use futures_signals::signal::{Mutable, ReadOnlyMutable};
use silkenweb_macros::cfg_browser;

use crate::{
    dom::Dom,
    elements::html::{a, A},
    prelude::ElementEvents,
    task,
};

/// Represent the path portion of a URL (including any query string)
#[derive(Clone, Eq, PartialEq)]
pub struct UrlPath {
    url: String,
    path_end: usize,
    query_end: usize,
}

impl UrlPath {
    /// Create a new `UrlPath`
    ///
    /// `path` should have any special characters percent escaped.
    /// Any leading `'/'`s are removed.
    pub fn new(path: &str) -> Self {
        let url = path.trim_start_matches('/').to_string();
        let query_end = url.find('#').unwrap_or(url.len());
        let path_end = url[..query_end].find('?').unwrap_or(query_end);

        Self {
            url,
            path_end,
            query_end,
        }
    }

    /// Get the path portion of the `UrlPath`
    ///
    /// ```
    /// # use silkenweb::router::UrlPath;
    /// assert_eq!(UrlPath::new("path?query_string").path(), "path");
    /// assert_eq!(UrlPath::new("?query_string").path(), "");
    /// assert_eq!(UrlPath::new("?").path(), "");
    /// assert_eq!(UrlPath::new("").path(), "");
    /// ```
    pub fn path(&self) -> &str {
        &self.url[..self.path_end]
    }

    /// Get the path components of the `UrlPath`
    ///
    /// ```
    /// # use silkenweb::router::UrlPath;
    /// let path = UrlPath::new("path1/path2/path3");
    /// let components: Vec<&str> = path.path_components().collect();
    /// assert_eq!(&components, &["path1", "path2", "path3"]);
    ///
    /// let path = UrlPath::new("");
    /// assert_eq!(path.path_components().next(), None);
    ///
    /// let path = UrlPath::new("path1//path2"); // Note the double `'/'`
    /// let components: Vec<&str> = path.path_components().collect();
    /// assert_eq!(&components, &["path1", "", "path2"]);
    pub fn path_components(&self) -> impl Iterator<Item = &str> {
        let path = self.path();
        let mut components = path.split('/');

        if path.is_empty() {
            components.next();
        }

        components
    }

    /// As [`UrlPath::path_components`] but collected into a `Vec`
    pub fn path_components_vec(&self) -> Vec<&str> {
        self.path_components().collect()
    }

    /// Get the query string portion of the `UrlPath`
    ///
    /// ```
    /// # use silkenweb::router::UrlPath;
    /// assert_eq!(
    ///     UrlPath::new("path?query_string").query_string(),
    ///     "query_string"
    /// );
    /// assert_eq!(UrlPath::new("?query_string").query_string(), "query_string");
    /// assert_eq!(UrlPath::new("?").query_string(), "");
    /// assert_eq!(UrlPath::new("").query_string(), "");
    /// assert_eq!(UrlPath::new("#hash").query_string(), "");
    /// assert_eq!(
    ///     UrlPath::new("?query_string#hash").query_string(),
    ///     "query_string"
    /// );
    /// ```
    pub fn query_string(&self) -> &str {
        self.range(self.path_end, self.query_end)
    }

    /// Split the query string into key/value pairs
    ///
    /// ```
    /// # use silkenweb::router::UrlPath;
    /// let path = UrlPath::new("path?x=1&y=2&flag");
    /// let kv_args: Vec<(&str, Option<&str>)> = path.query().collect();
    /// assert_eq!(
    ///     &kv_args,
    ///     &[("x", Some("1")), ("y", Some("2")), ("flag", None)]
    /// );
    /// ```
    pub fn query(&self) -> impl Iterator<Item = (&str, Option<&str>)> {
        self.query_string()
            .split('&')
            .map(|kv| kv.split_once('=').map_or((kv, None), |(k, v)| (k, Some(v))))
    }

    /// As [`UrlPath::query`] but collected into a `HashMap`
    pub fn query_map(&self) -> HashMap<&str, Option<&str>> {
        self.query().collect()
    }

    /// Get the query string portion of the `UrlPath`
    ///
    /// ```
    /// # use silkenweb::router::UrlPath;
    /// assert_eq!(UrlPath::new("path?query_string#hash").hash(), "hash");
    /// assert_eq!(UrlPath::new("#hash").hash(), "hash");
    /// assert_eq!(UrlPath::new("#").hash(), "");
    /// assert_eq!(UrlPath::new("").hash(), "");
    /// ```
    pub fn hash(&self) -> &str {
        self.range(self.query_end, self.url.len())
    }

    /// Get the whole path as a `&str`
    pub fn as_str(&self) -> &str {
        &self.url
    }

    fn range(&self, previous_end: usize, end: usize) -> &str {
        let start = previous_end + 1;

        if start > end {
            ""
        } else {
            &self.url[start..end]
        }
    }
}

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

impl<'a> From<&'a str> for UrlPath {
    fn from(path: &'a str) -> Self {
        Self::new(path)
    }
}

impl From<String> for UrlPath {
    fn from(path: String) -> Self {
        Self::new(&path)
    }
}

/// The path portion of the URL.
///
/// The path will never start with a '/'.
pub fn url_path() -> ReadOnlyMutable<UrlPath> {
    task::local::with(|local| local.router.0.read_only())
}

/// Set the path portion of the URL.
///
/// The path is the part of the URL after the scheme, host and port. For
/// example, the path of <http://example.com/this/is/the/path> is "/this/is/the/path".
///
/// [`set_url_path`] will:
/// - Set the browser URL
/// - Push it onto the history stack so the forward and back buttons work
/// - Set the [`url_path()`] signal
///
/// See [module-level documentation](self) for an example.
pub fn set_url_path(path: impl Into<UrlPath>) {
    arch::set_url_path(path)
}

/// Set up an HTML `<a>` element for routing.
///
/// Return an `<a>` element builder with the `href` attribute set to `path` and
/// an `on_click` handler. Modifier keys are correctly handled.
///
/// # Example
///
/// ```no_run
/// # use html::{a, A};
/// use silkenweb::{prelude::*, router::anchor};
/// let link: A = anchor("/my-path").text("click me");
/// ```
pub fn anchor<D: Dom>(path: impl Into<String>) -> A<D> {
    let path = path.into();

    a().href(&path).on_click(link_clicked(path))
}

/// An `on_click` handler for routed `<a>` elements.
///
/// This will correctly deal with modifier keys. See also: [`anchor`].
///
/// # Example
///
/// ```no_run
/// # use html::{a, A};
/// # use silkenweb::{prelude::*, router::link_clicked};
/// let path = "/my_path";
/// let link: A = a().href(path).text("click me").on_click(link_clicked(path));
/// ```
pub fn link_clicked(
    path: impl Into<String>,
) -> impl FnMut(web_sys::MouseEvent, web_sys::HtmlAnchorElement) + 'static {
    let path = path.into();
    move |ev, _| {
        let modifier_key_pressed = ev.meta_key() || ev.ctrl_key() || ev.shift_key() || ev.alt_key();

        if !modifier_key_pressed {
            ev.prevent_default();
            set_url_path(path.as_str());
        }
    }
}

pub(crate) struct TaskLocal(Mutable<UrlPath>);

impl Default for TaskLocal {
    fn default() -> Self {
        Self(Mutable::new(arch::new_url_path()))
    }
}

#[cfg_browser(false)]
mod arch {
    use super::UrlPath;
    use crate::task;

    pub fn new_url_path() -> UrlPath {
        UrlPath::new("")
    }

    pub fn set_url_path(path: impl Into<UrlPath>) {
        task::local::with(move |local| local.router.0.set(path.into()));
    }
}

#[cfg_browser(true)]
mod arch {
    use silkenweb_base::{document, window};
    use wasm_bindgen::{prelude::Closure, JsCast, JsValue, UnwrapThrowExt};

    use super::UrlPath;
    use crate::task;

    pub fn new_url_path() -> UrlPath {
        ON_POPSTATE
            .with(|on_popstate| window::set_onpopstate(Some(on_popstate.as_ref().unchecked_ref())));

        local_pathname()
    }

    pub fn set_url_path(path: impl Into<UrlPath>) {
        let path = path.into();
        let mut url = BASE_URI.with(String::clone);
        url.push_str(path.as_str());

        task::local::with(move |local| {
            window::history()
                .push_state_with_url(&JsValue::null(), "", Some(&url))
                .unwrap_throw();
            local.router.0.set(path);
        });
    }

    fn local_pathname() -> UrlPath {
        let url = window::location();

        BASE_URI.with(|base_uri| {
            url.href()
                .unwrap_throw()
                .strip_prefix(base_uri)
                .map_or_else(
                    || UrlPath::new(&url.pathname().unwrap_throw()),
                    UrlPath::new,
                )
        })
    }

    thread_local! {
        static BASE_URI: String = {
            let mut base_uri = document::base_uri();

            if ! base_uri.ends_with('/') {
                base_uri.push('/');
            }

            base_uri
        };

        static ON_POPSTATE: Closure<dyn FnMut(JsValue)> =
            Closure::wrap(Box::new(move |_event: JsValue|
                task::local::with(|local| local.router.0.set(local_pathname()))
            ));
    }
}