libp2p_websocket_websys/
web_context.rs

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