1
//! Hover state management for tracking mouse and touch hover history
2
//!
3
//! The `HoverManager` records hit test results for multiple input points
4
//! (mouse, touch, pen) over multiple frames to enable gesture detection
5
//! (like `DragStart`) that requires analyzing hover patterns over time
6
//! rather than just the current frame.
7

            
8
use std::collections::{BTreeMap, VecDeque};
9

            
10
use azul_core::{
11
    dom::DomNodeId,
12
    events::{EventData, EventSource, EventType, MouseButton, SyntheticEvent},
13
};
14

            
15
use crate::hit_test::FullHitTest;
16

            
17
/// Maximum number of frames to keep in hover history
18
const MAX_HOVER_HISTORY: usize = 5;
19

            
20
/// Pick the front-most deepest hovered node across all hit DOMs.
21
///
22
/// Iterates DOMs from highest `DomId` (most-nested child, composited on top)
23
/// to lowest and returns the FRONT-MOST hit of the first DOM that has a
24
/// regular hit: the smallest `hit_depth` (both hit testers number hits
25
/// front to back). Ties fall back to the highest `NodeId`, which is what
26
/// this used to return outright - right while the arena's DFS order was
27
/// also the depth order, wrong for an inline-docked `<transient-window>`
28
/// grafted under a zone with a higher id than its own subtree.
29
/// See [`HoverManager::current_hover_node_full`].
30
#[must_use]
31
350
pub fn deepest_node_across_doms(ht: &FullHitTest) -> Option<DomNodeId> {
32
350
    for (dom_id, hit) in ht.hovered_nodes.iter().rev() {
33
333
        let front = hit
34
333
            .regular_hit_test_nodes
35
333
            .iter()
36
729
            .min_by(|(a_id, a), (b_id, b)| a.hit_depth.cmp(&b.hit_depth).then(b_id.cmp(a_id)))
37
333
            .map(|(node_id, _)| *node_id);
38
333
        if let Some(node_id) = front {
39
329
            return Some(DomNodeId {
40
329
                dom: *dom_id,
41
329
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
42
329
                    node_id,
43
329
                )),
44
329
            });
45
4
        }
46
    }
47
21
    None
48
350
}
49

            
50
/// The node a mouse press FOCUSES: the nearest focusable ancestor (self
51
/// included) of the front-most hit, walking that node's OWN DOM only
52
/// (9g-ii-e-ii).
53
///
54
/// `is_focusable(dom, node)` and `parent(dom, node)` are the two questions
55
/// the walk asks of the layout results; taking them as closures keeps the
56
/// rule testable without a laid-out document, and lets the e2e runner and
57
/// the dll share it instead of each keeping a copy - both copies walked
58
/// EVERY hit DOM in ascending id order and let the LAST focusable win, so a
59
/// focusable host node under a `VirtualView` page took the focus a click on
60
/// the page meant for the page (or for nobody: a click on unfocusable page
61
/// content is a BLUR, not a focus of whatever the page covers).
62
#[must_use]
63
25
pub fn focusable_under_pointer(
64
25
    ht: &FullHitTest,
65
25
    is_focusable: impl Fn(azul_core::dom::DomId, azul_core::id::NodeId) -> bool,
66
25
    parent: impl Fn(azul_core::dom::DomId, azul_core::id::NodeId) -> Option<azul_core::id::NodeId>,
67
25
) -> Option<DomNodeId> {
68
25
    let target = deepest_node_across_doms(ht)?;
69
21
    let dom = target.dom;
70
21
    let mut current = target.node.into_crate_internal();
71
32
    while let Some(nid) = current {
72
29
        if is_focusable(dom, nid) {
73
18
            return Some(DomNodeId {
74
18
                dom,
75
18
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(nid)),
76
18
            });
77
11
        }
78
11
        current = parent(dom, nid);
79
    }
80
3
    None
81
25
}
82

            
83
/// Which seat an event belongs to: the seat on a mouse, scroll or keyboard
84
/// event, the primary for everything else. A keyboard seat IS a pointer seat
85
/// (9b-ii-a-i): X11 routes a master keyboard to its paired pointer's seat,
86
/// Wayland a `wl_seat`'s keyboard to that seat - so a seat's keys resolve
87
/// against that seat's focus (9b-ii-a-i-d).
88
#[must_use]
89
40
pub const fn seat_of_event(event: &SyntheticEvent) -> u64 {
90
40
    match &event.data {
91
21
        EventData::Mouse(m) => m.seat_id,
92
        EventData::Scroll(s) => s.seat_id,
93
19
        EventData::Keyboard(k) => k.seat_id,
94
        EventData::Touch(t) => t.seat_id,
95
        EventData::Composition(c) => c.seat_id,
96
        _ => azul_core::window::PRIMARY_POINTER_SEAT,
97
    }
98
40
}
99

            
100
/// An active pointer capture (`CallbackInfo::capture_pointer`): while set,
101
/// the capturing SEAT's moves and release are delivered to `node` no matter
102
/// what is under that cursor (W3C `setPointerCapture`). Per seat (9b-ii-b):
103
/// a capture a second cursor's press started must not swallow the first
104
/// cursor's moves, and vice versa.
105
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106
pub struct PointerCapture {
107
    pub seat_id: u64,
108
    pub node: DomNodeId,
109
}
110

            
111
/// Retarget the captured seat's `MouseMove` / `MouseOver` / `MouseUp` at the
112
/// capturing node; returns whether that seat RELEASED (the capture ends with
113
/// the release). Other seats' events pass through untouched.
114
2
pub fn apply_pointer_capture(events: &mut [SyntheticEvent], capture: PointerCapture) -> bool {
115
2
    let mut released = false;
116
4
    for ev in events.iter_mut() {
117
4
        let EventData::Mouse(mouse) = &ev.data else {
118
            continue;
119
        };
120
4
        if mouse.seat_id != capture.seat_id {
121
2
            continue;
122
2
        }
123
        if matches!(
124
2
            ev.event_type,
125
            EventType::MouseMove | EventType::MouseOver | EventType::MouseUp
126
2
        ) {
127
2
            ev.target = capture.node;
128
2
            ev.current_target = capture.node;
129
2
            released |= ev.event_type == EventType::MouseUp;
130
2
        }
131
    }
132
2
    released
133
2
}
134

            
135
/// Identifier for an input point (mouse, touch, pen, etc.)
136
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
137
pub enum InputPointId {
138
    /// Mouse cursor - the PRIMARY pointer seat.
139
    Mouse,
140
    /// Touch point with unique ID (from TouchEvent.id)
141
    Touch(u64),
142
    /// A non-primary pointer seat (9b-ii): a second cursor, keyed by the
143
    /// platform's seat id. Never carries `PRIMARY_POINTER_SEAT`; use
144
    /// [`InputPointId::for_seat`], which folds the primary into `Mouse`.
145
    Seat(u64),
146
}
147

            
148
impl InputPointId {
149
    /// The input point that tracks pointer seat `seat_id`.
150
    #[must_use]
151
74
    pub const fn for_seat(seat_id: u64) -> Self {
152
74
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
153
            Self::Mouse
154
        } else {
155
74
            Self::Seat(seat_id)
156
        }
157
74
    }
