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
use wasm_bindgen::{
    closure::Closure,
    JsCast,
};

/// utility function which returns the Window element
pub fn window() -> web_sys::Window {
    web_sys::window().expect("no global `window` exists")
}

/// utility function which returns the history api of the browser
pub fn history() -> web_sys::History {
    window().history().expect("should have a history object")
}

/// utility function which executes the agument closure in a request animation frame
pub fn request_animation_frame(f: &Closure<dyn FnMut()>) {
    window()
        .request_animation_frame(f.as_ref().unchecked_ref())
        .expect("should register `requestAnimationFrame` OK");
}

/// request animation frame and execute function
pub fn execute_in_request_animation_frame<F>(f: F) -> i32
where
    F: Fn() + 'static,
{
    let closure_raf: Closure<dyn Fn()> = Closure::wrap(Box::new(move || f()));
    let handle = window()
        .request_animation_frame(closure_raf.as_ref().unchecked_ref())
        .expect("should execute in requestAnimationFrame");

    closure_raf.forget();
    handle
}

/// provides access to the document element
pub fn document() -> web_sys::Document {
    window()
        .document()
        .expect("should have a document on window")
}

/// provides access to the document body
pub fn body() -> web_sys::HtmlElement {
    document().body().expect("document should have a body")
}

/// provides access to the window Performance api
pub fn performance() -> web_sys::Performance {
    window()
        .performance()
        .expect("should have performance on window")
}

/// return the instantaneous time
pub fn now() -> f64 {
    performance().now()
}