px_wsdom_core/js/
value.rs

1use crate::js_cast::JsCast;
2use crate::link::Browser;
3use crate::protocol::{DEL, GET, SET};
4use core::fmt::Write;
5
6/// Represents a value that exists on the JavaScript side.
7/// Value can be anything - number, string, object, undefined, null, ...
8#[derive(Debug)]
9pub struct JsValue {
10    pub(crate) id: u64,
11    pub(crate) browser: Browser,
12}
13
14
15impl Drop for JsValue {
16    fn drop(&mut self) {
17        let self_id = self.id;
18        let mut link = self.browser.0.lock();
19        writeln!(link.raw_commands_buf(), "{DEL}({self_id});",).unwrap();
20        link.wake_outgoing_lazy();
21    }
22}
23
24impl Clone for JsValue {
25    fn clone(&self) -> Self {
26        let self_id = self.id;
27        let out_id = {
28            let mut link = self.browser.0.lock();
29            let out_id = link.get_new_id();
30            writeln!(link.raw_commands_buf(), "{SET}({out_id},{GET}({self_id}));").unwrap();
31            link.wake_outgoing_lazy();
32            out_id
33        };
34        Self {
35            id: out_id,
36            browser: self.browser.clone(),
37        }
38    }
39}
40
41impl JsValue {
42    // const MAX_ID: u64 = (1 << 53) - 1;
43    pub fn browser(&self) -> &Browser {
44        &self.browser
45    }
46}
47
48impl AsRef<JsValue> for JsValue {
49    fn as_ref(&self) -> &JsValue {
50        self
51    }
52}
53
54impl JsCast for JsValue {
55    fn unchecked_from_js(val: JsValue) -> Self {
56        val
57    }
58
59    fn unchecked_from_js_ref(val: &JsValue) -> &Self {
60        val
61    }
62}