vertigo 0.14.1

Reactive Real-DOM library with SSR for Rust
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
use std::rc::Rc;

use crate::{
    AttrGroupValue, Computed, DomText, Drawing, DropFileItem, DropResource, JsJson,
    dev::JsJsonListDecoder,
    driver_module::{StaticString, api::api_callbacks, get_driver_dom},
    struct_mut::{ValueMut, VecDequeMut, VecMut},
};

use super::{
    attr_value::{AttrText, AttrValue, CssAttrValue, IntoAttrValue},
    callback::{Callback, Callback1},
    dom_element_class::{ClassState, DomElementClassMerge},
    dom_element_ref::DomElementRef,
    dom_id::DomId,
    dom_node::DomNode,
    events::{
        ClickEvent, DropFileEvent, IntersectionEvent, KeyDownEvent, PointerEvent, WheelEvent,
    },
};

/// A Real DOM representative - element kind
pub struct DomElement {
    id_dom: DomId,
    child_node: VecDequeMut<DomNode>,
    subscriptions: VecMut<DropResource>,
    /// See [`ClassState`]: inline until this element turns out to need a shared cell, which
    /// only a `css` or a reactive class does. `ValueMut` is a bare cell with no indirection
    /// of its own, so a static class allocates nothing at all.
    class_state: ValueMut<ClassState>,
}

impl DomElement {
    pub fn new(name: impl Into<StaticString>) -> Self {
        let name = name.into();
        let id_dom = DomId::from_name(name.as_str());

        get_driver_dom().create_node(id_dom, name);

        Self {
            id_dom,
            child_node: VecDequeMut::new(),
            subscriptions: VecMut::new(),
            class_state: ValueMut::new(ClassState::Empty),
        }
    }

    /// The shared merger, built on demand. Only a `css` or a reactive class needs one.
    fn class_manager(&self) -> DomElementClassMerge {
        self.class_state.change(|state| state.merger(self.id_dom))
    }

    /// An attribute whose name *and* value were literals in the source.
    ///
    /// Worth its own entry point rather than going through [`AttrValue`]: that enum has six
    /// variants, four of them reactive, and a literal can only ever be one of them. Reaching
    /// them through a shared non-generic function keeps `Computed`, `Value` and their drop
    /// glue linked into applications that never use a reactive attribute at all. This has no
    /// match to fold and nothing to allocate.
    #[inline]
    pub fn attr_static(self, name: &'static str, value: &'static str) -> Self {
        self.add_attr_static(name, value);
        self
    }

    #[inline]
    pub fn add_attr_static(&self, name: &'static str, value: &'static str) {
        if name == "class" {
            self.set_class(AttrText::Static(value));
        } else {
            get_driver_dom().set_attr(self.id_dom, name, value);
        }
    }

    /// The name is known when the element is built, so `class` is told apart from everything
    /// else here rather than on every write.
    ///
    /// Only `class` goes through the merger. Every other attribute captures the element's
    /// [`DomId`] - a `Copy` - and talks to the driver directly, so a reactive `href` no
    /// longer clones an `Rc` into its subscription and reaches into a cell to read back an id
    /// it could have kept.
    pub fn add_attr(&self, name: impl Into<StaticString>, value: impl IntoAttrValue) {
        let name = name.into();
        let value = value.into_attr_value();

        if name.as_str() == "class" {
            self.add_class_attr(value);
            return;
        }

        let id_dom = self.id_dom;
        let write = move |value: Option<AttrText>| match value {
            Some(value) => get_driver_dom().set_attr(id_dom, name.clone(), value.as_str()),
            None => get_driver_dom().remove_attr(id_dom, name.clone()),
        };

        match value {
            AttrValue::Static(value) => write(Some(AttrText::Static(value))),
            AttrValue::String(value) => write(Some(AttrText::Shared(value))),
            AttrValue::Computed(computed) => {
                self.subscribe(computed, move |value| write(Some(AttrText::from(value))));
            }
            AttrValue::ComputedOpt(computed) => {
                self.subscribe(computed, move |value| write(value.map(AttrText::from)));
            }
            AttrValue::Value(value) => {
                self.subscribe(value.to_computed(), move |value| {
                    write(Some(AttrText::from(value)))
                });
            }
            AttrValue::ValueOpt(value) => {
                self.subscribe(value.to_computed(), move |value| {
                    write(value.map(AttrText::from))
                });
            }
        };
    }