158
}
159

            
160
/// Manages hover state history for all input points
161
///
162
/// Records hit test results for mouse and touch inputs over multiple frames:
163
/// - `DragStart` detection (requires movement threshold over multiple frames)
164
/// - Hover-over event detection
165
/// - Multi-touch gesture detection
166
/// - Input path analysis
167
///
168
/// The manager maintains a separate history for each active input point.
169
#[derive(Debug, Clone, PartialEq, Eq)]
170
pub struct HoverManager {
171
    /// Hit test history for each input point
172
    /// Each point has its own ring buffer of the last N frames
173
    hover_histories: BTreeMap<InputPointId, VecDeque<FullHitTest>>,
174
    /// The node each mouse button was PRESSED on, per pointer seat, kept
175
    /// until that button's release has been delivered to it — see
176
    /// [`Self::apply_press_target_capture`]. Keyed by seat as well as button
177
    /// (9b-ii): two cursors can hold Left at once, and the second press must
178
    /// not overwrite the first's target.
179
    press_targets: Vec<(u64, MouseButton, DomNodeId)>,
180
}
181

            
182
impl HoverManager {
183
    /// Create a new empty `HoverManager`
184
    #[must_use]
185
7828
    pub const fn new() -> Self {
186
7828
        Self {
187
7828
            hover_histories: BTreeMap::new(),
188
7828
            press_targets: Vec::new(),
189
7828
        }
190
7828
    }
191

            
192
    /// The node `button` is currently pressed on by the PRIMARY seat, if its
193
    /// release is still owed.
194
    #[must_use]
195
8
    pub fn press_target(&self, button: MouseButton) -> Option<DomNodeId> {
196
8
        self.press_target_for(azul_core::window::PRIMARY_POINTER_SEAT, button)
197
8
    }
198

            
199
    /// [`Self::press_target`] for any pointer seat.
200
    #[must_use]
201
75
    pub fn press_target_for(&self, seat_id: u64, button: MouseButton) -> Option<DomNodeId> {
202
75
        self.press_targets
203
75
            .iter()
204
75
            .find(|(s, b, _)| *s == seat_id && *b == button)
205
75
            .map(|(_, _, t)| *t)
206
75
    }
207

            
208
    /// Forget every press target (the owed releases will never come — e.g.
209
    /// the layout window is torn down).
210
    pub fn clear_press_targets(&mut self) {
211
        self.press_targets.clear();
212
    }
213

            
214
    /// PRESS-TARGET CAPTURE.
215
    ///
216
    /// Events are derived from window-state diffs and
217
    /// targeted at whatever is under the pointer NOW, so a widget that
218
    /// latched on `MouseDown` only saw its `MouseUp` if the pointer was still
219
    /// over it when the button came up. Every "stuck input" of the demo test
220
    /// was this: a slider, a map pan, a paint stroke, a split-pane drag —
221
    /// each released off its node, each kept dragging on plain moves, each
222
    /// had grown its own "leave = release" workaround. Browsers and toolkits
223
    /// solve it the same way (implicit pointer capture / `SetCapture`): the
224
    /// pressed node gets the release.
225
    ///
226
    /// Records the target of every `MouseDown` in `events` per button. For
227
    /// every `MouseUp`, if the pressed node is neither the release target nor
228
    /// in its propagation path (`in_release_path(press, release)`), a second
229
    /// `MouseUp` for the pressed node — delivered AT THAT TARGET ONLY, its
230
    /// ancestors see the real release — is appended. The release through the
231
    /// hovered node is untouched (click semantics stay hover-based).
232
    ///
233
    /// Call once per pass, after `determine_all_events`, before dispatch. A
234
    /// release derived from a blur (the OS handlers clear the buttons) goes
235
    /// through the same door, so a press that ends with the pointer outside
236
    /// the window is released too.
237
158
    pub fn apply_press_target_capture(
238
158
        &mut self,
239
158
        events: &mut Vec<SyntheticEvent>,
240
158
        in_release_path: &dyn Fn(DomNodeId, DomNodeId) -> bool,
241
158
    ) {
242
158
        let mut captured_releases: Vec<SyntheticEvent> = Vec::new();
243
253
        for event in events.iter() {
244
253
            let EventData::Mouse(mouse) = &event.data else {
245
155
                continue;
246
            };
247
98
            match event.event_type {
248
                EventType::MouseDown => {
249
33
                    self.press_targets
250
33
                        .retain(|(s, b, _)| !(*s == mouse.seat_id && *b == mouse.button));
251
33
                    self.press_targets
252
33
                        .push((mouse.seat_id, mouse.button, event.target));
253
                }
254
                EventType::MouseUp => {
255
27
                    let Some(pos) = self
256
27
                        .press_targets
257
27
                        .iter()
258
28
                        .position(|(s, b, _)| *s == mouse.seat_id && *b == mouse.button)
259
                    else {
260
1
                        continue;
261
                    };
262
26
                    let (_, _, press_target) = self.press_targets.remove(pos);
263
26
                    if press_target == event.target || in_release_path(press_target, event.target) {
264
23
                        continue;
265
3
                    }
266
3
                    captured_releases.push(
267
3
                        SyntheticEvent::new(
268
3
                            EventType::MouseUp,
269
3
                            EventSource::Synthetic,
270
3
                            press_target,
271
3
                            event.timestamp.clone(),
272
3
                            event.data.clone(),
273
                        )
274
3
                        .at_target_only(),
275
                    );
276
                }
277
38
                _ => {}
278
            }
279
        }
280
158
        events.extend(captured_releases);
281
158
    }
282

            
283
    /// (input points, total history entries across all points). Used by
284
    /// `AZ_E2E_TEST` to watch for unbounded growth.
285
    #[must_use]
286
18
    pub fn debug_counts(&self) -> (usize, usize) {
287
18
        let points = self.hover_histories.len();
288
18
        let total: usize = self.hover_histories.values().map(VecDeque::len).sum();
289
18
        (points, total)
290
18
    }
291

            
292
    /// Push a new hit test result for a specific input point
293
    ///
294
    /// The most recent result is always at index 0 for that input point.
295
    /// If the history is full, the oldest frame is dropped.
296
6455
    pub fn push_hit_test(&mut self, input_id: InputPointId, hit_test: FullHitTest) {
297
6455
        let history = self
298
6455
            .hover_histories
299
6455
            .entry(input_id)
300
6455
            .or_insert_with(|| VecDeque::with_capacity(MAX_HOVER_HISTORY));
301

            
302
        // Add to front (most recent)
303
6455
        history.push_front(hit_test);
304

            
305
        // Remove oldest if we exceed the limit
306
6455
        if history.len() > MAX_HOVER_HISTORY {
307
5533
            history.pop_back();
308
5790
        }
309
6455
    }
310

            
311
    /// Remove an input point's history (e.g., when touch ends)
312
14
    pub fn remove_input_point(&mut self, input_id: &InputPointId) {
313
14
        self.hover_histories.remove(input_id);
314
14
    }
315

            
316
    /// Get the most recent hit test result for an input point
317
    ///
318
    /// Returns None if no hit tests have been recorded for this input point.
319
    #[must_use]
320
2282
    pub fn get_current(&self, input_id: &InputPointId) -> Option<&FullHitTest> {
321
2282
        self.hover_histories
322
2282
            .get(input_id)
323
2282
            .and_then(|history| history.front())
324
2282
    }
325

            
326
    /// Get the most recent mouse cursor hit test (convenience method)
327
    #[must_use]
328
1669
    pub fn get_current_mouse(&self) -> Option<&FullHitTest> {
329
1669
        self.get_current(&InputPointId::Mouse)
330
1669
    }
331

            
332
    /// Get the hit test result from N frames ago for an input point
333
    /// (0 = current frame)
334
    ///
335
    /// Returns None if the requested frame is not in history.
336
    #[must_use]
337
592
    pub fn get_frame(&self, input_id: &InputPointId, frames_ago: usize) -> Option<&FullHitTest> {
338
592
        self.hover_histories
339
592
            .get(input_id)
340
592
            .and_then(|history| history.get(frames_ago))
341
592
    }
342

            
343
    /// Get the entire hover history for an input point (most recent first)
344
    #[must_use]
345
8
    pub fn get_history(&self, input_id: &InputPointId) -> Option<&VecDeque<FullHitTest>> {
346
8
        self.hover_histories.get(input_id)
347
8
    }
348

            
349
    /// Get all currently tracked input points
350
    #[must_use]
351
707
    pub fn get_active_input_points(&self) -> Vec<InputPointId> {
352
707
        self.hover_histories.keys().copied().collect()
353
707
    }
354

            
355
    /// Get the number of frames in history for an input point
356
    #[must_use]
357
100
    pub fn frame_count(&self, input_id: &InputPointId) -> usize {
358
100
        self.hover_histories.get(input_id).map_or(0, VecDeque::len)
359
100
    }
360

            
361
    /// Purge every recorded hit-test entry for `dom_id` across all input
362
    /// points and all history frames.
363
    ///
364
    /// Called when a `VirtualView` child DOM is rebuilt IN PLACE (fresh `NodeIds`,
365
    /// no reconcile mapping — e.g. a `MapWidget` pan rebuilding the tile grid):
366
    /// the recorded hits for that DOM reference the OLD generation's `NodeIds`,
367
    /// and consumers that resolve them against the NEW styled DOM read out of
368
    /// bounds (the `hit_test.rs` cursor panic: "len is 25 but the index is 27")
369
    /// or target the wrong node. Unlike incremental reconciles there is no
370
    /// `NodeId` map to `remap` with, so the only safe option is to forget that
371
    /// DOM's hits; the next pointer move re-populates them from a fresh
372
    /// hit test.
373
288
    pub fn purge_dom(&mut self, dom_id: &azul_core::dom::DomId) {
374
288
        for history in self.hover_histories.values_mut() {
375
9
            for frame in history.iter_mut() {
376
9
                frame.hovered_nodes.remove(dom_id);
377
9
            }
378
        }
379
        // A press on a node of a purged (rebuilt) dom can never be released
380
        // to it: the ids are gone.
381
288
        self.press_targets.retain(|(_, _, t)| t.dom != *dom_id);
382
288
    }
383

            
384
    /// Clear all hover history for all input points
385
2
    pub fn clear(&mut self) {
386
2
        self.hover_histories.clear();
387
2
    }
388

            
389
    /// Clear history for a specific input point
390
3
    pub(crate) fn clear_input_point(&mut self, input_id: &InputPointId) {
391
3
        if let Some(history) = self.hover_histories.get_mut(input_id) {
392
2
            history.clear();
393
2
        }
394
3
    }
395

            
396
    /// Check if we have enough frames for gesture detection on an input point
397
    ///
398
    /// `DragStart` detection requires analyzing movement over multiple frames.
399
    /// This returns true if we have at least 2 frames of history.
400
    #[must_use]
401
39
    pub fn has_sufficient_history_for_gestures(&self, input_id: &InputPointId) -> bool {
402
39
        self.frame_count(input_id) >= 2
403
39
    }
404

            
405
    /// Check if any input point has enough history for gesture detection
406
    #[must_use]
407
27
    pub fn any_has_sufficient_history_for_gestures(&self) -> bool {
408
27
        self.hover_histories
409
27
            .iter()
410
31
            .any(|(_, history)| history.len() >= 2)
411
27
    }
412

            
413
    /// Get the deepest hovered node from the current mouse hit test.
414
    ///
415
    /// Returns the `NodeId` of the most specific (deepest in DOM tree) node
416
    /// that the mouse cursor is currently over, or None if not hovering anything.
417
    ///
418
    /// NOTE: Assumes single-DOM architecture (uses `DomId { inner: 0 }`).
419
    #[must_use]
420
17
    pub fn current_hover_node(&self) -> Option<azul_core::id::NodeId> {
421
17
        let current = self.get_current_mouse()?;
422
14
        let dom_id = azul_core::dom::DomId { inner: 0 };
423
14
        let ht = current.hovered_nodes.get(&dom_id)?;
424
11
        ht.regular_hit_test_nodes.keys().last().copied()
425
17
    }
426

            
427
    /// Get the deepest hovered node from the previous frame's mouse hit test.
428
    ///
429
    /// Returns the `NodeId` from one frame ago, or None if not hovering anything
430
    /// or no previous frame exists.
431
    ///
432
    /// NOTE: Assumes single-DOM architecture (uses `DomId { inner: 0 }`).
433
    #[must_use]
434
10
    pub fn previous_hover_node(&self) -> Option<azul_core::id::NodeId> {
435
10
        let history = self.hover_histories.get(&InputPointId::Mouse)?;
436
8
        let previous = history.get(1)?; // index 1 = one frame ago
437
5
        let dom_id = azul_core::dom::DomId { inner: 0 };
438
5
        let ht = previous.hovered_nodes.get(&dom_id)?;
439
4
        ht.regular_hit_test_nodes.keys().last().copied()
440
10
    }
441

            
442
    /// Multi-DOM aware: the deepest hovered node across ALL hit DOMs (current
443
    /// frame). Returns a full `DomNodeId` so events can target `VirtualView` /
444
    /// iframe child DOMs, not just the root.
445
    ///
446
    /// Selection rule: prefer the most-nested DOM that was hit. Child DOMs
447
    /// (`VirtualView` / iframe content) always have higher `DomId`s than their
448
    /// host and are composited on top of it, so the highest hit `DomId` is the
449
    /// front-most surface. Within that DOM the deepest node (last in `NodeId`
450
    /// order) is the W3C event target; bubbling then reaches ancestor handlers.
451
    ///
452
    /// For single-DOM apps only `DomId 0` is ever hit, so this is equivalent to
453
    /// [`current_hover_node`] wrapped in `DomId { inner: 0 }`.
454
    #[must_use]
455
1628
    pub fn current_hover_node_full(&self) -> Option<DomNodeId> {
456
1628
        deepest_node_across_doms(self.get_current_mouse()?)
457
1628
    }
458

            
459
    /// Multi-DOM aware counterpart of [`previous_hover_node`] (one frame ago).
460
    #[must_use]
461
7
    pub fn previous_hover_node_full(&self) -> Option<DomNodeId> {
462
7
        let history = self.hover_histories.get(&InputPointId::Mouse)?;
463
5
        deepest_node_across_doms(history.get(1)?)
464
7
    }
465

            
466
    /// [`current_hover_node_full`] for ANY input point, not just the mouse.
467
    ///
468
    /// Touch event determination needs this: a finger is a pointer of its own,
469
    /// so a `TouchStart` must target the node under THAT finger. Every getter
470
    /// here was mouse-only, which is part of why nothing ever derived a touch
471
    /// event from `FullWindowState::touch_state`.
472
    #[must_use]
473
79
    pub fn hover_node_full_for(&self, input_id: &InputPointId) -> Option<DomNodeId> {
474
79
        deepest_node_across_doms(self.get_current(input_id)?)
475
79
    }
476
}
477

            
478
impl crate::managers::NodeIdRemap for HoverManager {
479
    /// Remap `NodeIds` in all hover histories after DOM reconciliation.
480
    ///
481
    /// Hits on unmounted nodes are dropped (they cannot be hovered any more) —
482
    /// keeping them would make the hover history describe a node that no longer
483
    /// exists at that index.
484
460
    fn remap_node_ids(&mut self, dom_id: azul_core::dom::DomId, map: &crate::managers::NodeIdMap) {
485
        // A pressed node follows the rebuild like a hovered one; an unmounted
486
        // press target is dropped (its release can never be delivered).
487
460
        self.press_targets = core::mem::take(&mut self.press_targets)
488
460
            .into_iter()
489
460
            .filter_map(|(s, b, t)| map.resolve_dom_node_id(dom_id, t).map(|t| (s, b, t)))
490
460
            .collect();
491
460
        let node_id_map = map.as_btree_map();
492
460
        for history in self.hover_histories.values_mut() {
493
19
            for hit_test in history.iter_mut() {
494
19
                if let Some(ht) = hit_test.hovered_nodes.get_mut(&dom_id) {
495
18
                    crate::managers::remap_keys(&mut ht.regular_hit_test_nodes, map);
496
18
                    crate::managers::remap_keys(&mut ht.scroll_hit_test_nodes, map);
497
18
                    crate::managers::remap_keys(&mut ht.cursor_hit_test_nodes, map);
498

            
499
                    // Remap scrollbar_hit_test_nodes (ScrollbarHitId contains NodeId)
500
18
                    let old_sb: Vec<_> = ht.scrollbar_hit_test_nodes.keys().copied().collect();
501
18
                    let mut new_sb = BTreeMap::new();
502
24
                    for old_key in old_sb {
503
6
                        let Some(new_key) = remap_scrollbar_hit_id(&old_key, dom_id, node_id_map)
504
                        else {
505
                            // node unmounted — drop the scrollbar hit
506
1
                            ht.scrollbar_hit_test_nodes.remove(&old_key);
507
1
                            continue;
508
                        };
509
5
                        if let Some(item) = ht.scrollbar_hit_test_nodes.remove(&old_key) {
510
5
                            new_sb.insert(new_key, item);
511
5
                        }
512
                    }
513
18
                    ht.scrollbar_hit_test_nodes = new_sb;
514
1
                }
515
            }
516
        }
517
460
    }
518
}
519

            
520
impl Default for HoverManager {
521
1
    fn default() -> Self {
522
1
        Self::new()
523
1
    }
524
}
525

            
526
/// Remap a `ScrollbarHitId`'s `NodeId` using the reconciliation map.
527
/// `None` = the node was unmounted, so the hit must be dropped.
528
/// A `ScrollbarHitId` for a different `DomId` is returned unchanged.
529
15
fn remap_scrollbar_hit_id(
530
15
    id: &azul_core::hit_test::ScrollbarHitId,
531
15
    dom_id: azul_core::dom::DomId,
532
15
    node_id_map: &BTreeMap<azul_core::id::NodeId, azul_core::id::NodeId>,
533
15
) -> Option<azul_core::hit_test::ScrollbarHitId> {
534
    use azul_core::hit_test::ScrollbarHitId;
535
4
    Some(match id {
536
4
        ScrollbarHitId::VerticalTrack(d, n) if *d == dom_id => {
537
3
            ScrollbarHitId::VerticalTrack(*d, *node_id_map.get(n)?)
538
        }
539
7
        ScrollbarHitId::VerticalThumb(d, n) if *d == dom_id => {
540
7
            ScrollbarHitId::VerticalThumb(*d, *node_id_map.get(n)?)
541
        }
542
3
        ScrollbarHitId::HorizontalTrack(d, n) if *d == dom_id => {
543
1
            ScrollbarHitId::HorizontalTrack(*d, *node_id_map.get(n)?)
544
        }
545
1
        ScrollbarHitId::HorizontalThumb(d, n) if *d == dom_id => {
546
1
            ScrollbarHitId::HorizontalThumb(*d, *node_id_map.get(n)?)
547
        }
548
3
        other => *other,
549
    })
550
15
}
551

            
552
#[cfg(test)]
553
mod autotest_generated {
554
    use azul_core::{
555
        dom::{DomId, DomNodeId, ScrollbarOrientation},
556
        geom::LogicalPosition,
557
        hit_test::{
558
            CursorHitTestItem, CursorType, HitTest, HitTestItem, OverflowingScrollNode,
559
            ScrollHitTestItem, ScrollbarHitId, ScrollbarHitTestItem,
560
        },
561
        id::NodeId,
562
        styled_dom::NodeHierarchyItemId,
563
    };
564

            
565
    use super::*;
566
    use crate::managers::{NodeIdMap, NodeIdRemap};
567

            
568
    // ---------------------------------------------------------------- fixtures
569

            
570
    fn press_dnid(node: usize) -> DomNodeId {
571
        DomNodeId {
572
            dom: DomId { inner: 0 },
573
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
574
        }
575
    }
576

            
577
    fn mouse_event(ty: EventType, button: MouseButton, target: DomNodeId) -> SyntheticEvent {
578
        use azul_core::events::{KeyModifiers, MouseEventData};
579
        SyntheticEvent::new(
580
            ty,
581
            EventSource::User,
582
            target,
583
            azul_core::task::Instant::Tick(azul_core::task::SystemTick { tick_counter: 0 }),
584
            EventData::Mouse(MouseEventData {
585
                position: LogicalPosition::zero(),
586
                button,
587
                buttons: 0,
588
                modifiers: KeyModifiers::default(),
589
                ..Default::default()
590
            }),
591
        )
592
    }
593

            
594
    #[test]
595
    fn a_release_over_another_node_is_also_delivered_to_the_pressed_node() {
596
        // REPORTED (the whole "stuck input" family): a widget that latched on
597
        // MouseDown never saw its MouseUp when the pointer released off it.
598
        let mut hm = HoverManager::new();
599
        let never_related = |_: DomNodeId, _: DomNodeId| false;
600

            
601
        let mut events = vec![mouse_event(
602
            EventType::MouseDown,
603
            MouseButton::Left,
604
            press_dnid(3),
605
        )];
606
        hm.apply_press_target_capture(&mut events, &never_related);
607
        assert_eq!(events.len(), 1, "a press adds nothing");
608
        assert_eq!(hm.press_target(MouseButton::Left), Some(press_dnid(3)));
609

            
610
        let mut events = vec![mouse_event(
611
            EventType::MouseUp,
612
            MouseButton::Left,
613
            press_dnid(9),
614
        )];
615
        hm.apply_press_target_capture(&mut events, &never_related);
616
        assert_eq!(events.len(), 2, "the pressed node gets its own release");
617
        let captured = &events[1];
618
        assert_eq!(captured.event_type, EventType::MouseUp);
619
        assert_eq!(captured.target, press_dnid(3));
620
        assert!(
621
            captured.at_target_only,
622
            "its ancestors already saw the real release"
623
        );
624
        assert_eq!(
625
            events[0].target,
626
            press_dnid(9),
627
            "the hovered node's release is untouched"
628
        );
629
        assert_eq!(
630
            hm.press_target(MouseButton::Left),
631
            None,
632
            "the owed release was delivered"
633
        );
634

            
635
        // Nothing pending: a stray release adds nothing.
636
        let mut events = vec![mouse_event(
637
            EventType::MouseUp,
638
            MouseButton::Left,
639
            press_dnid(9),
640
        )];
641
        hm.apply_press_target_capture(&mut events, &never_related);
642
        assert_eq!(events.len(), 1);
643
    }
644

            
645
    #[test]
646
    fn a_release_on_the_pressed_node_or_its_descendant_is_not_doubled() {
647
        let mut hm = HoverManager::new();
648
        // The hovered node 5 is a descendant of the pressed node 3: the real
649
        // release bubbles through 3 already.
650
        let descendant_of = |press: DomNodeId, release: DomNodeId| {
651
            press == press_dnid(3) && release == press_dnid(5)
652
        };
653

            
654
        let mut events = vec![mouse_event(
655
            EventType::MouseDown,
656
            MouseButton::Left,
657
            press_dnid(3),
658
        )];
659
        hm.apply_press_target_capture(&mut events, &descendant_of);
660
        let mut events = vec![mouse_event(
661
            EventType::MouseUp,
662
            MouseButton::Left,
663
            press_dnid(5),
664
        )];
665
        hm.apply_press_target_capture(&mut events, &descendant_of);
666
        assert_eq!(
667
            events.len(),
668
            1,
669
            "no second release when the path already covers the press"
670
        );
671

            
672
        let mut events = vec![mouse_event(
673
            EventType::MouseDown,
674
            MouseButton::Left,
675
            press_dnid(3),
676
        )];
677
        hm.apply_press_target_capture(&mut events, &descendant_of);
678
        let mut events = vec![mouse_event(
679
            EventType::MouseUp,
680
            MouseButton::Left,
681
            press_dnid(3),
682
        )];
683
        hm.apply_press_target_capture(&mut events, &descendant_of);
684
        assert_eq!(events.len(), 1, "same node: one release");
685
    }
686

            
687
    #[test]
688
    fn press_targets_are_per_button_and_follow_remaps() {
689
        let mut hm = HoverManager::new();
690
        let never_related = |_: DomNodeId, _: DomNodeId| false;
691
        let mut events = vec![
692
            mouse_event(EventType::MouseDown, MouseButton::Left, press_dnid(3)),
693
            mouse_event(EventType::MouseDown, MouseButton::Right, press_dnid(4)),
694
        ];
695
        hm.apply_press_target_capture(&mut events, &never_related);
696
        // Releasing the right button elsewhere releases node 4 only.
697
        let mut events = vec![mouse_event(
698
            EventType::MouseUp,
699
            MouseButton::Right,
700
            press_dnid(9),
701
        )];
702
        hm.apply_press_target_capture(&mut events, &never_related);
703
        assert_eq!(events.len(), 2);
704
        assert_eq!(events[1].target, press_dnid(4));
705
        assert_eq!(hm.press_target(MouseButton::Left), Some(press_dnid(3)));
706

            
707
        // A rebuild renumbers node 3 → 7; the owed release follows it.
708
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(7))]);
709
        hm.remap_node_ids(DomId { inner: 0 }, &map);
