ps-dioxus-native-dom 0.7.4

Core headless native renderer for Dioxus based on blitz
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
use blitz_dom::{BaseDocument, Node};
use blitz_traits::events::{
    BlitzKeyEvent, BlitzPointerEvent, BlitzPointerId, BlitzScrollEvent, BlitzWheelDelta,
    BlitzWheelEvent, MouseEventButton,
};
use dioxus_html::{
    AnimationData, CancelData, ClipboardData, CompositionData, DragData, FocusData, FormData,
    FormValue, HasFileData, HasFocusData, HasFormData, HasKeyboardData, HasMouseData,
    HasPointerData, HasScrollData, HasTouchData, HasTouchPointData, HasWheelData,
    HtmlEventConverter, ImageData, KeyboardData, MediaData, MountedData, MountedError,
    MountedResult, MouseData, PlatformEventData, PointerData, RenderedElementBacking, ResizeData,
    ScrollBehavior, ScrollData, ScrollToOptions, SelectionData, ToggleData, TouchData, TouchPoint,
    TransitionData, VisibleData, WheelData,
    geometry::{
        ClientPoint, ElementPoint, PagePoint, PixelsRect, PixelsSize, PixelsVector2D, ScreenPoint,
        WheelDelta,
        euclid::{Point2D, Size2D, Vector3D},
    },
    input_data::{MouseButton, MouseButtonSet},
    point_interaction::{
        InteractionElementOffset, InteractionLocation, ModifiersInteraction, PointerInteraction,
    },
};
use keyboard_types::{Code, Key, Location, Modifiers};
use std::{
    any::Any,
    cell::{Ref, RefCell, RefMut},
    fmt::Display,
    future::Future,
    pin::Pin,
    rc::Rc,
};

use crate::NodeId;

pub struct NativeConverter {}

impl HtmlEventConverter for NativeConverter {
    fn convert_cancel_data(&self, _event: &PlatformEventData) -> CancelData {
        unimplemented!("todo: convert_cancel_data in dioxus-native. requires support in blitz")
    }

    fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
        event.downcast::<NativeFormData>().unwrap().clone().into()
    }

    fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
        event
            .downcast::<NativePointerData>()
            .unwrap()
            .clone()
            .into()
    }

    fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
        event
            .downcast::<BlitzKeyboardData>()
            .unwrap()
            .clone()
            .into()
    }

    fn convert_focus_data(&self, _event: &PlatformEventData) -> FocusData {
        NativeFocusData {}.into()
    }

    fn convert_animation_data(&self, _event: &PlatformEventData) -> AnimationData {
        unimplemented!("todo: convert_animation_data in dioxus-native. requires support in blitz")
    }

    fn convert_clipboard_data(&self, _event: &PlatformEventData) -> ClipboardData {
        unimplemented!("todo: convert_clipboard_data in dioxus-native. requires support in blitz")
    }

    fn convert_composition_data(&self, _event: &PlatformEventData) -> CompositionData {
        unimplemented!("todo: convert_composition_data in dioxus-native. requires support in blitz")
    }

    fn convert_drag_data(&self, _event: &PlatformEventData) -> DragData {
        unimplemented!("todo: convert_drag_data in dioxus-native. requires support in blitz")
    }

    fn convert_image_data(&self, _event: &PlatformEventData) -> ImageData {
        unimplemented!("todo: convert_image_data in dioxus-native. requires support in blitz")
    }

    fn convert_media_data(&self, _event: &PlatformEventData) -> MediaData {
        unimplemented!("todo: convert_media_data in dioxus-native. requires support in blitz")
    }

    fn convert_mounted_data(&self, event: &PlatformEventData) -> MountedData {
        event.downcast::<NodeHandle>().unwrap().clone().into()
    }

    fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData {
        event
            .downcast::<NativePointerData>()
            .unwrap()
            .clone()
            .into()
    }

    fn convert_scroll_data(&self, event: &PlatformEventData) -> ScrollData {
        event.downcast::<NativeScrollData>().unwrap().clone().into()
    }

    fn convert_selection_data(&self, _event: &PlatformEventData) -> SelectionData {
        unimplemented!("todo: convert_selection_data in dioxus-native. requires support in blitz")
    }

    fn convert_toggle_data(&self, _event: &PlatformEventData) -> ToggleData {
        unimplemented!("todo: convert_toggle_data in dioxus-native. requires support in blitz")
    }

    fn convert_touch_data(&self, event: &PlatformEventData) -> TouchData {
        event.downcast::<NativeTouchData>().unwrap().clone().into()
    }

    fn convert_transition_data(&self, _event: &PlatformEventData) -> TransitionData {
        unimplemented!("todo: convert_transition_data in dioxus-native. requires support in blitz")
    }

    fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData {
        event.downcast::<NativeWheelData>().unwrap().clone().into()
    }

    fn convert_resize_data(&self, _event: &PlatformEventData) -> ResizeData {
        unimplemented!("todo: convert_resize_data in dioxus-native. requires support in blitz")
    }

    fn convert_visible_data(&self, _event: &PlatformEventData) -> VisibleData {
        unimplemented!("todo: convert_visible_data in dioxus-native. requires support in blitz")
    }
}

