webru 0.4.0

Frequently used javascript functions for Rust and WebAssembly
Documentation
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// #![allow(dead_code, unused_variables, unused_imports)]

use wasm_bindgen::JsCast;
use wasm_bindgen_test::wasm_bindgen_test_configure;
use wasm_bindgen_test::*;
use web_sys::{window, HtmlElement};
use weblog::console_log;

use std::cell::Cell;
use std::rc::Rc;

use webru::*;

wasm_bindgen_test_configure!(run_in_browser);

#[wasm_bindgen_test]
fn create_element_test() {
    const INNER_HTML: &str = "Testing time";
    const ID: &str = "heading";

    // Creating an html element `h1` with the `create_element()` function
    let h1 = create_element("h1");

    // Setting some attributes
    h1.set_inner_html(INNER_HTML);
    h1.set_id(ID);

    // inserting the element inside the <body>
    body().append_child(&h1).unwrap();

    // Now asserting the newly created element
    assert_eq!(h1.inner_html(), INNER_HTML);
    assert_eq!(h1.id(), ID);
    assert_ne!(h1.inner_html(), "Wrong heading");
    assert_ne!(h1.id(), "wrong id");
}

#[wasm_bindgen_test]
fn get_element_by_id_test() {
    const PARAGRAPH_ID: &str = "little_para";
    const PARAGRAPH_CLASS: &str = "para graph";

    // Creating an html element <p>
    let p = create_element("p");

    // adding some attributes
    p.set_id(PARAGRAPH_ID);
    p.set_class_name(PARAGRAPH_CLASS);

    {
        // getting the element with the `get_element_by_id` without inserting it into the DOM
        let p = get_element_by_id(PARAGRAPH_ID);

        // at this moment, this should be None because the element hasn't been inserted in the <body>
        assert_eq!(p, None);
    }

    // inserting the element into the <body>
    body().append_child(&p).unwrap();

    // getting this element with the `get_element_by_id` function after inserting it into the DOM
    let p = get_element_by_id(PARAGRAPH_ID);

    // asserting
    assert_eq!(p.clone().unwrap().class_name(), PARAGRAPH_CLASS);
    assert_ne!(p, None);
}

#[wasm_bindgen_test]
fn get_elements_by_classname_test() {
    /// classname of the 1st and 2nd <p>
    const PARAGRAPH_CLASS: &str = "sad fsda fasdf";

    /// id of the 1st <p>
    const PARAGRAPH_1_ID: &str = "@%ASF";
    /// id of the 2nd <p>
    const PARAGRAPH_2_ID: &str = "@%ASGAH";

    // Creating 1st html element <p>
    let p1 = create_element("p");

    // adding some attributes
    p1.set_class_name(PARAGRAPH_CLASS);
    p1.set_id(PARAGRAPH_1_ID);

    // Creating 2nd html element <p>
    let p2 = create_element("p");

    // adding some attributes
    p2.set_class_name(PARAGRAPH_CLASS);
    p2.set_id(PARAGRAPH_2_ID);

    {
        // getting the element with the `get_elements_by_classname` function without inserting it into the DOM
        let p = get_elements_by_classname(PARAGRAPH_CLASS);

        assert_eq!(p.length(), 0);
    }

    // inserting the elements into the DOM
    body().append_child(&p1).unwrap();
    body().append_child(&p2).unwrap();

    // getting the element with the `get_elements_by_classname` function after inserting it into the DOM
    let p = get_elements_by_classname(PARAGRAPH_CLASS);

    // asserting
    assert_eq!(p.length(), 2);
    assert_eq!(p.item(0).unwrap().id(), PARAGRAPH_1_ID);
    assert_eq!(p.item(1).unwrap().id(), PARAGRAPH_2_ID);
}