710
        assert_eq!(hm.press_target(MouseButton::Left), Some(press_dnid(7)));
711

            
712
        // Purging the dom forgets the press.
713
        hm.purge_dom(&DomId { inner: 0 });
714
        assert_eq!(hm.press_target(MouseButton::Left), None);
715
    }
716

            
717
    #[test]
718
    fn press_targets_are_per_seat() {
719
        // Two cursors holding Left at once (9b-ii): the second press must not
720
        // overwrite the first's target, and each release finds its own.
721
        use azul_core::events::{KeyModifiers, MouseEventData};
722
        let seat_event = |ty: EventType, seat_id: u64, target: DomNodeId| {
723
            SyntheticEvent::new(
724
                ty,
725
                EventSource::User,
726
                target,
727
                azul_core::task::Instant::Tick(azul_core::task::SystemTick { tick_counter: 0 }),
728
                EventData::Mouse(MouseEventData {
729
                    position: LogicalPosition::zero(),
730
                    button: MouseButton::Left,
731
                    buttons: 0,
732
                    modifiers: KeyModifiers::default(),
733
                    seat_id,
734
                    ..Default::default()
735
                }),
736
            )
737
        };
738
        let never_related = |_: DomNodeId, _: DomNodeId| false;
739
        let mut hm = HoverManager::new();
740
        let mut events = vec![
741
            seat_event(EventType::MouseDown, 0, press_dnid(3)),
742
            seat_event(EventType::MouseDown, 9, press_dnid(4)),
743
        ];
744
        hm.apply_press_target_capture(&mut events, &never_related);
745
        assert_eq!(hm.press_target(MouseButton::Left), Some(press_dnid(3)));
746
        assert_eq!(
747
            hm.press_target_for(9, MouseButton::Left),
748
            Some(press_dnid(4))
749
        );
750

            
751
        // Seat 9 releases elsewhere: node 4 gets the captured release, and the
752
        // primary's press is still on file.
753
        let mut events = vec![seat_event(EventType::MouseUp, 9, press_dnid(1))];
754
        hm.apply_press_target_capture(&mut events, &never_related);
755
        assert_eq!(events.len(), 2);
756
        assert_eq!(events[1].target, press_dnid(4));
757
        assert_eq!(hm.press_target_for(9, MouseButton::Left), None);
758
        assert_eq!(hm.press_target(MouseButton::Left), Some(press_dnid(3)));
759
    }