pub(crate) enum DocumentCommand {
    SetFocus { node_id: NodeId, focus: bool },
}

pub(crate) type DocumentCommandQueue = Rc<RefCell<Vec<DocumentCommand>>>;

fn apply_focus(doc: &mut BaseDocument, node_id: NodeId, focus: bool) {
    if focus {
        doc.set_focus_to(node_id);
    } else if doc.get_focussed_node_id() == Some(node_id) {
        doc.clear_focus();
    }
}

fn queue_focus(queue: &DocumentCommandQueue, node_id: NodeId, focus: bool) {
    queue
        .borrow_mut()
        .push(DocumentCommand::SetFocus { node_id, focus });
}

/// Apply commands for one document that could not be applied when requested.
///
/// Call this only where the document is known not to be borrowed. Requests are
/// taken out of the queue before any is applied, so a handler that queues
/// another one does not extend this pass into an unbounded loop.
pub(crate) fn flush_document_commands(
    doc: &Rc<RefCell<BaseDocument>>,
    queue: &DocumentCommandQueue,
) {
    let queued = std::mem::take(&mut *queue.borrow_mut());
    for command in queued {
        let DocumentCommand::SetFocus { node_id, focus } = command;
        // Still fallible: a caller may hold the borrow for reasons of its own.
        // Dropping the request is wrong, so it goes back on the queue for the
        // next flush rather than panicking or being lost.
        let applied = match doc.try_borrow_mut() {
            Ok(mut doc_ref) => {
                apply_focus(&mut doc_ref, node_id, focus);
                true
            }
            Err(_) => false,
        };
        if !applied {
            queue_focus(queue, node_id, focus);
        }
    }
}

#[derive(Clone)]
pub struct NodeHandle {
    pub(crate) doc: Rc<RefCell<BaseDocument>>,
    pub(crate) command_queue: DocumentCommandQueue,
    pub(crate) node_id: NodeId,
}

impl NodeHandle {
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    pub fn doc(&self) -> Ref<'_, BaseDocument> {
        self.doc.borrow()
    }

    /// Returns `None` if the document is currently mutably borrowed.
    /// Use this from background tasks to avoid panicking during event handling.
    pub fn try_doc(&self) -> Option<Ref<'_, BaseDocument>> {
        self.doc.try_borrow().ok()
    }

    pub fn doc_mut(&self) -> RefMut<'_, BaseDocument> {
        self.doc.borrow_mut()
    }

    /// Returns `None` if the document is already borrowed.
    ///
    /// The mutable counterpart to [`Self::try_doc`], for the same reason:
    /// a background task that ticks on a timer will eventually land while the
    /// document is held, and a dropped tick is cheaper than a panic.
    pub fn try_doc_mut(&self) -> Option<RefMut<'_, BaseDocument>> {
        self.doc.try_borrow_mut().ok()
    }

    pub fn node(&self) -> Ref<'_, Node> {
        Ref::map(self.doc.borrow(), |doc| {
            doc.get_node(self.node_id)
                .expect("Node does not exist in the Document")
        })
    }

    pub fn node_mut(&self) -> RefMut<'_, Node> {
        RefMut::map(self.doc.borrow_mut(), |doc| {
            doc.get_node_mut(self.node_id)
                .expect("Node does not exist in the Document")
        })
    }

    fn node_not_exist_err<T>(&self) -> Pin<Box<dyn Future<Output = MountedResult<T>>>> {
        let node_id = self.node_id;
        let err = MountedError::OperationFailed(Box::new(NodeNotExistErr(node_id)));
        Box::pin(async move { Err(err) })
    }
}

#[derive(Debug)]
struct NodeNotExistErr(NodeId);
impl Display for NodeNotExistErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "The node {} does not exist", self.0)
    }
}
impl std::error::Error for NodeNotExistErr {}