    /// A *static* class needs no merger - see [`ClassState`] - but a reactive one does, and
    /// at *build* time rather than at first fire, because the subscription has to capture it.
    fn add_class_attr(&self, value: AttrValue) {
        match value {
            AttrValue::Static(value) => {
                self.set_class(AttrText::Static(value));
            }
            AttrValue::String(value) => {
                self.set_class(AttrText::Shared(value));
            }
            AttrValue::Computed(computed) => {
                let class_manager = self.class_manager();

                self.subscribe(computed, move |value| {
                    class_manager.set_attribute(AttrText::from(value));
                });
            }
            AttrValue::ComputedOpt(computed) => {
                let class_manager = self.class_manager();

                self.subscribe(computed, move |value| match value {
                    Some(value) => class_manager.set_attribute(AttrText::from(value)),
                    None => class_manager.remove_attribute(),
                });
            }
            AttrValue::Value(value) => {
                let class_manager = self.class_manager();

                self.subscribe(value.to_computed(), move |value| {
                    class_manager.set_attribute(AttrText::from(value));
                });
            }
            AttrValue::ValueOpt(value) => {
                let class_manager = self.class_manager();

                self.subscribe(value.to_computed(), move |value| match value {
                    Some(value) => class_manager.set_attribute(AttrText::from(value)),
                    None => class_manager.remove_attribute(),
                });
            }
        }
    }

    fn set_class(&self, value: AttrText) {
        self.class_state
            .change(|state| state.set_attribute(self.id_dom, value));
    }

    pub fn add_attr_group(
        mut self,
        values: impl IntoIterator<Item = (impl Into<String>, impl Into<AttrGroupValue>)>,
    ) -> Self {
        for (key, value) in values.into_iter() {
            self = self.add_attr_group_item(key.into(), value.into());
        }
        self
    }

    pub fn add_attr_group_item(self, key: String, value: AttrGroupValue) -> Self {
        match (key.as_str(), value) {
            ("css", AttrGroupValue::Css { css, class_name }) => {
                self.css_with_class_name(css, class_name)
            }
            ("draw", AttrGroupValue::Draw(drawing)) => self.draw(drawing),
            ("hook_key_down", AttrGroupValue::HookKeyDown(on_hook_key_down)) => {
                self.hook_key_down_rc(on_hook_key_down)
            }
            ("on_blur", AttrGroupValue::OnBlur(on_blur)) => self.on_blur_rc(on_blur),
            ("on_change", AttrGroupValue::OnChange(on_change)) => self.on_change_rc(on_change),
            ("on_click", AttrGroupValue::OnClick(on_click)) => self.on_click_rc(on_click),
            ("on_dropfile", AttrGroupValue::OnDropfile(on_dropfile)) => {
                self.on_dropfile_rc(on_dropfile)
            }
            ("on_change_file", AttrGroupValue::OnChangeFile(on_change_file)) => {
                self.on_change_file_rc(on_change_file)
            }
            ("on_change_checked", AttrGroupValue::OnChangeChecked(on_change_checked)) => {
                self.on_change_checked_rc(on_change_checked)
            }
            ("on_input", AttrGroupValue::OnInput(on_input)) => self.on_input_rc(on_input),
            ("on_intersect", AttrGroupValue::OnIntersect(on_intersect)) => {
                self.on_intersect_rc(on_intersect)
            }
            ("on_key_down", AttrGroupValue::OnKeyDown(on_key_down)) => {
                self.on_key_down_rc(on_key_down)
            }
            ("on_load", AttrGroupValue::OnLoad(on_load)) => self.on_load_rc(on_load),
            ("on_mouse_down", AttrGroupValue::OnMouseDown(on_mouse_down)) => {
                self.on_mouse_down_rc(on_mouse_down)
            }
            ("on_mouse_enter", AttrGroupValue::OnMouseEnter(on_mouse_enter)) => {
                self.on_mouse_enter_rc(on_mouse_enter)
            }
            ("on_mouse_leave", AttrGroupValue::OnMouseLeave(on_mouse_leave)) => {
                self.on_mouse_leave_rc(on_mouse_leave)
            }
            ("on_mouse_up", AttrGroupValue::OnMouseUp(on_mouse_up)) => {
                self.on_mouse_up_rc(on_mouse_up)
            }
            ("on_pointer_down", AttrGroupValue::OnPointerDown(on_pointer_down)) => {
                self.on_pointer_down_rc(on_pointer_down)
            }
            ("on_pointer_move", AttrGroupValue::OnPointerMove(on_pointer_move)) => {
                self.on_pointer_move_rc(on_pointer_move)
            }
            ("on_pointer_up", AttrGroupValue::OnPointerUp(on_pointer_up)) => {
                self.on_pointer_up_rc(on_pointer_up)
            }
            ("on_pointer_cancel", AttrGroupValue::OnPointerCancel(on_pointer_cancel)) => {
                self.on_pointer_cancel_rc(on_pointer_cancel)
            }
            ("on_submit", AttrGroupValue::OnSubmit(on_submit)) => self.on_submit_rc(on_submit),
            ("on_wheel", AttrGroupValue::OnWheel(on_wheel)) => self.on_wheel_rc(on_wheel),
            ("tw", AttrGroupValue::AttrValue(value)) => self.attr("class", value),
            (_, AttrGroupValue::AttrValue(value)) => self.attr(key, value),
            (_, _) => {
                crate::log::error!("Invalid attribute type for key {key}");
                self
            }
        }
    }

