azul-core 0.0.16

Common datatypes used for the Azul document object model, shared across all azul-* crates
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
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
//! Hit-test result types for determining which DOM nodes are under the cursor,
//! scroll state tracking, and pipeline/document identification. These types
//! feed into the event dispatch system.

use alloc::collections::BTreeMap;
use core::{
    fmt,
    sync::atomic::{AtomicU32, Ordering as AtomicOrdering},
};

use crate::{
    dom::{
        DomId, DomNodeHash, DomNodeId, OptionDomNodeId, ScrollTagId, ScrollbarOrientation, TagId,
    },
    geom::{LogicalPosition, LogicalRect, LogicalSize},
    id::NodeId,
    resources::IdNamespace,
    window::MouseCursorType,
    OrderedMap,
};

/// Result of a hit test against a single DOM, containing all nodes hit
/// by the cursor along with scroll, scrollbar, and cursor-type information.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub struct HitTest {
    pub regular_hit_test_nodes: BTreeMap<NodeId, HitTestItem>,
    pub scroll_hit_test_nodes: BTreeMap<NodeId, ScrollHitTestItem>,
    /// Hit test results for scrollbar components.
    pub scrollbar_hit_test_nodes: BTreeMap<ScrollbarHitId, ScrollbarHitTestItem>,
    /// Hit test results for cursor areas (text runs with cursor property).
    /// Maps `NodeId` to (`CursorType`, `hit_depth`) - the cursor type and z-depth of the hit.
    pub cursor_hit_test_nodes: BTreeMap<NodeId, CursorHitTestItem>,
}

/// Hit test item for cursor areas (determines which cursor icon to show).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct CursorHitTestItem {
    pub cursor_type: CursorType,
    pub hit_depth: u32,
    pub point_in_viewport: LogicalPosition,
}

impl HitTest {
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            regular_hit_test_nodes: BTreeMap::new(),
            scroll_hit_test_nodes: BTreeMap::new(),
            scrollbar_hit_test_nodes: BTreeMap::new(),
            cursor_hit_test_nodes: BTreeMap::new(),
        }
    }
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.regular_hit_test_nodes.is_empty()
            && self.scroll_hit_test_nodes.is_empty()
            && self.scrollbar_hit_test_nodes.is_empty()
            && self.cursor_hit_test_nodes.is_empty()
    }
}

/// Unique identifier for a specific component of a scrollbar.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum ScrollbarHitId {
    VerticalTrack(DomId, NodeId),
    VerticalThumb(DomId, NodeId),
    HorizontalTrack(DomId, NodeId),
    HorizontalThumb(DomId, NodeId),
}

/// Hit test item specifically for scrollbar components.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct ScrollbarHitTestItem {
    pub point_in_viewport: LogicalPosition,
    pub point_relative_to_item: LogicalPosition,
    pub orientation: ScrollbarOrientation,
}

/// Scroll frame identifier combining a unique `u64` tag with its owning `PipelineId`.
#[derive(Copy, Clone, Eq, Hash, PartialEq, Ord, PartialOrd)]
#[repr(C)]
pub struct ExternalScrollId(pub u64, pub PipelineId);

impl ::core::fmt::Display for ExternalScrollId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ExternalScrollId({})", self.0)
    }
}

impl ::core::fmt::Debug for ExternalScrollId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

/// A node whose content overflows its parent, requiring scroll handling.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
pub struct OverflowingScrollNode {
    pub parent_rect: LogicalRect,
    pub child_rect: LogicalRect,
    pub virtual_child_rect: LogicalRect,
    pub parent_external_scroll_id: ExternalScrollId,
    pub parent_dom_hash: DomNodeHash,
    pub scroll_tag_id: ScrollTagId,
}

impl Default for OverflowingScrollNode {
    fn default() -> Self {
        use crate::dom::TagId;
        Self {
            parent_rect: LogicalRect::zero(),
            child_rect: LogicalRect::zero(),
            virtual_child_rect: LogicalRect::zero(),
            parent_external_scroll_id: ExternalScrollId(0, PipelineId::DUMMY),
            parent_dom_hash: DomNodeHash { inner: 0 },
            scroll_tag_id: ScrollTagId {
                inner: TagId { inner: 0 },
            },
        }
    }
}

