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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
extern crate indexmap;
#[cfg(target_arch = "wasm32")]
#[macro_use]
extern crate stdweb;

use std::borrow::Cow;
use vnode::VNode;
use vtext::VText;
use velement::VElement;
use vlist::VList;
#[cfg(target_arch = "wasm32")]
use stdweb::web::event::ConcreteEvent;
use vcomponent::VComponent;

type CowStr = Cow<'static, str>;

mod vnode;
mod vtext;
mod velement;
mod vlist;
mod vcomponent;
#[cfg(target_arch = "wasm32")]
mod vdiff;
#[cfg(target_arch = "wasm32")]
mod events;
mod traits;

#[cfg(target_arch = "wasm32")]
pub use traits::DOMRender;
#[cfg(target_arch = "wasm32")]
pub use events::{DOMEventListener, RenderRequest};
pub use traits::{Render, Component, Lifecycle, ComponentOf};

pub mod prelude {
    pub use vnode::VNode;
    #[cfg(not(target_arch = "wasm32"))]
    pub use traits::RenderToString;
}

pub fn comp<P: ComponentOf>(props: <<P as ComponentOf>::Comp as Component>::Props) -> VComponent where
    P::Comp: Component + 'static {
    VComponent::new::<P::Comp>(props)
}

pub fn txt<T: Into<VText>>(txt: T) -> VText {
    txt.into()
}

pub fn el<T: Into<VElement>>(el: T) -> VElement {
    el.into()
}

pub fn li<T: Into<VList>>(li: T) -> VList {
    li.into()
}

pub fn h<T: Into<VNode>>(node_like: T) -> VNode {
    node_like.into()
}

#[cfg(target_arch = "wasm32")]
pub fn ev<E, T, F>(listener: E) -> Box<events::DOMEvent> where
    E: Into<events::DOMEventListener<T, F>>,
    F: FnMut(T) + 'static,
    T: ConcreteEvent + 'static {
    Box::new(listener.into())
}

#[macro_export]
macro_rules! h {
    // Creates a component vnode with map as props where props is a struct
    (comp $t:ty, { $( $k:ident => $v:expr ),* } $(,)*) => {{
        type T = <<$t as $crate::ComponentOf>::Comp as $crate::Component>::Props;
        $crate::h($crate::comp::<$t>(T {
            $( $k: $v ),*
        }))
    }};
    // Creates a component vnode with no props
    (comp $t:ty) => {
        $crate::h($crate::comp::<$t>(()))
    };
    // Creates vnodes from a vec
    (vec $n:expr) => {
        $crate::h($crate::li($n));
    };
    // Creates keyed vnodes
    ({ $( $k:expr => $v:expr ),* $(,)* }) => {
        $crate::h($crate::li(vec![ $( ($k, $v) ),* ]))
    };
    // Creates default-keyed vnodes
    ([ $( $v:expr ),* $(,)* ]) => {
        $crate::h($crate::li(vec![ $( $v ),* ]))
    };
    // Creates text vnode
    ($n:expr) => {
        $crate::h($crate::txt($n))
    };
    // Creates an empty element
    ($n:expr, _ $(,)*) => {
        $crate::h($crate::el(($n, ())))
    };
    // Creates an element with map based attributes
    ($n:expr, { $($k:expr => $v:expr),* $(,)* } $(,)*) => {
        $crate::h($crate::el(($n, vec![ $( ($k, $v) ),* ])))
    };
    // Creates an element with event handlers
    ($n:expr, [ $( $ev:expr ),* $(,)* ] $(,)*) => {{
        let mut el = $crate::el(($n, ()));
        #[cfg(target_arch = "wasm32")]
        el.set_events(vec![ $( $crate::ev( $ev ) ),* ]);
        $crate::h(el)
    }};
    // Creates an element with map based attributes and event handlers
    ($n:expr, { $($k:expr => $v:expr),* $(,)* }, [ $( $ev:expr ),* $(,)* ] $(,)*) => {{
        let mut el = $crate::el(($n, vec![ $( ($k, $v) ),* ]));
        #[cfg(target_arch = "wasm32")]
        el.set_events(vec![ $( $crate::ev( $ev ) ),* ]);
        $crate::h(el)
    }};
    // Creates an element with map based attributes, event handlers and other arguments
    ($n:expr, { $($k:expr => $v:expr),* $(,)* }, [ $( $ev:expr ),* $(,)* ], $( $o:expr ),* $(,)*) => {{
        let mut el = $crate::el(($n, vec![ $( ($k, $v) ),* ], $( $o ),*));
        #[cfg(target_arch = "wasm32")]
        el.set_events(vec![ $( $crate::ev( $ev ) ),* ]);
        $crate::h(el)
    }};
    // Creates an element with map based attributes along with other arguments
    ($n:expr, { $($k:expr => $v:expr),* $(,)* }, $( $o:expr ),* $(,)*) => {
        $crate::h($crate::el(($n, vec![ $( ($k, $v) ),* ], $( $o ),*)))
    };
    // Creates an element with plain arguments, except attributes (not strictly), and event handlers
    ($n:expr, [ $( $ev:expr ),* $(,)* ], $( $m:expr ),* $(,)*) => {{
        let mut el = $crate::el(($n, $( $m ),*));
        #[cfg(target_arch = "wasm32")]
        el.set_events(vec![ $( $crate::ev( $ev ) ),* ]);
        $crate::h(el)
    }};
    // Creates an element with plain arguments and event handlers
    ($n:expr, $s:expr, [ $( $ev:expr ),* $(,)* ], $( $m:expr ),* $(,)*) => {{
        let mut el = $crate::el(($n, $s, $( $m ),*));
        #[cfg(target_arch = "wasm32")]
        el.set_events(vec![ $( $crate::ev( $ev ) ),* ]);
        $crate::h(el)
    }};
    // Creates an element with plain arguments
    ($n:expr, $( $m:expr ),* $(,)*) => {
        $crate::h($crate::el(($n, $( $m ),*)))
    };
}

