1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use std::cell::RefCell;
use wasm_bindgen::prelude::*;
use web_sys::{js_sys::Function, HtmlElement};

#[wasm_bindgen]
extern "C" {
    fn _create_custom_element_js(name: String, renderer: BaseComponent);
}

enum HandlerVal {
    #[allow(dead_code)]
    Value(RefCell<Box<dyn Component>>),
    None,
}

/// A trait that provides the necessary methods for a custom element lifecycle
///
/// # Basic example
///
/// ```
/// use rs_web_component::{define_component, Component};
/// use wasm_bindgen::prelude::*;
/// use web_sys::{HtmlElement, ShadowRoot, ShadowRootInit, ShadowRootMode};

/// pub enum ThisVal {
///     Value(HtmlElement),
///     None,
/// }

/// pub enum RootVal {
///     Value(ShadowRoot),
///     None,
/// }

/// struct MyComponent {
///     root: RootVal,
///     this: ThisVal,
/// }

/// impl Component for MyComponent {
///     fn init(&mut self, this: HtmlElement) {
///         self.this = ThisVal::Value(this);
///     }

///     fn observed_attributes(&self) -> Vec<String> {
///         return vec!["test".to_string()];
///     }

///     fn attribute_changed_callback(&self, _name: String, _old_value: JsValue, _new_value: JsValue) {
///         if _old_value != _new_value {
///             self.get_root().set_inner_html(self.render().as_str())
///         }
///     }

///     fn connected_callback(&mut self) {
///         self.root = RootVal::Value(
///             self.get_this()
///                 .attach_shadow(&ShadowRootInit::new(ShadowRootMode::Open))
///                 .unwrap(),
///         );

///         self.get_root().set_inner_html(self.render().as_str())
///     }

///     fn disconnected_callback(&self) {}
/// }

/// impl MyComponent {
///     fn render(&self) -> String {
///         "<div><span>Hello from Rust</span></div>".to_string()
///     }

///     fn get_root(&self) -> &ShadowRoot {
///        return match &self.root {
///             RootVal::Value(root) => &root,
///             RootVal::None => panic!("not a root!"),
///         };
///     }

///     fn get_this(&self) -> &HtmlElement {
///         match &self.this {
///             ThisVal::Value(val) => val,
///             ThisVal::None => panic!("not an HtmlElement"),
///         }
///     }
/// }

/// #[wasm_bindgen(start)]
/// fn run() {
///     define_component("test-component".to_string(), || -> Box<dyn Component> {
///         Box::new(MyComponent {
///             root: RootVal::None,
///             this: ThisVal::None,
///         })
///     });
/// }
/// ```

///
/// # An Example with a button and an event handler
///
/// ```

/// use rs_web_component::{define_element, Component};
/// use wasm_bindgen::prelude::*;
/// use web_sys::{
///     CustomEvent, CustomEventInit, Event, HtmlElement, ShadowRoot, ShadowRootInit, ShadowRootMode,
/// };

/// const BUTTON_EVENT_NAME: &str = "buttonClicked";

/// pub enum ThisVal {
///     Value(HtmlElement),
///      None,
/// }

/// pub enum RootVal {
///     Value(ShadowRoot),
///     None,
/// }

/// pub enum CallbackVal {
///     Value(Closure<dyn FnMut(Event) + 'static>),
///     None,
/// }

/// struct MyComponent {
///     root: RootVal,
///     this: ThisVal,
///     callback: CallbackVal,
/// }

/// impl Component for MyComponent {
///     fn init(&mut self, this: HtmlElement) {
///         self.this = ThisVal::Value(this);
///     }
///
///     fn observed_attributes(&self) -> Vec<String> {
///         return vec!["test".to_string()];
///     }
///
///     fn attribute_changed_callback(&self, _name: String, _old_value: JsValue, _new_value: JsValue) {}
///
///     fn connected_callback(&mut self) {
///         self.root = RootVal::Value(
///             self.get_this()
///                 .attach_shadow(&ShadowRootInit::new(ShadowRootMode::Open))
///                 .unwrap(),
///         );
///
///         self.get_root().set_inner_html(self.render().as_str());
///         self.attach_event_handler();
///     }
///
///     fn disconnected_callback(&self) {
///         self.detach_event_handler();
///     }
/// }