/// Extra source identifier within a pipeline, allowing multiple independent
/// subsystems to generate `PipelineId` values without collision.
///
/// All pipelines still share the same `IdNamespace` and `DocumentId`.
pub type PipelineSourceId = u32;

/// Information about a scroll frame, given to the user by the framework.
///
/// The two rects are NOT in the same coordinate space — never subtract one
/// origin from the other. That silent ambiguity put the scrollbar thumb
/// partway down the track for every container not at the window origin.
/// See `ScrollManager::get_scroll_states_for_dom` for the producer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub struct ScrollPosition {
    /// The scroll container's border box in ABSOLUTE window coordinates.
    /// `size` is the scrollport ("how big is the parent container", so
    /// "scroll to left edge" can be implemented); `origin` is where that
    /// container sits on screen and is only meaningful to scroll-into-view.
    pub parent_rect: LogicalRect,
    /// `size` = the scrollable content ("the union of all children", or the
    /// `VirtualView` virtual size when one was reported).
    /// `origin` = the SCROLL OFFSET ITSELF — distance already scrolled from
    /// the scroll origin, normally clamped to `[0, content − container]`.
    /// It is NOT an absolute position and NOT relative to
    /// `parent_rect.origin`; content paints at `position − origin`.
    pub children_rect: LogicalRect,
}

/// Identifies a document within a namespace, used for multi-document rendering.
#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct DocumentId {
    pub namespace_id: IdNamespace,
    pub id: u32,
}

impl ::core::fmt::Display for DocumentId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "DocumentId {{ ns: {}, id: {} }}",
            self.namespace_id, self.id
        )
    }
}

impl ::core::fmt::Debug for DocumentId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

/// Identifies a rendering pipeline by source and sequence number.
#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct PipelineId(pub PipelineSourceId, pub u32);

impl ::core::fmt::Display for PipelineId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PipelineId({}, {})", self.0, self.1)
    }
}

impl ::core::fmt::Debug for PipelineId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

static LAST_PIPELINE_ID: AtomicU32 = AtomicU32::new(0);

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

impl PipelineId {
    pub const DUMMY: Self = Self(0, 0);

    pub fn new() -> Self {
        Self(LAST_PIPELINE_ID.fetch_add(1, AtomicOrdering::SeqCst), 0)
    }
}

/// A single hit-test result for a regular (non-scroll) DOM node.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
pub struct HitTestItem {
    /// The hit point in the coordinate space of the "viewport" of the display item.
    /// The viewport is the scroll node formed by the root reference frame of the display item's
    /// pipeline.
    pub point_in_viewport: LogicalPosition,
    /// The hit point relative to this node's static CONTENT-box origin, with
    /// the node's own scroll offset NOT applied.
    ///
    /// ## Why this space, and why it is typed
    ///
    /// The two hosts used to disagree here. `WebRender` reports the point
    /// relative to the hit RECT, which azul pushes before the scroll frame —
    /// i.e. [`BorderBoxLocal`](crate::spaces::BorderBoxLocal) — while the CPU
    /// tester used in headless E2E subtracted `padding + border` and reported
    /// [`ContentBoxLocal`]. Same click, two answers, differing by exactly the
    /// node's content inset. It stayed latent only because the default
    /// `TextInput`'s value `<p>` sets neither padding nor border; it goes live
    /// for any padded editable.
    ///
    /// Both producers now emit `ContentBoxLocal`, because that is the space
    /// the consumer that cares (`UnifiedLayout::hittest_cursor`, via
    /// `LayoutWindow::ifc_local_point`) actually needs. Consumers wanting the
    /// border-box-relative point the public
    /// `CallbackInfo::get_cursor_relative_to_node` promises convert back with
    /// [`ContentBoxLocal::to_border_box_local`].
    ///
    /// [`ContentBoxLocal`]: crate::spaces::ContentBoxLocal
    /// [`ContentBoxLocal::to_border_box_local`]: crate::spaces::ContentBoxLocal::to_border_box_local
    pub point_relative_to_item: crate::spaces::ContentBoxLocal,
    /// Necessary to easily get the nearest `VirtualView` node
    pub is_focusable: bool,
    /// If this hit is a `VirtualView` node, stores the `VirtualViews` `DomId` + the origin of the `VirtualView`
    pub is_virtual_view_hit: Option<(DomId, LogicalPosition)>,
    /// Z-order depth from `WebRender` hit test (0 = frontmost/topmost in z-order).
    /// Lower values are closer to the user. This preserves the ordering from
    /// `WebRender`'s hit test results which returns items front-to-back.
    pub hit_depth: u32,
}

