mika 0.0.0

A framework for building wasm front-end web application in Rust
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/*!
Mika does not support deprecated or non standard html tags
*/
use signals::signal::SignalExt;
use signals::signal_vec::{SignalVecExt, VecDiff};
//use wasm_bindgen::JsCast;
use wasm_bindgen::UnwrapThrowExt;

pub mod traits;
use traits::*;

fn create_element(tag: &str) -> web_sys::Element {
    crate::document()
        .create_element(tag)
        .expect_throw("create_element(tag)")
}

fn create_text_node(text: &str) -> web_sys::Text {
    crate::document().create_text_node(text)
}

// TODO: Store all future from signal and stop them when require
fn spawn_for_each<S, F>(signal: S, f: F)
where
    S: signals::signal::Signal + 'static,
    F: Fn(S::Item) + 'static,
{
    let f = signal.for_each(move |value| {
        f(value);
        futures_util::future::ready(())
    });
    wasm_bindgen_futures::futures_0_3::spawn_local(f);
}

// TODO: Store all future from signal and stop them when require
fn spawn_for_each_vec<S, F>(signal: S, f: F)
where
    S: signals::signal_vec::SignalVec + 'static,
    F: Fn(VecDiff<S::Item>) + 'static,
{
    let f = signal.for_each(move |value| {
        f(value);
        futures_util::future::ready(())
    });
    wasm_bindgen_futures::futures_0_3::spawn_local(f);
}

impl<T: Element> GlobalAttributes for T {}

pub enum InputType {
    Button,
    CheckBox,
    Color,
    Date,
    DateTimeLocal,
    Email,
    File,
    Hidden,
    Image,
    Month,
    Number,
    Password,
    Radio,
    Range,
    Reset,
    Search,
    Submit,
    Tel,
    Text,
    Time,
    Url,
    Week,
}
impl InputType {
    fn as_str(&self) -> &str {
        match self {
            InputType::Button => "button",
            InputType::CheckBox => "checkbox",
            InputType::Color => "color",
            InputType::Date => "date",
            InputType::DateTimeLocal => "datetime-local",
            InputType::Email => "email",
            InputType::File => "file",
            InputType::Hidden => "hidden",
            InputType::Image => "image",
            InputType::Month => "month",
            InputType::Number => "number",
            InputType::Password => "password",
            InputType::Radio => "radio",
            InputType::Range => "range",
            InputType::Reset => "reset",
            InputType::Search => "search",
            InputType::Submit => "submit",
            InputType::Tel => "tel",
            InputType::Text => "text",
            InputType::Time => "time",
            InputType::Url => "url",
            InputType::Week => "week",
        }
    }
}