    pub fn add_child(&self, child_node: impl Into<DomNode>) {
        let child_node = child_node.into();

        let child_id = child_node.id_dom();
        get_driver_dom().insert_before(self.id_dom, child_id, None);

        self.child_node.push(child_node);
    }

    pub fn add_child_text(&self, text: impl Into<String>) {
        let text = text.into();
        self.add_child(DomNode::Text {
            node: DomText::new(text),
        });
    }

    pub fn attr(self, name: impl Into<StaticString>, value: impl IntoAttrValue) -> Self {
        self.add_attr(name, value);
        self
    }

    pub fn attrs<T: IntoAttrValue>(self, attrs: Vec<(impl Into<StaticString>, T)>) -> Self {
        for (name, value) in attrs.into_iter() {
            self.add_attr(name, value)
        }
        self
    }

    pub fn child(self, child_node: impl Into<DomNode>) -> Self {
        self.add_child(child_node);
        self
    }

    pub fn child_text(self, text: impl Into<String>) -> Self {
        self.add_child_text(text);
        self
    }

    pub fn children<C: Into<DomNode>>(self, children: Vec<C>) -> Self {
        for child_node in children.into_iter() {
            self.add_child(child_node)
        }
        self
    }

    pub fn css(self, css: impl Into<CssAttrValue>) -> Self {
        self.css_with_class_name(css, None)
    }

    pub fn css_with_class_name(
        self,
        css: impl Into<CssAttrValue>,
        debug_class_name: Option<String>,
    ) -> Self {
        let css = css.into();

        match css {
            CssAttrValue::Css(css) => {
                self.class_manager().set_css(css, debug_class_name);
            }
            CssAttrValue::Computed(css) => {
                let class_manager = self.class_manager();

                self.subscribe(css, move |css| {
                    class_manager.set_css(css, debug_class_name.clone());
                });
            }
        }
        self
    }

    /// The picture of a `<canvas>`, see [`Drawing`]. Each new drawing clears the canvas and is
    /// drawn in its place, in the same batch of DOM changes as the rest of the transaction, so
    /// it never arrives before the canvas does. A drawing equal to the last is not sent again.
    pub fn draw(self, drawing: impl Into<Computed<Drawing>>) -> Self {
        let id = self.id_dom;

        self.subscribe(drawing.into(), move |drawing| {
            get_driver_dom().canvas_draw(id, drawing.as_bytes());
        });
        self
    }

    pub fn get_ref(&self) -> DomElementRef {
        DomElementRef::new(self.id_dom)
    }

    #[cfg(test)]
    pub fn get_children(&self) -> &VecDequeMut<DomNode> {
        &self.child_node
    }