/// A hit-test result for a scrollable DOM node.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
pub struct ScrollHitTestItem {
    /// The hit point in the coordinate space of the "viewport" of the display item.
    /// The viewport is the scroll node formed by the root reference frame of the display item's
    /// pipeline.
    pub point_in_viewport: LogicalPosition,
    /// The hit point relative to the container's static BORDER-box origin,
    /// with its own scroll NOT applied — i.e. where in its scrollPORT the
    /// pointer is.
    ///
    /// Deliberately a different space from [`HitTestItem::point_relative_to_item`]:
    /// this one is about the scroll box's chrome (which edge is the pointer
    /// near, is it over the scrollbar gutter), not about its text content, and
    /// scroll geometry is measured against the border box everywhere else.
    pub point_relative_to_item: crate::spaces::BorderBoxLocal,
    /// If this hit is a `VirtualView` node, stores the `VirtualViews` `DomId` + the origin of the `VirtualView`
    pub scroll_node: OverflowingScrollNode,
}

/// Map of active scroll states, keyed by their external scroll ID.
#[derive(Debug, Default)]
pub struct ScrollStates(pub OrderedMap<ExternalScrollId, ScrollState>);

impl ScrollStates {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn get_scroll_position(&self, scroll_id: &ExternalScrollId) -> Option<LogicalPosition> {
        self.0.get(scroll_id).map(ScrollState::get)
    }

    /// Set the scroll amount - does not update the `entry.used_this_frame`,
    /// since that is only relevant when we are actually querying the renderer.
    pub fn set_scroll_position(
        &mut self,
        node: &OverflowingScrollNode,
        scroll_position: LogicalPosition,
    ) {
        let max_scroll = max_scroll_rect(node);
        self.0
            .entry(node.parent_external_scroll_id)
            .or_default()
            .set(scroll_position.x, scroll_position.y, &max_scroll);
    }

    /// Updating (add to) the existing scroll amount does not update the
    /// `entry.used_this_frame`, since that is only relevant when we are
    /// actually querying the renderer.
    pub fn scroll_node(
        &mut self,
        node: &OverflowingScrollNode,
        scroll_by_x: f32,
        scroll_by_y: f32,
    ) {
        let max_scroll = max_scroll_rect(node);
        self.0
            .entry(node.parent_external_scroll_id)
            .or_default()
            .add(scroll_by_x, scroll_by_y, &max_scroll);
    }
}

/// Compute the maximum scrollable range for a scroll node.
///
/// The maximum scroll offset is `content − viewport` (`child_rect − parent_rect`),
/// clamped to `>= 0`. Previously the scroll position was clamped to the full
/// content size, which let the content scroll entirely out of view. The returned
/// rect keeps `child_rect.origin` and stores the max offset in `size`.
fn max_scroll_rect(node: &OverflowingScrollNode) -> LogicalRect {
    LogicalRect::new(
        node.child_rect.origin,
        LogicalSize::new(
            (node.child_rect.size.width - node.parent_rect.size.width).max(0.0),
            (node.child_rect.size.height - node.parent_rect.size.height).max(0.0),
        ),
    )
}

/// Current scroll position for a single scroll frame.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
#[repr(C)]
pub struct ScrollState {
    /// Amount in pixel that the current node is scrolled
    pub scroll_position: LogicalPosition,
}

impl_option!(
    ScrollState,
    OptionScrollState,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd]
);

impl ScrollState {
    /// Return the current position of the scroll state
    #[must_use]
    pub const fn get(&self) -> LogicalPosition {
        self.scroll_position
    }

