custom_element/
generated_constructor.rs

1use std::ops::Deref;
2
3use js_sys::{Array, Function, Reflect};
4use wasm_bindgen::JsValue;
5
6/// Wrapper type around the JavaScript `GeneratedCustomElement`
7/// class for easier/more ergonomic calling/conversions
8#[derive(Clone, Eq, PartialEq, Debug, Default)]
9pub struct GeneratedConstructor(pub Function);
10
11impl Deref for GeneratedConstructor {
12    type Target = Function;
13
14    fn deref(&self) -> &Self::Target {
15        &self.0
16    }
17}
18
19impl AsRef<Function> for GeneratedConstructor {
20    fn as_ref(&self) -> &Function {
21        &self.0
22    }
23}
24
25impl AsMut<Function> for GeneratedConstructor {
26    fn as_mut(&mut self) -> &mut Function {
27        &mut self.0
28    }
29}
30
31impl GeneratedConstructor {
32    /// Calls the `GeneratedCustomElement`'s constructor function with arguments.
33    /// Equivalent to calling `new GeneratedCustomElement()` in JavaScript
34    pub fn construct(&self) -> Result<Function, JsValue> {
35        Reflect::construct(self, &Array::new()).map(|js_value| js_value.into())
36    }
37
38    /// Calls the `GeneratedCustomElement`'s constructor function with arguments.
39    /// Equivalent to calling `new GeneratedCustomElement()` in JavaScript
40    pub fn construct_with_arguments(
41        &self,
42        args: impl AsRef<[JsValue]>,
43    ) -> Result<Function, JsValue> {
44        self.construct_with_array_arguments(&Array::from_iter(args.as_ref()))
45    }
46
47    /// Calls the `GeneratedCustomElement`'s constructor function with arguments.
48    /// Equivalent to calling `new GeneratedCustomElement()` in JavaScript
49    #[doc(hidden)]
50    pub fn construct_with_array_arguments(&self, args: &Array) -> Result<Function, JsValue> {
51        Reflect::construct(self, args).map(|js_value| js_value.into())
52    }
53
54    /// Get raw, inner JavaScript [`js_sys::Function`]
55    pub fn inner(&self) -> &Function {
56        &self.0
57    }
58
59    /// Clone and return the inner JavaScript [`js_sys::Function`]
60    pub fn to_inner(&self) -> Function {
61        self.0.clone()
62    }
63
64    /// Convert into the raw, inner JavaScript [`js_sys::Function`]
65    pub fn into_inner(self) -> Function {
66        self.0
67    }
68}