#[wasm_bindgen_test]
fn get_elements_by_classname_inside_vec_test() {
    /// classname of the 1st and 2nd <p>
    const PARAGRAPH_CLASS: &str = "as dfsadfasd  ffa";

    /// id of the 1st <p>
    const PARAGRAPH_1_ID: &str = "@%asdr4";
    /// id of the 2nd <p>
    const PARAGRAPH_2_ID: &str = "@%@%^^GA";

    // Creating 1st html element <p>
    let p1 = create_element("p");

    // adding some attributes
    p1.set_class_name(PARAGRAPH_CLASS);
    p1.set_id(PARAGRAPH_1_ID);

    // Creating 2nd html element <p>
    let p2 = create_element("p");

    // adding some attributes
    p2.set_class_name(PARAGRAPH_CLASS);
    p2.set_id(PARAGRAPH_2_ID);

    {
        // getting the element with the `get_elements_by_classname` function without inserting it into the DOM
        let p = get_elements_by_classname_inside_vec(PARAGRAPH_CLASS);

        assert_eq!(p.len(), 0);
    }

    // inserting the elements into the DOM
    body().append_child(&p1).unwrap();
    body().append_child(&p2).unwrap();

    // getting the element with the `get_elements_by_classname` function after inserting it into the DOM
    let p = get_elements_by_classname_inside_vec(PARAGRAPH_CLASS);

    // asserting
    assert_eq!(p.len(), 2);
    assert_eq!(p[0].id(), PARAGRAPH_1_ID);
    assert_eq!(p[1].id(), PARAGRAPH_2_ID);
}

#[wasm_bindgen_test]
fn query_selector_test() {
    /// id of the <p>
    const PARAGRAPH_ID: &str = "peraid";

    /// class of the <p>
    const PARAGRAPH_CLASS: &str = "perapera";

    // Creating an html element <p>
    let p = create_element("p");

    // adding some attributes
    p.set_id(PARAGRAPH_ID);
    p.set_class_name(PARAGRAPH_CLASS);

    {
        // getting the element with the `query_selector` without inserting it into the DOM
        let p = query_selector(&format!("#{}", PARAGRAPH_ID));

        // at this moment, this should be None because the element hasn't been inserted in the <body>
        assert_eq!(p, None);
    }

    // inserting the element into the <body>
    body().append_child(&p).unwrap();

    // getting the right element with the `query_selector` function after inserting it into the DOM
    let p_right = query_selector(&format!("#{}", PARAGRAPH_ID));

    // geeting the wrong element with the `query_selector` function after inserting it into the DOM
    let p_wrong = query_selector(&format!("#{}", "ewsdfs"));

    // asserting
    assert_eq!(p_right.clone().unwrap().class_name(), PARAGRAPH_CLASS);
    assert_ne!(p_right, p_wrong);
    assert_ne!(p_right, None);
}

#[wasm_bindgen_test]
fn query_selector_all_test() {
    /// classname of the 1st and 2nd <p>
    const PARAGRAPH_CLASS: &str = "sadjfalsdf";

    /// id of the 1st <p>
    const PARAGRAPH_1_ID: &str = "@***>>>";
    /// id of the 2nd <p>
    const PARAGRAPH_2_ID: &str = "!!__<<";

    // Creating 1st html element <p>
    let p1 = create_element("p");

    // adding some attributes
    p1.set_class_name(PARAGRAPH_CLASS);
    p1.set_id(PARAGRAPH_1_ID);

    // Creating 2nd html element <p>
    let p2 = create_element("p");

    // adding some attributes
    p2.set_class_name(PARAGRAPH_CLASS);
    p2.set_id(PARAGRAPH_2_ID);

    {
        // getting the element with the `get_elements_by_classname` function without inserting it into the DOM
        let p = query_selector_all(&format!(".{}", PARAGRAPH_CLASS));

        assert_eq!(p.length(), 0);
    }

    // inserting the elements into the DOM
    body().append_child(&p1).unwrap();
    body().append_child(&p2).unwrap();

    // getting the element with the `get_elements_by_classname` function after inserting it into the DOM
    let p = query_selector_all(&format!(".{}", PARAGRAPH_CLASS));

    // asserting
    assert_eq!(p.length(), 2);
}