    /// Add a scroll X / Y onto the existing scroll state.
    ///
    /// `max_scroll_rect` is the *scroll range* rect: its size is the maximum
    /// scrollable offset (`content − viewport`, clamped to `>= 0`), NOT the full
    /// content size. See [`ScrollStates::scroll_node`]. Clamping via `.max(0.0)`
    /// first also collapses any NaN input to `0.0` (`f32::max` returns the
    /// non-NaN operand), so a NaN delta can never poison the scroll position.
    pub fn add(&mut self, x: f32, y: f32, max_scroll_rect: &LogicalRect) {
        self.scroll_position.x = (self.scroll_position.x + x)
            .max(0.0)
            .min(max_scroll_rect.size.width.max(0.0));
        self.scroll_position.y = (self.scroll_position.y + y)
            .max(0.0)
            .min(max_scroll_rect.size.height.max(0.0));
    }

    /// Set the scroll state to a new position.
    ///
    /// `max_scroll_rect` is the *scroll range* rect (see [`ScrollState::add`]).
    pub const fn set(&mut self, x: f32, y: f32, max_scroll_rect: &LogicalRect) {
        self.scroll_position.x = x.max(0.0).min(max_scroll_rect.size.width.max(0.0));
        self.scroll_position.y = y.max(0.0).min(max_scroll_rect.size.height.max(0.0));
    }
}

impl Default for ScrollState {
    fn default() -> Self {
        Self {
            scroll_position: LogicalPosition::zero(),
        }
    }
}

/// Complete hit-test result across all DOMs, including the currently focused node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FullHitTest {
    pub hovered_nodes: BTreeMap<DomId, HitTest>,
    pub focused_node: OptionDomNodeId,
}

impl FullHitTest {
    /// Every node under the pointer, FRONT TO BACK (9g-ii-e).
    ///
    /// # Why this exists rather than the struct being exposed
    ///
    /// `FullHitTest` is a `BTreeMap` of `DomId` to a `HitTest` that is itself
    /// four more maps. Exposing that shape across the C ABI needs five map
    /// types nothing else would use, and no application wants the shape - it
    /// wants the ANSWER: what is under the cursor, nearest first. So the
    /// accessors return that, the same trade `get_hid_reports` makes by
    /// returning an owned vec rather than a borrowed slice.
    ///
    /// Ordered by `hit_depth`, which `WebRender` and the CPU tester both fill
    /// with a real z-order (0 = frontmost). That is a stronger ordering than
    /// the `NodeId` one some call sites use as a proxy: two overlapping
    /// absolutely-positioned nodes can have any id relationship, and the one
    /// on top is the one with the lower depth.
    ///
    /// Only the REGULAR hits: scroll frames, scrollbar parts and cursor areas
    /// are hit-tested separately and are not nodes an app would call "under
    /// the pointer" - a scrollbar is not the content beneath it.
    #[must_use]
    pub fn hovered_node_ids(&self) -> Vec<DomNodeId> {
        let mut with_depth: Vec<(u32, DomNodeId)> = Vec::new();
        for (dom_id, hit) in &self.hovered_nodes {
            for (node_id, item) in &hit.regular_hit_test_nodes {
                with_depth.push((
                    item.hit_depth,
                    DomNodeId {
                        dom: *dom_id,
                        node: crate::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
                            *node_id,
                        )),
                    },
                ));
            }
        }
        // Stable within a depth, so two nodes a backend reported at the same
        // z-order keep the order the maps gave them rather than an arbitrary
        // one that changes between frames.
        with_depth.sort_by_key(|(depth, _)| *depth);
        with_depth.into_iter().map(|(_, id)| id).collect()
    }

    /// The node nearest the user, or `None` when the pointer is over nothing.
    ///
    /// What an app almost always means by "the hit test": the topmost regular
    /// hit. Cheaper than [`Self::hovered_node_ids`] because it does not sort.
    #[must_use]
    pub fn topmost_node(&self) -> Option<DomNodeId> {
        let mut best: Option<(u32, DomNodeId)> = None;
        for (dom_id, hit) in &self.hovered_nodes {
            for (node_id, item) in &hit.regular_hit_test_nodes {
                let candidate = DomNodeId {
                    dom: *dom_id,
                    node: crate::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
                        *node_id,
                    )),
                };
                // STRICTLY less, so the first node at the frontmost depth wins
                // and the answer does not flip between frames for a tie.
                if best.is_none_or(|(d, _)| item.hit_depth < d) {
                    best = Some((item.hit_depth, candidate));
                }
            }
        }
        best.map(|(_, id)| id)
    }
}