#[cfg(test)]
mod test {
    use vtext::VText;
    use vnode::VNode;
    use velement::VElement;
    use std::borrow::Cow;
    #[cfg(target_arch = "wasm32")]
    use stdweb::web::event::InputEvent;
    use traits::{Component, Lifecycle, Render, RenderToString};
    use vcomponent::VComponent;
    use std::rc::Rc;
    use std::cell::RefCell;
    use ComponentOf;

    #[test]
    fn should_create_text_vnode() {
        let node = h!("Hello World");
        assert_eq!(VNode::Text(VText::new("Hello World".into())), node);
    }

    #[test]
    fn should_create_empty_velement() {
        let node = h!("div", _);
        assert_eq!(VNode::Element(VElement::new("div".into(), None, None, None, false)), node);
    }

    #[test]
    fn should_create_texted_velement() {
        let node = h!("span", h!("Hello World"));
        assert_eq!(
            VNode::Element(VElement::new(
                "span".into(),
                None,
                None,
                Some(VNode::Text(VText::new("Hello World".into()))),
                false,
            )),
            node
        );
    }

    #[test]
    fn should_create_self_closing_velement() {
        let node = h!("br", true);
        assert_eq!(
            VNode::Element(VElement::new(
                "br".into(),
                None,
                None,
                None,
                true,
            )),
            node
        );
    }