760

            
761
    fn hit_item(depth: u32) -> HitTestItem {
762
        HitTestItem {
763
            point_in_viewport: LogicalPosition::zero(),
764
            point_relative_to_item: Default::default(),
765
            is_focusable: false,
766
            is_virtual_view_hit: None,
767
            hit_depth: depth,
768
        }
769
    }
770

            
771
    fn scroll_item() -> ScrollHitTestItem {
772
        ScrollHitTestItem {
773
            point_in_viewport: LogicalPosition::zero(),
774
            point_relative_to_item: Default::default(),
775
            scroll_node: OverflowingScrollNode::default(),
776
        }
777
    }
778

            
779
    fn cursor_item() -> CursorHitTestItem {
780
        CursorHitTestItem {
781
            cursor_type: CursorType::Text,
782
            hit_depth: 0,
783
            point_in_viewport: LogicalPosition::zero(),
784
        }
785
    }
786

            
787
    fn scrollbar_item() -> ScrollbarHitTestItem {
788
        ScrollbarHitTestItem {
789
            point_in_viewport: LogicalPosition::zero(),
790
            point_relative_to_item: Default::default(),
791
            orientation: ScrollbarOrientation::Vertical,
792
        }
793
    }
794

            
795
    fn dom(inner: usize) -> DomId {
796
        DomId { inner }
797
    }
798

            
799
    /// A `FullHitTest` where every `(dom, &[node..])` entry is a set of regular hits.
800
    /// Node ids are inserted in the given (deliberately unsorted) order.
801
    fn hits(entries: &[(usize, &[usize])]) -> FullHitTest {
802
        let mut full = FullHitTest::empty(None);
803
        for (dom_inner, nodes) in entries {
804
            let ht = full
805
                .hovered_nodes
806
                .entry(dom(*dom_inner))
807
                .or_insert_with(HitTest::empty);
808
            for n in *nodes {
809
                ht.regular_hit_test_nodes
810
                    .insert(NodeId::new(*n), hit_item(0));
811
            }
812
        }
813
        full
814
    }
815

            
816
    /// `DomNodeId` for `(dom, node)`, matching what the hover getters return.
817
    fn dom_node(dom_inner: usize, node: usize) -> DomNodeId {
818
        DomNodeId {
819
            dom: dom(dom_inner),
820
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
821
        }
822
    }
823

            
824
    /// A manager whose mouse history is `frames` (pushed oldest-first, so the
825
    /// LAST element ends up at index 0 = current).
826
    fn mouse_history(frames: Vec<FullHitTest>) -> HoverManager {
827
        let mut hm = HoverManager::new();
828
        for f in frames {
829
            hm.push_hit_test(InputPointId::Mouse, f);
830
        }
831
        hm
832
    }
833

            
834
    // ------------------------------------------- deepest_node_across_doms (other)
835

            
836
    #[test]
837
    fn deepest_node_across_doms_empty_returns_none() {
838
        assert_eq!(deepest_node_across_doms(&FullHitTest::empty(None)), None);
839
    }
840

            
841
    #[test]
842
    fn deepest_node_across_doms_uses_nodeid_order_not_insertion_order() {
843
        // Inserted 2, 9, 7 — BTreeMap key order makes 9 the deepest regardless.
844
        let ht = hits(&[(0, &[2, 9, 7])]);
845
        assert_eq!(deepest_node_across_doms(&ht), Some(dom_node(0, 9)));
846
    }
847

            
848
    #[test]