#[wasm_bindgen_test]
fn query_selector_all_inside_vec_test() {
    /// classname of the 1st and 2nd <p>
    const PARAGRAPH_CLASS: &str = "cleardldls";

    /// id of the 1st <p>
    const PARAGRAPH_1_ID: &str = "@***>>>";
    /// id of the 2nd <p>
    const PARAGRAPH_2_ID: &str = "!!__<<";

    // Creating 1st html element <p>
    let p1 = create_element("p");

    // adding some attributes
    p1.set_class_name(PARAGRAPH_CLASS);
    p1.set_id(PARAGRAPH_1_ID);

    // Creating 2nd html element <p>
    let p2 = create_element("p");

    // adding some attributes
    p2.set_class_name(PARAGRAPH_CLASS);
    p2.set_id(PARAGRAPH_2_ID);

    {
        // getting the element with the `get_elements_by_classname` function without inserting it into the DOM
        let p = query_selector_all_inside_vec(&format!(".{}", PARAGRAPH_CLASS));

        assert_eq!(p.len(), 0);
    }

    // inserting the elements into the DOM
    body().append_child(&p1).unwrap();
    body().append_child(&p2).unwrap();

    // getting the element with the `get_elements_by_classname` function after inserting it into the DOM
    let p = query_selector_all_inside_vec(&format!(".{}", PARAGRAPH_CLASS));

    // asserting
    assert_eq!(p.len(), 2);
}

#[wasm_bindgen_test]
fn document_test() {
    assert_eq!(document(), window().unwrap().document().unwrap());
}

#[wasm_bindgen_test]
fn location_test() {
    assert_eq!(
        location(),
        window().unwrap().document().unwrap().location().unwrap()
    );
}

#[wasm_bindgen_test]
fn url_test() {
    // For this test, my url is http://127.0.0.1:8000/. Your might be different.

    console_log!("The value of `url()` for your website is: ", url());

    assert_eq!(
        url(),
        web_sys::window()
            .unwrap()
            .document()
            .unwrap()
            .url()
            .unwrap()
    );
}

#[wasm_bindgen_test]
fn body_test() {
    let body = body();

    assert_eq!(body, window().unwrap().document().unwrap().body().unwrap());
    assert_eq!(body.tag_name(), "BODY");
}

#[wasm_bindgen_test]
fn domain_name_test() {
    // In my case the domain name is 127.0.0.1
    assert_eq!(domain_name(), "127.0.0.1");

    console_log!(
        "The value of `domain_name()` for your website is: ",
        domain_name()
    )
}

#[wasm_bindgen_test]
fn path_name_test() {
    assert_eq!(path_name(), "/")
}

#[wasm_bindgen_test]
fn reload_test() {
    // NOTE: You need to test it manually

    // creating a <button> for reloading the page
    let button = create_element("button")
        .dyn_ref::<HtmlElement>()
        .unwrap()
        .clone();

    // adding some attributes
    button.set_inner_html("reload page");

    // callback/callback when the button will be clicked
    let callback = callback(|| {
        // reloading the page
        // if the page is reloaded, then this test is passed
        reload();
    });

    // setting `onclick` property to the <button>
    button.set_onclick(Some(callback.as_ref().dyn_ref().unwrap()));

    callback.forget();

    // creating a <p> for showing a message
    let p = create_element("p");

    // adding innerHtml
    p.set_inner_html("Click this button, if the website reloads after clicking, the test `reload_test` has passed");

    // <hr>
    let hr1 = create_element("hr");
    let hr2 = create_element("hr");

    // inserting the <hr> into the DOM
    body().append_child(&hr1).unwrap();
    // inserting the <p> into the DOM
    body().append_child(&p).unwrap();
    // inserting the <button> into the DOM
    body().append_child(&button).unwrap();
    // inserting the <hr> into the DOM
    body().append_child(&hr2).unwrap();
}

#[wasm_bindgen_test]
fn alert_test() {
    alert("If you see this message, the test `alert_test` has passed");
}

#[wasm_bindgen_test]
fn prompt_test() {
    prompt("If you see this prompt, the test `prompt_test` has passed");
}