    pub fn hook_key_down(self, on_hook_key_down: impl Into<Callback1<KeyDownEvent, bool>>) -> Self {
        self.hook_key_down_rc(Rc::new(on_hook_key_down.into()))
    }

    pub fn hook_key_down_rc(self, on_hook_key_down: Rc<Callback1<KeyDownEvent, bool>>) -> Self {
        let on_hook_key_down = self.install_callback1(on_hook_key_down);

        self.add_event_listener("hook_keydown", move |data| match get_key_down_event(data) {
            Ok(event) => {
                let prevent_default = on_hook_key_down(event);

                match prevent_default {
                    true => JsJson::True,
                    false => JsJson::False,
                }
            }
            Err(error) => {
                log::error!("export_websocket_callback_message -> params decode error -> {error}");
                JsJson::False
            }
        })
    }

    pub fn id_dom(&self) -> DomId {
        self.id_dom
    }

    pub fn on_blur(self, on_blur: impl Into<Callback<()>>) -> Self {
        self.on_blur_rc(Rc::new(on_blur.into()))
    }

    pub fn on_blur_rc(self, on_blur: Rc<Callback<()>>) -> Self {
        let on_blur = self.install_callback(on_blur);

        self.add_event_listener("blur", move |_data| {
            on_blur();
            JsJson::Null
        })
    }

    pub fn on_change(self, on_change: impl Into<Callback1<String, ()>>) -> Self {
        self.on_change_rc(Rc::new(on_change.into()))
    }

    pub fn on_change_rc(self, on_change: Rc<Callback1<String, ()>>) -> Self {
        let on_change = self.install_callback1(on_change);

        self.add_event_listener("change", move |data| {
            if let JsJson::String(text) = data {
                on_change(text);
            } else {
                log::error!("Invalid data: on_change: {}", data.typename());
            }

            JsJson::Null
        })
    }

    /// `change` of a checkbox or a radio button, with whether it is checked now. [`Self::on_change`]
    /// gets the `value` attribute, which a click doesn't change.
    pub fn on_change_checked(self, on_change_checked: impl Into<Callback1<bool, ()>>) -> Self {
        self.on_change_checked_rc(Rc::new(on_change_checked.into()))
    }

    pub fn on_change_checked_rc(self, on_change_checked: Rc<Callback1<bool, ()>>) -> Self {
        let on_change_checked = self.install_callback1(on_change_checked);

        self.add_event_listener("change_checked", move |data| {
            match data {
                JsJson::True => on_change_checked(true),
                JsJson::False => on_change_checked(false),
                _ => log::error!("Invalid data: on_change_checked: {}", data.typename()),
            }

            JsJson::Null
        })
    }

    pub fn on_change_file(self, on_change_file: impl Into<Callback1<DropFileEvent, ()>>) -> Self {
        self.on_change_file_rc(Rc::new(on_change_file.into()))
    }

    pub fn on_change_file_rc(self, on_change_file: Rc<Callback1<DropFileEvent, ()>>) -> Self {
        let on_change_file = self.install_callback1(on_change_file);

        self.add_event_listener("change_file", move |data| {
            let params = data.map_list(|mut params: JsJsonListDecoder| {
                let files = params.get_vec("change file", |item: JsJson| {
                    item.map_list(|mut item: JsJsonListDecoder| {
                        let name = item.get_string("name")?;
                        let data = item.get_buffer("data")?;

                        Ok(DropFileItem::new(name, data))
                    })
                })?;

                Ok(DropFileEvent::new(files))
            });

            match params {
                Ok(params) => {
                    on_change_file(params);
                }
                Err(error) => {
                    log::error!("on_change_file -> params decode error -> {error}");
                }
            };

            JsJson::Null
        })
    }

    /// The browser's default action still happens unless the callback calls
    /// [`ClickEvent::prevent_default`].
    pub fn on_click(self, on_click: impl Into<Callback1<ClickEvent, ()>>) -> Self {
        self.on_click_rc(Rc::new(on_click.into()))
    }