impl FullHitTest {
    /// Create an empty hit-test result
    #[must_use]
    pub fn empty(focused_node: Option<DomNodeId>) -> Self {
        Self {
            hovered_nodes: BTreeMap::new(),
            focused_node: focused_node.into(),
        }
    }

    /// Returns `true` if no nodes were hovered (ignores `focused_node`).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.hovered_nodes.is_empty()
    }
}

/// Result of determining which mouse cursor icon to display based on hit-test results.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CursorTypeHitTest {
    /// closest-node is used for determining the cursor: property
    /// The node is guaranteed to have a non-default cursor: property,
    /// so that the cursor icon can be set accordingly
    pub cursor_node: Option<(DomId, NodeId)>,
    /// Mouse cursor type to set (if `cursor_node` is None, this is set to
    /// `MouseCursorType::Default`)
    pub cursor_icon: MouseCursorType,
}

// ============================================================================
// Type-safe hit-test tag system (merged from the former `hit_test_tag` module).
//
// Encodes WebRender's ItemTag = (u64, u16): the tag *type* lives in the upper
// byte of tag.1 (DOM node / scrollbar / selection / cursor / scroll-container),
// keeping tag types free of bit-level conflicts. See the TAG_TYPE_* constants.
// ============================================================================
// ============================================================================
// Tag Type Markers (stored in upper byte of ItemTag.1)
// ============================================================================

/// Marker for DOM node tags (regular UI elements with callbacks, focus, etc.)
pub const TAG_TYPE_DOM_NODE: u16 = 0x0100;

/// Marker for scrollbar component tags
pub const TAG_TYPE_SCROLLBAR: u16 = 0x0200;

/// Marker for text selection hit-test areas (determines text selection regions)
///
/// These are pushed for text runs to enable text selection without affecting
/// other hit-test logic. Selection may trigger re-rendering.
///
/// NOTE: Text selection hit-testing currently uses `TAG_TYPE_CURSOR` (0x0400).
/// This constant is used by the `HitTestTag::Selection` variant for encoding
/// selection-specific tags (e.g., text run selection areas).
pub const TAG_TYPE_SELECTION: u16 = 0x0300;

/// Marker for cursor hit-test areas (determines which cursor icon to show)
///
/// These are separate from DOM node tags to allow efficient cursor resolution
/// without iterating over all DOM nodes. Cursor changes never require re-rendering.
pub const TAG_TYPE_CURSOR: u16 = 0x0400;

/// Marker for scroll container hit-test areas (for trackpad/wheel scrolling)
///
/// These identify scrollable containers even when no DOM node callbacks are registered.
/// Scroll containers push this tag so the scroll manager can find them during wheel events.
pub const TAG_TYPE_SCROLL_CONTAINER: u16 = 0x0500;

// ============================================================================
// Scrollbar Component Types (stored in lower byte of ItemTag.1 for scrollbar tags)
// ============================================================================

/// Scrollbar component type identifier.
///
/// Each scrollable container can have up to 2 scrollbars (vertical + horizontal),
/// and each scrollbar has 2 main hit regions (track + thumb).
///
/// Future extensions could add:
/// - `UpButton`, `DownButton`, `LeftButton`, `RightButton` for scroll arrows
/// - `PageUp`, `PageDown` for page-scroll regions
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum ScrollbarComponent {
    /// The vertical scrollbar track (background area)
    VerticalTrack = 0,
    /// The vertical scrollbar thumb (draggable handle)
    VerticalThumb = 1,
    /// The horizontal scrollbar track (background area)
    HorizontalTrack = 2,
    /// The horizontal scrollbar thumb (draggable handle)
    HorizontalThumb = 3,
    // Future: scroll arrow buttons
    // VerticalUpButton = 4,
    // VerticalDownButton = 5,
    // HorizontalLeftButton = 6,
    // HorizontalRightButton = 7,
}

