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
use crate::{
    dom::created_node::create_closure_wrap, dom::Cmd, dom::Dispatch,
    vdom::Attribute, Application,
};
use std::fmt::Debug;
use wasm_bindgen::{self, prelude::*, JsCast};
use web_sys::EventTarget;
use web_sys::ScrollToOptions;

/// Provides access to the Browser window
#[derive(Copy, Clone, Debug)]
pub struct Window;

impl Window {
    /// attach an event listender to the window
    pub fn add_event_listeners<APP, MSG>(
        event_listeners: Vec<Attribute<MSG>>,
    ) -> Cmd<APP, MSG>
    where
        APP: Application<MSG> + 'static,
        MSG: 'static,
    {
        Cmd::new(move |program| {
            let window = crate::window();
            let window: &EventTarget = window
                .dyn_ref()
                .expect("unable to cast window to event target");

            for event_attr in event_listeners.iter() {
                let event_str = event_attr.name();
                for event_cb in event_attr.value() {
                    let callback = event_cb
                        .as_event_listener()
                        .expect("expecting a callback");

                    let callback_wrapped: Closure<dyn FnMut(web_sys::Event)> =
                        create_closure_wrap(&program, callback);
                    window
                        .add_event_listener_with_callback(
                            event_str,
                            callback_wrapped.as_ref().unchecked_ref(),
                        )
                        .expect("Unable to attached event listener");

                    callback_wrapped.forget();
                }
            }
        })
    }

    /// set the title of the document
    pub fn set_title(title: &str) {
        crate::document().set_title(title);
    }

    /// Creates a Cmd in which the MSG will be emitted
    /// whenever the browser is resized
    pub fn on_resize<F, APP, MSG>(cb: F) -> Cmd<APP, MSG>
    where
        F: Fn(i32, i32) -> MSG + Clone + 'static,
        MSG: 'static,
        APP: Application<MSG> + 'static,
    {
        let cmd: Cmd<APP, MSG> = Cmd::new(move |program| {
            let cb_clone = cb.clone();
            let resize_callback: Closure<dyn Fn(web_sys::Event)> =
                Closure::wrap(Box::new(move |_| {
                    let (window_width, window_height) = Self::get_size();
                    let msg = cb_clone(window_width, window_height);
                    program.dispatch(msg);
                }));
            crate::window()
                .set_onresize(Some(resize_callback.as_ref().unchecked_ref()));
            resize_callback.forget();
        });
        cmd
    }

    /// attached a callback and will be triggered when the hash portion of the window location
    /// url is changed
    pub fn on_hashchange<F, APP, MSG>(cb: F) -> Cmd<APP, MSG>
    where
        F: Fn(String) -> MSG + Clone + 'static,
        MSG: 'static,
        APP: Application<MSG> + 'static,
    {
        let cmd: Cmd<APP, MSG> = Cmd::new(move |program| {
            let cb_clone = cb.clone();
            let hashchange_callback: Closure<dyn Fn(web_sys::Event)> =
                Closure::wrap(Box::new(move |_| {
                    let hash = Self::get_hash();
                    let msg = cb_clone(hash);
                    program.dispatch(msg);
                }));
            crate::window().set_onhashchange(Some(
                hashchange_callback.as_ref().unchecked_ref(),
            ));
            hashchange_callback.forget();
        });
        cmd
    }

    /// return the size of the browser at this moment
    pub fn get_size() -> (i32, i32) {
        let window = crate::window();
        let window_width = window
            .inner_width()
            .expect("unable to get window width")
            .as_f64()
            .expect("cant convert to f64");
        let window_height = window
            .inner_height()
            .expect("unable to get height")
            .as_f64()
            .expect("cant convert to f64");
        (window_width as i32, window_height as i32)
    }

    /// return the hash part of the browser current url location
    /// The hash part are the text right after the `#` sign
    pub fn get_hash() -> String {
        let window = crate::window();
        window.location().hash().expect("must have a hash")
    }

    /// scroll the browser to the top of the document
    pub fn scroll_to_top<APP, MSG>() -> Cmd<APP, MSG>
    where
        APP: 'static,
        MSG: 'static,
    {
        Cmd::new(|_program| {
            let mut options = ScrollToOptions::new();
            options.top(0.0);
            options.left(0.0);
            crate::window().scroll_to_with_scroll_to_options(&options);
        })
    }

    /// set the browser location hash
    pub fn set_location_hash(hash: &str) {
        let window = crate::window();
        let location = window.location();
        location.set_hash(hash).expect("must set the location hash");
    }
}