impl RenderedElementBacking for NodeHandle {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn get_scroll_offset(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsVector2D>>>> {
        let scroll_offset = *self.node().scroll_offset();
        Box::pin(async move { Ok(PixelsVector2D::new(scroll_offset.x, scroll_offset.y)) })
    }

    fn get_scroll_size(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsSize>>>> {
        let node = self.node();
        let scroll_width = node.final_layout().scroll_width() as f64;
        let scroll_height = node.final_layout().scroll_height() as f64;
        Box::pin(async move { Ok(PixelsSize::new(scroll_width, scroll_height)) })
    }

    fn get_client_rect(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsRect>>>> {
        let Some(bounding_rect) = self.doc_mut().get_client_bounding_rect(self.node_id) else {
            return self.node_not_exist_err();
        };
        let pixels_rect = PixelsRect::new(
            Point2D::new(bounding_rect.x, bounding_rect.y),
            Size2D::new(bounding_rect.width, bounding_rect.height),
        );
        Box::pin(async move { Ok(pixels_rect) })
    }

    fn scroll_to(
        &self,
        _options: ScrollToOptions,
    ) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
        Box::pin(async { Err(MountedError::NotSupported) })
    }

    fn scroll(
        &self,
        _coordinates: PixelsVector2D,
        _behavior: ScrollBehavior,
    ) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
        Box::pin(async { Err(MountedError::NotSupported) })
    }

    fn set_focus(&self, focus: bool) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
        // Deliberately not `doc_mut()`. This is reached from a spawned task, and
        // `DioxusDocument::poll` drives task wakeups *while it holds the
        // document borrow*, so taking it here panics with `RefCell already
        // borrowed`:
        //
        //     DioxusDocument::poll
        //       -> Runtime::handle_task_wakeup
        //         -> the component's focus task
        //           -> doc_mut()   panic
        //
        // Deferring the request further does not avoid it, because every later
        // tick is inside a poll too. So a request that cannot be applied now is
        // recorded in this document's command queue and applied once the
        // borrow is released.
        match self.doc.try_borrow_mut() {
            Ok(mut doc) => apply_focus(&mut doc, self.node_id, focus),
            Err(_) => queue_focus(&self.command_queue, self.node_id, focus),
        }

        Box::pin(async { Ok(()) })
    }
}

#[derive(Clone, Debug)]
pub struct NativeFormData {
    pub value: String,
    pub values: Vec<(String, FormValue)>,
}

impl HasFormData for NativeFormData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn value(&self) -> String {
        self.value.clone()
    }

    fn values(&self) -> Vec<(String, FormValue)> {
        self.values.clone()
    }
    fn valid(&self) -> bool {
        // todo: actually implement validation here.
        true
    }
}

impl HasFileData for NativeFormData {
    fn files(&self) -> Vec<dioxus_html::FileData> {
        vec![]
    }
}

#[derive(Clone, Debug)]
pub(crate) struct BlitzKeyboardData(pub(crate) BlitzKeyEvent);

impl ModifiersInteraction for BlitzKeyboardData {
    fn modifiers(&self) -> Modifiers {
        self.0.modifiers
    }
}

impl HasKeyboardData for BlitzKeyboardData {
    fn key(&self) -> Key {
        self.0.key.clone()
    }

    fn code(&self) -> Code {
        self.0.code
    }

    fn location(&self) -> Location {
        self.0.location
    }

    fn is_auto_repeating(&self) -> bool {
        self.0.is_auto_repeating
    }

    fn is_composing(&self) -> bool {
        self.0.is_composing
    }

    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }
}

#[derive(Clone)]
pub struct NativePointerData(pub(crate) BlitzPointerEvent);

impl InteractionLocation for NativePointerData {
    fn client_coordinates(&self) -> ClientPoint {
        ClientPoint::new(self.0.client_x() as f64, self.0.client_y() as f64)
    }

    fn screen_coordinates(&self) -> ScreenPoint {
        ScreenPoint::new(self.0.screen_x() as f64, self.0.screen_y() as f64)
    }

    fn page_coordinates(&self) -> PagePoint {
        PagePoint::new(self.0.page_x() as f64, self.0.page_y() as f64)
    }
}

impl InteractionElementOffset for NativePointerData {
    fn element_coordinates(&self) -> ElementPoint {
        ElementPoint::new(self.0.element_x() as f64, self.0.element_y() as f64)
    }
}