    pub fn on_click_rc(self, on_click: Rc<Callback1<ClickEvent, ()>>) -> Self {
        let on_click = self.install_callback1(on_click);

        self.add_event_listener("click", move |data| {
            let click_event = ClickEvent::from_driver(data);
            on_click(click_event.clone());
            JsJson::from(click_event)
        })
    }

    pub fn on_dropfile(self, on_dropfile: impl Into<Callback1<DropFileEvent, ()>>) -> Self {
        self.on_dropfile_rc(Rc::new(on_dropfile.into()))
    }

    pub fn on_dropfile_rc(self, on_dropfile: Rc<Callback1<DropFileEvent, ()>>) -> Self {
        let on_dropfile = self.install_callback1(on_dropfile);

        self.add_event_listener("drop", move |data| {
            let params = data.map_list(|mut params: JsJsonListDecoder| {
                let files = params.get_vec("drop file", |item: JsJson| {
                    item.map_list(|mut item: JsJsonListDecoder| {
                        let name = item.get_string("name")?;
                        let data = item.get_buffer("data")?;

                        Ok(DropFileItem::new(name, data))
                    })
                })?;

                Ok(DropFileEvent::new(files))
            });

            match params {
                Ok(params) => {
                    on_dropfile(params);
                }
                Err(error) => {
                    log::error!("on_dropfile -> params decode error -> {error}");
                }
            };

            JsJson::Null
        })
    }

    pub fn on_input(self, on_input: impl Into<Callback1<String, ()>>) -> Self {
        self.on_input_rc(Rc::new(on_input.into()))
    }

    pub fn on_input_rc(self, on_input: Rc<Callback1<String, ()>>) -> Self {
        let on_input = self.install_callback1(on_input);

        self.add_event_listener("input", move |data| {
            if let JsJson::String(text) = data {
                on_input(text);
            } else {
                log::error!("Invalid data: on_input: {}", data.typename());
            }

            JsJson::Null
        })
    }

    pub fn on_intersect(self, on_intersect: impl Into<Callback1<IntersectionEvent, ()>>) -> Self {
        self.on_intersect_rc(Rc::new(on_intersect.into()))
    }

    /// Observe this element with a browser `IntersectionObserver`. The callback
    /// fires whenever the element's intersection with the (default) root
    /// changes, receiving an [IntersectionEvent](crate::IntersectionEvent).
    /// Dropping the element disconnects the observer.
    pub fn on_intersect_rc(self, on_intersect: Rc<Callback1<IntersectionEvent, ()>>) -> Self {
        let on_intersect = self.install_callback1(on_intersect);

        self.add_event_listener("intersect", move |data| {
            match get_intersection_event(data) {
                Ok(event) => {
                    on_intersect(event);
                }
                Err(error) => {
                    log::error!("on_intersect -> params decode error -> {error}");
                }
            }

            JsJson::Null
        })
    }

    pub fn on_key_down(self, on_key_down: impl Into<Callback1<KeyDownEvent, bool>>) -> Self {
        self.on_key_down_rc(Rc::new(on_key_down.into()))
    }

    pub fn on_key_down_rc(self, on_key_down: Rc<Callback1<KeyDownEvent, bool>>) -> Self {
        let on_key_down = self.install_callback1(on_key_down);

        self.add_event_listener("keydown", move |data| match get_key_down_event(data) {
            Ok(event) => {
                let prevent_default = on_key_down(event);

                match prevent_default {
                    true => JsJson::True,
                    false => JsJson::False,
                }
            }
            Err(error) => {
                log::error!("export_websocket_callback_message -> params decode error -> {error}");
                JsJson::False
            }
        })
    }

    pub fn on_load(self, on_load: impl Into<Callback<()>>) -> Self {
        self.on_load_rc(Rc::new(on_load.into()))
    }

    pub fn on_load_rc(self, on_load: Rc<Callback<()>>) -> Self {
        let on_load = self.install_callback(on_load);

        self.add_event_listener("load", move |_data| {
            on_load();
            JsJson::Null
        })
    }

    pub fn on_mouse_down(self, on_mouse_down: impl Into<Callback<bool>>) -> Self {
        self.on_mouse_down_rc(Rc::new(on_mouse_down.into()))
    }

