-
Notifications
You must be signed in to change notification settings - Fork 219
/
dom.rs
executable file
·1489 lines (1312 loc) · 50.1 KB
/
dom.rs
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
fmt,
hash::{Hash, Hasher},
sync::atomic::{AtomicUsize, Ordering},
cmp::Ordering as CmpOrdering,
iter::FromIterator,
};
use crate::{
callbacks::{
Callback, CallbackType,
GlCallback, GlCallbackType,
IFrameCallback, IFrameCallbackType,
RefAny, DefaultCallback,
},
app_resources::{ImageId, TextId},
id_tree::{Arena, NodeDataContainer},
};
use azul_css::{NodeTypePath, CssProperty};
pub use crate::id_tree::{NodeHierarchy, Node, NodeId};
static TAG_ID: AtomicUsize = AtomicUsize::new(1);
/// Unique Ttag" that is used to annotate which rectangles are relevant for hit-testing
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct TagId(pub u64);
impl ::std::fmt::Display for TagId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ScrollTagId({})", self.0)
}
}
impl ::std::fmt::Debug for TagId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
/// Same as the `TagId`, but only for scrollable nodes
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct ScrollTagId(pub TagId);
impl ::std::fmt::Display for ScrollTagId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ScrollTagId({})", (self.0).0)
}
}
impl ::std::fmt::Debug for ScrollTagId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl TagId {
pub fn new() -> Self {
TagId(TAG_ID.fetch_add(1, Ordering::SeqCst) as u64)
}
pub fn reset() {
TAG_ID.swap(1, Ordering::SeqCst);
}
}
impl ScrollTagId {
pub fn new() -> ScrollTagId {
ScrollTagId(TagId::new())
}
}
static DOM_ID: AtomicUsize = AtomicUsize::new(1);
/// DomID - used for identifying different DOMs (for example IFrameCallbacks)
/// have a different DomId than the root DOM
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DomId {
/// Unique ID for this DOM
id: usize,
/// If this DOM was generated from an IFrameCallback, stores the parents
/// DomId + the NodeId (from the parent DOM) which the IFrameCallback
/// was attached to.
parent: Option<(Box<DomId>, NodeId)>,
}
impl DomId {
/// ID for the top-level DOM (of a window)
pub const ROOT_ID: DomId = Self { id: 0, parent: None };
/// Creates a new, unique DOM ID.
#[inline(always)]
pub fn new(parent: Option<(DomId, NodeId)>) -> DomId {
DomId {
id: DOM_ID.fetch_add(1, Ordering::SeqCst),
parent: parent.map(|(p, node_id)| (Box::new(p), node_id)),
}
}
/// Reset the DOM ID to 0, usually done once-per-frame for the root DOM
#[inline(always)]
pub fn reset() {
DOM_ID.swap(0, Ordering::SeqCst);
}
/// Returns if this is the root node
#[inline(always)]
pub fn is_root(&self) -> bool {
*self == Self::ROOT_ID
}
}
/// Calculated hash of a DOM node, used for querying attributes of the DOM node
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
pub struct DomHash(pub u64);
/// List of core DOM node types built-into by `azul`.
pub enum NodeType<T> {
/// Regular div with no particular type of data attached
Div,
/// Same as div, but only for the root node
Body,
/// A small label that can be (optionally) be selectable with the mouse
Label(DomString),
/// Larger amount of text, that has to be cached
Text(TextId),
/// An image that is rendered by WebRender. The id is acquired by the
/// `AppState::add_image()` function
Image(ImageId),
/// OpenGL texture. The `Svg` widget deserizalizes itself into a texture
/// Equality and Hash values are only checked by the OpenGl texture ID,
/// Azul does not check that the contents of two textures are the same
GlTexture((GlCallback, RefAny)),
/// DOM that gets passed its width / height during the layout
IFrame((IFrameCallback<T>, RefAny)),
}
impl<T> NodeType<T> {
fn get_text_content(&self) -> Option<String> {
use self::NodeType::*;
match self {
Div | Body => None,
Label(s) => Some(format!("{}", s)),
Image(id) => Some(format!("image({:?})", id)),
Text(t) => Some(format!("textid({:?})", t)),
GlTexture(g) => Some(format!("gltexture({:?})", g)),
IFrame(i) => Some(format!("iframe({:?})", i)),
}
}
}
// #[derive(Debug, Clone, PartialEq, Hash, Eq)] for NodeType<T>
impl<T> fmt::Debug for NodeType<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::NodeType::*;
match self {
Div => write!(f, "NodeType::Div"),
Body => write!(f, "NodeType::Body"),
Label(a) => write!(f, "NodeType::Label {{ {:?} }}", a),
Text(a) => write!(f, "NodeType::Text {{ {:?} }}", a),
Image(a) => write!(f, "NodeType::Image {{ {:?} }}", a),
GlTexture((ptr, cb)) => write!(f, "NodeType::GlTexture {{ ptr: {:?}, callback: {:?} }}", ptr, cb),
IFrame((ptr, cb)) => write!(f, "NodeType::IFrame {{ ptr: {:?}, callback: {:?} }}", ptr, cb),
}
}
}
impl<T> Clone for NodeType<T> {
fn clone(&self) -> Self {
use self::NodeType::*;
match self {
Div => Div,
Body => Body,
Label(a) => Label(a.clone()),
Text(a) => Text(a.clone()),
Image(a) => Image(a.clone()),
GlTexture((ptr, a)) => GlTexture((ptr.clone(), a.clone())),
IFrame((ptr, a)) => IFrame((ptr.clone(), a.clone())),
}
}
}
impl<T> Hash for NodeType<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
use self::NodeType::*;
use std::mem;
mem::discriminant(&self).hash(state);
match self {
Div | Body => { },
Label(a) => a.hash(state),
Text(a) => a.hash(state),
Image(a) => a.hash(state),
GlTexture((ptr, a)) => {
ptr.hash(state);
a.hash(state);
},
IFrame((ptr, a)) => {
ptr.hash(state);
a.hash(state);
},
}
}
}
impl<T> PartialEq for NodeType<T> {
fn eq(&self, rhs: &Self) -> bool {
use self::NodeType::*;
match (self, rhs) {
(Div, Div) => true,
(Body, Body) => true,
(Label(a), Label(b)) => a == b,
(Text(a), Text(b)) => a == b,
(Image(a), Image(b)) => a == b,
(GlTexture((ptr_a, a)), GlTexture((ptr_b, b))) => {
a == b && ptr_a == ptr_b
},
(IFrame((ptr_a, a)), IFrame((ptr_b, b))) => {
a == b && ptr_a == ptr_b
},
_ => false,
}
}
}
impl<T> Eq for NodeType<T> { }
impl<T> NodeType<T> {
#[inline]
pub fn get_path(&self) -> NodeTypePath {
use self::NodeType::*;
match self {
Div => NodeTypePath::Div,
Body => NodeTypePath::Body,
Label(_) | Text(_) => NodeTypePath::P,
Image(_) => NodeTypePath::Img,
GlTexture(_) => NodeTypePath::Texture,
IFrame(_) => NodeTypePath::IFrame,
}
}
}
/// When to call a callback action - `On::MouseOver`, `On::MouseOut`, etc.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum On {
/// Mouse cursor is hovering over the element
MouseOver,
/// Mouse cursor has is over element and is pressed
/// (not good for "click" events - use `MouseUp` instead)
MouseDown,
/// (Specialization of `MouseDown`). Fires only if the left mouse button
/// has been pressed while cursor was over the element
LeftMouseDown,
/// (Specialization of `MouseDown`). Fires only if the middle mouse button
/// has been pressed while cursor was over the element
MiddleMouseDown,
/// (Specialization of `MouseDown`). Fires only if the right mouse button
/// has been pressed while cursor was over the element
RightMouseDown,
/// Mouse button has been released while cursor was over the element
MouseUp,
/// (Specialization of `MouseUp`). Fires only if the left mouse button has
/// been released while cursor was over the element
LeftMouseUp,
/// (Specialization of `MouseUp`). Fires only if the middle mouse button has
/// been released while cursor was over the element
MiddleMouseUp,
/// (Specialization of `MouseUp`). Fires only if the right mouse button has
/// been released while cursor was over the element
RightMouseUp,
/// Mouse cursor has entered the element
MouseEnter,
/// Mouse cursor has left the element
MouseLeave,
/// Mousewheel / touchpad scrolling
Scroll,
/// The window received a unicode character (also respects the system locale).
/// Check `keyboard_state.current_char` to get the current pressed character.
TextInput,
/// A **virtual keycode** was pressed. Note: This is only the virtual keycode,
/// not the actual char. If you want to get the character, use `TextInput` instead.
/// A virtual key does not have to map to a printable character.
///
/// You can get all currently pressed virtual keycodes in the `keyboard_state.current_virtual_keycodes`
/// and / or just the last keycode in the `keyboard_state.latest_virtual_keycode`.
VirtualKeyDown,
/// A **virtual keycode** was release. See `VirtualKeyDown` for more info.
VirtualKeyUp,
/// A file has been dropped on the element
HoveredFile,
/// A file is being hovered on the element
DroppedFile,
/// A file was hovered, but has exited the window
HoveredFileCancelled,
/// Equivalent to `onfocus`
FocusReceived,
/// Equivalent to `onblur`
FocusLost,
}
/// Sets the target for what events can reach the callbacks specifically.
///
/// Filtering events can happen on several layers, depending on
/// if a DOM node is hovered over or actively focused. For example,
/// for text input, you wouldn't want to use hovering, because that
/// would mean that the user needs to hold the mouse over the text input
/// in order to enter text. To solve this, the DOM needs to fire events
/// for elements that are currently not part of the hit-test.
/// `EventFilter` implements `From<On>` as a shorthand (so that you can opt-in
/// to a more specific event) and use
///
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EventFilter {
/// Calls the attached callback when the mouse is actively over the
/// given element.
Hover(HoverEventFilter),
/// Inverse of `Hover` - calls the attached callback if the mouse is **not**
/// over the given element. This is particularly useful for popover menus
/// where you want to close the menu when the user clicks anywhere else but
/// the menu itself.
Not(NotEventFilter),
/// Calls the attached callback when the element is currently focused.
Focus(FocusEventFilter),
/// Calls the callback when anything related to the window is happening.
/// The "hit item" will be the root item of the DOM.
/// For example, this can be useful for tracking the mouse position
/// (in relation to the window). In difference to `Desktop`, this only
/// fires when the window is focused.
///
/// This can also be good for capturing controller input, touch input
/// (i.e. global gestures that aren't attached to any component, but rather
/// the "window" itself).
Window(WindowEventFilter),
}
/// Creates a function inside an impl <enum type> block that returns a single
/// variant if the enum is that variant.
///
/// ```rust
/// enum A {
/// Abc(AbcType),
/// }
///
/// struct AbcType { }
///
/// impl A {
/// // fn as_abc_type(&self) -> Option<AbcType>
/// get_single_enum_type!(as_abc_type, A::Abc(AbcType));
/// }
/// ```
macro_rules! get_single_enum_type {
($fn_name:ident, $enum_name:ident::$variant:ident($return_type:ty)) => (
pub fn $fn_name(&self) -> Option<$return_type> {
use self::$enum_name::*;
match self {
$variant(e) => Some(*e),
_ => None,
}
}
)
}
impl EventFilter {
get_single_enum_type!(as_hover_event_filter, EventFilter::Hover(HoverEventFilter));
get_single_enum_type!(as_focus_event_filter, EventFilter::Focus(FocusEventFilter));
get_single_enum_type!(as_not_event_filter, EventFilter::Not(NotEventFilter));
get_single_enum_type!(as_window_event_filter, EventFilter::Window(WindowEventFilter));
}
impl From<On> for EventFilter {
fn from(input: On) -> EventFilter {
use self::On::*;
match input {
MouseOver => EventFilter::Hover(HoverEventFilter::MouseOver),
MouseDown => EventFilter::Hover(HoverEventFilter::MouseDown),
LeftMouseDown => EventFilter::Hover(HoverEventFilter::LeftMouseDown),
MiddleMouseDown => EventFilter::Hover(HoverEventFilter::MiddleMouseDown),
RightMouseDown => EventFilter::Hover(HoverEventFilter::RightMouseDown),
MouseUp => EventFilter::Hover(HoverEventFilter::MouseUp),
LeftMouseUp => EventFilter::Hover(HoverEventFilter::LeftMouseUp),
MiddleMouseUp => EventFilter::Hover(HoverEventFilter::MiddleMouseUp),
RightMouseUp => EventFilter::Hover(HoverEventFilter::RightMouseUp),
MouseEnter => EventFilter::Hover(HoverEventFilter::MouseEnter),
MouseLeave => EventFilter::Hover(HoverEventFilter::MouseLeave),
Scroll => EventFilter::Hover(HoverEventFilter::Scroll),
TextInput => EventFilter::Focus(FocusEventFilter::TextInput), // focus!
VirtualKeyDown => EventFilter::Window(WindowEventFilter::VirtualKeyDown), // window!
VirtualKeyUp => EventFilter::Window(WindowEventFilter::VirtualKeyUp), // window!
HoveredFile => EventFilter::Hover(HoverEventFilter::HoveredFile),
DroppedFile => EventFilter::Hover(HoverEventFilter::DroppedFile),
HoveredFileCancelled => EventFilter::Hover(HoverEventFilter::HoveredFileCancelled),
FocusReceived => EventFilter::Focus(FocusEventFilter::FocusReceived), // focus!
FocusLost => EventFilter::Focus(FocusEventFilter::FocusLost), // focus!
}
}
}
/// Event filter that only fires when an element is hovered over
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum HoverEventFilter {
MouseOver,
MouseDown,
LeftMouseDown,
RightMouseDown,
MiddleMouseDown,
MouseUp,
LeftMouseUp,
RightMouseUp,
MiddleMouseUp,
MouseEnter,
MouseLeave,
Scroll,
ScrollStart,
ScrollEnd,
TextInput,
VirtualKeyDown,
VirtualKeyUp,
HoveredFile,
DroppedFile,
HoveredFileCancelled,
}
impl HoverEventFilter {
pub fn to_focus_event_filter(&self) -> Option<FocusEventFilter> {
use self::HoverEventFilter::*;
match self {
MouseOver => Some(FocusEventFilter::MouseOver),
MouseDown => Some(FocusEventFilter::MouseDown),
LeftMouseDown => Some(FocusEventFilter::LeftMouseDown),
RightMouseDown => Some(FocusEventFilter::RightMouseDown),
MiddleMouseDown => Some(FocusEventFilter::MiddleMouseDown),
MouseUp => Some(FocusEventFilter::MouseUp),
LeftMouseUp => Some(FocusEventFilter::LeftMouseUp),
RightMouseUp => Some(FocusEventFilter::RightMouseUp),
MiddleMouseUp => Some(FocusEventFilter::MiddleMouseUp),
MouseEnter => Some(FocusEventFilter::MouseEnter),
MouseLeave => Some(FocusEventFilter::MouseLeave),
Scroll => Some(FocusEventFilter::Scroll),
ScrollStart => Some(FocusEventFilter::ScrollStart),
ScrollEnd => Some(FocusEventFilter::ScrollEnd),
TextInput => Some(FocusEventFilter::TextInput),
VirtualKeyDown => Some(FocusEventFilter::VirtualKeyDown),
VirtualKeyUp => Some(FocusEventFilter::VirtualKeyDown),
HoveredFile => None,
DroppedFile => None,
HoveredFileCancelled => None,
}
}
}
/// The inverse of an `onclick` event filter, fires when an item is *not* hovered / focused.
/// This is useful for cleanly implementing things like popover dialogs or dropdown boxes that
/// want to close when the user clicks any where *but* the item itself.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum NotEventFilter {
Hover(HoverEventFilter),
Focus(FocusEventFilter),
}
/// Event filter similar to `HoverEventFilter` that only fires when the element is focused
///
/// **Important**: In order for this to fire, the item must have a `tabindex` attribute
/// (to indicate that the item is focus-able).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FocusEventFilter {
MouseOver,
MouseDown,
LeftMouseDown,
RightMouseDown,
MiddleMouseDown,
MouseUp,
LeftMouseUp,
RightMouseUp,
MiddleMouseUp,
MouseEnter,
MouseLeave,
Scroll,
ScrollStart,
ScrollEnd,
TextInput,
VirtualKeyDown,
VirtualKeyUp,
FocusReceived,
FocusLost,
}
/// Event filter that fires when any action fires on the entire window
/// (regardless of whether any element is hovered or focused over).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum WindowEventFilter {
MouseOver,
MouseDown,
LeftMouseDown,
RightMouseDown,
MiddleMouseDown,
MouseUp,
LeftMouseUp,
RightMouseUp,
MiddleMouseUp,
MouseEnter,
MouseLeave,
Scroll,
ScrollStart,
ScrollEnd,
TextInput,
VirtualKeyDown,
VirtualKeyUp,
HoveredFile,
DroppedFile,
HoveredFileCancelled,
}
impl WindowEventFilter {
pub fn to_hover_event_filter(&self) -> Option<HoverEventFilter> {
use self::WindowEventFilter::*;
match self {
MouseOver => Some(HoverEventFilter::MouseOver),
MouseDown => Some(HoverEventFilter::MouseDown),
LeftMouseDown => Some(HoverEventFilter::LeftMouseDown),
RightMouseDown => Some(HoverEventFilter::RightMouseDown),
MiddleMouseDown => Some(HoverEventFilter::MiddleMouseDown),
MouseUp => Some(HoverEventFilter::MouseUp),
LeftMouseUp => Some(HoverEventFilter::LeftMouseUp),
RightMouseUp => Some(HoverEventFilter::RightMouseUp),
MiddleMouseUp => Some(HoverEventFilter::MiddleMouseUp),
Scroll => Some(HoverEventFilter::Scroll),
ScrollStart => Some(HoverEventFilter::ScrollStart),
ScrollEnd => Some(HoverEventFilter::ScrollEnd),
TextInput => Some(HoverEventFilter::TextInput),
VirtualKeyDown => Some(HoverEventFilter::VirtualKeyDown),
VirtualKeyUp => Some(HoverEventFilter::VirtualKeyDown),
HoveredFile => Some(HoverEventFilter::HoveredFile),
DroppedFile => Some(HoverEventFilter::DroppedFile),
HoveredFileCancelled => Some(HoverEventFilter::HoveredFileCancelled),
// MouseEnter and MouseLeave on the **window** - does not mean a mouseenter
// and a mouseleave on the hovered element
MouseEnter => None,
MouseLeave => None,
}
}
}
/// Represents one single DOM node (node type, classes, ids and callbacks are stored here)
pub struct NodeData<T> {
/// `div`
node_type: NodeType<T>,
/// `#main #something`
ids: Vec<DomString>,
/// `.myclass .otherclass`
classes: Vec<DomString>,
/// `On::MouseUp` -> `Callback(my_button_click_handler)`
callbacks: Vec<(EventFilter, Callback<T>)>,
/// Usually not set by the user directly - `FakeWindow::add_default_callback`
/// returns a callback ID, so that we know which default callback(s) are attached
/// to this node.
///
/// This is only important if this node has any default callbacks.
default_callbacks: Vec<(EventFilter, (DefaultCallback<T>, RefAny))>,
/// Override certain dynamic styling properties in this frame. For this,
/// these properties have to have a name (the ID).
///
/// For example, in the CSS stylesheet:
///
/// ```css,ignore
/// #my_item { width: [[ my_custom_width | 200px ]] }
/// ```
///
/// ```rust,ignore
/// let node = NodeData {
/// id: Some("my_item".into()),
/// dynamic_css_overrides: vec![("my_custom_width".into(), CssProperty::Width(LayoutWidth::px(500.0)))]
/// }
/// ```
dynamic_css_overrides: Vec<(DomString, CssProperty)>,
/// Whether this div can be dragged or not, similar to `draggable = "true"` in HTML, .
///
/// **TODO**: Currently doesn't do anything, since the drag & drop implementation is missing, API stub.
is_draggable: bool,
/// Whether this div can be focused, and if yes, in what default to `None` (not focusable).
/// Note that without this, there can be no `On::FocusReceived` (equivalent to onfocus),
/// `On::FocusLost` (equivalent to onblur), etc. events.
tab_index: Option<TabIndex>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum TabIndex {
/// Automatic tab index, similar to simply setting `focusable = "true"` or `tabindex = 0`
/// (both have the effect of making the element focusable).
///
/// Sidenote: See https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
/// for interesting notes on tabindex and accessibility
Auto,
/// Set the tab index in relation to its parent element. I.e. if you have a list of elements,
/// the focusing order is restricted to the current parent.
///
/// Ex. a div might have:
///
/// ```no_run,ignore
/// div (Auto)
/// |- element1 (OverrideInParent 0) <- current focus
/// |- element2 (OverrideInParent 5)
/// |- element3 (OverrideInParent 2)
/// |- element4 (Global 5)
/// ```
///
/// When pressing tab repeatedly, the focusing order will be
/// "element3, element2, element4, div", since OverrideInParent elements
/// take precedence among global order.
OverrideInParent(usize),
/// Elements can be focused in callbacks, but are not accessible via
/// keyboard / tab navigation (-1)
NoKeyboardFocus,
}
impl TabIndex {
/// Returns the HTML-compatible number of the `tabindex` element
pub fn get_index(&self) -> isize {
use self::TabIndex::*;
match self {
Auto => 0,
OverrideInParent(x) => *x as isize,
NoKeyboardFocus => -1,
}
}
}
impl Default for TabIndex {
fn default() -> Self {
TabIndex::Auto
}
}
impl<T> PartialEq for NodeData<T> {
fn eq(&self, other: &Self) -> bool {
self.node_type == other.node_type &&
self.ids == other.ids &&
self.classes == other.classes &&
self.callbacks == other.callbacks &&
self.default_callbacks == other.default_callbacks &&
self.dynamic_css_overrides == other.dynamic_css_overrides &&
self.is_draggable == other.is_draggable &&
self.tab_index == other.tab_index
}
}
impl<T> Eq for NodeData<T> { }
impl<T> Default for NodeData<T> {
fn default() -> Self {
NodeData::new(NodeType::Div)
}
}
impl<T> Hash for NodeData<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.node_type.hash(state);
for id in &self.ids {
id.hash(state);
}
for class in &self.classes {
class.hash(state);
}
for callback in &self.callbacks {
callback.hash(state);
}
for default_callback in &self.default_callbacks {
default_callback.hash(state);
}
for dynamic_css_override in &self.dynamic_css_overrides {
dynamic_css_override.hash(state);
}
self.is_draggable.hash(state);
self.tab_index.hash(state);
}
}
impl<T> Clone for NodeData<T> {
fn clone(&self) -> Self {
Self {
node_type: self.node_type.clone(),
ids: self.ids.clone(),
classes: self.classes.clone(),
callbacks: self.callbacks.clone(),
default_callbacks: self.default_callbacks.clone(),
dynamic_css_overrides: self.dynamic_css_overrides.clone(),
is_draggable: self.is_draggable.clone(),
tab_index: self.tab_index.clone(),
}
}
}
impl<T> fmt::Display for NodeData<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let html_type = self.node_type.get_path();
let attributes_string = node_data_to_string(&self);
match self.node_type.get_text_content() {
Some(content) => write!(f, "<{}{}>{}</{}>", html_type, attributes_string, content, html_type),
None => write!(f, "<{}{}/>", html_type, attributes_string)
}
}
}
impl<T> NodeData<T> {
pub fn debug_print_start(&self, close_self: bool) -> String {
let html_type = self.node_type.get_path();
let attributes_string = node_data_to_string(&self);
format!("<{}{}{}>", html_type, attributes_string, if close_self { " /" } else { "" })
}
pub fn debug_print_end(&self) -> String {
let html_type = self.node_type.get_path();
format!("</{}>", html_type)
}
}
fn node_data_to_string<T>(node_data: &NodeData<T>) -> String {
let id_string = if node_data.ids.is_empty() {
String::new()
} else {
format!(" id=\"{}\"", node_data.ids.iter().map(|s| s.as_str().to_string()).collect::<Vec<String>>().join(" "))
};
let class_string = if node_data.classes.is_empty() {
String::new()
} else {
format!(" class=\"{}\"", node_data.classes.iter().map(|s| s.as_str().to_string()).collect::<Vec<String>>().join(" "))
};
let draggable = if node_data.is_draggable {
format!(" draggable=\"true\"")
} else {
String::new()
};
let tabindex = if let Some(tab_index) = node_data.tab_index {
format!(" tabindex=\"{}\"", tab_index.get_index())
} else {
String::new()
};
let callbacks = if node_data.callbacks.is_empty() {
String::new()
} else {
format!(" callbacks=\"{}\"", node_data.callbacks.iter().map(|(evt, cb)| format!("({:?}={:?})", evt, cb)).collect::<Vec<String>>().join(" "))
};
let default_callbacks = if node_data.default_callbacks.is_empty() {
String::new()
} else {
format!(" default-callbacks=\"{}\"", node_data.default_callbacks.iter().map(|(evt, cb)| format!("({:?}={:?})", evt, cb)).collect::<Vec<String>>().join(" "))
};
let css_overrides = if node_data.dynamic_css_overrides.is_empty() {
String::new()
} else {
format!(" css-overrides=\"{}\"", node_data.dynamic_css_overrides.iter().map(|(id, prop)| format!("{}={:?};", id, prop)).collect::<Vec<String>>().join(" "))
};
format!("{}{}{}{}{}{}{}", id_string, class_string, tabindex, draggable, callbacks, default_callbacks, css_overrides)
}
impl<T> fmt::Debug for NodeData<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"NodeData {{ \
\tnode_type: {:?}, \
\tids: {:?}, \
\tclasses: {:?}, \
\tcallbacks: {:?}, \
\tdefault_callbacks: {:?}, \
\tdynamic_css_overrides: {:?}, \
\tis_draggable: {:?}, \
\ttab_index: {:?}, \
}}",
self.node_type,
self.ids,
self.classes,
self.callbacks,
self.default_callbacks,
self.dynamic_css_overrides,
self.is_draggable,
self.tab_index,
)
}
}
impl<T> NodeData<T> {
/// Creates a new `NodeData` instance from a given `NodeType`
#[inline]
pub const fn new(node_type: NodeType<T>) -> Self {
Self {
node_type,
ids: Vec::new(),
classes: Vec::new(),
callbacks: Vec::new(),
default_callbacks: Vec::new(),
dynamic_css_overrides: Vec::new(),
is_draggable: false,
tab_index: None,
}
}
/// Checks whether this node is of the given node type (div, image, text)
#[inline]
pub fn is_node_type(&self, searched_type: NodeType<T>) -> bool {
self.node_type == searched_type
}
/// Checks whether this node has the searched ID attached
pub fn has_id(&self, id: &str) -> bool {
self.ids.iter().any(|self_id| self_id.equals_str(id))
}
/// Checks whether this node has the searched class attached
pub fn has_class(&self, class: &str) -> bool {
self.classes.iter().any(|self_class| self_class.equals_str(class))
}
pub fn calculate_node_data_hash(&self) -> DomHash {
use std::collections::hash_map::DefaultHasher as HashAlgorithm;
let mut hasher = HashAlgorithm::default();
self.hash(&mut hasher);
DomHash(hasher.finish())
}
/// Shorthand for `NodeData::new(NodeType::Body)`.
#[inline(always)]
pub const fn body() -> Self {
Self::new(NodeType::Body)
}
/// Shorthand for `NodeData::new(NodeType::Div)`.
#[inline(always)]
pub const fn div() -> Self {
Self::new(NodeType::Div)
}
/// Shorthand for `NodeData::new(NodeType::Label(value.into()))`
#[inline(always)]
pub fn label<S: Into<DomString>>(value: S) -> Self {
Self::new(NodeType::Label(value.into()))
}
/// Shorthand for `NodeData::new(NodeType::Text(text_id))`
#[inline(always)]
pub const fn text_id(text_id: TextId) -> Self {
Self::new(NodeType::Text(text_id))
}
/// Shorthand for `NodeData::new(NodeType::Image(image_id))`
#[inline(always)]
pub const fn image(image: ImageId) -> Self {
Self::new(NodeType::Image(image))
}
/// Shorthand for `NodeData::new(NodeType::GlTexture((callback, ptr)))`
#[inline(always)]
pub const fn gl_texture(callback: GlCallbackType, ptr: RefAny) -> Self {
Self::new(NodeType::GlTexture((GlCallback(callback), ptr)))
}
/// Shorthand for `NodeData::new(NodeType::IFrame((callback, ptr)))`
#[inline(always)]
pub const fn iframe(callback: IFrameCallbackType<T>, ptr: RefAny) -> Self {
Self::new(NodeType::IFrame((IFrameCallback(callback), ptr)))
}
// NOTE: Getters are used here in order to allow changing the memory allocator for the NodeData
// in the future (which is why the fields are all private).
#[inline(always)]
pub const fn get_node_type(&self) -> &NodeType<T> { &self.node_type }
#[inline(always)]
pub const fn get_ids(&self) -> &Vec<DomString> { &self.ids }
#[inline(always)]
pub const fn get_classes(&self) -> &Vec<DomString> { &self.classes }
#[inline(always)]
pub const fn get_callbacks(&self) -> &Vec<(EventFilter, Callback<T>)> { &self.callbacks }
#[inline(always)]
pub const fn get_default_callbacks(&self) -> &Vec<(EventFilter, (DefaultCallback<T>, RefAny))> { &self.default_callbacks }
#[inline(always)]
pub const fn get_dynamic_css_overrides(&self) -> &Vec<(DomString, CssProperty)> { &self.dynamic_css_overrides }
#[inline(always)]
pub const fn get_is_draggable(&self) -> bool { self.is_draggable }
#[inline(always)]
pub const fn get_tab_index(&self) -> Option<TabIndex> { self.tab_index }
#[inline(always)]
pub const fn set_node_type(&mut self, node_type: NodeType<T>) { self.node_type = node_type; }
#[inline(always)]
pub const fn set_ids(&mut self, ids: Vec<DomString>) { self.ids = ids; }
#[inline(always)]
pub const fn set_classes(&mut self, classes: Vec<DomString>) { self.classes = classes; }
#[inline(always)]
pub const fn set_callbacks(&mut self, callbacks: Vec<(EventFilter, Callback<T>)>) { self.callbacks = callbacks; }
#[inline(always)]
pub const fn set_default_callbacks(&mut self, default_callbacks: Vec<(EventFilter, (DefaultCallback<T>, RefAny))>) { self.default_callbacks = default_callbacks; }
#[inline(always)]
pub const fn set_dynamic_css_overrides(&mut self, dynamic_css_overrides: Vec<(DomString, CssProperty)>) { self.dynamic_css_overrides = dynamic_css_overrides; }
#[inline(always)]
pub const fn set_is_draggable(&mut self, is_draggable: bool) { self.is_draggable = is_draggable; }
#[inline(always)]
pub const fn set_tab_index(&mut self, tab_index: Option<TabIndex>) { self.tab_index = tab_index; }
#[inline(always)]
pub const fn with_node_type(self, node_type: NodeType<T>) -> Self { Self { node_type, .. self } }
#[inline(always)]
pub const fn with_ids(self, ids: Vec<DomString>) -> Self { Self { ids, .. self } }
#[inline(always)]
pub const fn with_classes(self, classes: Vec<DomString>) -> Self { Self { classes, .. self } }
#[inline(always)]
pub const fn with_callbacks(self, callbacks: Vec<(EventFilter, Callback<T>)>) -> Self { Self { callbacks, .. self } }
#[inline(always)]
pub const fn with_default_callbacks(self, default_callbacks: Vec<(EventFilter, (DefaultCallback<T>, RefAny))>) -> Self { Self { default_callbacks, .. self } }
#[inline(always)]
pub const fn with_dynamic_css_overrides(self, dynamic_css_overrides: Vec<(DomString, CssProperty)>) -> Self { Self { dynamic_css_overrides, .. self } }
#[inline(always)]
pub const fn is_draggable(self, is_draggable: bool) -> Self { Self { is_draggable, .. self } }
#[inline(always)]
pub const fn with_tab_index(self, tab_index: Option<TabIndex>) -> Self { Self { tab_index, .. self } }
}
/// Most strings are known at compile time, spares a bit of
/// heap allocations - for `&'static str`, simply stores the pointer,
/// instead of converting it into a String. This is good for class names
/// or IDs, whose content rarely changes.
#[derive(Debug, Clone)]
pub enum DomString {
Static(&'static str),
Heap(String),
}
impl Eq for DomString { }
impl PartialEq for DomString {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialOrd for DomString {
fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
Some(self.as_str().cmp(other.as_str()))
}
}
impl Ord for DomString {
fn cmp(&self, other: &Self) -> CmpOrdering {
self.as_str().cmp(other.as_str())
}
}
impl Hash for DomString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
impl DomString {
pub fn equals_str(&self, target: &str) -> bool {
use self::DomString::*;
match &self {
Static(s) => *s == target,
Heap(h) => h == target,
}
}
pub fn as_str(&self) -> &str {
use self::DomString::*;
match &self {
Static(s) => s,
Heap(h) => h,
}
}
}
impl fmt::Display for DomString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::DomString::*;
match &self {
Static(s) => write!(f, "{}", s),
Heap(h) => write!(f, "{}", h),
}
}
}
impl From<String> for DomString {
fn from(e: String) -> Self {
DomString::Heap(e)
}
}
impl From<&'static str> for DomString {