849
    fn deepest_node_across_doms_prefers_the_front_most_hit_over_the_highest_id() {
850
        // A grafted subtree (an inline-docked transient window under a zone
851
        // with a HIGHER id): the grip (3) is in front of the zone (5).
852
        let mut full = FullHitTest::empty(None);
853
        let ht = full
854
            .hovered_nodes
855
            .entry(dom(0))
856
            .or_insert_with(HitTest::empty);
857
        ht.regular_hit_test_nodes
858
            .insert(NodeId::new(3), hit_item(0));
859
        ht.regular_hit_test_nodes
860
            .insert(NodeId::new(5), hit_item(1));
861
        ht.regular_hit_test_nodes
862
            .insert(NodeId::new(0), hit_item(2));
863
        assert_eq!(deepest_node_across_doms(&full), Some(dom_node(0, 3)));
864
    }
865

            
866
    #[test]
867
    fn deepest_node_across_doms_prefers_highest_dom_even_if_its_node_is_shallower() {
868
        // dom 0 has the deeper NodeId (99) but dom 3 is composited on top.
869
        let ht = hits(&[(0, &[99]), (3, &[1])]);
870
        assert_eq!(deepest_node_across_doms(&ht), Some(dom_node(3, 1)));
871
    }
872

            
873
    #[test]
874
    fn deepest_node_across_doms_skips_dom_with_no_regular_hits() {
875
        // dom 5 is "hit" but only in the scroll/cursor/scrollbar maps — the
876
        // front-most DOM with a REGULAR hit (dom 0) must win instead.
877
        let mut ht = hits(&[(0, &[4])]);
878
        let mut empty_regular = HitTest::empty();
879
        empty_regular
880
            .scroll_hit_test_nodes
881
            .insert(NodeId::new(1), scroll_item());
882
        empty_regular
883
            .cursor_hit_test_nodes
884
            .insert(NodeId::new(1), cursor_item());
885
        empty_regular.scrollbar_hit_test_nodes.insert(
886
            ScrollbarHitId::VerticalThumb(dom(5), NodeId::new(1)),
887
            scrollbar_item(),
888
        );
889
        ht.hovered_nodes.insert(dom(5), empty_regular);
890

            
891
        assert_eq!(deepest_node_across_doms(&ht), Some(dom_node(0, 4)));
892
    }
893

            
894
    #[test]
895
    fn deepest_node_across_doms_all_doms_empty_returns_none() {
896
        let mut ht = FullHitTest::empty(None);
897
        ht.hovered_nodes.insert(dom(0), HitTest::empty());
898
        ht.hovered_nodes.insert(dom(usize::MAX), HitTest::empty());
899
        assert_eq!(deepest_node_across_doms(&ht), None);
900
    }
901

            
902
    #[test]
903
    fn deepest_node_across_doms_extreme_ids_survive_the_nodeid_encoding() {
904
        // usize::MAX - 1 is the largest NodeId that survives the 1-based
905
        // `NodeHierarchyItemId` encode (n + 1) without wrapping.
906
        let max_node = usize::MAX - 1;
907
        let ht = hits(&[(usize::MAX, &[0, max_node])]);
908
        let got = deepest_node_across_doms(&ht).expect("a hit exists");
909
        assert_eq!(got.dom, dom(usize::MAX));
910
        // The DomNodeId must decode back to exactly the NodeId that was hit.
911
        assert_eq!(got.node.into_crate_internal(), Some(NodeId::new(max_node)));
912
    }
913

            
914
    // ------------------------------------------------- new / Default (constructor)
915

            
916
    #[test]
917
    fn new_manager_is_empty_and_every_getter_is_none_or_zero() {
918
        let hm = HoverManager::new();
919
        let mouse = InputPointId::Mouse;
920

            
921
        assert_eq!(hm.debug_counts(), (0, 0));
922
        assert!(hm.get_active_input_points().is_empty());
923
        assert!(hm.get_current(&mouse).is_none());
924
        assert!(hm.get_current_mouse().is_none());
925
        assert!(hm.get_history(&mouse).is_none());
926
        assert_eq!(hm.frame_count(&mouse), 0);
927
        assert!(!hm.has_sufficient_history_for_gestures(&mouse));
928
        assert!(!hm.any_has_sufficient_history_for_gestures());
929
        assert!(hm.current_hover_node().is_none());
930
        assert!(hm.previous_hover_node().is_none());
931
        assert!(hm.current_hover_node_full().is_none());
932
        assert!(hm.previous_hover_node_full().is_none());
933
        // Frame lookups on an unknown point must not panic at any index.
934
        assert!(hm.get_frame(&mouse, 0).is_none());
935
        assert!(hm.get_frame(&mouse, usize::MAX).is_none());
936
    }
937

            
938
    #[test]
939
    fn default_matches_new() {
940
        assert_eq!(HoverManager::default(), HoverManager::new());
941
    }
942

            
943
    // ------------------------------------------------- push_hit_test (numeric)
944

            
945
    #[test]
946
    fn push_hit_test_index_zero_is_the_newest_frame() {
947
        let hm = mouse_history(vec![hits(&[(0, &[1])]), hits(&[(0, &[2])])]);
948

            
949
        assert_eq!(hm.frame_count(&InputPointId::Mouse), 2);
950
        assert_eq!(
951
            hm.get_frame(&InputPointId::Mouse, 0),
952
            Some(&hits(&[(0, &[2])]))
953
        );
954
        assert_eq!(
955
            hm.get_frame(&InputPointId::Mouse, 1),
956
            Some(&hits(&[(0, &[1])]))
957
        );
958
        assert_eq!(hm.get_current_mouse(), Some(&hits(&[(0, &[2])])));
959
    }
960

            
961
    #[test]
962
    fn push_hit_test_ring_buffer_never_exceeds_max_hover_history() {
963
        let mut hm = HoverManager::new();
964
        for i in 0..1000_usize {
965
            hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[i])]));
966
        }
967

            
968
        assert_eq!(hm.frame_count(&InputPointId::Mouse), MAX_HOVER_HISTORY);
969
        assert_eq!(hm.debug_counts(), (1, MAX_HOVER_HISTORY));
970
        // The retained window is the LAST MAX_HOVER_HISTORY pushes, newest first.
971
        for ago in 0..MAX_HOVER_HISTORY {
972
            assert_eq!(
973
                hm.get_frame(&InputPointId::Mouse, ago),
974
                Some(&hits(&[(0, &[999 - ago])])),
975
                "frame {ago} frames ago"
976
            );
977
        }
978
        // Anything older was dropped.
979
        assert!(hm
980
            .get_frame(&InputPointId::Mouse, MAX_HOVER_HISTORY)
981
            .is_none());
982
    }
983

            
984
    #[test]
985
    fn get_frame_out_of_range_index_returns_none_without_overflow() {
986
        let hm = mouse_history(vec![hits(&[(0, &[1])])]);
987
        let mouse = InputPointId::Mouse;
988

            
989
        assert!(hm.get_frame(&mouse, 0).is_some());
990
        assert!(hm.get_frame(&mouse, 1).is_none());
991
        assert!(hm.get_frame(&mouse, usize::MAX).is_none());
992
        assert!(hm.get_frame(&mouse, usize::MAX / 2).is_none());
993
        // Unknown input point at a huge index is still just None.
994
        assert!(hm
995
            .get_frame(&InputPointId::Touch(u64::MAX), usize::MAX)
996
            .is_none());
997
    }