    pub fn on_mouse_down_rc(self, on_mouse_down: Rc<Callback<bool>>) -> Self {
        let on_mouse_down = self.install_callback(on_mouse_down);

        self.add_event_listener("mousedown", move |_data| {
            if on_mouse_down() {
                JsJson::True
            } else {
                JsJson::False
            }
        })
    }

    pub fn on_mouse_enter(self, on_mouse_enter: impl Into<Callback<()>>) -> Self {
        self.on_mouse_enter_rc(Rc::new(on_mouse_enter.into()))
    }

    pub fn on_mouse_enter_rc(self, on_mouse_enter: Rc<Callback<()>>) -> Self {
        let on_mouse_enter = self.install_callback(on_mouse_enter);

        self.add_event_listener("mouseenter", move |_data| {
            on_mouse_enter();
            JsJson::Null
        })
    }

    pub fn on_mouse_leave(self, on_mouse_leave: impl Into<Callback<()>>) -> Self {
        self.on_mouse_leave_rc(Rc::new(on_mouse_leave.into()))
    }

    pub fn on_mouse_leave_rc(self, on_mouse_leave: Rc<Callback<()>>) -> Self {
        let on_mouse_leave = self.install_callback(on_mouse_leave);

        self.add_event_listener("mouseleave", move |_data| {
            on_mouse_leave();
            JsJson::Null
        })
    }

    pub fn on_mouse_up(self, on_mouse_up: impl Into<Callback<bool>>) -> Self {
        self.on_mouse_up_rc(Rc::new(on_mouse_up.into()))
    }

    pub fn on_mouse_up_rc(self, on_mouse_up: Rc<Callback<bool>>) -> Self {
        let on_mouse_up = self.install_callback(on_mouse_up);

        self.add_event_listener("mouseup", move |_data| {
            if on_mouse_up() {
                JsJson::True
            } else {
                JsJson::False
            }
        })
    }

    /// A mouse button pressed, or a finger or a pen touching the screen. See [`PointerEvent`].
    pub fn on_pointer_down(self, on_pointer_down: impl Into<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer_down_rc(Rc::new(on_pointer_down.into()))
    }

    pub fn on_pointer_down_rc(self, on_pointer_down: Rc<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer("pointerdown", on_pointer_down)
    }

    /// A pointer moved over the element, or anywhere once the element captured it. See
    /// [`PointerEvent`].
    pub fn on_pointer_move(self, on_pointer_move: impl Into<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer_move_rc(Rc::new(on_pointer_move.into()))
    }

    pub fn on_pointer_move_rc(self, on_pointer_move: Rc<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer("pointermove", on_pointer_move)
    }

    /// A mouse button released, or a finger or a pen lifted. See [`PointerEvent`].
    pub fn on_pointer_up(self, on_pointer_up: impl Into<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer_up_rc(Rc::new(on_pointer_up.into()))
    }

    pub fn on_pointer_up_rc(self, on_pointer_up: Rc<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer("pointerup", on_pointer_up)
    }

    /// The browser took the pointer over, f. ex. to scroll the page with a finger, and no more of
    /// its events come - not even the one of releasing it. See [`PointerEvent`].
    pub fn on_pointer_cancel(
        self,
        on_pointer_cancel: impl Into<Callback1<PointerEvent, ()>>,
    ) -> Self {
        self.on_pointer_cancel_rc(Rc::new(on_pointer_cancel.into()))
    }

    pub fn on_pointer_cancel_rc(self, on_pointer_cancel: Rc<Callback1<PointerEvent, ()>>) -> Self {
        self.on_pointer("pointercancel", on_pointer_cancel)
    }

    fn on_pointer(
        self,
        event_name: &'static str,
        callback: Rc<Callback1<PointerEvent, ()>>,
    ) -> Self {
        let callback = self.install_callback1(callback);

        self.add_event_listener(event_name, move |data| {
            match PointerEvent::from_driver(data) {
                Ok(event) => {
                    callback(event.clone());
                    JsJson::from(event)
                }
                Err(error) => {
                    log::error!("{event_name} -> params decode error -> {error}");
                    JsJson::Null
                }
            }
        })
    }

    pub fn on_submit(self, on_submit: impl Into<Callback<()>>) -> Self {
        self.on_submit_rc(Rc::new(on_submit.into()))
    }