#[wasm_bindgen_test]
fn set_timeout_clear_timeout_test() {
    // NOTE: You need to test it manually

    #[derive(Debug)]
    struct SetTimeoutId {
        id: Cell<Option<i32>>,
    }

    const HIDE_DURATION: u16 = 4000; // milli seconds
    let settimeout_id = Rc::new(SetTimeoutId {
        id: Cell::new(None),
    });

    // When this button is clicked, it will be hidden for `HIDE_DURATION` sec, and after that it will be shown again
    let hide_button = create_element("button")
        .dyn_ref::<HtmlElement>()
        .unwrap()
        .clone();

    hide_button.set_inner_html(&format!(
        "Hide this button for {} seconds",
        HIDE_DURATION / 1000
    ));

    // When this button is clicked, if the `hide_button` is hidden, it will be hide forever. Click this button only if the `hide_button` is hidden.
    let cancel_hide_button = create_element("button")
        .dyn_ref::<HtmlElement>()
        .unwrap()
        .clone();

    cancel_hide_button.set_inner_html("Hide that button forever");

    // callback/callback for onclick event for `hide_button`
    let cb = callback({
        let hide_button = hide_button.clone();
        let settimeout_id = Rc::clone(&settimeout_id.clone());

        move || {
            // hiding
            hide_button.style().set_property("display", "none").unwrap();

            let settimeout_id = Rc::clone(&settimeout_id.clone());
            let hide_button = hide_button.clone();

            let timeout_id = set_timeout(
                move || {
                    // display
                    hide_button
                        .style()
                        .set_property("display", "block")
                        .unwrap();
                },
                HIDE_DURATION as i32,
            )
            .unwrap();

            settimeout_id.id.set(Some(timeout_id));
        }
    });

    // setting `onclick` event
    hide_button.set_onclick(Some(cb.as_ref().dyn_ref().unwrap()));

    cb.forget();

    // callback/callback for onclick event for `cancel_hide_button`
    let cb = callback({
        move || {
            let settimeout_id = Rc::clone(&settimeout_id.clone());
            console_log!(format!("set timeout: {:?}", settimeout_id));

            if let Some(id) = settimeout_id.id.get() {
                clear_timeout(id);

                // setting its value to None
                settimeout_id.id.set(None);
            }
        }
    });

    cancel_hide_button.set_onclick(Some(cb.as_ref().dyn_ref().unwrap()));

    cb.forget();

    // <hr>
    let hr1 = create_element("hr");
    let hr2 = create_element("hr");

    // inserting the <hr> into the DOM
    body().append_child(&hr1).unwrap();
    // inserting `hide_button` into the DOM
    body().append_child(&hide_button).unwrap();
    // inserting `cancel_hide_button` into the DOM
    body().append_child(&cancel_hide_button).unwrap();
    // inserting the <hr> into the DOM
    body().append_child(&hr2).unwrap();
}

#[wasm_bindgen_test]
fn set_interval_clear_interval_test() {
    #[derive(Debug)]
    struct SetIntervalId {
        id: Cell<Option<i32>>,
    }

    #[derive(Debug)]
    struct Counter {
        count: Cell<usize>,
    }

    const INTERVAL_SPEED: u32 = 1000; // milliseconds
    let setinterval_id = Rc::new(SetIntervalId {
        id: Cell::new(None),
    });
    let counter = Rc::new(Counter {
        count: Cell::new(0),
    });

    // <p> element for displaying the couter
    let counter_element = create_element("p");
    counter_element.set_inner_html("0");

    // <button> element for start the counter
    let start_counter_button = create_element("button")
        .dyn_ref::<HtmlElement>()
        .unwrap()
        .clone();
    start_counter_button.set_inner_html("Start counter");

    // <button> element for stop the counter
    let stop_counter_button = create_element("button")
        .dyn_ref::<HtmlElement>()
        .unwrap()
        .clone();
    stop_counter_button.set_inner_html("Stop counter");

    // callback for `start_counter_button`
    let cb = callback({
        let counter_element = counter_element.clone();
        let setinterval_id = Rc::clone(&setinterval_id);

        move || {
            let counter = Rc::clone(&counter);

            let interval_id = set_interval(
                {
                    let counter_element = counter_element.clone();

                    move || {
                        counter.count.set(counter.count.get() + 1);
                        counter_element.set_inner_html(&format!("{}", counter.count.get()));
                    }
                },
                INTERVAL_SPEED as i32,
            );
            setinterval_id.id.set(Some(interval_id.unwrap()));
        }
    });

    start_counter_button.set_onclick(Some(cb.as_ref().dyn_ref().unwrap()));

    cb.forget();

    let cb = callback({
        move || {
            if let Some(id) = setinterval_id.id.get() {
                clear_interval(id)
            }
            setinterval_id.id.set(None);
        }
    });

    stop_counter_button.set_onclick(Some(cb.as_ref().dyn_ref().unwrap()));

    cb.forget();

    // <hr>
    let hr1 = create_element("hr");
    let hr2 = create_element("hr");

    // inserting the <hr> into the DOM
    body().append_child(&hr1).unwrap();
    // inserting `counter_element` into the DOM
    body().append_child(&counter_element).unwrap();
    // inserting `hide_button` into the DOM
    body().append_child(&start_counter_button).unwrap();
    // inserting `cancel_hide_button` into the DOM
    body().append_child(&stop_counter_button).unwrap();
    // inserting the <hr> into the DOM
    body().append_child(&hr2).unwrap();
}