998

            
999
    #[test]
    fn touch_ids_at_u64_boundaries_are_distinct_histories() {
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Touch(u64::MIN), hits(&[(0, &[1])]));
        hm.push_hit_test(InputPointId::Touch(u64::MAX), hits(&[(0, &[2])]));
        hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[3])]));
        assert_eq!(hm.debug_counts(), (3, 3));
        assert_eq!(
            hm.get_current(&InputPointId::Touch(u64::MIN)),
            Some(&hits(&[(0, &[1])]))
        );
        assert_eq!(
            hm.get_current(&InputPointId::Touch(u64::MAX)),
            Some(&hits(&[(0, &[2])]))
        );
        assert_eq!(hm.get_current_mouse(), Some(&hits(&[(0, &[3])])));
        // Ord derive: Mouse sorts before every Touch, touches sort by id.
        assert_eq!(
            hm.get_active_input_points(),
            vec![
                InputPointId::Mouse,
                InputPointId::Touch(0),
                InputPointId::Touch(u64::MAX),
            ]
        );
    }
    #[test]
    fn debug_counts_stays_bounded_under_a_flood_of_points_and_frames() {
        let mut hm = HoverManager::new();
        for point in 0..100_u64 {
            for frame in 0..50_usize {
                hm.push_hit_test(InputPointId::Touch(point), hits(&[(0, &[frame])]));
            }
        }
        // 100 points, each capped at MAX_HOVER_HISTORY frames — no unbounded growth.
        assert_eq!(hm.debug_counts(), (100, 100 * MAX_HOVER_HISTORY));
    }
    #[test]
    fn push_hit_test_stores_the_value_verbatim_including_focused_node() {
        let focused = dom_node(0, 7);
        let mut ht = FullHitTest::empty(Some(focused));
        ht.hovered_nodes.insert(dom(0), HitTest::empty());
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Mouse, ht.clone());
        assert_eq!(hm.get_current_mouse(), Some(&ht));
        assert_eq!(
            hm.get_current_mouse().map(|h| h.focused_node),
            Some(Some(focused).into())
        );
        // A hovered DOM with zero hits is still "no hovered node".
        assert!(hm.current_hover_node().is_none());
        assert!(hm.current_hover_node_full().is_none());
    }
    #[test]
    fn get_history_returns_all_frames_newest_first() {
        let hm = mouse_history(vec![
            hits(&[(0, &[1])]),
            hits(&[(0, &[2])]),
            hits(&[(0, &[3])]),
        ]);
        let history = hm
            .get_history(&InputPointId::Mouse)
            .expect("history exists");
        assert_eq!(history.len(), 3);
        assert_eq!(history[0], hits(&[(0, &[3])]));
        assert_eq!(history[2], hits(&[(0, &[1])]));
        assert!(hm.get_history(&InputPointId::Touch(0)).is_none());
    }
    // --------------------------------------- remove / clear / clear_input_point
    #[test]
    fn remove_absent_input_point_is_a_noop() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1])])]);
        let before = hm.clone();
        hm.remove_input_point(&InputPointId::Touch(0));
        hm.remove_input_point(&InputPointId::Touch(u64::MAX));
        assert_eq!(hm, before);
    }
    #[test]
    fn remove_input_point_only_drops_the_target_point() {
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[1])]));
        hm.push_hit_test(InputPointId::Touch(3), hits(&[(0, &[2])]));
        hm.remove_input_point(&InputPointId::Touch(3));
        assert_eq!(hm.debug_counts(), (1, 1));
        assert_eq!(hm.get_active_input_points(), vec![InputPointId::Mouse]);
        assert!(hm.get_current(&InputPointId::Touch(3)).is_none());
        assert_eq!(hm.frame_count(&InputPointId::Touch(3)), 0);
        assert!(hm.get_current_mouse().is_some());
    }
    #[test]
    fn remove_then_push_restarts_the_history_from_scratch() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1])]), hits(&[(0, &[2])])]);
        assert!(hm.has_sufficient_history_for_gestures(&InputPointId::Mouse));
        hm.remove_input_point(&InputPointId::Mouse);
        hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[3])]));
        assert_eq!(hm.frame_count(&InputPointId::Mouse), 1);
        assert!(!hm.has_sufficient_history_for_gestures(&InputPointId::Mouse));
        assert!(hm.previous_hover_node().is_none());
    }
    #[test]
    fn clear_drops_every_point() {
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[1])]));
        hm.push_hit_test(InputPointId::Touch(9), hits(&[(0, &[2])]));
        hm.clear();
        assert_eq!(hm, HoverManager::new());
        assert_eq!(hm.debug_counts(), (0, 0));
        assert!(!hm.any_has_sufficient_history_for_gestures());
        // Clearing twice is still fine.
        hm.clear();
        assert_eq!(hm.debug_counts(), (0, 0));
    }
    #[test]
    fn clear_input_point_empties_history_but_keeps_the_point_registered() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1])]), hits(&[(0, &[2])])]);
        hm.clear_input_point(&InputPointId::Mouse);
        // The point remains a key with an EMPTY deque (unlike remove_input_point).
        assert_eq!(hm.debug_counts(), (1, 0));
        assert_eq!(hm.get_active_input_points(), vec![InputPointId::Mouse]);
        assert_eq!(hm.frame_count(&InputPointId::Mouse), 0);
        assert!(hm.get_current_mouse().is_none());
        assert!(hm.get_history(&InputPointId::Mouse).is_some());
        assert!(!hm.has_sufficient_history_for_gestures(&InputPointId::Mouse));
        assert!(!hm.any_has_sufficient_history_for_gestures());
        assert!(hm.current_hover_node().is_none());
        assert!(hm.previous_hover_node().is_none());
    }
    #[test]
    fn clear_input_point_on_an_absent_point_is_a_noop() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1])])]);
        let before = hm.clone();
        hm.clear_input_point(&InputPointId::Touch(u64::MAX));
        assert_eq!(hm, before);
    }
    // ------------------------------------------------------------- predicates
    #[test]
    fn has_sufficient_history_needs_at_least_two_frames() {
        let mouse = InputPointId::Mouse;
        let mut hm = HoverManager::new();
        assert!(!hm.has_sufficient_history_for_gestures(&mouse));
        hm.push_hit_test(mouse, hits(&[(0, &[1])]));
        assert!(
            !hm.has_sufficient_history_for_gestures(&mouse),
            "1 frame is not enough"
        );
        hm.push_hit_test(mouse, hits(&[(0, &[2])]));
        assert!(
            hm.has_sufficient_history_for_gestures(&mouse),
            "2 frames is the threshold"
        );
        for i in 0..10 {
            hm.push_hit_test(mouse, hits(&[(0, &[i])]));
        }
        assert!(
            hm.has_sufficient_history_for_gestures(&mouse),
            "stays true when saturated"
        );
    }
    #[test]
    fn any_has_sufficient_history_is_an_or_across_points() {
        let mut hm = HoverManager::new();
        // Three points with one frame each => still false.
        for id in [
            InputPointId::Mouse,
            InputPointId::Touch(0),
            InputPointId::Touch(u64::MAX),
        ] {
            hm.push_hit_test(id, hits(&[(0, &[1])]));
        }
        assert!(!hm.any_has_sufficient_history_for_gestures());
        // A single point reaching 2 frames flips it.
        hm.push_hit_test(InputPointId::Touch(u64::MAX), hits(&[(0, &[2])]));
        assert!(hm.any_has_sufficient_history_for_gestures());
        // Emptying that point's history flips it back.
        hm.clear_input_point(&InputPointId::Touch(u64::MAX));
        assert!(!hm.any_has_sufficient_history_for_gestures());
    }
    // ---------------------------------------------------- hover node getters
    #[test]
    fn current_hover_node_returns_the_deepest_node_of_dom_zero() {
        let hm = mouse_history(vec![hits(&[(0, &[3, 8, 5])])]);
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(8)));
        // Single-DOM: the _full variant is the same node wrapped in DomId 0.
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(0, 8)));
    }
    #[test]
    fn current_hover_node_ignores_non_zero_doms_but_full_does_not() {
        // Only a child DOM was hit — the single-DOM getter is blind to it.
        let hm = mouse_history(vec![hits(&[(2, &[4])])]);
        assert_eq!(hm.current_hover_node(), None);
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(2, 4)));
    }
    #[test]
    fn current_hover_node_full_prefers_the_front_most_child_dom() {
        let hm = mouse_history(vec![hits(&[(0, &[9]), (1, &[2])])]);
        // The root getter still reports the root's deepest node...
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(9)));
        // ...while the multi-DOM getter targets the composited-on-top child.
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(1, 2)));
    }
    #[test]
    fn previous_hover_node_is_none_until_a_second_frame_exists() {
        let hm = mouse_history(vec![hits(&[(0, &[1])])]);
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(1)));
        assert_eq!(hm.previous_hover_node(), None);
        assert_eq!(hm.previous_hover_node_full(), None);
    }
    #[test]
    fn previous_hover_node_reads_frame_one_not_the_oldest_frame() {
        // 6 pushes => the oldest (node 0) is evicted; frame 1 is node 4.
        let hm = mouse_history((0..6).map(|i| hits(&[(0, &[i])])).collect());
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(5)));
        assert_eq!(hm.previous_hover_node(), Some(NodeId::new(4)));
        assert_eq!(hm.previous_hover_node_full(), Some(dom_node(0, 4)));
    }
    #[test]
    fn previous_hover_node_full_sees_child_doms_of_the_previous_frame() {
        let hm = mouse_history(vec![hits(&[(0, &[1]), (7, &[3])]), hits(&[(0, &[2])])]);
        assert_eq!(hm.previous_hover_node(), Some(NodeId::new(1)));
        assert_eq!(hm.previous_hover_node_full(), Some(dom_node(7, 3)));
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(0, 2)));
    }
    #[test]
    fn hover_node_getters_are_none_when_the_frame_hit_nothing() {
        let hm = mouse_history(vec![FullHitTest::empty(None), FullHitTest::empty(None)]);
        assert!(hm.current_hover_node().is_none());
        assert!(hm.previous_hover_node().is_none());
        assert!(hm.current_hover_node_full().is_none());
        assert!(hm.previous_hover_node_full().is_none());
    }
    #[test]
    fn hover_node_getters_ignore_touch_history_entirely() {
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Touch(1), hits(&[(0, &[5])]));
        hm.push_hit_test(InputPointId::Touch(1), hits(&[(0, &[6])]));
        assert!(hm.current_hover_node().is_none());
        assert!(hm.previous_hover_node().is_none());
        assert!(hm.current_hover_node_full().is_none());
        assert!(hm.previous_hover_node_full().is_none());
        assert!(hm.any_has_sufficient_history_for_gestures());
    }
    // ------------------------------------------------------ purge_dom (other)
    #[test]
    fn purge_dom_removes_that_dom_from_every_frame_of_every_point() {
        let mut hm = HoverManager::new();
        for id in [InputPointId::Mouse, InputPointId::Touch(2)] {
            hm.push_hit_test(id, hits(&[(0, &[1]), (1, &[2])]));
            hm.push_hit_test(id, hits(&[(0, &[3]), (1, &[4])]));
        }
        hm.purge_dom(&dom(1));
        // Frames themselves are kept — only DOM 1's hits are forgotten.
        assert_eq!(hm.debug_counts(), (2, 4));
        for id in [InputPointId::Mouse, InputPointId::Touch(2)] {
            let history = hm.get_history(&id).expect("history exists");
            for frame in history {
                assert!(!frame.hovered_nodes.contains_key(&dom(1)));
                assert!(frame.hovered_nodes.contains_key(&dom(0)));
            }
        }
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(0, 3)));
        assert_eq!(hm.previous_hover_node_full(), Some(dom_node(0, 1)));
    }
    #[test]
    fn purge_dom_zero_leaves_child_dom_hits_intact() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1]), (4, &[2])])]);
        hm.purge_dom(&dom(0));
        // The single-DOM getter now finds nothing, the multi-DOM one falls back.
        assert_eq!(hm.current_hover_node(), None);
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(4, 2)));
        assert_eq!(hm.frame_count(&InputPointId::Mouse), 1);
    }
    #[test]
    fn purge_absent_or_extreme_dom_id_is_a_noop() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1])])]);
        let before = hm.clone();
        hm.purge_dom(&dom(9));
        hm.purge_dom(&dom(usize::MAX));
        assert_eq!(hm, before);
        // Purging on an empty manager must not panic either.
        let mut empty = HoverManager::new();
        empty.purge_dom(&dom(0));
        assert_eq!(empty, HoverManager::new());
    }
    #[test]
    fn purge_dom_twice_is_idempotent() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1]), (1, &[2])])]);
        hm.purge_dom(&dom(1));
        let once = hm.clone();
        hm.purge_dom(&dom(1));
        assert_eq!(hm, once);
    }
    // -------------------------------------------- remap_scrollbar_hit_id (other)
    fn sb_map(pairs: &[(usize, usize)]) -> BTreeMap<NodeId, NodeId> {
        pairs
            .iter()
            .map(|(o, n)| (NodeId::new(*o), NodeId::new(*n)))
            .collect()
    }
    #[test]
    fn remap_scrollbar_hit_id_rewrites_every_variant_of_the_target_dom() {
        let map = sb_map(&[(1, 42)]);
        let d = dom(0);
        let old = NodeId::new(1);
        let new = NodeId::new(42);
        assert_eq!(
            remap_scrollbar_hit_id(&ScrollbarHitId::VerticalTrack(d, old), d, &map),
            Some(ScrollbarHitId::VerticalTrack(d, new))
        );
        assert_eq!(
            remap_scrollbar_hit_id(&ScrollbarHitId::VerticalThumb(d, old), d, &map),
            Some(ScrollbarHitId::VerticalThumb(d, new))
        );
        assert_eq!(
            remap_scrollbar_hit_id(&ScrollbarHitId::HorizontalTrack(d, old), d, &map),
            Some(ScrollbarHitId::HorizontalTrack(d, new))
        );
        assert_eq!(
            remap_scrollbar_hit_id(&ScrollbarHitId::HorizontalThumb(d, old), d, &map),
            Some(ScrollbarHitId::HorizontalThumb(d, new))
        );
    }
    #[test]
    fn remap_scrollbar_hit_id_drops_unmounted_nodes() {
        let map = sb_map(&[(1, 42)]);
        let d = dom(0);
        // Node 2 is absent from the map => unmounted => the hit must be dropped.
        let unmounted = ScrollbarHitId::VerticalThumb(d, NodeId::new(2));
        assert_eq!(remap_scrollbar_hit_id(&unmounted, d, &map), None);
        // Empty map: everything on the target DOM is unmounted.
        let hit = ScrollbarHitId::VerticalThumb(d, NodeId::new(1));
        assert_eq!(remap_scrollbar_hit_id(&hit, d, &BTreeMap::new()), None);
    }
    #[test]
    fn remap_scrollbar_hit_id_passes_other_doms_through_untouched() {
        // The map applies to DOM 0 only; an id naming DOM 1 must NOT be rewritten
        // even though its NodeId happens to be a key in the map.
        let map = sb_map(&[(1, 42)]);
        let other = ScrollbarHitId::HorizontalTrack(dom(1), NodeId::new(1));
        assert_eq!(remap_scrollbar_hit_id(&other, dom(0), &map), Some(other));
        // ...and it survives an empty map too (no accidental drop).
        assert_eq!(
            remap_scrollbar_hit_id(&other, dom(0), &BTreeMap::new()),
            Some(other)
        );
    }
    #[test]
    fn remap_scrollbar_hit_id_handles_extreme_ids() {
        let big = usize::MAX - 1;
        let map = sb_map(&[(big, 0)]);
        let d = dom(usize::MAX);
        assert_eq!(
            remap_scrollbar_hit_id(&ScrollbarHitId::VerticalTrack(d, NodeId::new(big)), d, &map),
            Some(ScrollbarHitId::VerticalTrack(d, NodeId::ZERO))
        );
    }
    // ------------------------------------------------ NodeIdRemap::remap_node_ids
    /// A hit test with one regular + scroll + cursor + scrollbar hit on `node`.
    fn all_maps_hit(dom_inner: usize, node: usize) -> FullHitTest {
        let mut full = FullHitTest::empty(None);
        let mut ht = HitTest::empty();
        ht.regular_hit_test_nodes
            .insert(NodeId::new(node), hit_item(0));
        ht.scroll_hit_test_nodes
            .insert(NodeId::new(node), scroll_item());
        ht.cursor_hit_test_nodes
            .insert(NodeId::new(node), cursor_item());
        ht.scrollbar_hit_test_nodes.insert(
            ScrollbarHitId::VerticalThumb(dom(dom_inner), NodeId::new(node)),
            scrollbar_item(),
        );
        full.hovered_nodes.insert(dom(dom_inner), ht);
        full
    }
    #[test]
    fn remap_node_ids_rewrites_all_four_hit_maps() {
        let mut hm = mouse_history(vec![all_maps_hit(0, 3)]);
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(11))]),
        );
        let ht = &hm.get_current_mouse().expect("frame exists").hovered_nodes[&dom(0)];
        assert_eq!(
            ht.regular_hit_test_nodes
                .keys()
                .copied()
                .collect::<Vec<_>>(),
            vec![NodeId::new(11)]
        );
        assert_eq!(
            ht.scroll_hit_test_nodes.keys().copied().collect::<Vec<_>>(),
            vec![NodeId::new(11)]
        );
        assert_eq!(
            ht.cursor_hit_test_nodes.keys().copied().collect::<Vec<_>>(),
            vec![NodeId::new(11)]
        );
        assert_eq!(
            ht.scrollbar_hit_test_nodes
                .keys()
                .copied()
                .collect::<Vec<_>>(),
            vec![ScrollbarHitId::VerticalThumb(dom(0), NodeId::new(11))]
        );
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(11)));
    }
    #[test]
    fn remap_node_ids_with_an_empty_map_drops_every_hit_of_that_dom() {
        let mut hm = mouse_history(vec![all_maps_hit(0, 3)]);
        // Empty map = nothing matched = every node was unmounted.
        hm.remap_node_ids(dom(0), &NodeIdMap::default());
        let ht = &hm.get_current_mouse().expect("frame exists").hovered_nodes[&dom(0)];
        assert!(ht.regular_hit_test_nodes.is_empty());
        assert!(ht.scroll_hit_test_nodes.is_empty());
        assert!(ht.cursor_hit_test_nodes.is_empty());
        assert!(ht.scrollbar_hit_test_nodes.is_empty());
        assert_eq!(hm.current_hover_node(), None);
        // The (now empty) DOM entry itself is kept — only purge_dom removes it.
        assert!(hm
            .get_current_mouse()
            .expect("frame exists")
            .hovered_nodes
            .contains_key(&dom(0)));
    }
    #[test]
    fn remap_node_ids_drops_unmounted_but_keeps_survivors() {
        // Nodes 1 and 4 hit; only 4 survives the rebuild (as node 0).
        let mut hm = mouse_history(vec![hits(&[(0, &[1, 4])])]);
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(4), NodeId::ZERO)]),
        );
        let ht = &hm.get_current_mouse().expect("frame exists").hovered_nodes[&dom(0)];
        assert_eq!(
            ht.regular_hit_test_nodes
                .keys()
                .copied()
                .collect::<Vec<_>>(),
            vec![NodeId::ZERO]
        );
        assert_eq!(hm.current_hover_node(), Some(NodeId::ZERO));
    }
    #[test]
    fn remap_node_ids_swap_does_not_lose_or_alias_entries() {
        // 1 -> 2 and 2 -> 1 in the same pass: the naive in-place rewrite would
        // clobber one of them. Both must survive with their items swapped.
        let mut full = FullHitTest::empty(None);
        let mut ht = HitTest::empty();
        ht.regular_hit_test_nodes
            .insert(NodeId::new(1), hit_item(10));
        ht.regular_hit_test_nodes
            .insert(NodeId::new(2), hit_item(20));
        full.hovered_nodes.insert(dom(0), ht);
        let mut hm = mouse_history(vec![full]);
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([
                (NodeId::new(1), NodeId::new(2)),
                (NodeId::new(2), NodeId::new(1)),
            ]),
        );
        let ht = &hm.get_current_mouse().expect("frame exists").hovered_nodes[&dom(0)];
        assert_eq!(ht.regular_hit_test_nodes.len(), 2);
        assert_eq!(ht.regular_hit_test_nodes[&NodeId::new(2)].hit_depth, 10);
        assert_eq!(ht.regular_hit_test_nodes[&NodeId::new(1)].hit_depth, 20);
    }
    // ------------------------------------------------- apply_pointer_capture
    fn seat_move(seat_id: u64, target: DomNodeId, ty: EventType) -> SyntheticEvent {
        use azul_core::events::{KeyModifiers, MouseEventData};
        SyntheticEvent::new(
            ty,
            EventSource::User,
            target,
            azul_core::task::Instant::Tick(azul_core::task::SystemTick { tick_counter: 0 }),
            EventData::Mouse(MouseEventData {
                position: LogicalPosition::zero(),
                button: MouseButton::Left,
                buttons: 0,
                modifiers: KeyModifiers::default(),
                seat_id,
                ..Default::default()
            }),
        )
    }
    #[test]
    fn a_capture_retargets_only_its_own_seat_and_ends_on_that_seats_release() {
        // Seat 0 captured node 3; seat 9 is moving over node 5 on its own.
        let capture = PointerCapture {
            seat_id: 0,
            node: press_dnid(3),
        };
        let mut events = vec![
            seat_move(0, press_dnid(8), EventType::MouseMove),
            seat_move(9, press_dnid(5), EventType::MouseMove),
            seat_move(9, press_dnid(5), EventType::MouseUp),
        ];
        let released = apply_pointer_capture(&mut events, capture);
        assert_eq!(
            events[0].target,
            press_dnid(3),
            "the captured seat's move went to the node"
        );
        assert_eq!(
            events[1].target,
            press_dnid(5),
            "the other seat's move did not"
        );
        assert!(
            !released,
            "the OTHER seat's release does not end this capture"
        );
        let mut events = vec![seat_move(0, press_dnid(8), EventType::MouseUp)];
        assert!(apply_pointer_capture(&mut events, capture));
        assert_eq!(events[0].target, press_dnid(3));
    }
    // ------------------------------------------------- focusable_under_pointer
    /// Hits: dom 0 (the host) node 3 at depth 1; dom 1 (a page over it) node
    /// 2 at depth 0. Parents: in dom 0, 3 -> 1 -> 0; in dom 1, 2 -> 0.
    fn host_and_page() -> FullHitTest {
        let mut full = FullHitTest::empty(None);
        let mut host = HitTest::empty();
        host.regular_hit_test_nodes
            .insert(NodeId::new(3), hit_item(1));
        full.hovered_nodes.insert(dom(0), host);
        let mut page = HitTest::empty();
        page.regular_hit_test_nodes
            .insert(NodeId::new(2), hit_item(0));
        full.hovered_nodes.insert(dom(1), page);
        full
    }
    fn parent_of(d: DomId, n: NodeId) -> Option<NodeId> {
        match (d.inner, n.index()) {
            (0, 3) => Some(NodeId::new(1)),
            (0, 1) => Some(NodeId::new(0)),
            (1, 2) => Some(NodeId::new(0)),
            _ => None,
        }
    }
    #[test]
    fn a_click_on_unfocusable_page_content_does_not_focus_the_host_beneath() {
        // THE DEFECT: both copies of this scan walked every hit DOM and let
        // the last focusable win, so the host's focusable node 1 - under the
        // page, not in the click's own DOM at all - took the focus.
        let ht = host_and_page();
        let host_node_1_is_focusable = |d: DomId, n: NodeId| d.inner == 0 && n.index() == 1;
        assert_eq!(
            focusable_under_pointer(&ht, host_node_1_is_focusable, parent_of),
            None,
            "nothing focusable in the page's own chain: a blur, not the host"
        );
    }
    #[test]
    fn a_click_on_a_page_focuses_the_pages_own_focusable_ancestor() {
        let ht = host_and_page();
        // Both DOMs have a focusable root; the page's wins because the page
        // is the front-most surface.
        let roots = |_: DomId, n: NodeId| n.index() == 0;
        let got = focusable_under_pointer(&ht, roots, parent_of).expect("the page root");
        assert_eq!(got.dom, dom(1));
        assert_eq!(got.node.into_crate_internal(), Some(NodeId::new(0)));
    }
    #[test]
    fn the_walk_starts_at_the_front_most_hit_not_the_largest_id() {
        // One DOM, node 7 (depth 2) behind node 4 (depth 0); 7 is focusable,
        // 4's chain is not. The old largest-id proxy would have focused 7.
        let mut full = FullHitTest::empty(None);
        let mut ht = HitTest::empty();
        ht.regular_hit_test_nodes
            .insert(NodeId::new(4), hit_item(0));
        ht.regular_hit_test_nodes
            .insert(NodeId::new(7), hit_item(2));
        full.hovered_nodes.insert(dom(0), ht);
        let seven = |_: DomId, n: NodeId| n.index() == 7;
        let no_parents = |_: DomId, _: NodeId| None;
        assert_eq!(focusable_under_pointer(&full, seven, no_parents), None);
        assert!(focusable_under_pointer(&FullHitTest::empty(None), seven, no_parents).is_none());
    }
    #[test]
    fn remap_node_ids_can_change_which_node_is_deepest() {
        // Old order: 7 is deepest. The rebuild renumbers 3 -> 9 and 7 -> 2,
        // so the deepest hit must be recomputed (9), not carried over.
        let mut hm = mouse_history(vec![hits(&[(0, &[3, 7])])]);
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(7)));
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([
                (NodeId::new(3), NodeId::new(9)),
                (NodeId::new(7), NodeId::new(2)),
            ]),
        );
        assert_eq!(hm.current_hover_node(), Some(NodeId::new(9)));
        assert_eq!(hm.current_hover_node_full(), Some(dom_node(0, 9)));
    }
    #[test]
    fn remap_node_ids_leaves_other_doms_alone() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1]), (1, &[1])])]);
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(5))]),
        );
        let frame = hm.get_current_mouse().expect("frame exists");
        assert_eq!(
            frame.hovered_nodes[&dom(0)]
                .regular_hit_test_nodes
                .keys()
                .copied()
                .collect::<Vec<_>>(),
            vec![NodeId::new(5)],
            "DOM 0 is remapped"
        );
        assert_eq!(
            frame.hovered_nodes[&dom(1)]
                .regular_hit_test_nodes
                .keys()
                .copied()
                .collect::<Vec<_>>(),
            vec![NodeId::new(1)],
            "DOM 1 must be untouched by DOM 0's reconciliation"
        );
    }
    #[test]
    fn remap_node_ids_keeps_foreign_dom_scrollbar_ids_stored_under_the_target_dom() {
        // A scrollbar hit recorded under DOM 0's HitTest but whose ScrollbarHitId
        // names DOM 1: remap_scrollbar_hit_id must pass it through, not drop it.
        let mut full = FullHitTest::empty(None);
        let mut ht = HitTest::empty();
        ht.scrollbar_hit_test_nodes.insert(
            ScrollbarHitId::VerticalTrack(dom(1), NodeId::new(1)),
            scrollbar_item(),
        );
        ht.scrollbar_hit_test_nodes.insert(
            ScrollbarHitId::VerticalTrack(dom(0), NodeId::new(1)),
            scrollbar_item(),
        );
        full.hovered_nodes.insert(dom(0), ht);
        let mut hm = mouse_history(vec![full]);
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(8))]),
        );
        let keys: Vec<_> = hm.get_current_mouse().expect("frame exists").hovered_nodes[&dom(0)]
            .scrollbar_hit_test_nodes
            .keys()
            .copied()
            .collect();
        assert!(
            keys.contains(&ScrollbarHitId::VerticalTrack(dom(1), NodeId::new(1))),
            "foreign-DOM scrollbar id must survive unchanged, got {keys:?}"
        );
        assert!(
            keys.contains(&ScrollbarHitId::VerticalTrack(dom(0), NodeId::new(8))),
            "target-DOM scrollbar id must be rewritten, got {keys:?}"
        );
        assert_eq!(keys.len(), 2);
    }
    #[test]
    fn remap_node_ids_applies_to_every_frame_and_every_input_point() {
        let mut hm = HoverManager::new();
        for id in [InputPointId::Mouse, InputPointId::Touch(1)] {
            hm.push_hit_test(id, hits(&[(0, &[2])]));
            hm.push_hit_test(id, hits(&[(0, &[2])]));
        }
        hm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(2), NodeId::new(6))]),
        );
        for id in [InputPointId::Mouse, InputPointId::Touch(1)] {
            for frame in hm.get_history(&id).expect("history exists") {
                assert_eq!(
                    frame.hovered_nodes[&dom(0)]
                        .regular_hit_test_nodes
                        .keys()
                        .copied()
                        .collect::<Vec<_>>(),
                    vec![NodeId::new(6)]
                );
            }
        }
        assert_eq!(hm.previous_hover_node(), Some(NodeId::new(6)));
    }
    #[test]
    fn remap_node_ids_on_an_empty_manager_or_unknown_dom_does_not_panic() {
        let mut empty = HoverManager::new();
        empty.remap_node_ids(dom(usize::MAX), &NodeIdMap::default());
        assert_eq!(empty, HoverManager::new());
        let mut hm = mouse_history(vec![hits(&[(0, &[1])])]);
        let before = hm.clone();
        // Reconciliation for a DOM that was never hit changes nothing.
        hm.remap_node_ids(
            dom(3),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(2))]),
        );
        assert_eq!(hm, before);
    }
    #[test]
    fn remap_node_ids_identity_map_is_idempotent() {
        let mut hm = mouse_history(vec![all_maps_hit(0, 3)]);
        let before = hm.clone();
        let identity = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(3))]);
        hm.remap_node_ids(dom(0), &identity);
        assert_eq!(hm, before, "identity remap must not change anything");
        hm.remap_node_ids(dom(0), &identity);
        assert_eq!(hm, before, "and applying it twice must not either");
    }
    // ------------------------------------------------------------- misc invariants
    #[test]
    fn clone_is_equal_and_independent_of_the_original() {
        let mut hm = mouse_history(vec![hits(&[(0, &[1])])]);
        let snapshot = hm.clone();
        assert_eq!(hm, snapshot);
        hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[2])]));
        assert_ne!(hm, snapshot, "the clone must not observe later pushes");
        assert_eq!(snapshot.frame_count(&InputPointId::Mouse), 1);
        assert_eq!(hm.frame_count(&InputPointId::Mouse), 2);
    }
    #[test]
    fn debug_counts_agrees_with_frame_count_and_active_points() {
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Mouse, hits(&[(0, &[1])]));
        hm.push_hit_test(InputPointId::Touch(7), hits(&[(0, &[1])]));
        hm.push_hit_test(InputPointId::Touch(7), hits(&[(0, &[2])]));
        let (points, total) = hm.debug_counts();
        let active = hm.get_active_input_points();
        assert_eq!(points, active.len());
        assert_eq!(
            total,
            active.iter().map(|id| hm.frame_count(id)).sum::<usize>()
        );
        assert_eq!((points, total), (2, 3));
    }
}