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
//! The WASM binary crate served by roost to handle client-side operations.

use std::cell::RefCell;
use std::rc::Rc;

use console_error_panic_hook;
use js_sys::Reflect;
use log::Level;
use wasm_bindgen;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys;
use web_sys::Url;

use virtual_dom_rs::prelude::*;

use roost_app;
use roost_app::Msg;
use roost_app::{App, Store};

/// Structure that is exported to JS along with its constructor
#[wasm_bindgen]
pub struct Client {
    /// The client instance of Roost's application structure
    app: App,
    /// Updates the actual DOM based on the virtual dom
    dom_updater: DomUpdater,
}

// Imported JS globals for updating the client state of Roost
//
// TODO: Remove this and use RAF from Rust
// https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Window.html#method.request_animation_frame
#[wasm_bindgen]
extern "C" {
    /// A JS function object used to import its update method
    pub type GlobalJS;
    /// The Rust instance of the GlobalJS function object
    pub static global_js: GlobalJS;
    /// The imported update method of GlobalJS that is executed when
    /// the client state is to be updated
    #[wasm_bindgen(method)]
    pub fn update(this: &GlobalJS);

    /// A function that updates all `<pre><code>` blocks within the body.
    /// The update results in syntax highlighting thanks to Highlight.js
    #[wasm_bindgen(js_name = "updateHljs")]
    pub fn update_hljs();
}

/// The included functions of a Roost client instance
#[wasm_bindgen]
impl Client {
    /// The constructor function that is exported to JS
    #[wasm_bindgen(constructor)]
    pub fn new(initial_state: &str) -> Client {
        // Enable console_log in debug mode
        #[cfg(debug_assertions)]
        console_log::init_with_level(Level::Debug).expect("Unable to enable console_log");

        // Logs panics for wasm32-unknown-unknown
        console_error_panic_hook::set_once();

        // Creates an instance of the Roost application from the JSON included in index.html
        let app = App::from_state_json(initial_state);

        // Whenever the state of the client's application changes, global_js.update() is called
        //
        // TODO: Use request animation frame from web_sys
        // https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Window.html#method.request_animation_frame
        app.store.borrow_mut().subscribe(Box::new(|| {
            web_sys::console::log_1(&"Updating state".into());
            global_js.update();
        }));

        // When the route of the client's application changes, the new path is pushed to the
        // history
        //
        // TODO: Allow history to pop state more than once
        app.store.borrow_mut().set_after_route(Box::new(|new_path| {
            let history = window().history().unwrap();
            history
                .push_state_with_url(&JsValue::null(), "Roost", Some(new_path))
                .expect("Unable to push_state_with_url");
        }));

        // Sets the closure for when the history is popped, which updates the current path
        // to the old path
        let store = Rc::clone(&app.store);
        let on_popstate = move |_: web_sys::Event| {
            let path = location().pathname().unwrap() + &location().search().unwrap();

            store.borrow_mut().msg(&Msg::SetPath(path))
        };
        let on_popstate = Box::new(on_popstate) as Box<FnMut(_)>;
        let on_popstate = Closure::wrap(on_popstate);
        window().set_onpopstate(Some(on_popstate.as_ref().unchecked_ref()));
        on_popstate.forget();

        // Renders the application within the element with the id 'roost-content'
        let root_node = document()
            .get_element_by_id("roost-content")
            .expect("Unable to find repo-path <div>");
        let dom_updater = DomUpdater::new_replace_mount(app.render(), root_node);
        update_hljs();

        // Change the behavior of anchor tags with relative href's
        let store = Rc::clone(&app.store);
        intercept_relative_links(store);

        Client { app, dom_updater }
    }

    /// Updates the DOM based on the virtual dom generated by app.render()
    pub fn render(&mut self) {
        let vdom = self.app.render();
        self.dom_updater.update(vdom);
    }
}

/// Ensure that anytime a link such as `<a href="/foo"></a>` is clicked we re-render the page locally
/// instead of hitting the server to load a new page.
fn intercept_relative_links(store: Rc<RefCell<Store>>) {
    let on_anchor_click = move |event: web_sys::Event| {
        // Get the tag name of the element that was clicked
        let target = event
            .target()
            .unwrap()
            .dyn_into::<web_sys::Element>()
            .unwrap();
        let tag_name = target.tag_name();
        let tag_name = tag_name.as_str();

        // If the clicked element is an anchor tag, check if it points to the current website
        // (ex: '<a href="/some-page"></a>'
        if tag_name.to_lowercase() == "a" {
            let link = Reflect::get(&target, &"href".into())
                .unwrap()
                .as_string()
                .unwrap();
            let link_url = Url::new(link.as_str()).unwrap();

            // If this was indeed a relative URL, let our single page application router
            // handle it
            let hostname = location().hostname().unwrap();
            let port = location().port().unwrap();
            if link_url.hostname() == hostname && link_url.port() == port {
                event.prevent_default();

                // Sets the selected patch when changing routes from a relative link
                //
                // TODO: This won't be necessary when we can borrow from `app/src/lib.rs` route
                // handlers.
                let path = link_url.pathname();
                if path.starts_with("/patch/") {
                    store
                        .borrow_mut()
                        .msg(&Msg::SetSelectedPatch(Some(path.split('/').collect::<Vec<&str>>()[2].to_string())));
                } else {
                    store.borrow_mut().msg(&Msg::SetSelectedPatch(None));
                }

                store.borrow_mut().msg(&Msg::SetPath(path));
            }
        }
    };
    let on_anchor_click = Closure::wrap(Box::new(on_anchor_click) as Box<FnMut(_)>);

    window()
        .add_event_listener_with_callback("click", on_anchor_click.as_ref().unchecked_ref())
        .unwrap();
    on_anchor_click.forget();
}

/// Retrieves web_sys::Window
fn window() -> web_sys::Window {
    web_sys::window().unwrap()
}
/// Retrieves web_sys::Document
fn document() -> web_sys::Document {
    window().document().unwrap()
}
/// Retrieves web_sys::Location
fn location() -> web_sys::Location {
    document().location().unwrap()
}