#[wasm_bindgen_test]
fn timeout_test() {
    // Wait for 5 secs and look at the console and see if there is an error message. If not then these tests passed.

    #[derive(Clone, Copy, Debug, PartialEq)]
    enum EarthShape {
        Flat,
        Round,
    }

    let earth_shape = Rc::new(Cell::new(EarthShape::Flat));

    {
        let earth_shape = Rc::clone(&earth_shape);
        // setTimeout without stopping it
        Timeout::start(
            move || {
                earth_shape.set(EarthShape::Round);
            },
            4000,
        );
    }

    set_timeout(
        move || {
            assert_eq!(earth_shape.get(), EarthShape::Round);
        },
        5000,
    )
    .unwrap();

    let earth_shape = Rc::new(Cell::new(EarthShape::Flat));

    {
        let earth_shape = Rc::clone(&earth_shape);
        // setTimeout by stopping it
        let timeout_id = Timeout::start(
            move || {
                earth_shape.set(EarthShape::Round);
            },
            4000,
        );
        timeout_id.stop();
    }

    set_timeout(
        move || {
            assert_eq!(earth_shape.get(), EarthShape::Flat);
        },
        5000,
    )
    .unwrap();
}

#[wasm_bindgen_test]
fn interval_test() {
    // Wait for 5-10 secs and look at the console and see if there is an error message. If not then these tests passed.

    #[derive(Clone, Copy, Debug, PartialEq)]
    enum EarthShape {
        Flat,
        Round,
    }

    let earth_shape = Rc::new(Cell::new(EarthShape::Flat));

    {
        let earth_shape = Rc::clone(&earth_shape);
        // setInterval without stopping it
        Interval::start(
            move || {
                earth_shape.set(EarthShape::Round);
            },
            4000,
        );
    }

    set_interval(
        move || {
            assert_eq!(earth_shape.get(), EarthShape::Round);
        },
        5000,
    )
    .unwrap();

    let earth_shape = Rc::new(Cell::new(EarthShape::Flat));

    {
        let earth_shape = Rc::clone(&earth_shape);
        // setInterval by stopping it
        let interval_id = Interval::start(
            move || {
                earth_shape.set(EarthShape::Round);
            },
            4000,
        );
        interval_id.stop();
    }

    set_interval(
        move || {
            assert_eq!(earth_shape.get(), EarthShape::Flat);
        },
        5000,
    )
    .unwrap();
}

#[wasm_bindgen_test]
fn media_query_text() {
    use webru::{body, create_element, media_query};

    let p = create_element("p");
    p.set_inner_html("You cannot see me if you are less then 1000px");

    // render the "p" tag into the DOM
    body().append_child(&p).unwrap();

    media_query(
        // if the window width is less then 1000px
        {
            let p = p.clone();
            move || {
                p.set_inner_html("");
            }
        },
        // if the window width is more then 1000px
        move || {
            p.clone()
                .set_inner_html("You cannot see me if you are less then 1000px");
        },
        // the maxium width when the callback will be called
        1000,
    );
}