impl ScrollbarComponent {
    /// Convert from raw u8 value
    #[must_use]
    pub const fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Self::VerticalTrack),
            1 => Some(Self::VerticalThumb),
            2 => Some(Self::HorizontalTrack),
            3 => Some(Self::HorizontalThumb),
            _ => None,
        }
    }
}

// ============================================================================
// WebRender Hit-Test Tag (unified type-safe representation)
// ============================================================================

/// Unified, type-safe representation of a `WebRender` hit-test tag.
///
/// This enum represents all possible types of hit-test targets. Each variant
/// can be encoded to and decoded from `WebRender`'s `(u64, u16)` `ItemTag` format.
///
/// ## Namespace Separation
///
/// Different tag types are kept in separate namespaces to:
/// - Enable efficient hit-test queries (only iterate over relevant tags)
/// - Get automatic depth sorting from `WebRender` per namespace
/// - Prevent accidental collisions between different hit-test purposes
///
/// | Namespace | Purpose                              |
/// |-----------|--------------------------------------|
/// | 0x0100    | DOM nodes (callbacks, focus, hover)  |
/// | 0x0200    | Scrollbar components                 |
/// | 0x0300    | Selection areas (text selection)     |
/// | 0x0400    | Cursor areas (cursor icon display)     |
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum HitTestTag {
    /// A regular DOM node (button, div, text container, etc.)
    ///
    /// These are nodes that have callbacks, are focusable, or have hover styles.
    /// The `TagId` is a sequential counter assigned during DOM styling.
    DomNode {
        /// The unique tag ID assigned to this DOM node
        tag_id: TagId,
    },

    /// A scrollbar component (track or thumb)
    ///
    /// Each scrollable container can have up to 2 scrollbars.
    /// The scrollbar is identified by the `DomId` and `NodeId` of the scrollable container.
    Scrollbar {
        /// The DOM that contains the scrollable container
        dom_id: DomId,
        /// The `NodeId` of the scrollable container (not the scrollbar itself)
        node_id: NodeId,
        /// Which component of the scrollbar was hit
        component: ScrollbarComponent,
    },

    /// A cursor hit-test area (determines which cursor icon to display)
    ///
    /// These are pushed separately from DOM nodes to allow efficient cursor
    /// resolution. The cursor type is encoded in the lower byte of tag.1.
    Cursor {
        /// The DOM node this cursor area belongs to
        dom_id: DomId,
        /// The `NodeId` of the element with the cursor property
        node_id: NodeId,
        /// The cursor type to display when hovering over this area
        cursor_type: CursorType,
    },

    /// A text selection hit-test area
    ///
    /// These are pushed for text runs to enable text selection.
    /// Separate from DOM nodes to prevent interference with other hit-testing.
    Selection {
        /// The DOM containing the text
        dom_id: DomId,
        /// The `NodeId` of the text container (not the Text node itself)
        container_node_id: NodeId,
        /// The index of the text run within the container (for multi-line text)
        text_run_index: u16,
    },
}

/// Cursor type encoded in cursor hit-test tags.
/// Stored in the lower byte of the ItemTag.1 field.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(u8)]
pub enum CursorType {
    #[default]
    Default = 0,
    Pointer = 1,
    Text = 2,
    Crosshair = 3,
    Move = 4,
    NotAllowed = 5,
    Grab = 6,
    Grabbing = 7,
    EResize = 8,
    WResize = 9,
    NResize = 10,
    SResize = 11,
    EwResize = 12,
    NsResize = 13,
    NeswResize = 14,
    NwseResize = 15,
    ColResize = 16,
    RowResize = 17,
    Wait = 18,
    Help = 19,
    Progress = 20,
    // Add more as needed, up to 255
}

impl CursorType {
    /// Convert from raw u8 value
    // Explicit u8 -> variant table documenting every discriminant; `0 => Default`
    // intentionally mirrors the `_ => Default` fallback (the `#[default]` is 0).
    #[allow(clippy::match_same_arms)]
    #[must_use]
    pub const fn from_u8(value: u8) -> Self {
        match value {
            0 => Self::Default,
            1 => Self::Pointer,
            2 => Self::Text,
            3 => Self::Crosshair,
            4 => Self::Move,
            5 => Self::NotAllowed,
            6 => Self::Grab,
            7 => Self::Grabbing,
            8 => Self::EResize,
            9 => Self::WResize,
            10 => Self::NResize,
            11 => Self::SResize,
            12 => Self::EwResize,
            13 => Self::NsResize,
            14 => Self::NeswResize,
            15 => Self::NwseResize,
            16 => Self::ColResize,
            17 => Self::RowResize,
            18 => Self::Wait,
            19 => Self::Help,
            20 => Self::Progress,
            _ => Self::Default,
        }
    }
}

