duid_core/core/
util.rs

1
2use wasm_bindgen::{closure::Closure, JsCast};
3
4thread_local!(static WINDOW: web_sys::Window = web_sys::window().expect("no global `window` exists"));
5
6
7pub fn window() -> web_sys::Window {
8    WINDOW.with(|window| window.clone())
9}
10
11pub fn history() -> web_sys::History {
12    window().history().expect("should have a history object")
13}
14
15pub fn request_animation_frame<F>(f: F)
16where
17    F: FnMut() + 'static,
18{
19    let closure_raf: Closure<dyn FnMut() + 'static> = Closure::once(f);
20    window()
21        .request_animation_frame(closure_raf.as_ref().unchecked_ref())
22        .expect("should register `requestAnimationFrame` OK");
23    closure_raf.forget();
24}
25
26#[allow(unused)]
27pub(crate) fn request_animation_frame_for_closure(f: &Closure<dyn FnMut()>) {
28    window()
29        .request_animation_frame(f.as_ref().unchecked_ref())
30        .expect("should register `requestAnimationFrame` OK");
31}
32
33thread_local!(static DOCUMENT: web_sys::Document = window().document().expect("should have a document on window"));
34
35pub fn document() -> web_sys::Document {
36    DOCUMENT.with(|document| document.clone())
37}
38
39pub fn body() -> web_sys::HtmlElement {
40    document().body().expect("document should have a body")
41}
42
43pub fn performance() -> web_sys::Performance {
44    window()
45        .performance()
46        .expect("should have performance on window")
47}
48
49pub fn now() -> f64 {
50    performance().now()
51}