/// impl MyComponent {
///     fn render(&self) -> String {
///         "<div><button>Click me</button></div>".to_string()
///     }
///
///     fn attach_event_handler(&mut self) {
///         let btn = self.get_root().query_selector("button").unwrap().unwrap();
///         let closure = Closure::<dyn FnMut(Event) + 'static>::new(move |e: Event| {
///             let evt = CustomEvent::new_with_event_init_dict(
///                 BUTTON_EVENT_NAME,
///                 CustomEventInit::new().composed(true).bubbles(true),
///             )
///             .unwrap();
///             let _ = btn.dispatch_event(&evt);
///         });
///         self.callback = CallbackVal::Value(closure);
///         let btn = self.get_root().query_selector("button").unwrap().unwrap();
///         let _ = btn.add_event_listener_with_callback(
///             "click",
///             self.get_callback().as_ref().unchecked_ref(),
///         );
///     }
///
///     fn detach_event_handler(&self) {
///         let btn = self.get_this().query_selector("button").unwrap().unwrap();
///         let _ = btn.remove_event_listener_with_callback(
///             "click",
///             self.get_callback().as_ref().unchecked_ref(),
///         );
///     }
///
///     fn get_callback(&self) -> &Closure<dyn FnMut(Event) + 'static> {
///         return match &self.callback {
///             CallbackVal::Value(callback) => callback,
///             &CallbackVal::None => panic!("not a callback!"),
///         };
///     }
///
///     fn get_root(&self) -> &ShadowRoot {
///         return match &self.root {
///             RootVal::Value(root) => &root,
///             RootVal::None => panic!("not a root!"),
///         };
///     }
///
///     fn get_this(&self) -> &HtmlElement {
///         match &self.this {
///             ThisVal::Value(val) => val,
///             ThisVal::None => panic!("not an HtmlElement"),
///         }
///     }
/// }
///
/// #[wasm_bindgen(start)]
/// fn run() {
///     define_element("test-component".to_string(), || -> Box<dyn Component> {
///         Box::new(MyComponent {
///             root: RootVal::None,
///             this: ThisVal::None,
///             callback: CallbackVal::None,
///         })
///     });
/// }
/// ```

fn create_global_func() {
    let _ = create_custom_element().call0(&JsValue::default());
}

pub trait Component {
    /// Gives access to a web_sys::HtmlElement
    /// # Arguments
    ///
    /// * `this` - A structure that holds an HtmlElement
    fn init(&mut self, this: HtmlElement);

    /// Returns list of observed attributes
    fn observed_attributes(&self) -> Vec<String> {
        vec![]
    }

    /// Invoked when one of the custom element's attributes is added, removed, or changed.
    /// # Arguments
    ///
    /// * `_name` - A name of an attribute
    /// * `_old_value` - A previous value of an attribute
    /// * `_old_value` - A new value of an attribute
    fn attribute_changed_callback(&self, _name: String, _old_value: JsValue, _new_value: JsValue);

    /// Invoked when the custom element is first connected to the document's DOM.
    fn connected_callback(&mut self);

    /// Invoked when the custom element is disconnected from the document's DOM.
    fn disconnected_callback(&self);

    /// Invoked when the custom element is moved to a new document.
    fn adopted_callback(&self) {}

    /// Can be invoked to pass state to a custom element
    fn set_data(&mut self, _data: JsValue) {}
}

#[wasm_bindgen]
struct BaseComponent {
    #[allow(dead_code)]
    handler: RefCell<HandlerVal>,
    #[allow(dead_code)]
    component_constructor: fn() -> Box<(dyn Component + 'static)>,
}

#[wasm_bindgen]
impl BaseComponent {
    #[allow(dead_code)]
    pub fn init(&mut self, this: HtmlElement) {
        let is_empty = match &(*self.handler.borrow()) {
            HandlerVal::None => true,
            HandlerVal::Value(_val) => false,
        };
        if is_empty {
            self.handler = RefCell::new(HandlerVal::Value(RefCell::new((self
                .component_constructor)(
            ))));
        }
        self.get_handler().get_mut().init(this);
    }