impl HitTestTag {
    /// Encode this tag to `WebRender`'s `ItemTag` format.
    ///
    /// Returns `(u64, u16)` suitable for passing to `WebRender`'s `push_hit_test`.
    #[must_use]
    pub fn to_item_tag(&self) -> (u64, u16) {
        match self {
            Self::DomNode { tag_id } => {
                // tag.0 = TagId.inner (the sequential counter)
                // tag.1 = TAG_TYPE_DOM_NODE marker
                (tag_id.inner, TAG_TYPE_DOM_NODE)
            }
            Self::Scrollbar {
                dom_id,
                node_id,
                component,
            } => {
                // tag.0 = DomId (upper 32 bits) | NodeId (lower 32 bits)
                let tag_value = ((dom_id.inner as u64) << 32) | (node_id.index() as u64);
                // tag.1 = TAG_TYPE_SCROLLBAR | component type in lower byte
                let tag_type = TAG_TYPE_SCROLLBAR | (*component as u16);
                (tag_value, tag_type)
            }
            Self::Cursor {
                dom_id,
                node_id,
                cursor_type,
            } => {
                // tag.0 = DomId (upper 32 bits) | NodeId (lower 32 bits)
                let tag_value = ((dom_id.inner as u64) << 32) | (node_id.index() as u64);
                // tag.1 = TAG_TYPE_CURSOR | cursor type in lower byte
                let tag_type = TAG_TYPE_CURSOR | (*cursor_type as u16);
                (tag_value, tag_type)
            }
            Self::Selection {
                dom_id,
                container_node_id,
                text_run_index,
            } => {
                // tag.0 = DomId (upper 16 bits) | NodeId (middle 32 bits) | text_run_index (lower 16 bits)
                // AUDIT: mask each field to its bit width so an out-of-range DomId /
                // NodeId can never bleed into an adjacent field (silent cross-field
                // corruption). Masking clamps consistently in debug and release —
                // a >16-bit DomId is absurd but must degrade gracefully, not panic.
                let dom_bits = (dom_id.inner as u64) & 0xFFFF;
                let node_bits = (container_node_id.index() as u64) & 0xFFFF_FFFF;
                let tag_value = (dom_bits << 48) | (node_bits << 16) | u64::from(*text_run_index);
                (tag_value, TAG_TYPE_SELECTION)
            }
        }
    }

    /// Decode a `WebRender` `ItemTag` back to a typed `HitTestTag`.
    ///
    /// Returns `None` if the tag format is invalid or unrecognized.
    #[must_use]
    pub fn from_item_tag(tag: (u64, u16)) -> Option<Self> {
        let (tag_value, tag_type) = tag;

        // Extract tag type from upper byte
        let type_marker = tag_type & 0xFF00;

        match type_marker {
            TAG_TYPE_DOM_NODE => {
                // DOM node tag: tag.0 is the TagId
                Some(Self::DomNode {
                    tag_id: TagId { inner: tag_value },
                })
            }
            TAG_TYPE_SCROLLBAR => {
                // Scrollbar tag: decode DomId, NodeId, and component
                let dom_id = DomId {
                    inner: ((tag_value >> 32) & 0xFFFF_FFFF) as usize,
                };
                let node_id = NodeId::new((tag_value & 0xFFFF_FFFF) as usize);
                let component_value = (tag_type & 0x00FF) as u8;
                let component = ScrollbarComponent::from_u8(component_value)?;

                Some(Self::Scrollbar {
                    dom_id,
                    node_id,
                    component,
                })
            }
            TAG_TYPE_CURSOR => {
                // Cursor tag: decode DomId, NodeId, and cursor type
                let dom_id = DomId {
                    inner: ((tag_value >> 32) & 0xFFFF_FFFF) as usize,
                };
                let node_id = NodeId::new((tag_value & 0xFFFF_FFFF) as usize);
                let cursor_value = (tag_type & 0x00FF) as u8;
                let cursor_type = CursorType::from_u8(cursor_value);

                Some(Self::Cursor {
                    dom_id,
                    node_id,
                    cursor_type,
                })
            }
            TAG_TYPE_SELECTION => {
                // Selection tag: decode DomId, NodeId, and text run index
                let dom_id = DomId {
                    inner: ((tag_value >> 48) & 0xFFFF) as usize,
                };
                let container_node_id = NodeId::new(((tag_value >> 16) & 0xFFFF_FFFF) as usize);
                let text_run_index = (tag_value & 0xFFFF) as u16;

                Some(Self::Selection {
                    dom_id,
                    container_node_id,
                    text_run_index,
                })
            }
            _ => {
                // Unknown tag type - could be a legacy tag or corruption
                // For backwards compatibility, treat tags with tag_type == 0
                // as legacy DOM node tags (old format before type markers)
                if tag_type == 0 {
                    Some(Self::DomNode {
                        tag_id: TagId { inner: tag_value },
                    })
                } else {
                    None
                }
            }
        }
    }