macro_rules! define_html_elements {
    ($(
        $([mdn=$doc_link:expr])? $html_element_tag:ident $HtmlElementType:ident $([$($tt:tt)+])?
    ),+) => {
        pub enum Node {
            $(
                $HtmlElementType($HtmlElementType),
            )+
            NodeList(NodeList),
        }
        impl Node {
            pub(crate) fn append_to(&self, parent: &web_sys::Node) {
                match self {
                    $(
                        Node::$HtmlElementType(element) => element.append_to(parent),
                    )+
                    Node::NodeList(list) => list.append_to(parent),
                }
            }

            pub(crate) fn insert_at(&self, index: usize, parent: &web_sys::Node) {
                match self {
                    $(
                        Node::$HtmlElementType(element) => element.insert_at(index, parent),
                    )+
                    Node::NodeList(_) => {
                        log::info!("Node::NodeList::remove_from do nothing");
                    }
                }
            }

            pub(crate) fn remove_from(&self, parent: &web_sys::Node) {
                match self {
                    $(
                        Node::$HtmlElementType(element) => element.remove_from(parent),
                    )+
                    Node::NodeList(_) => {
                        log::info!("Node::NodeList::remove_from do nothing");
                    }
                }
            }
        }
        $(
            define_html_elements!{ @doc $($doc_link)?, $html_element_tag $HtmlElementType $([$($tt)+])? }
        )+
    };
    ( @doc $doc_link:expr, $html_element_tag:ident $HtmlElementType:ident $([$($tt:tt)+])? ) => {
        define_html_elements!{ @one_element $doc_link, $html_element_tag $HtmlElementType $([$($tt)+])? }
    };
    ( @doc , $html_element_tag:ident $HtmlElementType:ident $([$($tt:tt)+])? ) => {
        define_html_elements!{ @one_element
            concat!("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($html_element_tag)),
            $html_element_tag $HtmlElementType $([$($tt)+])?
        }
    };
    (@one_element $doc_link:expr, $html_element_tag:ident $HtmlElementType:ident) => {
        #[doc = $doc_link]
        pub struct $HtmlElementType {
            websys_element: web_sys::Element,
            listeners: Vec<Box<crate::events::Listener>>,
        }

        impl $HtmlElementType {
            pub fn new() -> Self {
                Self {
                    websys_element: create_element(stringify!($html_element_tag)),
                    listeners: Vec::new(),
                }
            }
        }

        impl Default for $HtmlElementType {
            fn default() -> Self {
                Self::new()
            }
        }

        impl From<$HtmlElementType> for Node {
            fn from(item: $HtmlElementType) -> Self {
                Node::$HtmlElementType(item)
            }
        }

        impl Element for $HtmlElementType {
            fn websys_element(&self) -> &web_sys::Element {
                &self.websys_element
            }

            fn websys_node(&self) -> &web_sys::Node {
                self.websys_element.as_ref()
            }

            fn store_future(&mut self) {
                //
            }

            fn listeners_mut(&mut self) -> &mut Vec<Box<crate::events::Listener>> {
                &mut self.listeners
            }
        }
    };
    (@one_element $doc_link:expr, $html_element_tag:ident $HtmlElementType:ident [$($tt:tt)+]) => {
        #[doc = $doc_link]
        pub struct $HtmlElementType {
            websys_element: web_sys::Element,
            listeners: Vec<Box<crate::events::Listener>>,
            node_list: std::sync::Arc<std::sync::Mutex<NodeList>>,
        }

        impl $HtmlElementType {
            pub fn new() -> Self {
                Self {
                    websys_element: create_element(stringify!($html_element_tag)),
                    listeners: Vec::new(),
                    node_list: std::sync::Arc::new(std::sync::Mutex::new(NodeList::new())),
                }
            }
            pub fn child<T: Attachable + Into<Node> + $($tt)+>(self, child: T) -> Self {
                self.push_child(child)
            }
        }

        impl Default for $HtmlElementType {
            fn default() -> Self {
                Self::new()
            }
        }

        impl From<$HtmlElementType> for Node {
            fn from(item: $HtmlElementType) -> Self {
                Node::$HtmlElementType(item)
            }
        }

        impl Element for $HtmlElementType {
            fn websys_element(&self) -> &web_sys::Element {
                &self.websys_element
            }

            fn websys_node(&self) -> &web_sys::Node {
                self.websys_element.as_ref()
            }

            fn store_future(&mut self) {
                //
            }

            fn listeners_mut(&mut self) -> &mut Vec<Box<crate::events::Listener>> {
                &mut self.listeners
            }
        }

        impl HasChildren for $HtmlElementType {
            fn node_list(&self) -> std::sync::Arc<std::sync::Mutex<NodeList>> {
                std::sync::Arc::clone(&self.node_list)
            }
        }
    };
}

macro_rules! implement_marker_trait_for {
    ($($TraitName:ident {$($ElementType:ident)+})+) => {
        $(
            $(
                impl $TraitName for $ ElementType {}
            )+
        )+
    }
}

define_html_elements! {
    // See ChildOfA in traits.rs
    a A [ChildOfA],
    abbr Abbr [PhrasingContent],
    // TODO How about special conditions?
    address Address [FlowContent],
    // area is an empty element
    area Area,
    article Article [FlowContent],
    aside Aside [FlowContent],
    audio Audio [ChildOfAudioVideo],
    b B [PhrasingContent],
    bdi Bdi [PhrasingContent],
    bdo Bdo [PhrasingContent],
    blockquote BlockQuote [FlowContent],
    // br is an empty element
    br Br,
    // TODO PhrasingNonInteractiveContent must not appear as descendant as well
    button Button [PhrasingNonInteractiveContent],
    // TODO Transparent but with no interactive content descendants except for <a> elements,
    // <button> elements, <input> elements whose type attribute is checkbox, radio, or button.
    canvas Canvas [Element],
    caption Caption [FlowContent],
    cite Cite [PhrasingContent],
    code Code [PhrasingContent],
    // col is an empty element
    col Col,
    colgroup ColGroup [TraitCol],
    data Data [PhrasingContent],
    datalist DataList [ChildOfDataList],
    dd Dd [FlowContent],
    // TODO Transparent?
    // Allow everything for now
    // See also ins
    del Del [Element],
    // TODO One <summary> element followed by flow content.
    details Details [ChildOfDetails],
    // TODO No dfn descendant
    dfn Dfn [PhrasingContent],
    dialog Dialog [FlowContent],
    div Div [FlowContent],
    // TODO Either
    // * (dt)+ (dd)+
    // * (div)+
    dl Dl [ChildOfDl],
    dt Dt [FlowContent],
    em Em [PhrasingContent],
    // embed is an empty element
    embed Embed,
    fieldset FieldSet [ChildOfFieldSet],
    figcaption FigCaption [FlowContent],
    // TODO Replace ChildOfFigure by FlowContent and TraitCaption?
    figure Figure [ChildOfFigure],
    // TODO How about no header or no footer descendant?
    footer Footer [FlowContent],
    // TODO Not contains a form
    form Form [FlowContent],
    h1 H1 [PhrasingContent],
    h2 H2 [PhrasingContent],
    h3 H3 [PhrasingContent],
    h4 H4 [PhrasingContent],
    h5 H5 [PhrasingContent],
    h6 H6 [PhrasingContent],
    // TODO How about no header or no footer descendant?
    header Header [FlowContent],
    hgroup Hgroup [Headings],
    // hr is an empty element
    hr Hr,
    i I [PhrasingContent],
    // TODO: Fallback content?
    // Allow everything now
    iframe Iframe [Element],
    // img is an empty element
    img Img,
    // input is an empty element
    input Input,
    // TODO Transparent?
    // Allow everything for now
    // See also del
    ins Ins [Element],
    kbd Kbd [PhrasingContent],
    // TODO No label descendant or actually FormLabelableContent?
    label Label [PhrasingContent],
    legend Legend [PhrasingContent],
    li Li [FlowContent],
    main Main [FlowContent],
    // TODO Any transparent element.?
    // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map
    map Map [Element],
    mark Mark [PhrasingContent],
    // TODO <math>'s children
    [mdn = "https://developer.mozilla.org/en-US/docs/Web/MathML/Element/math"]
    math Math,
    // This is an experimental technology. Check the Browser compatibility table carefully before using this in production.
    // Not support now.
    // ==========> menu Menu,
    // Deprecated since HTML5.2
    // ==========> menuitem MenuItem,
    // TODO No meter descendant
    meter Meter [PhrasingContent],
    nav Nav [FlowContent],
    // TODO Does this need to be supported in mika?
    // Will mika support for SSR?
    // ==========> noscript NoScript [Element],
    // TODO zero or more <param> elements, then transparent.
    object Object [Element],
    ol Ol [TraitLi],
    optgroup OptGroup [TraitOption],
    // Text only, TextContent is impled for Option
    option Option,
    output Output [PhrasingContent],
    p P [PhrasingContent],
    // param is an empty element
    param Param,
    // Replace ChildOfPicture with TraitPicture and TraitSource?
    picture Picture [ChildOfPicture],
    pre Pre [PhrasingContent],
    // TODO no progress descendant
    progress Progress [PhrasingContent],
    q Q [PhrasingContent],
    // Text only, TextContent is impled for Rp
    rp Rp,
    rt Rt [PhrasingContent],
    rtc Rtc [ChildOfRtc],
    ruby Ruby [PhrasingContent],
    s S [PhrasingContent],
    samp Samp [PhrasingContent],
    // ==========> script Script, Not support in mika
    section Section [FlowContent],
    select Select [ChildOfSelect],
    // TODO Transparent?
    slot Slot [Element],
    small Small [PhrasingContent],
    // source is an empty element
    source Source,
    span Span [PhrasingContent],
    strong Strong [PhrasingContent],
    sub Sub [PhrasingContent],
    summary Summary [ChildOfSummary],
    sup Sup [PhrasingContent],
    // TODO <svg>'s children
    [mdn = "https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg"]
    svg Svg,
    table Table [ChildOfTable],
    tbody Tbody [TraitTr],
    td Td [FlowContent],
    template Template [Element],
    // impled text by TraitTextArea
    textarea TextArea,
    tfoot Tfoot [TraitTr],
    // TODO Flow content, but with no header, footer, sectioning content, or heading content descendants.
    th Th [FlowContent],
    thead Thead [TraitTr],
    time Time [PhrasingContent],
    // TODO Zero or more <td> and/or <th> elements; script-supporting elements (<script> and <template>) are also allowed
    tr Tr [ChildOfTr],
    // tract is an empty element
    track Track,
    u U [PhrasingContent],
    ul Ul [TraitLi],
    var Var [PhrasingContent],
    video Video [ChildOfAudioVideo],
    // Empty element
    wbr Wbr
}

implement_marker_trait_for! {
    // Category traits
    EmbeddedContent { Audio Canvas Embed Iframe Img Math Object Picture Svg Video }
    FlowContent { A Abbr Address Article Aside Audio B Bdi Bdo BlockQuote Br Button
        Canvas Cite Code Data DataList Del Details Dfn Div Dl
        Em Embed FieldSet Figure Footer Form
        H1 H2 H3 H4 H5 H6 Header Hgroup Hr
        I Iframe Img Input Ins Kbd Label
        Main Map Mark Math /*Menu*/ Meter Nav /*NoScript*/
        Object Ol Output P Picture Pre Progress Q Ruby
        S Samp /*Script*/ Section Select Small Span Strong Sub Sup Svg
        Table Template TextArea Time
        U Ul Var Video Wbr
    }
    FlowNonInteractiveContent { Abbr Address Article Aside Audio
        B Bdi Bdo BlockQuote Br Canvas Cite Code
        Data DataList Del Dfn Div Dl Em FieldSet Figure Footer Form
        H1 H2 H3 H4 H5 H6 Header Hgroup Hr I Img Input Ins Kbd
        Main Map Mark Math /*Menu*/ Meter Nav /*NoScript*/
        Object Ol Output P Picture Pre Progress Q Ruby
        S Samp /*Script*/ Section Small Span Strong Sub Sup Svg
        Table Template Time U Ul Var Video Wbr
    }
    FormContent { Button FieldSet Input Label Meter Object Output Progress Select TextArea }
    FormListedContent { Button FieldSet Input Object Output Select TextArea }
    FormLabelableContent { Button Input Meter Output Progress Select TextArea }
    FormSubmittableContent { Button Input Object Select TextArea }
    FormResettableContent { Input Output Select TextArea }
    HeadingContent { H1 H2 H3 H4 H5 H6 Hgroup }
    // TODO: audio, img, input, menu, object, video
    InteractiveContent { A Button Details Embed Iframe Label Select TextArea }
    //MetadataContent { NoScript Script}
    PhrasingContent {
        // TODO: link, meta?
        // TODO: This first line contains elements that is phrasing content with a specific condition
        A Area Del Ins Map
        Abbr Audio B Bdo Br Button Canvas Cite Code
        Data DataList Dfn Em Embed I Iframe Img Input
        Kbd Label Mark Math Meter /*NoScript*/ Object Output Picture Progress Q Ruby
        Samp /*Script*/ Select Small Span Strong Sub Svg TextArea Time U Var Video
    }
    PhrasingNonInteractiveContent {
        Abbr Audio B Bdo Br Canvas Cite Code
        Data DataList Dfn Em I Img Input
        Kbd Mark Math Meter /*NoScript*/ Object Output Picture Progress Q Ruby
        Samp /*Script*/ Small Span Strong Sub Svg Time U Var Video
    }
    SectioningContent { Article Aside Nav Section }
    // Special traits
    TextContent { Option Rp}
    Headings { H1 H2 H3 H4 H5 H6 }
    TraitA { A }
    TraitCol { Col }
    TraitInput { Input }
    TraitLabel { Label }
    TraitLi { Li }
    TraitOption { Option }
    TraitTextArea { TextArea }
    // ChildOfXXX
    ChildOfAudioVideo { Source Track }
    ChildOfDataList { Option }
    ChildOfDetails { Summary }
    ChildOfDl { Div Dd Dt }
    ChildOfFieldSet { Legend }
    ChildOfFigure { FigCaption }
    ChildOfPicture { Img Source }
    ChildOfRtc { Rt }
    ChildOfSelect { Option OptGroup }
    ChildOfSummary { H1 H2 H3 H4 H5 H6 Hgroup }
    ChildOfTable { Caption ColGroup Thead Tbody Tr Tfoot }
    ChildOfTr { Td Th }
}

pub struct NodeList {
    nodes: Vec<Node>,
}

impl Attachable for NodeList {
    fn append_to(&self, parent: &web_sys::Node) {
        self.nodes.iter().for_each(|n| {
            n.append_to(parent);
        })
    }
    fn insert_at(&self, _: usize, _: &web_sys::Node) {
        log::info!("Attachable::insert_at(self: &NodeList) do nothing!");
    }
    fn replace_at(&self, _: usize, _: &web_sys::Node) {
        log::info!("Attachable::replace_at(self: &NodeList) do nothing!");
    }
    fn remove_from(&self, _: &web_sys::Node) {
        log::info!("Attachable::remove_from(self: &NodeList) do nothing!");
    }
}

impl NodeList {
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    pub fn child<T>(mut self, child: T) -> Self
    where
        T: Into<Node>,
    {
        self.nodes.push(child.into());
        self
    }
}

impl Default for NodeList {
    fn default() -> Self {
        Self::new()
    }
}

impl From<NodeList> for Node {
    fn from(item: NodeList) -> Self {
        Node::NodeList(item)
    }
}

pub trait HasChildren: Element + Sized {
    fn node_list(&self) -> std::sync::Arc<std::sync::Mutex<NodeList>>;
    /// This is primarily for internal use only
    fn push_child<T>(self, child: T) -> Self
    where
        T: Attachable + Into<Node>,
    {
        child.append_to(self.websys_node());
        self.node_list()
            .lock()
            .expect_throw("self.node_list().lock()")
            .nodes
            .push(child.into());
        self
    }

    /// Create children for self from a SignalVec. You should not add any child via .child
    /// on the element you invoke this method.
    fn list_signal<S, T, F, N>(self, signal: S, render_item: F) -> Self
    where
        T: Clone + 'static,
        S: signals::signal_vec::SignalVec<Item = T> + 'static,
        F: Fn(T) -> N + 'static,
        N: crate::dom::Element + Into<crate::dom::Node>,
    {
        let parent_node = self.websys_node().clone();
        let child_list = self.node_list();

        debug_assert_eq!(
            0,
            child_list
                .lock()
                .expect_throw("child_list.lock()")
                .nodes
                .len()
        );

        spawn_for_each_vec(signal, move |change| {
            let mut child_list = child_list.lock().expect_throw("child_list.lock()");
            match change {
                VecDiff::Replace { values } => {
                    //log::info!("Replace all items");

                    parent_node.set_text_content(None);
                    child_list.nodes.clear();

                    values.into_iter().for_each(|item| {
                        let child = render_item(item);
                        child.append_to(&parent_node);
                        child_list.nodes.push(child.into());
                    });
                }
                VecDiff::Push { value } => {
                    //log::info!("Current item count: {}, push new item", child_list.nodes.len());

                    let child = render_item(value);
                    child.append_to(&parent_node);
                    child_list.nodes.push(child.into());
                }
                VecDiff::Pop {} => {
                    debug_assert!(!child_list.nodes.is_empty());

                    child_list
                        .nodes
                        .pop()
                        .expect_throw("child_list.nodes.pop()")
                        .remove_from(&parent_node);
                }
                VecDiff::InsertAt { index, value } => {
                    //log::info!("Insert new item at {}", index);

                    let child = render_item(value);
                    child.insert_at(index, &parent_node);
                    child_list.nodes.insert(index, child.into());
                }
                VecDiff::RemoveAt { index } => {
                    //log::info!("Current item count: {}, remove at {}", child_list.nodes.len(), index);

                    child_list.nodes.remove(index).remove_from(&parent_node);
                }
                VecDiff::UpdateAt { index, value } => {
                    //log::info!("Current item count: {}, update at {}", child_list.nodes.len(), index);
                    let child = render_item(value);
                    child.replace_at(index, &parent_node);
                }
                VecDiff::Move {
                    old_index,
                    new_index,
                } => {
                    let moved = child_list.nodes.remove(old_index);
                    // TODO: Does this need to be removed_from first?
                    // This desperately need a #[test]
                    moved.remove_from(&parent_node);
                    moved.insert_at(new_index, &parent_node);
                    child_list.nodes.insert(new_index, moved);
                }
                VecDiff::Clear {} => {
                    parent_node.set_text_content(None);
                    child_list.nodes.clear();
                }
            }
        });
        self
    }
}