impl ModifiersInteraction for NativePointerData {
    fn modifiers(&self) -> Modifiers {
        self.0.mods
    }
}

impl PointerInteraction for NativePointerData {
    fn trigger_button(&self) -> Option<MouseButton> {
        Some(match self.0.button {
            MouseEventButton::Main => MouseButton::Primary,
            MouseEventButton::Auxiliary => MouseButton::Auxiliary,
            MouseEventButton::Secondary => MouseButton::Secondary,
            MouseEventButton::Fourth => MouseButton::Fourth,
            MouseEventButton::Fifth => MouseButton::Fifth,
        })
    }

    fn held_buttons(&self) -> MouseButtonSet {
        dioxus_html::input_data::decode_mouse_button_set(self.0.buttons.bits() as u16)
    }
}
impl HasMouseData for NativePointerData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }
}

impl HasPointerData for NativePointerData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn is_primary(&self) -> bool {
        self.0.is_primary
    }

    fn pointer_id(&self) -> i32 {
        match self.0.id {
            BlitzPointerId::Mouse => 0,
            BlitzPointerId::Pen => 0,
            BlitzPointerId::Finger(id) => id as i32,
        }
    }

    fn pointer_type(&self) -> String {
        match self.0.id {
            BlitzPointerId::Mouse => String::from("mouse"),
            BlitzPointerId::Pen => String::from("pen"),
            BlitzPointerId::Finger(_) => String::from("touch"),
        }
    }

    fn pressure(&self) -> f32 {
        self.0.details.pressure as f32
    }
    fn tangential_pressure(&self) -> f32 {
        self.0.details.tangential_pressure
    }
    fn tilt_x(&self) -> i32 {
        self.0.details.tilt_x as i32
    }
    fn tilt_y(&self) -> i32 {
        self.0.details.tilt_y as i32
    }
    fn twist(&self) -> i32 {
        self.0.details.twist as i32
    }

    // TODO: implement these fields with real values
    fn width(&self) -> f64 {
        1.0
    }
    fn height(&self) -> f64 {
        1.0
    }
}

/// Touch event data exposed to Dioxus Native application code.
///
/// Blitz tracks input via pointer events, so a touch event is generated from the
/// pointer event of the finger that triggered it (`touches_changed`). The full
/// list of concurrent touches is carried on the triggering event's
/// [`BlitzPointerEvent::active_pointers`] list and reported via `touches`.
#[derive(Clone)]
pub struct NativeTouchData(pub(crate) BlitzPointerEvent);

impl ModifiersInteraction for NativeTouchData {
    fn modifiers(&self) -> Modifiers {
        self.0.mods
    }
}

impl HasTouchData for NativeTouchData {
    fn touches(&self) -> Vec<TouchPoint> {
        // All pointers currently active on the surface (multi-touch).
        self.0
            .active_pointers
            .borrow()
            .iter()
            .map(|event| TouchPoint::new(NativeTouchPointData(event.clone())))
            .collect()
    }

    fn touches_changed(&self) -> Vec<TouchPoint> {
        // Just the touch that triggered this event.
        vec![TouchPoint::new(NativeTouchPointData(self.0.clone()))]
    }

    fn target_touches(&self) -> Vec<TouchPoint> {
        // We don't track a per-touch target, so approximate `targetTouches`
        // (touches that started on the event target) with all active touches.
        self.touches()
    }

    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }
}

#[derive(Clone)]
pub struct NativeTouchPointData(BlitzPointerEvent);

impl InteractionLocation for NativeTouchPointData {
    fn client_coordinates(&self) -> ClientPoint {
        ClientPoint::new(self.0.client_x() as f64, self.0.client_y() as f64)
    }

    fn screen_coordinates(&self) -> ScreenPoint {
        ScreenPoint::new(self.0.screen_x() as f64, self.0.screen_y() as f64)
    }

    fn page_coordinates(&self) -> PagePoint {
        PagePoint::new(self.0.page_x() as f64, self.0.page_y() as f64)
    }
}

impl HasTouchPointData for NativeTouchPointData {
    fn identifier(&self) -> i32 {
        match self.0.id {
            BlitzPointerId::Finger(id) => id as i32,
            BlitzPointerId::Mouse | BlitzPointerId::Pen => 0,
        }
    }

    fn force(&self) -> f64 {
        self.0.details.pressure
    }

    fn radius(&self) -> ScreenPoint {
        // TODO: expose real touch radius once blitz tracks it
        ScreenPoint::new(1.0, 1.0)
    }