    /// Check if this is a DOM node tag
    #[must_use]
    pub const fn is_dom_node(&self) -> bool {
        matches!(self, Self::DomNode { .. })
    }

    /// Check if this is a scrollbar tag
    #[must_use]
    pub const fn is_scrollbar(&self) -> bool {
        matches!(self, Self::Scrollbar { .. })
    }

    /// Check if this is a cursor tag
    #[must_use]
    pub const fn is_cursor(&self) -> bool {
        matches!(self, Self::Cursor { .. })
    }

    /// Check if this is a selection tag
    #[must_use]
    pub const fn is_selection(&self) -> bool {
        matches!(self, Self::Selection { .. })
    }

    /// Get the `TagId` if this is a DOM node tag
    #[must_use]
    pub const fn as_dom_node(&self) -> Option<TagId> {
        match self {
            Self::DomNode { tag_id } => Some(*tag_id),
            _ => None,
        }
    }

    /// Get cursor info if this is a cursor tag
    #[must_use]
    pub const fn as_cursor(&self) -> Option<(DomId, NodeId, CursorType)> {
        match self {
            Self::Cursor {
                dom_id,
                node_id,
                cursor_type,
            } => Some((*dom_id, *node_id, *cursor_type)),
            _ => None,
        }
    }

    /// Get selection info if this is a selection tag
    #[must_use]
    pub const fn as_selection(&self) -> Option<(DomId, NodeId, u16)> {
        match self {
            Self::Selection {
                dom_id,
                container_node_id,
                text_run_index,
            } => Some((*dom_id, *container_node_id, *text_run_index)),
            _ => None,
        }
    }

    /// Get scrollbar info if this is a scrollbar tag
    #[must_use]
    pub const fn as_scrollbar(&self) -> Option<(DomId, NodeId, ScrollbarComponent)> {
        match self {
            Self::Scrollbar {
                dom_id,
                node_id,
                component,
            } => Some((*dom_id, *node_id, *component)),
            _ => None,
        }
    }
}

impl fmt::Display for HitTestTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DomNode { tag_id } => {
                write!(f, "DomNode(tag:{})", tag_id.inner)
            }
            Self::Scrollbar {
                dom_id,
                node_id,
                component,
            } => {
                write!(
                    f,
                    "Scrollbar(dom:{}, node:{}, {:?})",
                    dom_id.inner,
                    node_id.index(),
                    component
                )
            }
            Self::Cursor {
                dom_id,
                node_id,
                cursor_type,
            } => {
                write!(
                    f,
                    "Cursor(dom:{}, node:{}, {:?})",
                    dom_id.inner,
                    node_id.index(),
                    cursor_type
                )
            }
            Self::Selection {
                dom_id,
                container_node_id,
                text_run_index,
            } => {
                write!(
                    f,
                    "Selection(dom:{}, container:{}, run:{})",
                    dom_id.inner,
                    container_node_id.index(),
                    text_run_index
                )
            }
        }
    }
}

#[cfg(test)]
#[path = "hit_test_test.rs"]
mod tests;