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
use crate::events::MountEvent;
use crate::Listener;
use crate::{
dom::Dispatch,
html,
html::attributes::{AttributeValue, SegregatedAttributes, Special},
Attribute, Event,
};
use once_cell::sync::OnceCell;
use std::{collections::HashMap, sync::Mutex};
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
use web_sys::{
self, Element, EventTarget, HtmlElement, HtmlInputElement,
HtmlTextAreaElement, Node, Text,
};
static DATA_SAURON_VDOM_ID_VALUE: OnceCell<Mutex<u32>> = OnceCell::new();
fn create_unique_identifier() -> u32 {
let mut elem_unique_id = DATA_SAURON_VDOM_ID_VALUE
.get_or_init(|| Mutex::new(0))
.lock()
.expect("Unable to obtain lock");
*elem_unique_id += 1;
*elem_unique_id
}
pub(crate) const DATA_VDOM_ID: &str = "data-vdom-id";
pub type ActiveClosure =
HashMap<u32, Vec<(&'static str, Closure<dyn FnMut(web_sys::Event)>)>>;
#[derive(Debug)]
pub struct CreatedNode {
pub node: Node,
pub(crate) closures: ActiveClosure,
}
impl CreatedNode {
pub fn without_closures(node: Node) -> Self {
CreatedNode {
node,
closures: HashMap::with_capacity(0),
}
}
pub fn create_text_node(txt: &str) -> Text {
crate::document().create_text_node(txt)
}
pub fn create_dom_node<DSP, MSG>(
program: &DSP,
vnode: &crate::Node<MSG>,
focused_node: &mut Option<Node>,
) -> CreatedNode
where
MSG: 'static,
DSP: Clone + Dispatch<MSG> + 'static,
{
match vnode {
crate::Node::Text(txt) => {
let text_node = Self::create_text_node(&txt.text);
CreatedNode::without_closures(text_node.unchecked_into())
}
crate::Node::Element(element_node) => {
Self::create_element_node(program, element_node, focused_node)
}
}
}
fn dispatch_mount_event<DSP, MSG>(
program: &DSP,
velem: &crate::Element<MSG>,
element: &Element,
) where
MSG: 'static,
DSP: Clone + Dispatch<MSG> + 'static,
{
for att in velem.attrs.iter() {
if *att.name() == "mount" {
for val in att.value().iter() {
if let AttributeValue::EventListener(cb) = val {
let msg = cb.emit(Event::from(MountEvent {
target_node: element.clone().unchecked_into(),
}));
program.dispatch(msg);
}
}
}
}
}
fn create_element_node<DSP, MSG>(
program: &DSP,
velem: &crate::Element<MSG>,
focused_node: &mut Option<Node>,
) -> CreatedNode
where
MSG: 'static,
DSP: Clone + Dispatch<MSG> + 'static,
{
let document = crate::document();
let element = if let Some(namespace) = velem.namespace() {
document
.create_element_ns(Some(namespace), velem.tag())
.expect("Unable to create element")
} else {
document
.create_element(velem.tag())
.expect("Unable to create element")
};
Self::dispatch_mount_event(program, velem, &element);
if velem.is_focused() {
*focused_node = Some(element.clone().unchecked_into());
log::trace!("element is focused..{:?}", focused_node);
}
let mut closures = ActiveClosure::new();
Self::set_element_attributes(
program,
&mut closures,
&element,
&velem.get_attributes().iter().collect::<Vec<_>>(),
);
let mut previous_node_was_text = false;
for child in velem.get_children().iter() {
match child {
crate::Node::Text(txt) => {
let current_node: &web_sys::Node = element.as_ref();
if previous_node_was_text {
let separator = document.create_comment("mordor");
current_node
.append_child(separator.as_ref())
.expect("Unable to append child");
}
if txt.safe_html {
element
.insert_adjacent_html("beforeend", &txt.text)
.expect("must not error");
} else {
let text_node = Self::create_text_node(&txt.text);
current_node
.append_child(&text_node)
.expect("Unable to append text node");
}
previous_node_was_text = true;
}
crate::Node::Element(_element_node) => {
previous_node_was_text = false;
let created_child =
Self::create_dom_node(program, child, focused_node);
closures.extend(created_child.closures);
element
.append_child(&created_child.node)
.expect("Unable to append element node");
}
}
}
let node: Node = element.unchecked_into();
CreatedNode { node, closures }
}
pub fn set_element_attributes<DSP, MSG>(
program: &DSP,
closures: &mut ActiveClosure,
element: &Element,
attrs: &[&Attribute<MSG>],
) where
MSG: 'static,
DSP: Clone + Dispatch<MSG> + 'static,
{
let attrs = mt_dom::merge_attributes_of_same_name(attrs);
for att in attrs {
Self::set_element_attribute(program, closures, element, &att);
}
}
pub fn set_element_attribute<DSP, MSG>(
program: &DSP,
closures: &mut ActiveClosure,
element: &Element,
attr: &Attribute<MSG>,
) where
MSG: 'static,
DSP: Clone + Dispatch<MSG> + 'static,
{
let SegregatedAttributes {
listeners,
plain_values,
styles,
function_calls,
} =
html::attributes::partition_callbacks_from_plain_styles_and_func_calls(
attr,
);
if let Some(merged_plain_values) =
html::attributes::merge_plain_attributes_values(&plain_values)
{
if let Some(namespace) = attr.namespace() {
element
.set_attribute_ns(
Some(namespace),
attr.name(),
&merged_plain_values,
)
.unwrap_or_else(|_| {
panic!(
"Error setting an attribute_ns for {:?}",
element
)
});
} else {
match *attr.name() {
"value" => {
if let Some(input) =
element.dyn_ref::<HtmlInputElement>()
{
input.set_value(&merged_plain_values);
} else if let Some(textarea) =
element.dyn_ref::<HtmlTextAreaElement>()
{
textarea.set_value(&merged_plain_values);
}
}
"checked" => {
if let Some(input) =
element.dyn_ref::<HtmlInputElement>()
{
let checked: bool = plain_values
.first()
.map(|av| {
av.get_simple()
.map(|v| v.as_bool())
.flatten()
})
.flatten()
.unwrap_or(false);
input.set_checked(checked);
}
}
_ => {
element
.set_attribute(attr.name(), &merged_plain_values)
.unwrap_or_else(|_| {
panic!(
"Error setting an attribute for {:?}",
element
)
});
}
}
}
} else if let Some(merged_styles) =
html::attributes::merge_styles_attributes_values(&styles)
{
element
.set_attribute(attr.name(), &merged_styles)
.unwrap_or_else(|_| {
panic!("Error setting an attribute_ns for {:?}", element)
});
} else {
element
.remove_attribute(attr.name())
.expect("must remove attribute");
}
if let Some(merged_func_values) =
html::attributes::merge_plain_attributes_values(&function_calls)
{
if *attr.name() == "inner_html" {
element.set_inner_html(&merged_func_values);
}
}
for listener in listeners {
let unique_id = create_unique_identifier();
element
.set_attribute(DATA_VDOM_ID, &unique_id.to_string())
.expect("Could not set attribute on element");
closures.insert(unique_id, vec![]);
let event_str = attr.name();
let current_elm: &EventTarget =
element.dyn_ref().expect("unable to cast to event targe");
if *event_str == "enter" {
let program_clone = program.clone();
let listener_clone = listener.clone();
let key_press_func: Closure<dyn FnMut(web_sys::Event)> =
Closure::wrap(Box::new(move |event: web_sys::Event| {
let ke: &web_sys::KeyboardEvent = event
.dyn_ref()
.expect("should be a keyboard event");
if ke.key() == "Enter" {
let msg = listener_clone.emit(Event::from(event));
program_clone.dispatch(msg);
}
}));
current_elm
.add_event_listener_with_callback(
"keypress",
key_press_func.as_ref().unchecked_ref(),
)
.expect("unable to attach enter event listener");
key_press_func.forget();
} else {
let callback_wrapped: Closure<dyn FnMut(web_sys::Event)> =
create_closure_wrap(program, listener);
current_elm
.add_event_listener_with_callback(
event_str,
callback_wrapped.as_ref().unchecked_ref(),
)
.expect("Unable to attached event listener");
closures
.get_mut(&unique_id)
.expect("Unable to get closure")
.push((event_str, callback_wrapped));
}
}
}
pub(crate) fn set_element_focus(element: &Element) {
let html_element: &HtmlElement = element.unchecked_ref();
html_element.focus().expect("must focus")
}
pub fn remove_element_attribute<MSG>(
element: &Element,
attr: &Attribute<MSG>,
) -> Result<(), JsValue> {
log::trace!("removing attribute: {}", attr.name());
element.remove_attribute(attr.name())?;
if *attr.name() == "checked" {
if let Some(input) = element.dyn_ref::<HtmlInputElement>() {
input.set_checked(false);
}
}
Ok(())
}
}
pub(crate) fn create_closure_wrap<DSP, MSG>(
program: &DSP,
listener: &Listener<MSG>,
) -> Closure<dyn FnMut(web_sys::Event)>
where
MSG: 'static,
DSP: Clone + Dispatch<MSG> + 'static,
{
let listener_clone = listener.clone();
let program_clone = program.clone();
Closure::wrap(Box::new(move |event: web_sys::Event| {
let msg = listener_clone.emit(Event::from(event));
program_clone.dispatch(msg);
}))
}