    pub fn on_submit_rc(self, on_submit: Rc<Callback<()>>) -> Self {
        let on_submit = self.install_callback(on_submit);

        self.add_event_listener("submit", move |_data| {
            on_submit();
            JsJson::Null
        })
    }

    /// The wheel scrolls the page, and in Chrome and Firefox with Ctrl held zooms it, unless the
    /// callback calls [`WheelEvent::prevent_default`]. The listener isn't passive, so the browser
    /// waits for the callback before it scrolls: keep it short.
    pub fn on_wheel(self, on_wheel: impl Into<Callback1<WheelEvent, ()>>) -> Self {
        self.on_wheel_rc(Rc::new(on_wheel.into()))
    }

    pub fn on_wheel_rc(self, on_wheel: Rc<Callback1<WheelEvent, ()>>) -> Self {
        let on_wheel = self.install_callback1(on_wheel);

        self.add_event_listener("wheel", move |data| match WheelEvent::from_driver(data) {
            Ok(event) => {
                on_wheel(event.clone());
                JsJson::from(event)
            }
            Err(error) => {
                log::error!("on_wheel -> params decode error -> {error}");
                JsJson::Null
            }
        })
    }

    pub fn append_drop_resource(&self, resource: DropResource) {
        self.subscriptions.push(resource);
    }

    fn subscribe<T: Clone + PartialEq + 'static>(
        &self,
        value: Computed<T>,
        call: impl Fn(T) + 'static,
    ) {
        let client = value.subscribe(call);
        self.subscriptions.push(client);
    }

    fn add_event_listener(
        self,
        name: &'static str,
        callback: impl Fn(JsJson) -> JsJson + 'static,
    ) -> Self {
        let (callback_id, drop) = api_callbacks().register(callback);

        let drop_event = DropResource::new(move || {
            get_driver_dom().callback_remove(self.id_dom, name, callback_id);
            drop.off();
        });

        get_driver_dom().callback_add(self.id_dom, name, callback_id);
        self.subscriptions.push(drop_event);
        self
    }

    fn install_callback<R: 'static>(
        &self,
        callback: Rc<Callback<R>>,
    ) -> Rc<dyn Fn() -> R + 'static> {
        let (callback, drop) = callback.subscribe();
        if let Some(drop) = drop {
            self.subscriptions.push(drop);
        }
        callback
    }

    fn install_callback1<T: 'static, R: 'static>(
        &self,
        callback: Rc<Callback1<T, R>>,
    ) -> Rc<dyn Fn(T) -> R + 'static> {
        let (callback, drop) = callback.subscribe();
        if let Some(drop) = drop {
            self.subscriptions.push(drop);
        }
        callback
    }
}

impl Drop for DomElement {
    fn drop(&mut self) {
        get_driver_dom().remove_node(self.id_dom);
    }
}

fn get_intersection_event(data: JsJson) -> Result<IntersectionEvent, String> {
    data.map_list(|mut params: JsJsonListDecoder| {
        let is_intersecting = params.get_bool("isIntersecting")?;
        let intersection_ratio = params.get_f64("intersectionRatio")?;
        let bounding_top = params.get_f64("boundingTop")?;
        let bounding_bottom = params.get_f64("boundingBottom")?;
        let bounding_height = params.get_f64("boundingHeight")?;
        params.expect_no_more()?;

        Ok(IntersectionEvent {
            is_intersecting,
            intersection_ratio,
            bounding_top,
            bounding_bottom,
            bounding_height,
        })
    })
}

fn get_key_down_event(data: JsJson) -> Result<KeyDownEvent, String> {
    data.map_list(|mut params: JsJsonListDecoder| {
        let key = params.get_string("key")?;
        let code = params.get_string("code")?;
        let alt_key = params.get_bool("altKey")?;
        let ctrl_key = params.get_bool("ctrlKey")?;
        let shift_key = params.get_bool("shiftKey")?;
        let meta_key = params.get_bool("metaKey")?;
        params.expect_no_more()?;

        Ok(KeyDownEvent {
            key,
            code,
            alt_key,
            ctrl_key,
            shift_key,
            meta_key,
        })
    })
}