    fn rotation(&self) -> f64 {
        // TODO: expose real touch rotation once blitz tracks it
        0.0
    }

    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }
}

#[derive(Clone)]
pub struct NativeFocusData;
impl HasFocusData for NativeFocusData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }
}

#[derive(Clone)]
pub struct NativeScrollData(pub(crate) BlitzScrollEvent);
impl HasScrollData for NativeScrollData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn scroll_top(&self) -> f64 {
        self.0.scroll_top
    }

    fn scroll_left(&self) -> f64 {
        self.0.scroll_left
    }

    fn scroll_width(&self) -> i32 {
        self.0.scroll_width
    }

    fn scroll_height(&self) -> i32 {
        self.0.scroll_height
    }

    fn client_width(&self) -> i32 {
        self.0.client_width
    }

    fn client_height(&self) -> i32 {
        self.0.client_height
    }
}

#[derive(Clone)]
pub struct NativeWheelData(pub(crate) BlitzWheelEvent);
impl HasWheelData for NativeWheelData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn delta(&self) -> WheelDelta {
        match self.0.delta {
            BlitzWheelDelta::Lines(x, y) => {
                dioxus_html::geometry::WheelDelta::Lines(Vector3D::new(x, y, 0.0))
            }
            BlitzWheelDelta::Pixels(x, y) => {
                dioxus_html::geometry::WheelDelta::Pixels(Vector3D::new(x, y, 0.0))
            }
        }
    }
}

impl HasMouseData for NativeWheelData {
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }
}

impl PointerInteraction for NativeWheelData {
    fn trigger_button(&self) -> Option<MouseButton> {
        None
    }

    fn held_buttons(&self) -> MouseButtonSet {
        dioxus_html::input_data::decode_mouse_button_set(self.0.buttons.bits() as u16)
    }
}

impl ModifiersInteraction for NativeWheelData {
    fn modifiers(&self) -> Modifiers {
        self.0.mods
    }
}

impl InteractionElementOffset for NativeWheelData {
    fn element_coordinates(&self) -> ElementPoint {
        ElementPoint::new(self.0.element_x() as f64, self.0.element_y() as f64)
    }
}

impl InteractionLocation for NativeWheelData {
    fn client_coordinates(&self) -> ClientPoint {
        ClientPoint::new(self.0.client_x() as f64, self.0.client_y() as f64)
    }

    fn screen_coordinates(&self) -> ScreenPoint {
        ScreenPoint::new(self.0.screen_x() as f64, self.0.screen_y() as f64)
    }

    fn page_coordinates(&self) -> PagePoint {
        PagePoint::new(self.0.page_x() as f64, self.0.page_y() as f64)
    }
}

