nw_sys/
utils.rs

1//!
2//! Helper utilities for the browser Window, Document and DOM element access
3//!
4
5use wasm_bindgen::prelude::*;
6use web_sys::{Document, HtmlElement, Window};
7
8/// Return Document element
9pub fn document() -> Document {
10    let window = web_sys::window().expect("no global `window` exists");
11    window.document().expect("unable to get `document` node")
12}
13
14/// Return Body element
15pub fn body(win: Option<Window>) -> HtmlElement {
16    let window = win.unwrap_or_else(|| web_sys::window().expect("no global `window` exists"));
17    let document = window.document().expect("unable to get `document` node");
18    document.body().expect("unable to get `document.body` node")
19}
20
21/// Return Window object
22pub fn window() -> Window {
23    web_sys::window().expect("no global `window` exists")
24}
25
26/// Obtain a `u64` value from an object property.
27/// Returns successfully parsed value or 0.
28pub fn try_get_u64_from_prop(jsv: &JsValue, prop: &str) -> Result<u64, JsValue> {
29    let v = js_sys::Reflect::get(jsv, &JsValue::from(prop))?;
30    Ok(v.as_f64().ok_or_else(|| {
31        JsValue::from(format!(
32            "try_get_u64(): error parsing property '{}' with value '{:?}'",
33            prop, v
34        ))
35    })? as u64)
36}
37
38/// Obtain `f64` value from an object property.
39pub fn try_get_f64_from_prop(jsv: &JsValue, prop: &str) -> Result<f64, JsValue> {
40    let v = js_sys::Reflect::get(jsv, &JsValue::from(prop))?;
41    v.as_f64().ok_or_else(|| {
42        JsValue::from(format!(
43            "try_get_f64(): error parsing property '{}' with value '{:?}'",
44            prop, v
45        ))
46    })
47}
48
49/// Obtain a `bool` value from the object property `prop`
50pub fn try_get_bool_from_prop(jsv: &JsValue, prop: &str) -> Result<bool, JsValue> {
51    js_sys::Reflect::get(jsv, &JsValue::from(prop))?
52        .as_bool()
53        .ok_or_else(|| {
54            JsValue::from(format!(
55                "try_get_bool(): property {} is missing or not a boolean",
56                prop
57            ))
58        })
59}
60
61/// Obtain a `JsValue` value from the object property `prop`
62pub fn try_get_js_value(this_jsv: &JsValue, prop: &str) -> Result<JsValue, JsValue> {
63    let v = js_sys::Reflect::get(this_jsv, &JsValue::from(prop))?;
64    Ok(v)
65}