    #[test]
    fn should_create_vlist() {
        let node = h!({ "1" => h!("div", _), "2" => h!("div", _), "3" => h!("div", _) });
        assert_eq!(
            VNode::List(vec![
                (Cow::from("1"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
                (Cow::from("2"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
                (Cow::from("3"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
            ].into()),
            node
        );
    }

    #[test]
    fn should_create_vlist_without_keys() {
        let node = h!([h!("div", _), h!("div", _), h!("div", _)]);
        assert_eq!(
            VNode::List(vec![
                (Cow::from("0"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
                (Cow::from("1"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
                (Cow::from("2"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
            ].into()),
            node
        );
    }

    #[test]
    fn should_create_vlist_from_vec() {
        let list = vec![h!("div", _), h!("div", _), h!("div", _)];
        let node = h!(vec list);
        assert_eq!(
            VNode::List(vec![
                (Cow::from("0"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
                (Cow::from("1"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
                (Cow::from("2"), VNode::Element(VElement::new("div".into(), None, None, None, false))),
            ].into()),
            node
        );
    }

    #[test]
    fn should_create_velement_with_class() {
        let node = h!("div", vec![("class", "container")]);
        assert_eq!(
            VNode::Element(VElement::new("div".into(), Some("container".into()), None, None, false)),
            node
        );
    }

    #[test]
    fn should_create_velement_with_class_with_alt_syntax() {
        let node = h!("div", { "class" => "container" });
        assert_eq!(
            VNode::Element(VElement::new("div".into(), Some("container".into()), None, None, false)),
            node
        );
    }

    #[test]
    fn should_create_velement_with_attributes() {
        let node = h!("div", { "style" => "background-color: black;" });
        assert_eq!(
            VNode::Element(VElement::new("div".into(), None, Some(vec![("style", "background-color: black;")].into()), None, false)),
            node
        );
    }

    #[test]
    fn should_create_nested_structure() {
        let node = h!("div", h!("span", _));
        assert_eq!(
            VNode::Element(VElement::new(
                "div".into(),
                None,
                None,
                Some(VNode::Element(VElement::new(
                    "span".into(),
                    None,
                    None,
                    None,
                    false))),
                false)
            ),
            node
        );
    }

    #[test]
    fn should_create_heterogenous_vlist() {
        let node = h!([
            h!("div", _),
            h!("Hello World"),
            h!([
                h!("div", _),
                h!("Hello World"),
            ])
        ]);
        assert_eq!(
            VNode::List(vec![
                VNode::Element(VElement::new("div".into(), None, None, None, false)),
                VNode::Text(VText::new("Hello World".into())),
                VNode::List(vec![
                    VNode::Element(VElement::new("div".into(), None, None, None, false)),
                    VNode::Text(VText::new("Hello World".into()))
                ].into())
            ].into()),
            node
        );
    }

    #[test]
    fn should_create_empty_input_with_event() {
        let node = h!("input", [ |_: InputEvent| {} ]);
        assert_eq!(
            VNode::Element(VElement::new("input".into(), None, None, None, false)),
            node
        );
    }

    #[test]
    fn should_create_empty_input_with_attribute_and_event() {
        let node = h!("input", { "disabled" => "true" }, [ |_: InputEvent| {} ]);
        assert_eq!(
            VNode::Element(VElement::new(
                "input".into(),
                None,
                Some(vec![("disabled", "true")].into()),
                None,
                false)
            ),
            node
        );
    }

    #[test]
    fn should_create_texted_div_with_attribute_and_event() {
        let node = h!("div", { "style" => "color: white;" }, [ |_: InputEvent| {} ], h!("Hello"));
        assert_eq!(
            VNode::Element(VElement::new(
                "div".into(),
                None,
                Some(vec![("style", "color: white;")].into()),
                Some(VNode::Text(VText::new("Hello".into()))),
                false)
            ),
            node
        );
    }

    #[test]
    fn should_create_texted_div_with_event() {
        let node = h!("div", [ |_: InputEvent| {} ], h!("Hello"));
        assert_eq!(
            VNode::Element(VElement::new(
                "div".into(),
                None,
                None,
                Some(VNode::Text(VText::new("Hello".into()))),
                false)
            ),
            node
        );
    }

    #[test]
    fn should_create_a_component() {
        struct Button;

        impl Lifecycle for Button {}
        impl Render for Button {
            fn render(&self) -> VNode {
                unimplemented!();
            }
        }

        impl ComponentOf for Button {
            type Comp = ButtonComponent;
        }

        struct ButtonComponent {
            inner: Rc<RefCell<Button>>
        }

        impl Component for ButtonComponent {
            type Props = ();

            fn create(_: (), _: Box<Fn()>) -> Self {
                ButtonComponent {
                    inner: Rc::new(RefCell::new(Button))
                }
            }
            fn update(&mut self, props: Self::Props) {}
            fn props(&self) -> &Self::Props {
                &()
            }
        }

        impl Lifecycle for ButtonComponent {}
        impl Render for ButtonComponent {
            fn render(&self) -> VNode {
                h!("button", h!("Click"))
            }
        }

        let node = h!(comp Button);
        assert_eq!(
            VNode::Component(VComponent::new::<ButtonComponent>(())),
            node
        );
    }

    #[test]
    fn should_print_html_for_empty_div() {
        let node = h!("div", _);
        assert_eq!(node.to_string(), "<div></div>");
    }

    #[test]
    fn should_print_html_for_self_closing_br() {
        let node = h!("br", true);
        assert_eq!(node.to_string(), "<br>");
    }

    #[test]
    fn should_print_html_for_texted_div() {
        let node = h!("div", h!("Hello World"));
        assert_eq!(node.to_string(), "<div>Hello World</div>");
    }

    #[test]
    fn should_print_html_for_attributed_button() {
        let node = h!("button", { "class" => "container", "style" => "background-color: black;" }, h!("Click"));
        assert_eq!(node.to_string(), r#"<button class="container" style="background-color: black;">Click</button>"#)
    }

    #[test]
    fn should_print_html_for_nested_spans() {
        let node = h!("span", h!("span", _));
        assert_eq!(node.to_string(), "<span><span></span></span>");
    }

    #[test]
    fn should_print_html_for_ordered_list() {
        let node = h!("ol", h!([
            h!("li", h!("content")),
            h!("li", h!("content")),
            h!("li", h!("content")),
            h!("li", h!("content")),
        ]));
        assert_eq!(node.to_string(), "<ol><li>content</li><li>content</li><li>content</li><li>content</li></ol>");
    }

    #[test]
    fn should_print_html_for_list_of_text() {
        let node = h!("div", h!([
            h!("Hello"),
            h!("Hello"),
            h!("Hello"),
            h!("Hello"),
        ]));
        assert_eq!(node.to_string(), "<div>HelloHelloHelloHello</div>");
    }

    #[test]
    fn should_print_html_for_plain_list() {
        let node = h!([
            h!("div", _),
            h!("div", _),
            h!("div", _),
            h!("div", _),
        ]);
        assert_eq!(node.to_string(), "<div></div><div></div><div></div><div></div>");
    }

    #[test]
    fn should_print_html_for_component() {
        struct Button;

        impl Lifecycle for Button {}
        impl Render for Button {
            fn render(&self) -> VNode {
                unimplemented!();
            }
        }

        impl ComponentOf for Button {
            type Comp = ButtonComponent;
        }

        struct ButtonComponent {
            inner: Rc<RefCell<Button>>
        }

        impl Component for ButtonComponent {
            type Props = ();

            fn create(_: (), _: Box<Fn()>) -> Self {
                ButtonComponent {
                    inner: Rc::new(RefCell::new(Button))
                }
            }
            fn update(&mut self, props: Self::Props) {}
            fn props(&self) -> &Self::Props {
                &()
            }
        }

        impl Lifecycle for ButtonComponent {}
        impl Render for ButtonComponent {
            fn render(&self) -> VNode {
                h!("button", h!("Click"))
            }
        }

        let mut node = h!(comp Button);
        assert_eq!(node.render_to_string(), "<button>Click</button>");
    }

    #[test]
    fn should_print_html_for_nested_components() {
        struct Button;

        impl Lifecycle for Button {}
        impl Render for Button {
            fn render(&self) -> VNode {
                unimplemented!();
            }
        }

        impl ComponentOf for Button {
            type Comp = ButtonComponent;
        }

        struct ButtonComponent {
            inner: Rc<RefCell<Button>>
        }

        impl Component for ButtonComponent {
            type Props = ();

            fn create(_: (), _: Box<Fn()>) -> Self {
                ButtonComponent {
                    inner: Rc::new(RefCell::new(Button))
                }
            }
            fn update(&mut self, props: Self::Props) {}
            fn props(&self) -> &Self::Props {
                &()
            }
        }

        impl Lifecycle for ButtonComponent {}
        impl Render for ButtonComponent {
            fn render(&self) -> VNode {
                h!("button", h!("Click"))
            }
        }

        struct Div;

        impl Lifecycle for Div {}
        impl Render for Div {
            fn render(&self) -> VNode {
                unimplemented!();
            }
        }
        impl ComponentOf for Div {
            type Comp = DivComponent;
        }

        struct DivComponent {
            inner: Rc<RefCell<Div>>
        }

        impl Component for DivComponent {
            type Props = ();

            fn create(_:(), _: Box<Fn()>) -> Self {
                DivComponent {
                    inner: Rc::new(RefCell::new(Div))
                }
            }
            fn update(&mut self, props: Self::Props) {}
            fn props(&self) -> &Self::Props {
                &()
            }
        }

        impl Lifecycle for DivComponent {}
        impl Render for DivComponent {
            fn render(&self) -> VNode {
                h!("div", h!(comp Button))
            }
        }

        let mut node = h!(comp Div);
        assert_eq!(node.render_to_string(), "<div><button>Click</button></div>");
    }
}