pub fn synthetic_click_event(node: &Node, modifiers: Modifiers) -> Box<dyn Any> {
    Box::new(NativePointerData(
        node.synthetic_click_event_data(modifiers),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use blitz_traits::events::{
        BlitzPointerId, MouseEventButton, MouseEventButtons, Point, PointerCoords, PointerDetails,
    };

    fn finger_event(id: u64, x: f32, y: f32) -> BlitzPointerEvent {
        BlitzPointerEvent {
            id: BlitzPointerId::Finger(id),
            is_primary: id == 0,
            coords: PointerCoords {
                page_x: x,
                page_y: y,
                screen_x: x,
                screen_y: y,
                client_x: x,
                client_y: y,
            },
            button: MouseEventButton::Main,
            buttons: MouseEventButtons::from(MouseEventButton::Main),
            mods: Default::default(),
            details: PointerDetails::default(),
            element: Point::default(),
            active_pointers: Default::default(),
        }
    }

    #[test]
    fn touches_reports_all_active_pointers() {
        let f0 = finger_event(0, 10.0, 20.0);
        let f1 = finger_event(1, 30.0, 40.0);

        // The triggering event (second finger down) carries the list of all
        // currently-active pointers.
        let trigger = f1.clone();
        {
            let mut list = trigger.active_pointers.borrow_mut();
            list.push(f0.clone());
            list.push(f1.clone());
        }

        let data = NativeTouchData(trigger);

        // `touches` reports every active pointer ...
        let touches = data.touches();
        assert_eq!(touches.len(), 2);
        let coords: Vec<(f64, f64)> = touches
            .iter()
            .map(|t| {
                let c = t.client_coordinates();
                (c.x, c.y)
            })
            .collect();
        assert!(coords.contains(&(10.0, 20.0)));
        assert!(coords.contains(&(30.0, 40.0)));

        // ... while `changed_touches` reports only the triggering touch.
        assert_eq!(data.touches_changed().len(), 1);
        let changed = data.touches_changed();
        let changed_coords = changed[0].client_coordinates();
        assert_eq!((changed_coords.x, changed_coords.y), (30.0, 40.0));
    }

    /// A focus request made while the document is borrowed must survive rather
    /// than panic.
    ///
    /// This is not hypothetical: `DioxusDocument::poll` drives task wakeups
    /// while holding the document borrow, so a component that asks for focus
    /// from a spawned task lands here every time. Before the queue, this test
    /// panicked with `RefCell already borrowed` on the `set_focus` line.
    ///
    /// The borrow below stands in for the one `poll` is holding — what matters
    /// is only that the document is borrowed when the request is made.
    #[test]
    fn focus_requested_while_the_document_is_borrowed_is_applied_later() {
        use blitz_dom::DocumentConfig;

        let doc = Rc::new(RefCell::new(BaseDocument::new(DocumentConfig::default())));
        let root_id = doc.borrow().root_node().id;
        let handle = NodeHandle {
            doc: Rc::clone(&doc),
            command_queue: Rc::new(RefCell::new(Vec::new())),
            node_id: root_id,
        };

        {
            let _held = doc.borrow_mut();
            // Must not panic, and must not apply yet: the borrow is held.
            let _ = handle.set_focus(true);
        }

        assert_eq!(
            doc.borrow().get_focussed_node_id(),
            None,
            "the request cannot have been applied while the document was borrowed"
        );

        flush_document_commands(&doc, &handle.command_queue);

        assert_eq!(
            doc.borrow().get_focussed_node_id(),
            Some(root_id),
            "the queued request should be applied once the borrow is released"
        );
    }

    /// The uncontended path must not be made lazy by the queue: with nothing
    /// holding the borrow, focus applies immediately and needs no flush.
    #[test]
    fn focus_applies_immediately_when_the_document_is_free() {
        use blitz_dom::DocumentConfig;

        let doc = Rc::new(RefCell::new(BaseDocument::new(DocumentConfig::default())));
        let root_id = doc.borrow().root_node().id;
        let handle = NodeHandle {
            doc: Rc::clone(&doc),
            command_queue: Rc::new(RefCell::new(Vec::new())),
            node_id: root_id,
        };

        let _ = handle.set_focus(true);

        assert_eq!(doc.borrow().get_focussed_node_id(), Some(root_id));
    }

    #[test]
    fn flushing_one_document_does_not_apply_another_documents_focus() {
        use blitz_dom::DocumentConfig;

        let first = Rc::new(RefCell::new(BaseDocument::new(DocumentConfig::default())));
        let second = Rc::new(RefCell::new(BaseDocument::new(DocumentConfig::default())));
        let first_id = first.borrow().root_node().id;
        let second_id = second.borrow().root_node().id;
        let first_queue = Rc::new(RefCell::new(Vec::new()));
        let second_queue = Rc::new(RefCell::new(Vec::new()));
        let first_handle = NodeHandle {
            doc: Rc::clone(&first),
            command_queue: Rc::clone(&first_queue),
            node_id: first_id,
        };
        let second_handle = NodeHandle {
            doc: Rc::clone(&second),
            command_queue: Rc::clone(&second_queue),
            node_id: second_id,
        };

        {
            let _first_borrow = first.borrow_mut();
            let _second_borrow = second.borrow_mut();
            let _ = first_handle.set_focus(true);
            let _ = second_handle.set_focus(true);
        }

        // This stands in for polling only the first DioxusDocument. A global
        // command queue incorrectly drains the second document's command too.
        flush_document_commands(&first, &first_queue);

        assert_eq!(first.borrow().get_focussed_node_id(), Some(first_id));
        assert_eq!(
            second.borrow().get_focussed_node_id(),
            None,
            "polling one document must not execute another document's commands",
        );
    }

    #[test]
    fn touches_is_empty_when_no_pointers_are_active() {
        // e.g. a `touchend` for the last finger: it has been removed from the
        // active list before dispatch, so `touches` is empty but
        // `changed_touches` still reports the finger that ended.
        let data = NativeTouchData(finger_event(0, 1.0, 2.0));
        assert!(data.touches().is_empty());
        assert_eq!(data.touches_changed().len(), 1);
    }
}