libp2p_websocket_websys/
web_context.rs

1use wasm_bindgen::prelude::*;
2use web_sys::window;
3
4/// Web context that abstract the window vs web worker API
5#[derive(Debug)]
6pub(crate) enum WebContext {
7    Window(web_sys::Window),
8    Worker(web_sys::WorkerGlobalScope),
9}
10
11impl WebContext {
12    pub(crate) fn new() -> Option<Self> {
13        match window() {
14            Some(window) => Some(Self::Window(window)),
15            None => {
16                #[wasm_bindgen]
17                extern "C" {
18                    type Global;
19
20                    #[wasm_bindgen(method, getter, js_name = WorkerGlobalScope)]
21                    fn worker(this: &Global) -> JsValue;
22                }
23                let global: Global = js_sys::global().unchecked_into();
24                if !global.worker().is_undefined() {
25                    Some(Self::Worker(global.unchecked_into()))
26                } else {
27                    None
28                }
29            }
30        }
31    }
32
33    /// The `setInterval()` method.
34    pub(crate) fn set_interval_with_callback_and_timeout_and_arguments(
35        &self,
36        handler: &::js_sys::Function,
37        timeout: i32,
38        arguments: &::js_sys::Array,
39    ) -> Result<i32, JsValue> {
40        match self {
41            WebContext::Window(w) => {
42                w.set_interval_with_callback_and_timeout_and_arguments(handler, timeout, arguments)
43            }
44            WebContext::Worker(w) => {
45                w.set_interval_with_callback_and_timeout_and_arguments(handler, timeout, arguments)
46            }
47        }
48    }
49
50    /// The `clearInterval()` method.
51    pub(crate) fn clear_interval_with_handle(&self, handle: i32) {
52        match self {
53            WebContext::Window(w) => w.clear_interval_with_handle(handle),
54            WebContext::Worker(w) => w.clear_interval_with_handle(handle),
55        }
56    }
57}