    #[allow(dead_code)]
    pub fn observed_attributes(&mut self) -> Vec<String> {
        let is_empty = match &(*self.handler.borrow()) {
            HandlerVal::None => true,
            HandlerVal::Value(_val) => false,
        };
        if is_empty {
            self.handler = RefCell::new(HandlerVal::Value(RefCell::new((self
                .component_constructor)(
            ))));
        }
        return self.get_handler().get_mut().observed_attributes();
    }

    #[allow(dead_code)]
    pub fn attribute_changed_callback(
        &mut self,
        _name: String,
        _old_value: JsValue,
        _new_value: JsValue,
    ) {
        self.get_handler()
            .get_mut()
            .attribute_changed_callback(_name, _old_value, _new_value);
    }

    #[allow(dead_code)]
    pub fn connected_callback(&mut self) {
        self.get_handler().get_mut().connected_callback();
    }

    #[allow(dead_code)]
    pub fn disconnected_callback(&mut self) {
        self.get_handler().get_mut().disconnected_callback();
    }

    #[allow(dead_code)]
    pub fn adopted_callback(&mut self) {
        self.get_handler().get_mut().adopted_callback();
    }

    #[allow(dead_code)]
    pub fn set_data(&mut self, _data: JsValue) {
        self.get_handler().get_mut().set_data(_data);
    }

    fn get_handler(&mut self) -> &mut RefCell<Box<dyn Component>> {
        match self.handler.get_mut() {
            HandlerVal::Value(val) => val,
            HandlerVal::None => panic!("not a component"),
        }
    }
}

/// Defines a new custom element
/// # Arguments
///
/// * `name` - A name of a new custom element
/// * `constructor` - Function/Closure which creates an instance of a custom element
pub fn define_element(name: String, constructor: fn() -> Box<dyn Component>) {
    create_global_func();
    let renderer: BaseComponent = BaseComponent {
        handler: RefCell::new(HandlerVal::None),
        component_constructor: constructor,
    };
    _create_custom_element_js(name, renderer);
}

/**
 * Creates a template element with the specified content
 * # Arguments
 *
 * * `template_id` - An id of a template
 * * `template_content` - A string representation of a content without the Template tag.
 *                      Can be validated/sanitized with some great libs <https://crates.io/search?q=sanitize%20html>
 */
pub fn add_template(template_id: String, template_content: String) {
    let window = if let Some(window) = web_sys::window() {
        window
    } else {
        panic!("could not get a window");
    };

    let document = if let Some(document) = window.document() {
        document
    } else {
        panic!("could not get a document");
    };

    let template = if let Ok(template) = document.create_element("template") {
        template
    } else {
        panic!("could not create template element");
    };
    template.set_id(&template_id);
    template.set_inner_html(&template_content);

    let body = if let Some(body) = document.body() {
        body
    } else {
        panic!("could not get a body element");
    };

    if let Err(_) = body.append_child(&template) {
        panic!("could not add a template to the body element");
    };
}

fn create_custom_element() -> Function {
    Function::new_no_args(
        "
            if(window._create_custom_element_js) {
                return;
            }
            window._create_custom_element_js = function(
                name,
                component
            ) {
                class CustomElement extends HTMLElement {
                    constructor() {
                        super();
                        component.init(this);
                    }
            
                    static get observedAttributes() {
                        return component.observed_attributes();
                    }
            
                    setData(data = []) {
                        component.set_data(data);
                    }
            
                    attributeChangedCallback(name, oldValue, newValue) {
                        component.attribute_changed_callback(name, oldValue ?? undefined, newValue);
                    }
            
                    connectedCallback() {
                        component.connected_callback();
                    }
            
                    disconnectedCallback() {
                        component.disconnected_callback();
                    }
            
                    adoptedCallback() {
                        component.adopted_callback();
                    }
                };
                customElements.define(name, CustomElement);
            }
        
    ",
    )
}